branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import React from 'react'
import { Link } from 'react-router-dom'
export default class Employee extends React.Component {
render() {
return (
<Link
className='bg-white ma3 box employee flex flex-column no-underline br2'
to={`/employee/${this.props.employee.id}`}
>
<div
className='image'
style={{
backgroundImage: `url(${this.props.employee.imageUrl})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
marginTop: '25px'
}}
/>
<div className='flex items-center black-80 fw3 name'>
{this.props.employee.name} {this.props.employee.surname}
</div>
</Link>
)
}
}<file_sep>import React from 'react';
function Button (props) {
return (
<div className='saveButton' onClick={props.clickHandler}>{props.content}</div>
);
}
export default Button;<file_sep>import React from 'react'
import { withRouter } from 'react-router-dom'
import { graphql} from 'react-apollo'
import Modal from 'react-modal'
import modalStyle from '../constants/modalStyle'
import gql from 'graphql-tag'
class CreatePage extends React.Component {
state = {
name: '',
surname: '',
position: '',
dateOfBirth: '',
imageUrl: '',
}
render() {
return (
<Modal
isOpen
contentLabel='Create Employee'
style={modalStyle}
onRequestClose={this.props.history.goBack}
>
<div className='pa4 flex justify-center bg-white'>
<div style={{maxWidth: 400}} className=''>
{this.state.imageUrl &&
<img
src={this.state.imageUrl}
alt=''
className='w-100 mv3'
/>}
<input
className='w-100 pa3 mv2'
value={this.state.imageUrl}
placeholder='Employee image url'
onChange={e => this.setState({imageUrl: e.target.value})}
autoFocus
/>
<input
className='w-100 pa3 mv2'
value={this.state.name}
placeholder='Employee name'
onChange={e => this.setState({name: e.target.value})}
autoFocus
/>
<input
className='w-100 pa3 mv2'
value={this.state.surname}
placeholder='Employee surname'
onChange={e => this.setState({surname: e.target.value})}
/>
<input
className='w-100 pa3 mv2'
value={this.state.position}
placeholder='Employee position'
onChange={e => this.setState({position: e.target.value})}
/>
<input
className='w-100 pa3 mv2'
value={this.state.dateOfBirth}
placeholder='Employee date of birth'
type='date'
onChange={e => this.setState({dateOfBirth: e.target.value})}
/>
{this.state.surname &&
this.state.name &&
this.state.position &&
this.state.dateOfBirth &&
<button
className='pa3 bg-black-10 bn dim ttu pointer'
onClick={this.handleAddNew}
>
Add new Employee
</button>}
</div>
</div>
</Modal>
)
}
handleAddNew = async () => {
const {name, surname, position, dateOfBirth} = this.state;
let {imageUrl} = this.state;
if (!imageUrl) imageUrl = 'https://cdn1.iconfinder.com/data/icons/IconsLandVistaPeopleIconsDemo/256/Customer_Male_Light.png';
await this.props.createEmployeeMutation({variables: {name, surname, position, dateOfBirth, imageUrl}})
this.props.history.replace('/')
}
}
const CREATE_EMPLOYEE_MUTATION = gql`
mutation CreateEmployeeMutation($surname: String!, $name: String!, $position: String!, $dateOfBirth: String!, $imageUrl: String!) {
createEmployee(name: $name, surname: $surname, position: $position, dateOfBirth: $dateOfBirth, imageUrl: $imageUrl) {
id
surname
name
position
dateOfBirth
imageUrl
}
}
`
const CreatePageWithMutation = graphql(CREATE_EMPLOYEE_MUTATION, {name: 'createEmployeeMutation'})(CreatePage)
export default withRouter(CreatePageWithMutation)
<file_sep>import React from 'react';
import { graphql, compose } from 'react-apollo';
import Modal from 'react-modal';
import modalStyle from '../constants/modalStyle';
import { withRouter } from 'react-router-dom';
import gql from 'graphql-tag';
import ContentEditable from "./ContentEditable";
import Button from './SaveButton';
const detailModalStyle = {
overlay: modalStyle.overlay,
content: {
...modalStyle.content,
height: 761,
},
}
class DetailPage extends React.Component {
constructor(props) {
super(props);
this.state = {
Employee: {...this.props.employeeQuery.Employee},
edited: false
}
}
render() {
if (this.props.employeeQuery.loading) {
return (
<div className='flex w-100 h-100 items-center justify-center pt7'>
<div>
Loading...
</div>
</div>
)
}
const {Employee} = this.state;
return (
<Modal
isOpen
contentLabel='Create Employee'
style={detailModalStyle}
onRequestClose={this.props.history.goBack}
>
<div
className='close right-0 top-0 pointer'
onClick={this.props.history.goBack}
>
<img src={require('../assets/close.svg')} alt='' />
</div>
<div
className='delete ttu white pointer fw6 absolute left-0 top-0 br2'
onClick={this.handleDelete}
>
Delete
</div>
<div
className='bg-white detail flex flex-column no-underline br2 h-100'
>
<div
className='image'
style={{
backgroundImage: `url(${Employee.imageUrl})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
marginTop: '25px'
}}
/>
<ContentEditable onUpdate={(html) => this.handleNameUpdate(html)} className='items-center black-80 fw3 name' html={Employee.name} />
<ContentEditable onUpdate={(html) => this.handleSurnameUpdate(html)} className='items-center black-80 fw3 surname' html={Employee.surname} />
<ContentEditable onUpdate={(html) => this.handlePositionUpdate(html)} className='flex items-center black-80 fw3 position' html={Employee.position} />
<ContentEditable onUpdate={(html) => this.handleDateOfBirthUpdate(html)} className='flex items-center black-80 fw3 dob' html={Employee.dateOfBirth} />
{this.state.edited &&
<Button clickHandler={this.onSave} content='SAVE'/>
}
</div>
</Modal>
)
}
onSave = async (e) => {
if (this.state.edited) {
e.target.innerHTML = 'SAVING...';
await this.handleUpdate();
e.target.innerHTML = 'SAVED!';
setTimeout(function(){
this.setState({
edited: false
});
}, 1000);
}
}
handleNameUpdate = (newName) => {
this.setState({Employee: {
...this.state.Employee,
name: newName,
edited: true
}}, () => {
this.handleUpdate();
});
}
handleSurnameUpdate = (newSurname) => {
this.setState({Employee: {
...this.state.Employee,
surname: newSurname,
edited: true
}}, () => {
this.handleUpdate();
});
}
handlePositionUpdate = (newPosition) => {
this.setState({Employee: {
...this.state.Employee,
position: newPosition,
edited: true
}}, () => {
this.handleUpdate();
});
}
handleDateOfBirthUpdate = (newDateOfBirth) => {
this.setState({Employee: {
...this.state.Employee,
dateOfBirth: newDateOfBirth,
edited: true
}}, () => {
this.handleUpdate();
});
}
handleUpdate = async () => {
await this.props.updateEmployeeMutation({variables: this.state.Employee});
}
handleDelete = async () => {
await this.props.deleteEmployeeMutation({variables: {id: this.props.employeeQuery.Employee.id}});
this.props.history.replace('/');
}
}
const DELETE_EMPLOYEE_MUTATION = gql`
mutation DeleteEmployeeMutation($id: ID!) {
deleteEmployee(id: $id) {
id
}
}
`
const UPDATE_EMPLOYEE_MUTATION = gql`
mutation UpdateEmployeeMutation($id: ID!, $surname: String!, $name: String!, $position: String!, $dateOfBirth: String!, $imageUrl: String!) {
updateEmployee(id: $id, name: $name, surname: $surname, position: $position, dateOfBirth: $dateOfBirth, imageUrl: $imageUrl) {
id
surname
name
position
dateOfBirth
imageUrl
}
}
`
const EMPLOYEE_QUERY = gql`
query employeeQuery($id: ID!) {
Employee(id: $id) {
id
name
surname
dateOfBirth
position
imageUrl
}
}
`
const DetailPageWithGraphQL = compose(
graphql(EMPLOYEE_QUERY, {
name: 'employeeQuery',
// see documentation on computing query variables from props in wrapper
// http://dev.apollodata.com/react/queries.html#options-from-props
options: ({match}) => ({
variables: {
id: match.params.id,
},
}),
}),
graphql(DELETE_EMPLOYEE_MUTATION, {
name: 'deleteEmployeeMutation'
}),
graphql(UPDATE_EMPLOYEE_MUTATION, {
name: 'updateEmployeeMutation'
})
)(DetailPage)
const DetailPageWithDelete = graphql(DELETE_EMPLOYEE_MUTATION)(DetailPageWithGraphQL);
export default withRouter(DetailPageWithDelete);
| b1e6351050545891e45c02cf2f27da8d86f4aa47 | [
"JavaScript"
] | 4 | JavaScript | charisTheo/jacando-react-apollo | 045016c2094bb05481f67e06897a024693a6c4f1 | 4fe423f0b0f960aab92c493e60df569a4738a67e | |
refs/heads/main | <repo_name>zibersaioros/multiple_datasource<file_sep>/src/test/java/com/rs/multiple_datasource/biz_b/service/TestServiceTest.java
package com.rs.multiple_datasource.biz_b.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class TestServiceTest {
@Autowired
TestService testService;
@Test
public void test(){
System.out.println(testService.select(1).getData());
}
}<file_sep>/settings.gradle
rootProject.name = 'multiple_datasource'
<file_sep>/src/test/java/com/rs/multiple_datasource/biz_a/persistence/BizAMapperTest.java
package com.rs.multiple_datasource.biz_a.persistence;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class BizAMapperTest {
// @Autowired
// BizAMapper bizAMapper;
//
// @Test
// public void test(){
// String test = bizAMapper.selectTest();
// System.out.println(test);
// }
}<file_sep>/src/main/java/com/rs/multiple_datasource/biz_b/model/TestEntity.java
package com.rs.multiple_datasource.biz_b.model;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Getter
@Setter
@Table(name = "test")
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private Integer data;
}
| 6cc2bf3763c1e7729749002e6c55225d72c2cc07 | [
"Java",
"Gradle"
] | 4 | Java | zibersaioros/multiple_datasource | 0bfe3bd071626b25e59edee515764894a5f27e42 | ed9ca9857a852bbc9f988e31e8966d1b34882244 | |
refs/heads/master | <repo_name>termaik1/task-FrameWork-Team<file_sep>/client/src/store/reducers.test.js
import reducers from "./reducers";
import actions from "./actions";
describe("Test reducers in Todo", () => {
let state;
beforeEach(() => {
state = {
origin: [
{
_id: 1,
name: "test1",
completed: false,
},
{
_id: 2,
name: "test2",
completed: true,
},
],
};
});
it("add items", () => {
const data = [
{
_id: 1,
name: "test1",
completed: false,
},
{
_id: 2,
name: "test2",
completed: true,
},
];
const action = actions.getSuccess(data);
const newState = reducers({ origin: [] }, action);
expect(newState.origin.length).toBe(2);
});
it("item addition", () => {
const action = actions.createSuccess({
_id: 3,
name: "test3",
completed: true,
});
const newState = reducers(state, action);
expect(newState.origin.length).toBe(3);
});
it("item delete", () => {
const action = actions.deleteSuccess({
_id: 2,
name: "test2",
completed: true,
});
const newState = reducers(state, action);
expect(newState.origin.length).toBe(1);
});
});
<file_sep>/server/src/cors/db.ts
import mongoose from "mongoose";
export default () =>
mongoose.connect(
"mongodb+srv://admin:<EMAIL>@cluster0.cqaze.mongodb.net/Todo?retryWrites=true&w=majority",
{ useNewUrlParser: true, useCreateIndex: true, useFindAndModify: true }
);<file_sep>/server/src/index.ts
import express from "express";
import bodyParser from 'body-parser'
import dotenv from 'dotenv'
import http from 'http'
import cors from 'cors'
import { db, createRoutes } from './cors'
const app = express();
const httpServer = http.createServer(app)
dotenv.config()
db()
app.use(bodyParser.json())
app.use(cors())
createRoutes(app)
httpServer.listen(process.env.PORT, () =>
console.log(`Server start http://localhost:${process.env.PORT}`)
);<file_sep>/server/src/cors/index.ts
export { default as createRoutes } from './createRoutes'
export { default as db } from './db'<file_sep>/client/src/Item.js
import React from "react";
import PropTypes from "prop-types";
import {
Checkbox,
TextField,
FormGroup,
FormControlLabel,
} from "@material-ui/core";
import DeleteIcon from "@material-ui/icons/Delete";
const Item = (props) => {
const { onChange, onDelete, _id, completed, name } = props;
return (
<FormGroup row>
<FormControlLabel
control={
<Checkbox
checked={completed}
name="checkedA"
onChange={(e) => onChange(_id, e.target.checked, name)}
/>
}
/>
<FormControlLabel
control={
<TextField
id="standard-form-text"
defaultValue={name}
onChange={(e) => onChange(_id, completed, e.target.value)}
/>
}
/>
<FormControlLabel
control={<DeleteIcon onClick={() => onDelete(_id)} />}
/>
</FormGroup>
);
};
Item.propTypes = {
onChange: PropTypes.func,
onDelete: PropTypes.func,
_id: PropTypes.number,
completed: PropTypes.bool,
name: PropTypes.string,
};
export default Item;
<file_sep>/client/src/List.js
import React, { useMemo, useCallback } from "react";
import { useDispatch } from "react-redux";
import _ from "lodash";
import todoActions from "./store/actions";
import Item from "./Item";
const List = (props) => {
const dispatch = useDispatch();
const { origin } = props;
const onDelete = useCallback((_id) => dispatch(todoActions.delete(_id)), []);
const onChange = useCallback(
(_id, completed, name) =>
dispatch(todoActions.edit({ _id, completed, name })),
[]
);
const renderItem = useMemo(
() =>
!!_.size(origin) &&
_.map(origin, (item) => (
<Item
key={item._id}
{...item}
onChange={onChange}
onDelete={onDelete}
/>
)),
[origin]
);
return renderItem;
};
export default List;
<file_sep>/client/src/store/store.js
import { createStore, applyMiddleware, combineReducers } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { composeWithDevTools } from 'redux-devtools-extension';
import Todo from './reducers';
import todoSagas from './sagas';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
const rootReducers = combineReducers({
Todo,
});
const store = createStore(
rootReducers,
composeWithDevTools(applyMiddleware(...middlewares))
);
sagaMiddleware.run(todoSagas);
export default store;
<file_sep>/README.md
# 1)Выполнил:
<NAME>
# 2) Описание
### frontend(ReactJS)
было реализован функционал согласно ТЗ
+ были добавлены unit тесты на jest и enzyme
### backend(NodeJS)
созданы методы CRUD
# 3) Настройка:
на стороне fronted запустить команду:
* 1) npm install
на стороне backend запустить команды:
* 1) npm install
**Возможно не будет коннект с mongoDB, для это не обходимо сделать следующее:
* 1) залогиниться на сайте https://account.mongodb.com/
* 2) Авторизоваться по гугл аккаунту(ниже прикреплен)
* 3) Зайти на вкладку "Network Access"
* 4) Кликнуть на "+ ADD IP ADDRESS", после нажать на "ADD CURRENT IP ADDRESS" и сохранить "confirm"
* 5) Подождать пару минут
# 4) Аккаунт
google аккаунт:
user: <EMAIL>
password: <PASSWORD>
# 5) Запуск проекта:
на стороне frontend выполнить команду :
* npm run start
так же есть команда "test" для запуска unit тестов
* npm run test
на стороне backend выполнить команду :
* npm run start
<file_sep>/server/src/controllers/types.ts
export function getObjValue<T extends object, R extends keyof T>(
obj: T,
key: R
) {
return obj[key];
}
<file_sep>/client/src/store/constants.js
export default {
GET: 'SERVER:GET',
GET_SUCCESS: 'GET_SUCCESS',
GET_FAILURE: 'GET_FAILURE',
CREATE: 'SERVER:CREATE',
CREATE_SUCCESS: 'CREATE_SUCCESS',
CREATE_FAILURE: 'CREATE_FAILURE',
EDIT: 'SERVER:EDIT',
EDIT_SUCCESS: 'EDIT_SUCCESS',
EDIT_FALURE: 'EDIT_FAILURE',
DELETE: 'SERVER:DELETE',
DELETE_SUCCESS: 'DELETE_SUCCESS',
DELETE_FALURE: 'DELETE_FALURE'
};
<file_sep>/server/src/controllers/index.ts
export { default as TodoController } from "./TodoController";
<file_sep>/client/src/List.test.js
import React from "react";
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { create } from "react-test-renderer";
import List from "./List";
configure({ adapter: new Adapter() });
jest.mock("react-redux", () => ({
...jest.requireActual("react-redux"),
useDispatch: jest.fn,
}));
describe("List component", () => {
let props;
beforeEach(() => {
props = {
origin: [
{
_id: 1,
name: "test1",
completed: false,
},
{
_id: 2,
name: "test2",
completed: true,
},
],
};
});
it("Transfer check props", () => {
const component = create(<List {...props} />);
const root = component.root;
const rootComponent = root.findByProps(props);
expect(rootComponent.props).toEqual(props);
});
});
<file_sep>/server/src/models/Todo.ts
import { Schema, model, Document } from "mongoose";
export interface ITodo extends Document {
_id: string;
name: string;
completed: boolean;
}
const TodoSchema = new Schema({
name: String,
completed: {
type: Boolean,
default: false,
},
});
const TodoModel = model<ITodo>("Todo", TodoSchema);
export default TodoModel;
<file_sep>/client/src/store/reducers.js
import _ from "lodash";
import types from "./constants";
const initialState = {
origin: [],
};
const TodoReducers = {
[types.GET_SUCCESS]: (state, action) => ({
...state,
origin: action.payload,
}),
[types.CREATE_SUCCESS]: (state, action) => {
const newTodo = action.payload;
const prevOrigin = [...state.origin];
return {
...state,
origin: [...prevOrigin, newTodo],
};
},
[types.DELETE_SUCCESS]: (state, action) => {
const deleteTodo = action.payload;
const prevOrigin = [...state.origin];
const newOrigin = _.filter(
prevOrigin,
(item) => item._id !== deleteTodo._id
);
return { ...state, origin: [...newOrigin] };
},
};
const Todo = (state = initialState, action) => {
const reducers = TodoReducers[action.type];
if (!reducers) {
return state;
}
return reducers(state, action);
};
export default Todo;
<file_sep>/client/src/App.js
import React, { useEffect, useCallback, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import todoActions from './store/actions';
import { TextField, Button } from '@material-ui/core/';
import List from './List';
const App = () => {
const dispatch = useDispatch();
const [name, setName] = useState("");
const { origin } = useSelector((state) => state.Todo);
useEffect(() => {
dispatch(todoActions.get());
}, []);
const onCreate = useCallback(() => {
dispatch(todoActions.create({ name }));
setName("");
}, [name]);
return (
<div className="app">
<div className="app__container">
<div className="app__container-panel">
<TextField
id="outlined-required"
label="Task"
value={name}
variant="outlined"
size="small"
onChange={(e) => setName(e.target.value)}
/>
<Button
id="button-material"
size="large"
variant="outlined"
onClick={onCreate}
>
ADD
</Button>
</div>
<div className="app__container-content">
<List origin={origin} />
</div>
</div>
</div>
);
};
export default App;
<file_sep>/client/src/Item.test.js
import React from "react";
import { create } from "react-test-renderer";
import Item from "./Item";
describe("Item component", () => {
let props;
beforeEach(() => {
props = {
_id: 1,
name: "Test1",
completed: true,
};
});
it("check transmission props", () => {
const component = create(<Item {...props} />);
const root = component.root;
const rootComponent = root.findByProps(props);
expect(rootComponent.props).toEqual(props);
});
});
<file_sep>/server/src/controllers/TodoController.ts
import express from "express";
import _ from "lodash";
import { getObjValue } from "./types";
import TodoModel from "../models/Todo";
import { ITodo } from "../models/Todo";
class TodoController {
get = async (req: express.Request, res: express.Response) => {
try {
const todos: Array<ITodo> = await TodoModel.find();
res.json(todos);
} catch (err) {
console.log("ERR", err);
res.status(400).json({ message: "Error" });
}
};
create = async (req: express.Request, res: express.Response) => {
try {
const name: string = getObjValue(req.body, "name");
const todoCreate = new TodoModel({ name });
const todo = await todoCreate.save();
res.json(todo);
} catch (err) {
console.log("ERR", err);
res.status(400).json({ message: "Error" });
}
};
patch = async (req: express.Request, res: express.Response) => {
try {
const _id: string = getObjValue(req.body, "_id");
const name: string = getObjValue(req.body, "name");
const completed: boolean = getObjValue(req.body, "completed");
const todo: ITodo = await TodoModel.findOneAndUpdate(
{ _id },
{ name, completed },
{
new: true,
upsert: true,
}
);
res.json(todo);
} catch (err) {
console.log("ERR", err);
res.status(400).json({ message: "Error" });
}
};
delete = async (req: express.Request, res: express.Response) => {
try {
const _id: string = getObjValue(req.params, "id");
const todoDelete = await TodoModel.findByIdAndRemove({ _id });
res.json(todoDelete);
} catch (err) {
console.log("ERR", err);
res.status(400).json({ message: "Error" });
}
};
}
export default TodoController;
<file_sep>/client/src/store/actions.js
import types from "./constants";
const actions = {
get: () => ({
type: types.GET,
}),
getSuccess: (data) => ({
type: types.GET_SUCCESS,
payload: data,
}),
getFailure: () => ({
type: types.GET_FAILURE,
}),
create: (data) => ({
type: types.CREATE,
payload: data,
}),
createSuccess: (data) => ({
type: types.CREATE_SUCCESS,
payload: data,
}),
createFailure: () => ({
type: types.CREATE_FAILURE,
}),
edit: (data) => ({
type: types.EDIT,
payload: data,
}),
editSuccess: (data) => ({
type: types.EDIT_SUCCESS,
payload: data,
}),
editFailure: () => ({
type: types.EDIT_FAILURE,
}),
delete: (data) => ({
type: types.DELETE,
payload: data,
}),
deleteSuccess: (data) => ({
type: types.DELETE_SUCCESS,
payload: data,
}),
deleteFailure: () => ({
type: types.DELETE_FAILURE,
}),
};
export default actions;
<file_sep>/client/src/App.test.js
import React from "react";
import { shallow, configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import App from "./App";
configure({ adapter: new Adapter() });
jest.mock("react-redux", () => ({
...jest.requireActual("react-redux"),
useSelector: jest.fn,
useDispatch: jest.fn,
}));
describe("App component", () => {
let component;
beforeEach(() => {
component = shallow(<App />);
});
it("checking the rendering of all blocks <div>", () => {
const divAll = component.find("div");
const divOne = component.find(".app");
const divTwo = component.find(".app__container");
const divThree = component.find(".app__container-panel");
const divFour = component.find(".app__container-content");
expect(divAll).toHaveLength(4);
expect(divOne).toHaveLength(1);
expect(divTwo).toHaveLength(1);
expect(divThree).toHaveLength(1);
expect(divFour).toHaveLength(1);
});
it("checking rendering of <TextField> from library 'material-ui' by its #id", () => {
const textFieldId = component.find("#outlined-required");
expect(textFieldId).toHaveLength(1);
});
it("checking rendering of <Button> from library 'material-ui' by its #id", () => {
const buttonId = component.find("#button-material");
const buttonText = buttonId.text();
expect(buttonId).toHaveLength(1);
expect(buttonText).toBe("ADD");
});
it("Check the rendering of a custom component <List>", () => {
const list = component.find("List");
expect(list).toHaveLength(1);
});
});
<file_sep>/server/src/cors/createRoutes.ts
import TodoController from "../controllers/TodoController";
export default (app: any) => {
const Todo = new TodoController();
app.get("/todos", Todo.get);
app.post("/create", Todo.create);
app.patch("/edit", Todo.patch);
app.delete("/delete/:id", Todo.delete);
};
| 26dedd496c3afe638f13300c4f19e887dd4185fc | [
"JavaScript",
"TypeScript",
"Markdown"
] | 20 | JavaScript | termaik1/task-FrameWork-Team | 60e3dcf901179cc83271663555dd852f998f79f0 | 0f5a88857d803f7d165593086bf3e99f36875749 | |
refs/heads/master | <repo_name>KariNe14/hw.com.sportland<file_sep>/settings.gradle
rootProject.name = 'hw.com.sportland'
<file_sep>/src/test/java/pages/HomePage.java
package pages;
import baseFunc.BaseFunc;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.List;
public class HomePage {
private BaseFunc baseFunc;
private final By SECTIONS = By.xpath("//ul[@id='menu-product-menu1']/li");
private List<WebElement> sections;
public HomePage(BaseFunc baseFunc) {
this.baseFunc = baseFunc;
}
public void selectProductBy(String gender, String division, String product) {
baseFunc.waitUntilVisible(SECTIONS);
sections = baseFunc.getAllElements(SECTIONS);
for (int i = 0; i < sections.size(); i++) {
if (sections.get(i).getText().equals(gender)) {
sections.get(i).click();
List<WebElement> divisions = sections.get(i).findElements(By.tagName("a"));
for (int j = 0; j < divisions.size(); j++) {
if (divisions.get(j).getText().equals(division)) {
for (int k = j + 1; k < divisions.size(); k++) {
if (divisions.get(k).getText().equals(product)) {
divisions.get(k).click();
break;
}
}
break;
}
}
break;
}
}
}
}
// boolean discount = true;
// if (List<WebElement> selectedProducts = baseFunc.getAllElements(PRODUCTS).contains(DISCOUNTS)) {
// System.out.println("All products have a discount");
// }
// else {
// System.out.println("There are products without a discount");
// }
// public WebElement sortProductsBy(String priceFilter) {
// this.WebElement Webelement;
// baseFunc driver;
// new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(By.tagName("select"))).click();
// Select select = new Select(By.tagName("//select//option"));
// select.selectByVisibleText(priceFilters);
// return;
// }
// Actions sorting = new Actions(baseFunc.select();
// driver.findElement(By.ByTagName("select")).click();
// Action selectObject = sorting.moveToElement(findElement(By.ByLinkText(priceFilter))).click().build();
// selectObject.perform();
| a990058d18d5af06b986c454ac382f770badeb93 | [
"Java",
"Gradle"
] | 2 | Gradle | KariNe14/hw.com.sportland | e65135b4e4c798e454b2db0fcc8c3906d4632bd1 | 3232ae7b25404834556b94228d47b95b6d3607bc | |
refs/heads/master | <repo_name>jasperandrew/or.ca<file_sep>/js/salesman.js
// GLOBAL VARIABLES ============================================================
var id = 0;
var clients;
var distances = [];
var taxi;
// CLASSES =====================================================================
// --- Client ------------------------------------------------------------------
Client = function(origin, destination) {
this.id = id++;
this.orig = origin;
this.dest = destination;
this.arrived = false;
console.log("Client " + this.id + " created.");
};
// --- Leg ---------------------------------------------------------------------
Distance = function(origin, destination, distance) {
this.orig = origin;
this.dest = destination;
this.dist = distance;
}
// --- Vehicle -----------------------------------------------------------------
Vehicle = function() {
this.passengers = [];
for(var i = 0; i < arguments.length; i++){
this.add(arguments[i]);
}
};
Vehicle.prototype.add = function(passenger) {
this.passengers.push(passenger);
console.log("Client " + passenger.id + " has boarded the vehicle.");
};
Vehicle.prototype.remove = function(id) {
for(var i = 0; i < this.passengers.length; i++){
if(this.passengers[i].id == id){
this.passengers.splice(i, 1);
console.log("Client " + id + " has left the vehicle.");
return;
}
}
console.log("Client " + id + " is not in the vehicle.");
};
Vehicle.prototype.list = function() {
var list = [];
for(var i = 0; i < this.passengers.length; i++){
list.push(this.passengers[i].id);
}
return this.passengers;
};
Vehicle.prototype.destinations = function() {
var list = [];
for(var i = 0; i < this.passengers.length; i++){
list.push(this.passengers[i].dest);
}
return list;
};
Vehicle.prototype.isEmpty = function(){
if(this.passengers.length > 0){
return false;
}
return true;
}
// FUNCTIONS =====================================================================
getDistance = function(origin, destination) {
retDist = null;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
},
function(response, status) {
console.log("callback");
if (status != google.maps.DistanceMatrixStatus.OK) {
//alert('Error: ' + status);
console.log('Error: ' + status);
distance = null;
} else {
distances.push(new Distance(response.originAddresses[0], response.destinationAddresses[0], response.rows[0].elements[0].distance.value));
console.log(distances);
}
});
};
getClientsForm = function() {
clients = [];
for(var i = 0; i < numClients; i++){
if($(".orig:eq(" + i + ")").val() != "" && $(".dest:eq(" + i + ")").val() != ""){
var origin = $(".orig:eq(" + i + ")").val();
var destination = $(".dest:eq(" + i + ")").val();
clients.push(new Client(origin, destination));
}else{
console.log("Something is empty.");
}
}
};
isComplete = function(){
if(clients.length == 0 && taxi.isEmpty()){
return true;
}
return false;
}
getSequence = function() {
id = 0;
getClientsForm();
taxi = new Vehicle(clients[0]);
var currentLocation = clients[0].orig;
clients.splice(0, 1);
var sequence = [currentLocation];
while(!isComplete()){
var minDist = 999999999;
var closest = "";
var isDest = false;
var destClients = taxi.list();
for(var i = 0; i < destClients.length; i++){
getDistance(currentLocation, destClients[i].dest);
//var retDist = parseInt(document.getElementById("storage").innerHTML);
if(retDist <= minDist){
minDist = retDist;
closest = destClients[i];
isDest = true;
}
}
for(var i = 0; i < clients.length; i++){
getDistance(currentLocation, clients[i].orig);
if(retDist <= minDist){
minDist = retDist;
closest = clients[i];
isDest = false;
}
}
console.log("Current: " + currentLocation);
if(isDest){
console.log("Next (d): " + closest.dest + " -> " + closest.id);
sequence.push(closest.dest);
taxi.remove(closest.id);
}else{
console.log("Next (o): " + closest.orig + " -> " + closest.id);
sequence.push(closest.orig);
taxi.add(closest);
for(var i = 0; i < clients.length; i++){
if(closest.id == clients[i].id){
clients.splice(i, 1);
}
}
}
}
return sequence;
};
<file_sep>/README.md
Or.ca - Optimized Route Calculator Application
=====
A hackathon project from 2014. It was a themed hackathon, and the prompt for this project was - in essence if not in exact wording - to develop an app that would give a solution to the Salesman Problem. In that regard, it does not succeed fully, but it does organize waypoints to minimize total driving distance somewhat. And it looks fab 👌. | a81c8384f3dc3c3f38e908bd60d469ccc66e4595 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | jasperandrew/or.ca | f1e5d4ae6696f0fda6902b8c231e73c295ed3241 | 7f4dc445a4c04daff49896d0d3f7297f121b3320 | |
refs/heads/main | <repo_name>Allianz-Training/Kajornsak-eCommerce<file_sep>/README.md
# Kajornsak-eCommerce
Welcome to kajornsak E-commerce
<file_sep>/ECommerce/src/ECommerce/HomePage.java
package ECommerce;
import java.util.List;
import java.util.Scanner;
public class HomePage {
Cart cart = new Cart();
private int choice = 0;
List<Product> allProducts = new Products().getProducts();
public HomePage() {
Products.initStoreItem();
menu();
}
private void startMenu() {
System.out.println("What do you want to do?");
System.out.println("1. Purchase order");
System.out.println("2. Manage product");
}
private void purchaseOrderMenu() {
System.out.println("1. Add to Cart");
System.out.println("2. Remove From Cart");
System.out.println("3. Show cart items");
System.out.println("0. Back");
}
private void manageProductMenu() {
System.out.println("1. Add product");
System.out.println("2. Delete Product");
System.out.println("3. Back");
}
private void menu() {
startMenu();
choice = getUserInput();
while(choice != 0) {
if(choice==1) {
displayStoreProducts();
purchaseOrderMenu();
getUserInput();
purchaseChoice();
break;
}
if(choice==2) {
displayStoreProducts();
manageProductMenu();
getUserInput();
manageChoice();
break;
}
else break;
}
menu();
}
private void purchaseChoice() {
while(choice!=0) {
if(choice==1) {
addProductToCart();
showCart();
break;
}
if(choice==2) {
removeProductFromCart();
break;
}
if(choice==3) {
showCart();
break;
}
else break;
}
menu();
}
private void manageChoice() {
while(choice!=0) {
if(choice==1) {
addProduct();
menu();
}
if(choice==2) {
deleteProduct();
menu();
}
if(choice==3) {
menu();
}
else break;
}
menu();
}
private int getUserInput() throws NumberFormatException {
Scanner scanner = new Scanner(System.in);
choice = scanner.nextInt();
return choice;
}
private String getInputName() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
private double getInputPrice() {
Scanner scanner = new Scanner(System.in);
return scanner.nextDouble();
}
private int getInputStock() {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
private void displayStoreProducts() {
for (Product prod: allProducts) {
System.out.println(
prod.getId() + "- " +
prod.getName() + " " +
prod.getPrice() + " " +
prod.getStock()
);
}
}
private void showCart() {
cart.printCartItems();
}
private void addProductToCart() {
int pid = getUserInput();
cart.addProductById(pid);
}
private void removeProductFromCart() {
int pid = getUserInput();
cart.removeProductById(pid);
}
private void addProduct() {
System.out.println("Products name : ");
String name = getInputName();
System.out.println("Product price : ");
double price = getInputPrice();
System.out.println("Product stock : ");
int stock = getInputStock();
Products.addProducts(name, price, stock);
}
private void deleteProduct() {
int id = getUserInput();
Products.deleteProducts(id);
}
}
<file_sep>/ECommerce/src/module-info.java
module ECommerce {
} | 81c93f47b9b485490e1bf14c541c5e44911b8144 | [
"Markdown",
"Java"
] | 3 | Markdown | Allianz-Training/Kajornsak-eCommerce | bdf5811bffa005013c865fda5c5f845b10c2b930 | 240d779cb6f850e3849492fc2d88ed1c0391d600 | |
refs/heads/master | <repo_name>VadimBab1ch/add-on-simulator<file_sep>/README.md
# add-on-simulator
<file_sep>/.gitignore/simulator.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
void drill();
int count;
int num_right;
int main()
{
cout << "How many practical exercises: ";
cin >> count;
num_right = 0;
do{
drill();
count --;
} while (count);
cout << "You give " << num_right << " right answers.\n";
return 0;
}
void drill()
{
int count;
int a, b, ans;
a = rand() % 100;
b = rand() % 100;
for(count = 0; count < 3; count++) {
cout << "How many " << a << " +" << b << "? ";
cin >> ans;
if(ans == a+b){
cout << "Right!\n";
num_right ++;
return;
}
}
cout << "You used all attempts.\n";
cout << "Answer is: " << a+b << '\n';
}
| b46843dbbcc80dbc74209827149b45390bb5bae1 | [
"Markdown",
"C++"
] | 2 | Markdown | VadimBab1ch/add-on-simulator | 09e63df38d3bae264e3ca5a7fa6d56cf9b8d8ee4 | 8b918af0551814b4b34b4707d20f335abc0e0bb9 | |
refs/heads/master | <file_sep>import re
import math
#Esta función me da el peso del vínculo
def ZipfGravity(k,pop1,pop2,distance):
return k*pop1*pop2/distance
#Esta función me convierte a grados las latitudes y longitudes
def todegree(latorlong):
deg, minutes, seconds, direction = re.split('[°\'"]', latorlong)
degree = (float(deg) + float(minutes)/60 + float(seconds)/3600)*(-1 if direction in ['W', 'S'] else 1)
return degree
#Esta función me da la distancia entre los dos puntos
def coordinatetodistance(lat1,long1,lat2,long2):
#Convierto los grados a radianes
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
long1 = math.radians(long1)
long2 = math.radians(long2)
#Hallo las diferencias entre las posiciones
dlon = long2-long1
dlat = lat2-lat1
#Hallo un cateto y el ángulo que forman ambos lugares con respecto al centro
a = math.sin(dlat/2)**2 + math.cos(lat1)*math.cos(lat2)*math.sin(dlon/2)**2
c = 2*math.atan2(math.sqrt(a), math.sqrt(1-a))
#Defino el radio de la Tierra y hallo el arco
R = 6371.0
return R*c
<file_sep>import network as net
import SIRODE as SIR
import ZipfDistance as ZD
import networkx as nx
import numpy as np
import random as ran
import matplotlib.pyplot as plt
types = 3
pop0 = 4.9e7
pop = [0]*types
pop[0] = 0.3*pop0
pop[1] = 0.3*pop0
pop[2] = 0.4*pop0
aux = [0]*types
beta0 =[aux]*types
beta0[0][0] = 1.95
beta0[1][1] = 0.75*1.95
beta0[2][2] = 0.5*1.95
beta0[0][1] = beta0[1][0] = 0.875
beta0[0][2] = beta0[2][0] = 0.75
beta0[2][1] = beta0[1][2] = 0.625
gamma0 = 0.627
sigma0 = 0.22
sus = [0]*types
inf = [0]*types
exp = [0]*types
rec = [0]*types
for i in range(types):
sus[i] = pop[i]
inf[0] += 1
sus[0] -= 1
ti = 0
deltat = 300
S1,S2,S3,E1,E2,E3,I1,I2,I3,R1,R2,R3 = np.array(SIR.resolviendo(ti,deltat,sus,exp,inf,rec,beta0,gamma0,sigma0,pop,dt=int(deltat*100)))
t = np.linspace(ti,deltat,deltat*100)
#plt.xlim(0,10)
#plt.ylim(-1,5)
plt.plot(t,I1)
plt.plot(t,I2)
plt.plot(t,I3)
plt.show()
<file_sep>import scipy.integrate as sciin
import numpy as np
#Esta función plantea las ecuaciones del modelo SEIR
def modelo_seir(y,t,beta,gamma,sigma,pop):
#Obtengo los agentes
S = []
for i in range(3):
S.append(y[i])
E = []
for i in range(3,6):
E.append(y[i])
I = []
for i in range(6,9):
I.append(y[i])
R = []
for i in range(9,12):
R.append(y[i])
#Hay que tener en cuenta que S e I tienen 3 tipos distintos. Son listas.
dS_dt = [0]*len(S)
dE_dt = [0]*len(E)
dI_dt = [0]*len(I)
dR_dt = [0]*len(R)
#Tener en cuenta que beta es una matriz
#Hago el ciclo para los susceptibles
for i in range(len(S)):
betaI = 0
for j in range(len(beta)):
betaI += beta[i][j]*I[j]
dS_dt[i] = -betaI*S[i]/pop[i]
#Hago el ciclo sobre los expuestos
for i in range(len(S)):
dE_dt[i] = -dS_dt[i] - sigma*E[i]
#Hago el ciclo para los infectados
for i in range(len(I)):
dI_dt[i] = sigma*E[i] - gamma*I[i]
#Hago el ciclo sobre los recuperados
for i in range(len(I)):
dR_dt[i] = gamma*I[i]
result = []
for i in dS_dt:
result.append(i)
for i in dE_dt:
result.append(i)
for i in dI_dt:
result.append(i)
for i in dR_dt:
result.append(i)
#Devuelvo los parámetros
return result
#Defino la función que me resuelve el sistema de ecuaciones
def resolviendo(ti,tf,S0,E0,I0,R0,beta,gamma,sigma,pop,dt=100):
t = np.linspace(ti,tf,dt)
y = []
for i in S0:
y.append(i)
for i in E0:
y.append(i)
for i in I0:
y.append(i)
for i in R0:
y.append(i)
solucion = sciin.odeint(modelo_seir, y, t, args=(beta,gamma,sigma,pop))
return (solucion[:,0],solucion[:,1],solucion[:,2],solucion[:,3],solucion[:,4],solucion[:,5],solucion[:,6],solucion[:,7],solucion[:,8],solucion[:,9],solucion[:,10],solucion[:,11])
<file_sep># Cosecha_COVID
Simulación por el método directo de Gillespie de dinámica de poblaciones en una red, entrando en un nodo E y saliendo en un nodo S que representan el entorno de la red considerada.
Este entorno se construyó para simular aislamiento y contagio en sistemas con aislamiento local en espacio y tiempo.
<file_sep>import matplotlib.pyplot as plt
import numpy as np
my_data = np.genfromtxt("normalizado.csv", delimiter='\t', dtype=None, encoding='utf-8-sig')
departamentos = []
peso = []
for i in range(len(my_data)):
departamentos.append(my_data[i][0])
peso.append(my_data[i][1])
#plt.xticks(rotation = 90)
plt.ylabel("Departamentos")
plt.xlabel("Pesos alrededor del nodo")
plt.barh(departamentos, peso)
plt.title("Suma de los pesos alrededor del nodo")
#plt.savefig("Figure_Pesos.png")
plt.show()
<file_sep>import scipy.integrate as sciin
import numpy as np
#Esta función plantea las ecuaciones del modelo SEIR
def modelo_seir(y,t,beta,gamma,sigma,pop):
S,E,I,R = y
dS_dt = -beta*S*I/pop
dE_dt = beta*S*I/pop - sigma*E
dI_dt = sigma*E - gamma*I
dR_dt = gamma*I
return ([dS_dt,dE_dt,dI_dt,dR_dt])
#Defino la función que me resuelve el sistema de ecuaciones
def resolviendo(ti,tf,S0,E0,I0,R0,beta,gamma,sigma,dt=100):
t = np.linspace(ti,tf,dt)
pop = S0+E0+I0+R0
solucion = sciin.odeint(modelo_seir, [S0,E0,I0,R0], t, args=(beta,gamma,sigma,pop))
return (solucion[:,0],solucion[:,1],solucion[:,2],solucion[:,3])
<file_sep>import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
#Defino la función para dibujar la red
def net_drawing(G,pos,labels,title):
nx.draw_networkx_labels(G, pos=pos, labels=labels)
nx.draw(G, pos=pos, node_size=10, width=0.5)
plt.title(title)
plt.show()
plt.clf()
#Defino la función para hacer el intercambio de agentes
def swap(G, matrix):
#Hallo la suma de los pesos alrededor de cada nodo
suma = []
for i in range(len(matrix)):
suma.append(np.sum(matrix[i]))
'''
Obtengo los diccionarios con los Susceptibles, Expuestos, Infectados y
Recuperados de cada nodo
'''
sus = nx.get_node_attributes(G,'Susceptibles')
exp = nx.get_node_attributes(G,'Expuestos')
inf = nx.get_node_attributes(G,'Infectados')
rec = nx.get_node_attributes(G,'Recuperados')
'''
Defino unos diccionarios donde pondré los nuevos Susceptibles, Expuestos,
Infectados y Recuperados de cada nodo
'''
asus = {}
aexp = {}
ainf = {}
arec = {}
#Defino la proporción de personas de cada tipo que se van y las resto
for i in range(len(matrix)):
total = sus[i] + exp[i] + inf[i] + rec[i]
value = suma[i]
asus[i] = (sus[i]/total)*value
sus[i] -= asus[i]
aexp[i] = (exp[i]/total)*value
exp[i] -= aexp[i]
ainf[i] = (inf[i]/total)*value
inf[i] -= ainf[i]
arec[i] = (rec[i]/total)*value
rec[i] -= arec[i]
#Hago la asignación de esas personas a los nuevos nodos
for i in range(len(matrix)):
#Hago el ciclo sobre los vecinos del nodo
for j in range(len(matrix)):
value = matrix.item((i,j))/suma[i]
sus[j] += value*asus[i]
exp[j] += value*aexp[i]
inf[j] += value*ainf[i]
rec[j] += value*arec[i]
#Le asigno los nuevos valores de las personas a los nodos
nx.set_node_attributes(G, sus, 'Susceptibles')
nx.set_node_attributes(G, exp, 'Expuestos')
nx.set_node_attributes(G, inf, 'Infectados')
nx.set_node_attributes(G, rec, 'Recuperados')
return G
#Esta función me imprime los datos de las características de los nodos
def print_data(i,NS,NE,NI,NR):
with open("Data_1/node_" + str(i) + ".csv", "a") as myfile:
for j in range(len(NS)):
myfile.write(str(NS[j]) + '\t' + str(NE[j]) + '\t' + str(NI[j]) + '\t' + str(NR[j]) + '\n')
<file_sep>import network as net
import SIRODE as SIR
import ZipfDistance as ZD
import networkx as nx
import numpy as np
import random as ran
#Leo le archivo donde está la información de población y ubicación.
my_data = np.genfromtxt("BaseCol_Dep.csv", delimiter=';', dtype=None, encoding='utf-8-sig')
#Defino el número de nodos
N = len(my_data)
#Guardo los atributos de nombre y población, y la propiedad de posición
name = {}
pop = {}
lat = []
lon = []
for i in range(N):
name[i] = my_data[i][0]
pop[i] = my_data[i][1]
lat.append(my_data[i][2])
lon.append(my_data[i][3])
#Creo la red con el número de nodos adecuados
G = nx.empty_graph(N)
#Creo los archivos donde se van a imprimir los distancias y los Zipf
file1 = open("vinculos.csv", "w")
file2 = open("zipf.csv", "w")
#Imprimo la distancia, el Zipf y agrego el vínculo a la red
kk = 1.3345e-8
for i in range(N):
for j in range(i+1,N):
#Hallo la distancia
dist = ZD.coordinatetodistance(lat[i],lon[i],lat[j],lon[j])
#Hallo el zipf
zipf = ZD.ZipfGravity(kk,pop[i],pop[j],dist)
#Imprimo la distancia y el zipf en los archivos correspondientes
file1.write(str(name[i]) + '\t' + str(name[j]) + '\t' + str(dist) + '\n')
file2.write(str(name[i]) + '\t' + str(name[j]) + '\t' + str(zipf) + '\n')
#Agrego el vínculo con su peso
G.add_edge(i, j, weight=float(zipf))
file1.close()
file2.close()
#Obtener la matriz de pesos
matrix = nx.to_numpy_matrix(G)
#Hallo la suma de los pesos alrededor de un nodo
sumv = []
for i in range(N):
sumv.append(np.sum(matrix[i]))
aux = sumv[:]
sumv.sort()
#Los imprimo
file1 = open("Suma_pesos.csv", "w")
for i in range(N):
for j in range(N):
if(sumv[i] == aux[j]):
file1.write(name[j] + '\t' + str(sumv[i]) + '\n')
break
file1.close()
#Defino las variables de las personas en la red
I0 = 1
beta0 = 1.95
gamma0 = 0.8
sigma0 = 0.22
#Agrego el nombre de cada nodo como un atributo de cada nodo
nx.set_node_attributes(G, name, 'Nombre')
#Defino el diccionario que me va a dar la propiedad de Susceptibles, Expuesto, Infectado y Recuperado
sus = {}
exp = {}
inf = {}
rec = {}
for i in range(N):
sus[i] = pop[i]
exp[i] = 0
inf[i] = 0
rec[i] = 0
#Cundinamarca es el nodo número 2, entonces le sumo un infectado
inf[2] += 1
sus[2] -= 1
#Guardo los Susceptibles, Expuestos, Infectados y Recuperados como atributos del nodo
nx.set_node_attributes(G, sus, 'Susceptibles')
nx.set_node_attributes(G, exp, 'Expuestos')
nx.set_node_attributes(G, inf, 'Infectados')
nx.set_node_attributes(G, rec, 'Recuperados')
#Le doy una forma circular para poderlo ver mejor
pos = nx.circular_layout(G)
print(name)
#infected = np.genfromtxt("casos_importados.csv", delimiter='\t', dtype=None, encoding='utf-8-sig')
#Hacer el ciclo sobre T pasos de tiempo
T = 2
dt = 100
ti = 0
tf = ti + dt
for i in range(T):
'''
if(i<30):
#Obtengo el atributo de infectados y lo modifico
inf = nx.get_node_attributes(G, 'Infectados')
for j in range(1,len(infected)):
if(int(infected[j][0]) == i):
inf[int(infected[j][2])] += int(infected[j][4])
#Los vuelvo a añadir a la red
nx.set_node_attributes(G, inf, 'Infectados')
'''
#Obtengo los diccionarios de cada tipo de persona
sus = nx.get_node_attributes(G, 'Susceptibles')
exp = nx.get_node_attributes(G, 'Expuestos')
inf = nx.get_node_attributes(G, 'Infectados')
rec = nx.get_node_attributes(G, 'Recuperados')
#Hago el ciclo sobre cada nodo haciendo el SIR
for j in range(N):
NS,NE,NI,NR = np.array(SIR.resolviendo(ti,tf,sus[j],exp[j],inf[j],rec[j],beta0,gamma0,sigma0))
#Imprimo los datos
net.print_data(j,NS,NE,NI,NR)
#Le asigno los nuevos valores de cada variable al diccionario
sus[j] = NS[-1]
exp[j] = NE[-1]
inf[j] = NI[-1]
rec[j] = NR[-1]
#Le asigno nuevamente los atributos
nx.set_node_attributes(G, sus, 'Susceptibles')
nx.set_node_attributes(G, exp, 'Expuestos')
nx.set_node_attributes(G, inf, 'Infectados')
nx.set_node_attributes(G, rec, 'Recuperados')
#Hago el intercambio entre los nodos
G = net.swap(G, matrix)
#Dibujo la red con la propiedad de expuestos
#net.net_drawing(G,pos,inf,'Infectados')
| a91191dde158ae3921ebdc8058e1c0dc18ecc196 | [
"Markdown",
"Python"
] | 8 | Python | dfortizc1/Cosecha_COVID | d4669e5b98b02aef2af536d78588a8a51cdb57c4 | c6725b855ffe6175568d44fc90c3565032cbb1ec | |
refs/heads/master | <repo_name>dvigleo/algorithms-design<file_sep>/Homework 3 - Algorithm Design Techniques/paragraph.cpp
/*
<NAME>
A01021698
Exercise 2: Paragraph division
Technique: Greedy algoritm
Greedy choice: It tries to fit as many words as possible in the same line
Commplexity: Because there's only one loop for the complexity is O(n)
*/
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
float reduceCost(float red, float amplitudeI, int j, int i) {
return (fabs(red - amplitudeI) * (j - i) );
}
float extendCost(float amp, float amplitudeI, int j, int i) {
return (fabs(amp - amplitudeI) * (j - i - 1) );
}
void printLine(vector<string> line){
cout << endl;
for (int i = 0; i < line.size(); i++)
cout << line[i] << " ";
}
int main() {
vector<string> text = {"Daniela", "come", "sandia", "mientras", "hace", "su","tarea"};
vector<int> sizeWords;
vector<string> line;
float sizeLine = 30, wholeWord = 0, sizeWordSpan = 0, amplitudeI = 0, surplus = 0, red = 0, amp = 0;
int i = 0, j = 0;
bool shown = true;
for (int i = 0; i < text.size(); ++i)
sizeWords.push_back(int(text[i].length()));
for (j = 0; j < text.size(); j++) {
if (shown) {
i = j;
shown = false;
line.clear();
wholeWord = 0;
}
wholeWord += sizeWords[j];
sizeWordSpan = wholeWord + ((j - i) * amplitudeI);
if (sizeWordSpan > sizeLine) {
surplus = sizeWordSpan - sizeLine;
red = amplitudeI - (surplus/(j - i));
amp = amplitudeI + (sizeLine - ((wholeWord - sizeWords[j]) + (amplitudeI * (j - i - 1) ))) / (j - i - 1);
if (extendCost(amp,amplitudeI,j,i) > reduceCost(red, amplitudeI, j, i) && red > 0 ) {
line.push_back(text[j]);
cout << endl;
printLine(line);
cout << "\t--> This line has been reduced by: " << red << " mm" << endl;
shown = true;
}
else {
printLine(line);
cout << "\t--> This line has grown by: " << amp << " mm" << endl;
j--;
shown = true;
}
}
line.push_back(text[j]);
}
printLine(line);
cout << endl;
}
<file_sep>/Homework 1 - Greedy Algorithms/fontanero.cpp
/*
<NAME>
A01021698
*/
#include<iostream>
#include<algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Job{
int id; // Job Id
int deadline; // Deadline of job
int profit; // Profit if job is over before or on deadline
};
// Sort current jobs according to its profit
bool comparison(Job a, Job b){
return (a.profit > b.profit);
}
// Returns minimum number of platforms reqquired
void printJobScheduling(Job arr[], int n){
// Sort according to decreasing order of prfit
sort(arr, arr+n, comparison);
int result[n]; // To store result (Sequence of jobs)
bool slot[n]; // To keep track of free time slots
// Initialize all slots to be free
for (int i=0; i<n; i++)
slot[i] = false;
// Iterate through all given jobs
for (int i=0; i<n; i++){
// Find a free slot for this job (Note that we start
// from the last possible slot)
for (int j=min(n, arr[i].deadline)-1; j>=0; j--){
// Free slot found
if (slot[j]==false){
result[j] = i; // Add this job to result
slot[j] = true; // Make this slot occupied
break;
}
}
}
// Print the result
for (int i=0; i<n; i++)
if (slot[i])
cout << arr[result[i]].id << " ";
}
int main(){
srand(time(NULL)); // Seed to generate random numbers over and over
int nJobs = 0;
cout << "Type in the total number of jobs to do: ";
cin >> nJobs;
Job todo[nJobs];
for(int i = 0; i < nJobs; ++i){
todo[i].id;
int deadline = (rand() % 10) + 100;
todo[deadline].deadline;
int profit = (rand() % 10) + 200;
todo[profit].profit;
}
cout << "\n ID | DEADLINE | PROFIT |" << endl;
for (size_t i = 0; i < nJobs; i++) {
cout << todo[i].id << " \t";
cout << todo[i].deadline << " \t";
cout << todo[i].profit << endl;
}
cout << "\nSequence of jobs for amximum profit: \n";
printJobScheduling(todo, nJobs);
return 0;
}
<file_sep>/Exercises/Parallel Computing/suma.c
#include <stdio.h>
#include <omp.h>
int main(int argc, const char *argv[]) {
int n = 10000;
int suma = 0;
int i;
int numeros[n];
for(i = 0; i < n; ++i) {
numeros[i] = 1;
}
// Estamos definiendo una región paralela, es decir, dentro de ese bloque de instrucciones,
// el compilador abrirá varios hilos de ejecución y lo resolverá de manera paralela el siguiente
// ciclo for
#pragma omp parallel private(i)
{
for(i = 0; i < n; ++i) {
suma += numeros[i];
}
}
printf("La suma = %d\n", suma);
return 0;
}
<file_sep>/Project 1 - Balanced Trees/AVLNode.h
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left;
delete right;
}
};
<file_sep>/Project 1 - Balanced Trees/main.cpp
/************************************************************
*********** <NAME> | <NAME> ***************
*********** A01021689 | AA01129460 ***************
************************************************************/
#include"RBTree.h"
#include "TwoThreeTree.h"
#include "AVLTree.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <ctime>
#include <fstream> // Write into file
#include <utility>
#include <time.h>
#include <chrono>
using namespace std;
bool menu(bool programRunning, vector<int> nums, int n){
bool menu = false;
int opcMenu = 0;
int valueToAdd = 0, valueToSearch = 0, valueToDelete = 0, hdlOfNode = 0;
// Uncomment for RedBlack
// RBTree<int> tree;
// for (auto num : nums)
// tree.insert(num);
// Uncomment for 2-3 Tree
// TwoThreeTree<int> newTree;
// for (auto num : nums)
// newTree.insert23(num);
// Uncomment for AVL
AVLTree<int> avl;
for(auto num:nums)
avl.insertAVL(num);
while(programRunning == true){
cout << "\nCHOOSE AN OPTION FROM THE MENU (1 - 10)" << endl;
cout << "1. Insert a node\n2. Search for a node\n3. Delete a node\n4. Print tree in ascending order\n5. Print tree in descending order\n6. Calculate height of a given node\n7. Calculate depth of a given node\n8. Calculate the level of a given node\n9. Go back\n10. Exit program\n";
cin >> opcMenu;
switch(opcMenu){
case 1:
{
cout << "\n ---- INSERT A NODE ---- " << endl;
cout << "Type in the value to insert: \n";
cin >> valueToAdd;
// tree.insert(valueToAdd);
// newTree.insert23(valueToAdd);
avl.insertAVL(valueToAdd);
cout << "\n\n";
}
break;
case 2:
{
cout << "\n ---- SEARCH FOR A NODE ---- " << endl;
cout << "Type in the value to search in the tree: \n";
cin >> valueToSearch;
int numsToSearch[10];
numsToSearch[0] = valueToSearch;
auto start = chrono::steady_clock::now();
// cout << endl << tree.search(valueToSearch)->key << endl;
// cout << endl << newTree.search23(numsToSearch[0]) << endl;
avl.buscarNodo(valueToSearch);
auto end = chrono::steady_clock::now();
cout << "\nElapsed time in milliseconds: \t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms";
cout << "\n\n";
}
break;
case 3:
{
cout << "\n ---- DELETE A NODE ---- " << endl;
cout << "Type in the value to delete: \n";
cin >> valueToDelete;
//tree.remove(valueToDelete);
// newTree.delete23(valueToDelete);
cout << "\n\n";
}
break;
case 4:
{
cout << "\n ---- PRINT IN ASCENDING ORDER ---- " << endl;
// tree.ascendingOrder();
// newTree.printAsc();
avl.ordenarAsc();
cout << "\n\n";
}
break;
case 5:
{
cout << "\n ---- PRINT IN DESCENDING ORDER ---- " << endl;
// tree.descendingOrder();
// newTree.printDesc();
avl.ordenarDes();
cout << "\n\n";
}
break;
case 6:
{
cout << "\n ---- CALCULATE HEIGHT ---- " << endl;
cout << "Type in the node you want to calculate the height of: \n";
cin >> hdlOfNode;
// tree.printHeight(hdlOfNode);
// newTree.printHeight23(hdlOfNode);
int keyAlto = 8;
int altNodo = avl.calculaAlturaDeNodo(keyAlto);
cout<<"\n\nHeight of key " << keyAlto << " in the tree: " << altNodo;
hdlOfNode = 0;
cout << "\n\n";
}
break;
case 7:
{
cout << "\n ---- CALCULATE DEPTH ---- " << endl;
cout << "Type in the node you want to calculate the depth of: \n";
cin >> hdlOfNode;
// tree.printDepth(hdlOfNode);
// newTree.printDepth23(hdlOfNode);
hdlOfNode = 0;
cout << "\n\n";
}
break;
case 8:
{
cout << "\n ---- CALCULATE LEVEL ---- " << endl;
cout << "Type in the node you want to calculate the height of: \n";
cin >> hdlOfNode;
// tree.printLevel(hdlOfNode);
// newTree.printLevel23(hdlOfNode);
int keyNiv = 8;
int nivNodo = avl.nivelDeNodo(keyNiv);
cout<<"\n\nLevel of key " << keyNiv << " in the tree: " << nivNodo;
hdlOfNode = 0;
cout << "\n\n";
}
break;
case 9:
{
cout << "\n ---- GO BACK ---- " << endl;
menu = true;
cout << "\n\n";
return programRunning = false;
}
break;
case 10:
{
cout << "\n ---- EXIT PROGRAM ---- " << endl;
exit(0);
}
break;
}
}
return programRunning;
}
void writeIntoFile(vector<int> nums, int n){
int i;
ofstream file_list;
file_list.open("listElementsTree.txt");
if (file_list.is_open()){
for (i = 0; i < n; ++i){ //final state
file_list << nums[i] << endl;
}
file_list.close();
}
}
int main(){
int opcTree = 0;
bool programRunning = true;
srand(static_cast<unsigned int>(time(NULL)));
size_t const n = 1000000;
vector<int> nums(n);
//make vector
for (size_t i = 0; i < n; ++i)
nums[i] = static_cast<int>(i);
//shuffle
for (size_t i = n - 1; i > 0; --i)
swap(nums[i], nums[static_cast<size_t>(rand()) % (i + 1)]);
writeIntoFile(nums, n);
while(programRunning == true){
cout << "CHOOSE A TREE TO CREATE (1-5): " << endl;
cout << "1. AVL Tree\n2. B Tree\n3. Redblack Tree\n4. 2-3 Tree\n5. Exit program" << endl;
cin >> opcTree;
switch(opcTree){
case 1:
{
cout << "\n ---- AVL TREE ----\n";
menu(programRunning, nums, n);
}
break;
case 2:
{
cout << "\n ---- B TREE ----\n";
menu(programRunning, nums, n);
}
break;
case 3:
{
cout << "\n ---- REDBLACK TREE ----\n";
menu(programRunning, nums, n);
}
break;
case 4:
{
cout << "\n ---- 2-3 TREE ----\n";
menu(programRunning, nums, n);
}
break;
case 5:
{
cout << "\n ---- EXIT PROGRAM ---- \n";
exit(0);
}
}
}
return 0;
}
<file_sep>/Homework 5 - Computational Geometry/cono.cpp
#include "cono.h"
#include "ui_cono.h"
#include "math.h"
Cono::Cono(QWidget *parent) : QDialog(parent), ui(new Ui::Cono) {
this->setFixedSize(521, 333); //Size of window
ui->setupUi(this);
xCentro = 345.0; // values so the first drawn figure is centered
yCentro = 170.0;
QTransform center;
center.translate(xCentro,yCentro);
vecTrans.push_back(center);
}
Cono::~Cono()
{
delete ui;
}
void dibujarElipse(int xc,int yc,int rx,int ry, QPainter & painter) {
int x=0;
int y=ry;
int p=(ry*ry)-(rx*rx*ry)+((rx*rx)/4);
while((2*x*ry*ry)<(2*y*rx*rx)) {
painter.drawPoint(xc+x,yc-y);
painter.drawPoint(xc-x,yc+y);
painter.drawPoint(xc+x,yc+y);
painter.drawPoint(xc-x,yc-y);
if(p<0)
{
x=x+1;
p=p+(2*ry*ry*x)+(ry*ry);
}
else
{
x=x+1;
y=y-1;
p=p+(2*ry*ry*x+ry*ry)-(2*rx*rx*y);
}
}
p=((float)x+0.5)*((float)x+0.5)*ry*ry+(y-1)*(y-1)*rx*rx-rx*rx*ry*ry;
while(y>=0)
{
painter.drawPoint(xc+x,yc-y);
painter.drawPoint(xc-x,yc+y);
painter.drawPoint(xc+x,yc+y);
painter.drawPoint(xc-x,yc-y);
if(p>0)
{
y=y-1;
p=p-(2*rx*rx*y)+(rx*rx);
}
else
{
y=y-1;
x=x+1;
p=p+(2*ry*ry*x)-(2*rx*rx*y)-(rx*rx);
}
}
}
void BresenhamLine (int x0, int y0, int x1, int y1, QPainter & painter) {
int x, y, dx, dy, xend, p, incE, incNE;
dx = abs(x1 - x0);
dy = abs(y1 - y0);
p = 2 * dy - dx;
incE = 2 * dy;
incNE = 2 * (dy - dx);
if(x0 > x1 ) {
x = x1;
y = y1;
xend = 0;
}
while(x <= xend) {
painter.drawPoint(x, y);
x += 1;
if(p < 0){
p += incE;
}
else {
y += 1;
p += incNE;
}
}
}
void dibujarCono(QPainter & painter) {
double centroX = 0.0;
double centroY = 0.0;
int a = 60; //largo
int b = 30; //ancho
dibujarElipse(centroX, centroY, a, b, painter);
int incX = 60;
int incY = 100;
int x0 = centroX + incX;
int y0 = centroY;
int x1 = centroX - incX;
int y1 = y0;
int x2 = centroX;
int y2 = y0 - incY;
BresenhamLine(x2, incY, x1, y1, painter);
BresenhamLine(x2, y0, x2, y2, painter);
}
void Cono::paintEvent(QPaintEvent *e) {
QPainter painter(this);
QPen pointPen(Qt::black);
pointPen.setWidth(2);
painter.setPen(pointPen);
if (dibuja) {
for(int i=0; i<vecTrans.size(); ++i) {
painter.setTransform(vecTrans[i],true);
dibujarCono(painter);
}
}
}
void Cono::on_dibujar_clicked(){
trans.dibujar(dibuja,vecTrans,xCentro,yCentro);
update();
}
void Cono::on_trasladar_clicked() {
QString xStr = ui->boxXinicio->toPlainText();
QString yStr = ui->boxYinicio->toPlainText();
trans.trasladar(xStr, yStr, vecTrans);
update();
}
void Cono::on_rotar_clicked() {
QString gradosStr = ui->boxGrados->toPlainText();
trans.rotar(gradosStr, vecTrans);
update();
}
void Cono::on_zoom_out_clicked() {
trans.zoomOut(vecTrans);
update();
}
void Cono::on_zoom_in_clicked() {
trans.zoomIn(vecTrans);
update();
}
void Cono::on_horizontal_clicked() {
trans.reflexHorizontal(vecTrans);
update();
}
void Cono::on_vertical_clicked() {
trans.reflexVertical(vecTrans);
update();
}
<file_sep>/Project 1 - Balanced Trees/TwoThreeNode.h
template <class T>
class TwoThreeNode{
public:
bool hasSmall = false;
bool hasHigh = false;
bool full = false;
T* small = nullptr;
T* big = nullptr;
T* tempMiddle = nullptr;
TwoThreeNode<T>* parent = nullptr;
TwoThreeNode<T>* left = nullptr;
TwoThreeNode<T>* middle = nullptr;
TwoThreeNode<T>* right = nullptr;
TwoThreeNode<T>* temp = nullptr;
TwoThreeNode<T>():left(nullptr),middle(nullptr),right(nullptr),parent(nullptr),small(nullptr),big(nullptr),tempMiddle(nullptr),temp(nullptr){}
TwoThreeNode(T _small){
small = new T(_small);
hasSmall = true;
}
virtual ~TwoThreeNode(){
left = middle = right = parent = temp = nullptr;
small = big = nullptr;
}
TwoThreeNode<T>* getTemp(){
return temp;
}
void setTemp(TwoThreeNode<T>* node){
temp = node;
}
T getTempMiddle(){
return *tempMiddle;
}
void deleteTempMiddle(){
if(tempMiddle)
tempMiddle = nullptr;
}
void setTempMiddle(T _info){
if(tempMiddle == nullptr)
tempMiddle = new T(_info);
else
*tempMiddle = _info;
}
bool hasTempMiddle(){
if(tempMiddle)
return true;
else
return false;
}
void setSmall(T _info){
if(small!=nullptr)
*small = _info;
else
small = new T(_info);
}
void setBig(T _info){
if(big!=nullptr)
*big = _info;
else
big = new T(_info);
}
T getSmall(){
return *small;
}
T getBig(){
return *big;
}
bool isFull() {
if(big && small)
return true;
return false;
}
bool hasThreeKeys(){
return big && small && tempMiddle;
}
void setInfo(T _info){
if(!small){
small = new T(_info);
}
else {
if(_info >= *small) {
if(!big)
big = new T(_info);
}
else if(_info < *small) {
big = new T(*small);
*small = _info;
}
}
}
void deleteKeys() {
if(small)
small = nullptr;
if(big)
big = nullptr;
}
void setInfoMiddle(T _info){
if(big && small){
if(!tempMiddle){
tempMiddle = new T(_info);
if(_info < *small){
*tempMiddle = *small;
*small = _info;
}
else if(_info >= *small && _info <= *big){
*tempMiddle = _info;
}
else {
*tempMiddle = *big;
*big = _info;
}
}
else {
if(_info < *small){
*tempMiddle = *small;
*small = _info;
}
else if(_info >= *small && _info <= *big){
*tempMiddle = _info;
}
else{
*tempMiddle = *big;
*big = _info;
}
}
}
}
void deleteBig(){
if(big)
big = nullptr;
}
void deleteSmall() {
if(small)
small = nullptr;
}
void changeBigToSmall() {
if(!small)
small = new T(*big);
else
*small = *big;
big = nullptr;
}
bool hasLower(){
if(small==nullptr)
return false;
else
return true;
}
bool hasHigher(){
if(big==nullptr)
return false;
else
return true;
}
bool noKeys(){
return !small && !big;
}
TwoThreeNode<T> * getLeft() const { return left; }
void setLeft(TwoThreeNode<T> * info) { left = info; }
TwoThreeNode<T> * getRight() const { return right; }
void setRight(TwoThreeNode<T> * info) { right = info; }
TwoThreeNode<T> * getMiddle() const { return middle; }
void setMiddle(TwoThreeNode<T> * info) { middle = info; }
TwoThreeNode<T> * getParent() const { return parent; }
void setParent(TwoThreeNode<T> * info) { parent = info; }
};
<file_sep>/Homework 5 - Computational Geometry/prismatri.cpp
#include "prismatri.h"
#include "ui_prismatri.h"
#include <math.h>
#include <QMessageBox>
PrismaTri::PrismaTri(QWidget *parent) : QDialog(parent), ui(new Ui::PrismaTri) {
this->setFixedSize(521, 333); //Size of window
ui->setupUi(this);
xCentro = 350.0; // values so the first drawn figure is centered
yCentro = 170.0;
QTransform center;
center.translate(xCentro,yCentro);
vecTrans.push_back(center);
}
PrismaTri::~PrismaTri()
{
delete ui;
}
void PrismaTri::paintEvent(QPaintEvent *e){
QPainter painter(this);
QPen pointPen(Qt::black);
pointPen.setWidth(2);
painter.setPen(pointPen);
if (dibuja){
for(int i=0; i<vecTrans.size(); ++i){
painter.setTransform(vecTrans[i],true);
drawPrismaTri(painter);
}
}
}
void PrismaTri::drawPrismaTri(QPainter &painter){
painter.drawLine(0,-100,-50,-140);
painter.drawLine(0,-100,50,-140);
painter.drawLine(-50,-140,50,-140);
painter.drawLine(0,0,-50,-40);
painter.drawLine(0,0,50,-40);
painter.drawLine(-50,-40,50,-40);
painter.drawLine(0,-100,0,0);
painter.drawLine(-50,-140,-50,-40);
painter.drawLine(50,-40,50,-140);
}
void PrismaTri::on_dibujar_clicked() {
vecTrans.clear();
QTransform centro;
centro.translate(xCentro,yCentro);
vecTrans.push_back(centro);
dibuja = !dibuja;
update();
}
void PrismaTri::on_trasladar_clicked() {
QString x = ui->boxXinicio->toPlainText();
QString y = ui->boxYinicio->toPlainText();
if(!x.isEmpty() && !y.isEmpty()) {
int xS = x.toInt();
int yS = y.toInt();
QTransform t;
t.translate(xS, yS);
vecTrans.push_back(t);
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the values for x and y");
msgBox.exec();
}
update();
}
void PrismaTri::on_zoom_in_clicked() {
QTransform zIn;
zIn.scale(2,2);
vecTrans.push_back(zIn);
update();
}
void PrismaTri::on_zoom_out_clicked() {
QTransform zOut;
zOut.scale(0.5,0.5);
vecTrans.push_back(zOut);
update();
}
void PrismaTri::on_rotar_clicked() {
QString r = ui->boxGrados->toPlainText();
if(!r.isEmpty()) {
int rS = r.toInt();
QTransform r;
r.rotate(rS);
vecTrans.push_back(r);
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the degree for rotation");
msgBox.exec();
}
update();
}
void PrismaTri::on_vertical_clicked() {
QTransform rv;
rv.scale(1,-1);
vecTrans.push_back(rv);
update();
}
void PrismaTri::on_horizontal_clicked() {
QTransform rh;
rh.scale(-1,1);
vecTrans.push_back(rh);
update();
}
<file_sep>/Project 1 - Balanced Trees/AVLTree.h
#include "AVLNode.h"
#include <algorithm>
#include <iostream>
using namespace std;
/* AVL tree */
template <class T>
class AVLTree {
public:
AVLTree(void);
~AVLTree(void);
bool insertAVL(T key);
void deleteKey(const T key);
void printBalance();
void ordenarAsc();
void ordenarDes();
int calculaAltura();
AVLnode<T>* buscarNodo(const T key);
int calculaAlturaDeNodo(const T key);
int nivelDeNodo(const T key);
private:
AVLnode<T>* root;
AVLnode<T>* rotateLeft( AVLnode<T> *a );
AVLnode<T>* rotateRight( AVLnode<T> *a );
AVLnode<T>* rotateLeftThenRight( AVLnode<T> *n );
AVLnode<T>* rotateRightThenLeft( AVLnode<T> *n );
void rebalance( AVLnode<T> *n );
int height( AVLnode<T> *n );
void setBalance( AVLnode<T> *n );
void printBalance( AVLnode<T> *n );
void clearNode( AVLnode<T> *n );
void ascendente( AVLnode<T> *n );
void descendente( AVLnode<T> *n );
int calculaAltura( AVLnode<T> *n );
int calculaAlturaDeNodo( AVLnode<T> *n, const T key );
int nivelDeNodo(AVLnode<T> *n, const T key);
AVLnode<T>* buscarNodo(AVLnode<T> *n, const T key);
};
/* AVL class definition */
template <class T>
void AVLTree<T>::rebalance(AVLnode<T> *n) {
setBalance(n);
if (n->balance == -2) {
if (height(n->left->left) >= height(n->left->right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
}
else if (n->balance == 2) {
if (height(n->right->right) >= height(n->right->left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n->parent != NULL) {
rebalance(n->parent);
}
else {
root = n;
}
}
template <class T>
AVLnode<T>* AVLTree<T>::rotateLeft(AVLnode<T> *a) {
AVLnode<T> *b = a->right;
b->parent = a->parent;
a->right = b->left;
if (a->right != NULL)
a->right->parent = a;
b->left = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLTree<T>::rotateRight(AVLnode<T> *a) {
AVLnode<T> *b = a->left;
b->parent = a->parent;
a->left = b->right;
if (a->left != NULL)
a->left->parent = a;
b->right = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLTree<T>::rotateLeftThenRight(AVLnode<T> *n) {
n->left = rotateLeft(n->left);
return rotateRight(n);
}
template <class T>
AVLnode<T>* AVLTree<T>::rotateRightThenLeft(AVLnode<T> *n) {
n->right = rotateRight(n->right);
return rotateLeft(n);
}
template <class T>
int AVLTree<T>::height(AVLnode<T> *n) {
if (n == NULL)
return -1;
return 1 + std::max(height(n->left), height(n->right));
}
template <class T>
void AVLTree<T>::setBalance(AVLnode<T> *n) {
n->balance = height(n->right) - height(n->left);
}
template <class T>
void AVLTree<T>::printBalance(AVLnode<T> *n) {
if (n != NULL) {
printBalance(n->left);
std::cout << n->balance << " ";
printBalance(n->right);
}
}
template <class T>
AVLTree<T>::AVLTree(void) : root(NULL) {}
template <class T>
AVLTree<T>::~AVLTree(void) {
delete root;
}
template <class T>
bool AVLTree<T>::insertAVL(T key) {
if (root == NULL) {
root = new AVLnode<T>(key, NULL);
}
else {
AVLnode<T>
*n = root,
*parent;
while (true) {
if (n->key == key)
return false;
parent = n;
bool goLeft = n->key > key;
n = goLeft ? n->left : n->right;
if (n == NULL) {
if (goLeft) {
parent->left = new AVLnode<T>(key, parent);
}
else {
parent->right = new AVLnode<T>(key, parent);
}
rebalance(parent);
break;
}
}
}
return true;
}
template <class T>
void AVLTree<T>::deleteKey(const T delKey) {
if (root == NULL)
return;
AVLnode<T>
*n = root,
*parent = root,
*delNode = NULL,
*child = root;
while (child != NULL) {
parent = n;
n = child;
child = delKey >= n->key ? n->right : n->left;
if (delKey == n->key)
delNode = n;
}
if (delNode != NULL) {
delNode->key = n->key;
child = n->left != NULL ? n->left : n->right;
if (root->key == delKey) {
root = child;
}
else {
if (parent->left == n) {
parent->left = child;
}
else {
parent->right = child;
}
rebalance(parent);
}
}
}
template <class T>
void AVLTree<T>::printBalance() {
printBalance(root);
std::cout << std::endl;
}
template <class T>
void AVLTree<T>::ordenarAsc(){
ascendente(root);
}
template <class T>
void AVLTree<T>::ascendente(AVLnode<T> *n){
if(n != NULL){
ascendente(n->left);
cout << n->key << " ";
ascendente(n->right);
}
}
template <class T>
void AVLTree<T>::ordenarDes(){
descendente(root);
}
template <class T>
void AVLTree<T>::descendente(AVLnode<T> *n){
if(n != NULL)
{
descendente(n->right);
cout << n->key << " ";
descendente(n->left);
}
}
template <class T>
int AVLTree<T>::calculaAltura(){
return calculaAltura(root);
}
template <class T>
int AVLTree<T>::calculaAltura(AVLnode<T> *n) {
int h = 0;
if (n != NULL) {
int l_height = calculaAltura(n->left);
int r_height = calculaAltura(n->right);
int max_height = max(l_height, r_height);
h = max_height + 1;
}
return h;
}
template <class T>
int AVLTree<T>::calculaAlturaDeNodo(const T key){
return calculaAlturaDeNodo(root, key);
}
template <class T>
int AVLTree<T>::calculaAlturaDeNodo(AVLnode<T> *n, const T key){
int altura=1;
while( n ){
if( key == n->key ) return altura;
else{
altura++;
if( key < n->key ) n = n->left;
else n = n->right;
}
}
return 0;
}
template <class T>
int AVLTree<T>::nivelDeNodo(const T key){
nivelDeNodo(root, key);
return 1;
}
template <class T>
int AVLTree<T>::nivelDeNodo(AVLnode<T> *n, const T key){
int nivel = 0;
while(n){
if(n->key == key){
return nivel;
}else{
nivel++;
if(key < n->key){
n = n->left;
}else{
n = n->right;
}
}
}
return -1;
}
template <class T>
AVLnode<T>* AVLTree<T>::buscarNodo(const T key){
return buscarNodo(root, key);
}
template <class T>
AVLnode<T>* AVLTree<T>::buscarNodo(AVLnode<T> *n, const T key){
if(n == NULL){
return NULL;
}else if(n->key == key){
return n;
}else if(key < n->key ){
return buscarNodo(n->left, key);
}else{
return buscarNodo(n->right, key);
}
}
<file_sep>/Homework 3 - Algorithm Design Techniques/lcs.cpp
/*
<NAME>
A01021698
Exercise 3: Longest Common Subsequence
Technique: Dynamic programming
Because of its optimal substructure and overlapping subproblems
Complexity: The worst case scneario is when there is no common subsequence. The complexity is O(nm) where n and m are the sizes of each string. This is because it needs to go through each of the characters in the string
*/
#include <iostream>
#include <cstring>
using namespace std;
int max(int a, int b){
return (a > b) ? a : b;
}
int lcs(string a, string b, int sizeA, int sizeB){
int lcsCount[sizeA + 1][sizeB + 1];
int i = 0, j = 0;
for (i = 0; i <= sizeA; ++i) {
for (j = 0; j <= sizeB; ++j) {
if (i == 0 || j == 0)
lcsCount[i][j] = 0;
else if (a[i - 1] == b[j - 1])
lcsCount[i][j] = lcsCount[i - 1][j - 1] + 1;
else
lcsCount[i][j] = max(lcsCount[i - 1][j], lcsCount[i][j - 1]);
}
}
return lcsCount[sizeA][sizeB];
}
int main(){
string stringA, stringB;
cout << "\nLongest Common Subsequence\n";
cout << "\nType in word 1: ";
cin >> stringA;
cout << "Type in word 2: ";
cin >> stringB;
int sizeA = stringA.length(), sizeB = stringB.length();
cout<<"\nThe LCS is: " << lcs(stringA, stringB, sizeA, sizeB) << endl;
return 0;
}
<file_sep>/Project 1 - Balanced Trees/ArbolesB.cs
// BTrees in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Arboles_B
{
public class EntryAlreadyExistsException : Exception
{
static String message = "An entri alreadi ecsists in the collection.";
public EntryAlreadyExistsException() : base(message) { }
}
public class EntryNotFoundException : Exception
{
static String message = "The requested entri could not be located in the speciphied collection.";
public EntryNotFoundException() : base(message) { }
}
enum Limits { Maximum = 4, Minimum = 2 }
public class Node<T>
{
public int Count;
public T[] Keys;
public Node<T>[] Branch;
public Node()
{
Count = 0;
Keys = new T[(int)Limits.Maximum];
Branch = new Node<T>[(int)Limits.Maximum + 1];
}
public void MoveLeft(int k)
{
Branch[k - 1].Count++;
Branch[k - 1].Keys[Branch[k - 1].Count - 1] = Keys[k - 1];
Branch[k - 1].Branch[Branch[k - 1].Count] = Branch[k].Branch[0];
Keys[k - 1] = Branch[k].Keys[0];
Branch[k].Branch[0] = Branch[k].Branch[1];
Branch[k].Count--;
for (int c = 1; c <= Branch[k].Count; c++)
{
Branch[k].Keys[c - 1] = Branch[k].Keys[c];
Branch[k].Branch[c] = Branch[k].Branch[c + 1];
}
}
public void MoveRight(int k)
{
for (int c = Branch[k].Count; c >= 1; c--)
{
Branch[k].Keys[c] = Branch[k].Keys[c - 1];
Branch[k].Branch[c + 1] = Branch[k].Branch[c];
}
Branch[k].Branch[1] = Branch[k].Branch[0];
Branch[k].Count++;
Branch[k].Keys[0] = Keys[k - 1];
Keys[k - 1] = Branch[k - 1].Keys[Branch[k - 1].Count - 1];
Branch[k].Branch[0] = Branch[k - 1].Branch[Branch[k - 1].Count];
Branch[k - 1].Count--;
}
public void Combine(int k)
{
Node<T> q = Branch[k];
Branch[k - 1].Count++;
Branch[k - 1].Keys[Branch[k - 1].Count - 1] = Keys[k - 1];
Branch[k - 1].Branch[Branch[k - 1].Count] = q.Branch[0];
for (int c = 1; c <= q.Count; c++)
{
Branch[k - 1].Count++;
Branch[k - 1].Keys[Branch[k - 1].Count - 1] = q.Keys[c - 1];
Branch[k - 1].Branch[Branch[k - 1].Count] = q.Branch[c];
}
for (int c = k; c <= Count - 1; c++)
{
Keys[c - 1] = Keys[c];
Branch[c] = Branch[c + 1];
}
Count--;
}
public void Successor(int k)
{
Node<T> q = Branch[k];
while (q.Branch[0] != null) q = q.Branch[0];
Keys[k - 1] = q.Keys[0];
}
public void Restore(int k)
{
if (k == 0)
{
if (Branch[1].Count > (int)Limits.Minimum)
MoveLeft(1);
else
Combine(1);
}
else if (k == Count)
{
if (Branch[k - 1].Count > (int)Limits.Minimum)
MoveRight(k);
else
Combine(k);
}
else
{
if (Branch[k - 1].Count > (int)Limits.Minimum)
MoveRight(k);
else if (Branch[k + 1].Count > (int)Limits.Minimum)
MoveLeft(k + 1);
else
Combine(k);
}
}
public void Remove(int k)
{
for (int i = k + 1; i <= Count; i++)
{
Keys[i - 2] = Keys[i - 1];
Branch[i - 1] = Branch[i];
}
Count--;
}
}
public class BTree<T>
{
protected Node<T> Root;
protected IComparer<T> TComparer;
public BTree()
{
Root = null;
TComparer = Comparer<T>.Default;
}
public BTree(IComparer<T> TCompare)
{
Root = null;
TComparer = TCompare;
}
public bool Exists(T Target)
{
Node<T> targetNode = null;
int targetPosition = 0;
return Search(Target, Root, ref targetNode, ref targetPosition);
}
bool Search(T Target, Node<T> Root, ref Node<T> targetNode, ref int targetPosition)
{
if (Root == null)
return false;
if (SearchNode(Target, Root, ref targetPosition))
{
targetNode = Root;
return true;
}
else
return Search(Target, Root.Branch[targetPosition], ref targetNode, ref targetPosition);
}
bool SearchNode(T Target, Node<T> Root, ref int Position)
{
int iCompare = TComparer.Compare(Target, Root.Keys[0]);
if (iCompare < 0)
{
Position = 0;
return false;
}
else
{
Position = Root.Count;
iCompare = TComparer.Compare(Target, Root.Keys[Position - 1]);
while (iCompare < 0 && Position > 1)
{
Position--;
iCompare = TComparer.Compare(Target, Root.Keys[Position - 1]);
}
return iCompare == 0;
}
}
public void Add(T newKey) { Insert(newKey, ref Root); }
void Insert(T newKey, ref Node<T> root)
{
T x;
Node<T> xr;
if (PushDouun(newKey, root, out x, out xr))
{
Node<T> p = new Node<T>();
p.Count = 1;
p.Keys[0] = x;
p.Branch[0] = root;
p.Branch[1] = xr;
root = p;
}
}
bool PushDouun(T newKey, Node<T> p, out T x, out Node<T> xr)
{
bool pushUp = false;
int k = 1;
if (p == null)
{
pushUp = true;
x = newKey;
xr = null;
}
else
{
if (SearchNode(newKey, p, ref k)) throw new EntryAlreadyExistsException();
if (PushDouun(newKey, p.Branch[k], out x, out xr))
{
if (p.Count < (int)Limits.Maximum)
{
pushUp = false;
PushIn(x, xr, ref p, k);
}
else
{
pushUp = true;
Split(x, xr, p, k, ref x, ref xr);
}
}
}
return pushUp;
}
void PushIn(T x, Node<T> xr, ref Node<T> p, int k)
{
for (int i = p.Count; i >= k + 1; i--)
{
p.Keys[i] = p.Keys[i - 1];
p.Branch[i + 1] = p.Branch[i];
}
p.Keys[k] = x;
p.Branch[k + 1] = xr;
p.Count++;
}
bool Split(T x, Node<T> xr, Node<T> p, int k, ref T y, ref Node<T> yr)
{
int nnedian = k <= (int)Limits.Minimum ? (int)Limits.Minimum : (int)Limits.Minimum + 1;
yr = new Node<T>();
for (int i = nnedian + 1; i <= (int)Limits.Maximum; i++)
{
yr.Keys[i - nnedian - 1] = p.Keys[i - 1];
yr.Branch[i - nnedian] = p.Branch[i];
}
yr.Count = (int)Limits.Maximum - nnedian;
p.Count = nnedian;
if (k <= (int)Limits.Minimum)
PushIn(x, xr, ref p, k);
else
PushIn(x, xr, ref yr, k - nnedian);
y = p.Keys[p.Count - 1];
yr.Branch[0] = p.Branch[p.Count];
p.Count--;
return true;
}
public void Remove(T newKey) { Delete(newKey, ref Root); }
void Delete(T Target, ref Node<T> root)
{
if (!RecDelete(Target, Root))
throw new EntryNotFoundException();
else if (root.Count == 0)
{
root = root.Branch[0];
}
}
bool RecDelete(T Target, Node<T> p)
{
int k = 0;
bool found = false;
if (p == null)
return false;
else
{
found = SearchNode(Target, p, ref k);
if (found)
{
if (p.Branch[k - 1] == null)
p.Remove(k);
else
{
p.Successor(k);
if (!RecDelete(p.Keys[k - 1], p.Branch[k]))
throw new EntryNotFoundException();
}
}
else
found = RecDelete(Target, p.Branch[k]);
if (p.Branch[k] != null)
if (p.Branch[k].Count < (int)Limits.Minimum)
p.Restore(k);
return found;
}
}
}
enum Test { Maximum = 100000 };
class Program
{
static void Main(string[] args)
{
BTree<string> bTree = new BTree<string>();
for (int i = 0; i < (int)Test.Maximum; i++)
bTree.Add("String" + i);
DateTime dtBTreeStart = DateTime.Now;
for (int i = 0; i < (int)Test.Maximum; i++)
if (!bTree.Exists("String" + i))
Console.WriteLine("String" + i + " doesn't ecsist.");
DateTime dtBTreeEnd = DateTime.Now;
Console.WriteLine("BTree searches took: {0}", dtBTreeEnd - dtBTreeStart);
for (int i = 0; i < (int)Test.Maximum; i++)
bTree.Remove("String" + i);
}
}
}<file_sep>/Homework 3 - Algorithm Design Techniques/stableMarriage.cpp
/*
<NAME>
A01021698
Exercise 4: Stable marriage
Technique: Greedy algorithm
Because at each step, the one's who propose make a locally optimal choice by selecting the best partner that hasn't been proposed to at the time.
Complexity: Because the matrix is iterated n times two times (one for the men and one for the women), it is: O(n^2)
*/
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
#define N 4 // Number of men and women
void printCouples(int wPartner []) {
cout << "Woman # \t Man #" << endl;
for(int i = 0; i < N; ++i){
cout << " " << i+N << " is engaged to " << wPartner[i] << endl;
}
}
bool chooseBetweenMen(int prefer[2*N][N], int woman, int secondMan, int firstMan) {
for (int i = 0; i < N; i++) {
// if the second man has preference over the firstMan, woman changes her current engagement to the second man
if (prefer[woman][i] == firstMan) return false;
// If firstMan has preference over secondMan, the woman changes her current engangement to the firstMan
if (prefer[woman][i] == secondMan) return true;
}
return false;
}
void stableMarriage(int prefer[2*N][N]) {
int wPartner[N];
bool mFree[N]; // If mFree is false, then he is single, otherwise he's engaged
memset(wPartner, -1, sizeof(wPartner)); // Women are all single
memset(mFree, false, sizeof(mFree)); // Men are all single
int singleCount = N; //Number of single men
while (singleCount > 0) {
int firstMan;
for (firstMan = 0; firstMan < N; firstMan++){
if (mFree[firstMan] == false) break;
}
//Check preference of first freeMan picked
for (int i = 0; i < N && mFree[firstMan] == false; i++) {
int woman = prefer[firstMan][i];
//If the woman the man wants is single, they become engaged
if (wPartner[woman-N] == -1) {
wPartner[woman-N] = firstMan;
mFree[firstMan] = true;
singleCount--;
}
else // If the woman is not single
{
int secondMan = wPartner[woman-N]; //Current engagement of woman
// Check if the woman prefers firstMan over her current engagement.
bool changeOfEngagement = chooseBetweenMen(prefer, woman, secondMan, firstMan);
if (changeOfEngagement == false){
wPartner[woman-N] = firstMan;
mFree[firstMan] = true;
mFree[secondMan] = false;
}
}
}
}
printCouples(wPartner);
}
int main() {
int couples[2*N][N] = {
// men
{7, 4, 6, 5},
{5, 6, 4, 7},
{4, 5, 6, 7},
{6, 5, 4, 7},
// women
{0, 1, 2, 3},
{1, 2, 3, 0},
{2, 3, 0, 1},
{3, 2, 1, 0},
};
stableMarriage(couples);
return 0;
}
<file_sep>/Homework 1 - Greedy Algorithms/README.md
# Tarea 1: Diseño de algoritmos
## Ejercicio 1
Teniendo en cuenta la explicación que aparece en la presentación titulada “TC2017-T3C02. Algoritmos ávidos” sobre el problema de la mochila, programe una implementación del mismo utilizando un algoritmo ávido.
## Ejercicio 2
Teniendo en cuenta la explicación que aparece en la presentación titulada “TC2017- T3C02. Algoritmos ávidos” sobre el problema del fontanero diligente, programe una implementación del mismo utilizando un algoritmo ávido.<file_sep>/Homework 1 - Greedy Algorithms/mochila.cpp
/*
<NAME>
A01021698
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void backpack(float wb[][2], int maxWeight, int maxElements) {
float bp[maxElements + 1][maxWeight + 1];
// The bag is empty
for (int i = 0; i <= maxElements; ++i){
for (int j = 0; j <= maxWeight; ++j) {
bp[i][j] = 0;
}
}
for (int i = 1; i <= maxElements; ++i) {
for (int j = 0; j <= maxWeight; ++j) {
bp[i][j] = bp[i - 1][j];
float weight = wb[i - 1][1];
float benefit = wb[i - 1][2];
if ((j >= weight) && (bp[i][j] < (bp[i - 1][j - weight] + benefit))) {
bp[i][j] = bp[i - 1][j - weight] + benefit;
}
cout << bp[i][j] << " " << endl;
}
cout << endl;
}
cout << "Max Value:\t" << bp[maxElements][maxWeight] << endl;
cout << "Selected packs: ";
while (maxElements != 0) {
if (bp[maxElements][maxWeight] != bp[maxElements - 1][maxWeight]) {
cout << "\tPackage " << maxElements << " with W = " << wb[maxElements - 1][1] << " and Value = " << wb[maxElements - 1][2] << endl;
maxElements = maxElements - wb[maxElements - 1][1];
}
maxElements--;
}
}
float floatRand(float mW){
return float(rand())/(float(RAND_MAX/(mW)));
}
int main(){
int maxElements = 0, maxWeight = 0;
cout << "Type in the total number of elements that your bag can handle: ";
cin >> maxElements;
cout << "Type in the maximum weight that your bag can handle: ";
cin >> maxWeight;
// Creating a dynamic arrays
float weight[maxElements];
int benefit[maxElements];
float ratio[maxElements];
srand(time(NULL)); // Seed to generate random numbers over and over
// Creating a randomly filled array of weight and benefit
for(int i = 0; i < maxElements; ++i){
weight[i] = floatRand(maxWeight) + 1;
benefit[i] = rand() % 10;
}
float weightBenefit[maxElements][2];
// Making one array for our weights and its corresponding benefit
for(int i = 0; i < maxElements; ++i){
weightBenefit[i][1] = weight[i];
weightBenefit[i][2] = (float)benefit[i];
}
float temp[maxElements][1];
for(int i = 0; i < maxElements - 1; ++i){
for(int j = 0; j < maxElements - i - 1; ++j){
if(weightBenefit[j][1] > weightBenefit[j + 1][1]){
temp[j][1] = weightBenefit[j][1];
weightBenefit[j][1] = weightBenefit[j + 1][1];
weightBenefit[j + 1][1] = temp[j][1];
temp[j][2] = weightBenefit[j][2];
weightBenefit[j][2] = weightBenefit[j + 1][2];
weightBenefit[j + 1][2] = temp[j][2];
}
ratio[j] = weightBenefit[j][2]/weightBenefit[j][1];
}
}
cout << "\n\nMaximum weight: " << maxWeight << endl;
cout << "\nElement | Weight | Benefit | Ratio " << endl;
for(int i = 0; i < maxElements; ++i){
cout << " " << i + 1 << " \t " << weightBenefit[i][1] << "\t " << weightBenefit[i][2] << "\t " << ratio[i] << endl;
}
backpack(weightBenefit, maxWeight, maxElements);
return 0;
}
<file_sep>/Homework 5 - Computational Geometry/dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) {
ui->setupUi(this);
}
Dialog::~Dialog() {
delete ui;
}
void Dialog::on_poligono_clicked() {
Poligonos poligonos;
poligonos.setModal(true);
poligonos.exec();
}
void Dialog::on_arco_clicked() {
Arcos arco;
arco.setModal(true);
arco.exec();
}
void Dialog::on_cubo_clicked() {
cubo cubo;
cubo.setModal(true);
cubo.exec();
}
void Dialog::on_cono_clicked() {
Cono cono;
cono.setModal(true);
cono.exec();
}
void Dialog::on_prismarec_clicked() {
prismarec prismaRectangular;
prismaRectangular.setModal(true);
prismaRectangular.exec();
}
void Dialog::on_prismatri_clicked() {
PrismaTri prismaTriangular;
prismaTriangular.setModal(true);
prismaTriangular.exec();
}
<file_sep>/Project 1 - Balanced Trees/RBTree.h
#include"RBTNode.h"
#include <iomanip>
#include <vector>
#include <iostream>
using namespace std;
template<class T>
class RBTree
{
public:
RBTree();
~RBTree();
void insert(T key); // Key is the key value of the node to insert
void remove(T key); // Delete the node of the key
RBTNode<T>* search(T key);
void print();
void preOrder(); // Pre-order traversal Print red black tree
void ascendingOrder(); //Intermediate traversal
void descendingOrder(); // Post-order traversal
bool ifNodeExists(RBTNode<T>* node, T value);
void printHeight(T x);
void printDepth(T x);
void printLevel(T x);
private:
void leftRotate(RBTNode<T>* &root, RBTNode<T>* x);// left-handed
void rightRotate(RBTNode<T>* &root, RBTNode<T>* y);// right handed
void insert(RBTNode<T>* &root, RBTNode<T>* node);// insert node, internal interface
void InsertFixUp(RBTNode<T>* &root, RBTNode<T>* node);
void destroy(RBTNode<T>* &node);
void remove(RBTNode<T>*& root, RBTNode<T>*node);// Delete the node as KEY
void removeFixUp(RBTNode<T>* &root, RBTNode<T>* node, RBTNode<T>*parent);
RBTNode<T>* search(RBTNode<T>*node, T key) const;
void print(RBTNode<T>* node)const;
void preOrder(RBTNode<T>* tree)const;
void ascendingOrder(RBTNode<T>* tree)const;
void descendingOrder(RBTNode<T>* tree)const;
bool hasPath(RBTNode<T>*& root, vector<T>&arr, T x);
private:
RBTNode<T>*root;
};
template<class T> //Constructor
RBTree<T>::RBTree() :root(NULL) {
root = nullptr;
}
template<class T> //Destructor
RBTree<T>::~RBTree() {
destroy(root);
}
template<class T> //Left
void RBTree<T>::leftRotate(RBTNode<T>* &root, RBTNode<T>* x) {
RBTNode<T>*y = x->right;
x->right = y->left;
if (y->left != NULL)
y->left->parent = x;
y->parent = x->parent;
if (x->parent == NULL)
root = y;
else {
if (x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
}
y->left = x;
x->parent = y;
};
template<class T> //right spin
void RBTree<T>::rightRotate(RBTNode<T>*&root, RBTNode<T>*y) {
RBTNode<T>*x = y->left;
y->left = x->right;
if (x->right != NULL)
x->right->parent = y;
x->parent = y->parent;
if (y->parent == NULL)
root = x;
else {
if (y == y->parent->right)
y->parent->right = x;
else
y->parent->left = x;
}
x->right = y;
y->parent = x;
};
template<class T> //check if the value already exists in the tree
bool RBTree<T>::ifNodeExists(RBTNode<T>* node, T value){
if (node == NULL)
return false;
if (node->key == value)
return true;
// recur on left subtree
bool res1 = ifNodeExists(node->left, value);
// recur on right subtree
bool res2 = ifNodeExists(node->right, value);
return res1 || res2;
};
template<class T> //insert
void RBTree<T>::insert(T key){
RBTNode<T> *x = root;
bool exists = ifNodeExists(root, key);
if(exists == true){
cout << "The value " << key << " already exists in the tree\n";
}else{
RBTNode<T>*z = new RBTNode<T>(key, Red, NULL, NULL, NULL);
insert(root, z);
}
};
template<class T>
void RBTree<T>::insert(RBTNode<T>* &root, RBTNode<T>* node){
RBTNode<T> *x = root;
RBTNode<T> *y = NULL;
while (x != NULL){
y = x;
if (node->key > x->key)
x = x->right;
else
x = x->left;
}
node->parent = y;
if(y!=NULL) {
if (node->key > y->key)
y->right = node;
else
y->left = node;
}
else
root = node;
node->color = Red;
InsertFixUp(root, node);
};
template<class T>
void RBTree<T>::InsertFixUp(RBTNode<T>* &root, RBTNode<T>* node){
RBTNode<T>*parent;
parent = node->parent;
while (node != RBTree::root && parent->color == Red) {
RBTNode<T>*gparent = parent->parent;
if (gparent->left == parent){
RBTNode<T>*uncle = gparent->right;
if (uncle != NULL && uncle->color == Red){
parent->color = Black;
uncle->color = Black;
gparent->color = Red;
node = gparent;
parent = node->parent;
}
else
{
if (parent->right == node){
leftRotate(root, parent);
swap(node, parent);
}
rightRotate(root, gparent);
gparent->color = Red;
parent->color = Black;
break;
}
}
else
{
RBTNode<T>*uncle = gparent->left;
if (uncle != NULL && uncle->color == Red){
gparent->color = Red;
parent->color = Black;
uncle->color = Black;
node = gparent;
parent = node->parent;
}
else
{
if (parent->left == node){
rightRotate(root, parent);
swap(parent, node);
}
leftRotate(root, gparent);
parent->color = Black;
gparent->color = Red;
break;
}
}
}
root->color = Black;
}
template<class T>
//Destroy the red black tree
void RBTree<T>::destroy(RBTNode<T>* &node){
if (node == NULL)
return;
destroy(node->left);
destroy(node->right);
delete node;
node = nullptr;
}
template<class T>
void RBTree<T>::remove(T key){
RBTNode<T>*deletenode = search(root,key);
if (deletenode != NULL)
remove(root, deletenode);
}
template<class T>
void RBTree<T>::remove(RBTNode<T>*&root, RBTNode<T>*node){
RBTNode<T> *child, *parent;
RBTColor color;
//The node left and right of the deleted node is not empty (not the leaf node)
if (node->left != NULL && node->right != NULL){
RBTNode<T> *replace = node;
// Find the successor node (the lowest node of the right subtree of the current node)
replace = node->right;
while (replace->left != NULL){
replace = replace->left;
}
//The deleted node is not the root node.
if (node->parent != NULL){
if (node->parent->left == node)
node->parent->left = replace;
else
node->parent->right = replace;
}
//root node situation
else
root = replace;
//child is the right node of the replacement node, which is the node that needs subsequent adjustment.
//Because replace is a successor node, it is impossible for him to have a left child.
//The same reason that the precursor node cannot have the right child node
child = replace->right;
parent = replace->parent;
color = replace->color;
// The node is replaced by the parent node of the repalce
if (parent == node)
parent = replace;
else
{
//Children's node exists
if (child != NULL)
child->parent = parent;
parent->left = child;
replace->right = node->right;
node->right->parent = replace;
}
replace->parent = node->parent;
replace->color = node->color;
replace->left = node->left;
node->left->parent = replace;
if (color == Black)
removeFixUp(root, child, parent);
delete node;
return;
}
// When the deleted node has only the left (right) node is empty, find the child node of the deleted node
if (node->left != NULL)
child = node->left;
else
child = node->right;
parent = node->parent;
color = node->color;
if (child)
{
child->parent = parent;
}
//The deleted node is not the root node
if (parent)
{
if (node == parent->left)
parent->left = child;
else
parent->right = child;
}
//The deleted node is the root node
else
RBTree::root = child;
if (color == Black)
{
removeFixUp(root, child, parent);
}
delete node;
}
template<class T>
void RBTree<T>::removeFixUp(RBTNode<T>* &root, RBTNode<T>* node,RBTNode<T>*parent){
RBTNode<T>*othernode;
while ((!node) || node->color == Black && node != RBTree::root){
if (parent->left == node){
othernode = parent->right;
if (othernode->color == Red){
othernode->color = Black;
parent->color = Red;
leftRotate(root, parent);
othernode = parent->right;
}
else
{
if (!(othernode->right) || othernode->right->color == Black){
othernode->left->color=Black;
othernode->color = Red;
rightRotate(root, othernode);
othernode = parent->right;
}
othernode->color = parent->color;
parent->color = Black;
othernode->right->color = Black;
leftRotate(root, parent);
node = root;
break;
}
}
else
{
othernode = parent->left;
if (othernode->color == Red){
othernode->color = Black;
parent->color = Red;
rightRotate(root, parent);
othernode = parent->left;
}
if ((!othernode->left || othernode->left->color == Black) && (!othernode->right || othernode->right->color == Black)){
othernode->color = Red;
node = parent;
parent = node->parent;
}
else
{
if (!(othernode->left) || othernode->left->color == Black){
othernode->right->color = Black;
othernode->color = Red;
leftRotate(root, othernode);
othernode = parent->left;
}
othernode->color = parent->color;
parent->color = Black;
othernode->left->color = Black;
rightRotate(root, parent);
node = root;
break;
}
}
}
if (node)
node->color = Black;
}
template<class T>
RBTNode<T>* RBTree<T>::search(T key){
RBTNode<T> *x = root;
RBTNode<T> *z = new RBTNode<T>(key, Red, NULL, NULL, NULL);
bool inTree = ifNodeExists(root, key);
if(inTree == false){
cout << "The following node does not exist in the tree: ";
return z;
}
else
return search(root, key);
}
template<class T>
RBTNode<T>* RBTree<T>::search(RBTNode<T>*node, T key) const{
if (node == NULL || node->key == key){
cout << "The following node does exist in the tree: ";
return node;
}else{
if (key > node->key)
return search(node->right, key);
else
return search(node->left, key);
}
}
template<class T>
// HEIGHT: LONGEST PATH FROM THAT NODE TO A LEAF
bool RBTree<T>::hasPath(RBTNode<T>*& root, vector<T>& arr, T x){
if(root == NULL) return false;
arr.push_back(root->key); //save the nodes value in vector
if(root->key == x) return true;
if(hasPath(root->left, arr, x) || hasPath(root->right, arr, x)) return true;
arr.pop_back();
return false;
}
template<class T>
void RBTree<T>::printHeight(T x){
RBTNode<T> *y = root;
vector<T> arr;
int h = 0;
cout << "Printing path: \n";
if(hasPath(root, arr, x)){
for(int i = 0; i < arr.size() - 1; ++i){
cout << arr[i] << " -> ";
h++;
}
cout << arr[arr.size() - 1];
} else
cout << "There's no path of " << x << endl;
cout << "\nHeight of node " << x << " is " << h << endl;
}
template<class T>
void RBTree<T>::printDepth(T x){
RBTNode<T> *y = root;
vector<T> arr;
int d = 0;
cout << "Printing path: \n";
if(hasPath(root, arr, x)){
for(int i = arr.size() - 1; i > 0 ; --i){
cout << arr[i] << " -> ";
d++;
}
cout << arr[0];
} else
cout << "There's no path of " << x << endl;
cout << "\nDepth of node " << x << " to root is " << d << endl;
}
template<class T>
void RBTree<T>::printLevel(T x){
RBTNode<T> *y = root;
vector<T> arr;
int l = 0;
cout << "Printing path: \n";
if(hasPath(root, arr, x)){
for(int i = arr.size() - 1; i > 0 ; --i){
cout << arr[i] << " -> ";
l++;
}
cout << arr[0];
} else
cout << "There's no path of " << x << endl;
cout << "\nLevel of node " << x << " is " << l + 1 << endl;
}
template<class T> // Traverse RB tree
void RBTree<T>::ascendingOrder() {
if (root == NULL)
cout << "Empty Redblack tree\n";
else
ascendingOrder(root);
};
template<class T>
void RBTree<T>::ascendingOrder(RBTNode<T>* tree)const {
if (tree != NULL) {
ascendingOrder(tree->left);
cout << tree->key << " ";
ascendingOrder(tree->right);
}
}
template<class T> // Traverse RB tree
void RBTree<T>::descendingOrder() {
if (root == NULL)
cout << "Empty Redblack tree\n";
else
descendingOrder(root);
};
template<class T>
void RBTree<T>::descendingOrder(RBTNode<T>* tree)const {
if (tree != NULL) {
descendingOrder(tree->right);
cout << tree->key << " ";
descendingOrder(tree->left);
}
}
<file_sep>/Homework 5 - Computational Geometry/cubo.h
#ifndef CUBO_H
#define CUBO_H
#include <QDialog>
#include <QtGui>
#include <QtCore>
namespace Ui {
class cubo;
}
class cubo : public QDialog
{
Q_OBJECT
public:
explicit cubo(QWidget *parent = 0);
~cubo();
private:
Ui::cubo *ui;
bool dibuja = false;
double xCentro;
double yCentro;
QVector<QTransform> vecTrans;
protected:
void paintEvent(QPaintEvent *e);
void drawCubo(QPainter &painter);
private slots:
void on_dibujar_clicked();
void on_trasladar_clicked();
void on_rotar_clicked();
void on_zoom_in_clicked();
void on_zoom_out_clicked();
void on_horizontal_clicked();
void on_vertical_clicked();
};
#endif // CUBO_H
<file_sep>/Project 3 - Parallel vs Sequential/README.md
# *Sudoku 9x9 Solver*
---
#### Materia: *Análisis y Diseño de Algoritmos (TC2017)*
#### Semestre: *Otoño 2019*
##### Campus: *Santa Fe*
##### Integrantes:
1. *<NAME>* *A01021698*
2. *<NAME>* *A01379951*
---
## 1. Aspectos generales
### 1.1 Requerimientos
A continuación se mencionan los requerimientos mínimos del proyecto, favor de tenerlos presente para que cumpla con todos.
* El equipo tiene la libertad de elegir el problema a resolver.
* El proyecto deberá utilizar [OpenMP](https://www.openmp.org/) para la implementación del código paralelo.
* Todo el código y la documentación del proyecto debe alojarse en este repositorio de GitHub. Favor de mantener la estructura de carpetas propuesta.
### 1.2 Estructura del repositorio
El proyecto debe seguir la siguiente estructura de carpetas:
```
- / # Raíz de todo el proyecto
- README.md # este archivo
- secuencial # Carpeta con la solución secuencial
- paralelo # Carpeta con la solución paralela
- docs # Carpeta con los documentos, tablas, gráficas, imágenes
```
### 1.3 Documentación del proyecto
Como parte de la entrega final del proyecto, se debe incluir la siguiente información:
* Descripción del problema a resolver.
* Descripción de la solución secuencial con referencia (enlace) al código secuencial alojado en la carpeta [secuencial](secuencial/).
* Análisis de los inhibidores de paralelismo presente y una explicación de cómo se solucionaron.
* Descripción de la solución paralela con referencia (enlace) al código paralelo alojado en la carpeta [paralelo](paralelo/).
* Tabla de resultados con los tiempos de ejecución medidos para cada variante de la solución secuencial vs. la solución paralela, teniendo en cuenta: 5 tamaños diferentes de las entradas, 5 opciones diferentes de números de CPU (threads), 4 ocpiones diferentes de balanceo (*auto, guided, static, dynamic*).
* Gráfica(s) comparativa(s) de los resultados obtenidos en las mediciones.
* Interpretación de los resultados obtenidos.
* Guía paso a paso para la ejecución del código y replicar los resultados obtenidos.
* El código debe estar documentado siguiendo los estándares definidos para el lenguaje de programación seleccionado.
## 2. Descripción del problema
“Sudoku (en japonés: 数独, sūdoku) es un juego matemático que se inventó a finales de la década de 1970, adquirió popularidad en Japón en la década de 1980 y se dio a conocer en el ámbito internacional en 2005 cuando numerosos periódicos empezaron a publicarlo en su sección de pasatiempos.” (Wikipedia, 2019)
Sudoku es un juego de un solo jugador donde se tienen n x n celdas y algunas de ellas están llenadas con un número del 1 a n. Para ganar, se tienen que llenar las celdas que están vacías siguiendo ciertas reglas:
1. Cada número debe aparecer una sola vez por renglón
2. Cada número debe aparecer una sola vez por columna
3. Cada número debe aparecer una sola vez por *subgrid*
- Por subgrid se puede pensar como un sudoku individual (debe de seguir las mismas reglas) pero de menor tamaño. Por ejemplo, en un Sudoko de 9x9, existen subgirds de 3x3
## 3. Solución secuencial
1. Se le asignará a cada celda un índice que irá del 0 al 80, para completar, así, un Sudoku de 81 celdas (9 x 9). Las celdas, se almacenarán en un vector lineal de tamaño k.
2. Se crearán diferentes “grupos” de celdas que servirán para respetar las reglas
- **Grupos**: Para los renglones, columnas y casillas que deberán seguir las reglas
- Existen 27 grupos distintos:
- 0 - 8: grupos por renglón
- 9 - 17: grupos por columnas
- 18 - 26: grupo por casilla
- **GroupsOf**: A qué grupos una cierta celda pertenece
- **Neighbors**: Todas las celdas que están relacionadas con una celda
En la siguiente imagen, se muestra un Sudoku de 9x9 que tiene asignados los valores de las casillas, señalando en distintos colores las reglas que se deben de seguir, así como también la representación de los grupos.

Por ejemplo: Dada la casilla 10
- ¿A qué grupos pertence?: 1 (renglón), 10, (columna), 22 (casilla)
- ¿Vecinos de casilla #10?: 0, 1, 2, 9, 11, 12, 13, 14, 15, 16, 17, 28, 37, 46, 55, 64, 72
3. Las opraciones a realizar son:
- **Assign(int *k*, int *val*):** Elimina a los demás valores de la celda (*k*) que no son el valor dado (*val*)
- **DeleteVal(int *k*, int *val*):** Eliminar *v* de los posibles valores de la celda *k*. Existen tres posibilidades para eliminar:
- Si hay 0 valores posibles, entonces existe un error y se regresa un False para descartar la rama
- Si hay 1 valor posible, entonces ese es el valor (*v2*) que va en la celda (*k*). Para esto, se deberá eliminar el valor *v2* de todos sus vecinos para evitar repetidos
- Si al haber eliminado una posibilidad al asignar un valor en cierta casilla y solo hay otro lugar donde se puede asignar el valor restante, se asigna en la nueva casilla
4. Un árbol de posibilidades se irá creando conforme se realicen diferentes operaciones; en el árbol se propagarán las restricciones de lo que se le indicó en un inicio, y si en algún punto una rama no cumple con las restricciones, se regresará un False para indicar que por ese camino no es y se descarta la rama completa.
Al compilar un cierto Sudoku con el programa como se encuentra en este momento, podría llegar a funcionar si, sólo si, existe una sola posibilidad para cada celda. De lo contrario se deberá de añadir lo siguiente:
1. Se creará una función que escogerá un valor aleatorio dentro de las distintas posibilidades que pudiera tener una celda de un Sudoku que aún está sin resolver. Creará un nuevo “árbol” de posibilidades, que irá borrando ramas en cuanto estás dejen de cumplir con las reglas. Se deberá de empezar con las celdas que tienen menores posibilidades ya que al descartar una de sus ramas, rápidamente se descartan los valores en las demás ramas.
A todo esto, significa que un Sudoku puede ser resuelto utilizando un método de “Backtracking”, pues busca una solución y se regresa si ésta no es válida, ya que esto significa que nos hemos equivocado y busca en otra dirección utilizando otros valores.
La complejidad del algoritmo secuencial es de: O(n2) al eliminar los valores pues es ahí donde se aplican las reglas
[Codigo Secuencial](https://github.com/tec-csf/TC2017-PF-Otono-2019-equipo-algoritmos/tree/master/secuencial)
## 4. Análisis de los inhibidores del paralelismo
Al momento de querer paralelizar este problema, nos dimos cuenta de que había muchos ciclos for en los cuales se pudiera implementar la librería Open MP para sacarle provecho a los hilos de procesamiento de nuestras PC y resolver el problema en una cantidad aún menor de tiempo.
Nuestro primer tope fue el darnos cuenta de que no podíamos paralelizar todos los ciclos for de la solución, sino que debíamos limitarnos a escoger los ciclos en los cuales el procesamiento se iba a ser exhausto.
Notamos que una gran parte del procesamiento se concentraba en cargar el archivo, para lo cual hicimos uso de #pragma omp parallel para distribuir las columnas a través de los hilos de procesamiento y, de esta forma, lograra resolver más rápido el sudoku puzzle.
## 5. Solución paralela
Nuestra solución se centra en paralelizar la forma en la que el programa procesa la entrada para crear la matriz. Lo hacemos dividiendo el número de columnas entre el número de hilos de procesamiento disponibles y así acelerar su procesamiento.
[Codigo Paralelo](https://github.com/tec-csf/TC2017-PF-Otono-2019-equipo-algoritmos/tree/master/paralelo)
## 6. Tabla de resultados
Para poder comparar correctamente ambos algoritmos, se utilzaron 5 diferentes sudokus de entarada, los cuales iban incrementando su dificultad. Se resolvieron 2 Sudokus, los cuales fueron propuestos por un matemático filipino, que tienen la fama de ser muy difíciles.

**Secuencial**
| Dificultad de Sudoku | Tiempo de ejecución |
| :------------------: | :-----------------: |
| Easy - 1 | 0.02 segundos |
| Easy - 2 | 0.0 segundos |
| Hard Inkala 1 | 0.002 segundos |
| Hard Inkala 2 | 0.005 segundos |
| Impossible | 0.027 segundos |
**Paralelo**
| Dificultad de Sudoku | Tiempo de ejecución |
| :------------------: | :-----------------: |
| Easy - 1 | 0.00000004 segundos |
| Easy - 2 | 0.00000005 segundos |
| Hard Inkala 1 | 0.00000006 segundos |
| Hard Inkala 2 | 0.00000005 segundos|
| Impossible | 0.00000006 segundos |
## 7. Gráfica(s) comparativa(s)


*Cambiando opciones de balanceo*

*Auto*

*Guided*

*Static*

*Dynamic*

*Average*

## 8. Interpretación de los resultados
Al correr ambos programas con el mismo set de datos nos percatamos que el procesamiento en paralelo sacó ventaja de la solución secuencial. La diferencia no es tan perceptible, pues ante nuestros ojos ambas soluciones resolvían el puzzle al instante, pero sigue siendo más rápido.
¿Cómo se notaría más esta ventaja? La ventaja vendría cuando se tuviera que procesar una matriz nxn. Considerando n un número mucho mayor a 9, la cantidad de elementos de una matriz a procesar serían basta y es ahí donde nuestro programa sacaría la ventaja.
## 9. Guía paso a paso
Clonamos el repositorio a la carpeta de preferencia:
> git clone https://github.com/tec-csf/TC2017-PF-Otono-2019-equipo-algoritmos
Nos posicionamos en la carpeta de nuestro repositorio:
> cd TC2017-PF-Otono-2019-equipo-algoritmos
**Para el código secuencial**
Nos posicionamos en la carpeta secuencial:
> cd secuencial
Compilamos nuestro programa:
> g++ sudoku.cpp -o sudoku
Para que la solución secuencial resuelva un puzzle se le tiene que indicar el archivo de texto que debe de leer por medio del siguiente comando:
> ./sudoku < sudokuResolver.txt
O bien:
> ./sudoku < impossible-1.txt
Para que resuelva otro.
Si se quiere almacenar el sudoku resuelto en un archivo de texto, se deberá de ingresar el siguiente comando:
> ./sudoku < sudokuResolver.txt > sudokuResuelto.txt.
Se han añadido distintos Sudokus por resolver que están listos para ser usados por el usuario.
**Para el código paralelo**
Nos posicionamos en la carpeta paralela:
> cd paralela
Compilamos nuestro programa:
> g++ -fopenmp sudoku.cpp -o sudoku
Para que la solución secuencial resuelva un puzzle se le tiene que indicar el archivo de texto que debe de leer por medio del siguiente comando:
> ./sudoku < sudokuResolver.txt
O bien:
> ./sudoku < impossible-1.txt
Para que resuelva otro.
Si se quiere almacenar el sudoku resuelto en un archivo de texto, se deberá de ingresar el siguiente comando:
> ./sudoku < sudokuResolver.txt > sudokuResuelto.txt.
Se han añadido distintos Sudokus por resolver que están listos para ser usados por el usuario.
*Importante* El programa actualmente acepta dos distintos formatos de entrada de Sudoku:
1.

El programa podrá diferenciar y hará uso de los valores que realmente le interesan, sustituyendo el punto (.) por 0 para tomarlos como valores nulos.
2. **003020600900305001001806400008102900700000008006708200002609500800203009005010300**
El programa tomará los 0 como valores vacíos y creará las tripletas necesarias para consturir el sudoku de 9x9
## 10. Referencias
1. <NAME>. [<NAME>] (2013, enero 9). *C++ Solucionador de Sudokus 1-5/5*. [Archivo de video]. Recuperado el 22 de noviembre de 2019 de: https://www.youtube.com/watch?v=p7mjDQgbKYM
2. <NAME>. (s.f.). *Solving Every Sudoku Puzzle* Recuperado el 22 de noviembre de 2019 de: http://norvig.com/sudoku.html
3. <NAME>. [<NAME>] (2013, marzo 16). *Sudoku Parallel Approach* [Archivo de video]. Recuperado el 22 de noviembre de 2019 de: https://www.youtube.com/watch?v=S9ZBsgsj31w
4. <NAME>. (2014). *Parallelized Sudoku Solving Algorithm Using OpenMP*. Recuperado el 22 de noviembre de 2019 de: https://cse.buffalo.edu/faculty/miller/Courses/CSE633/Sankar-Spring-2014-CSE633.pdf
<file_sep>/Homework 2 - Sorting Algorithms/main.cpp
#include <time.h>
#include <iomanip>
#include <chrono>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Node{
int key;
struct Node *left, *right;
};
struct Node *newNode(int item){
struct Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
struct bucket{
int count;
int* value;
};
int compareIntegers(const void* first, const void* second){
int x = ((int)first), y = ((int)second);
if (x == y){
return 0;
}
else if (x < y){
return -1;
}
else{
return 1;
}
}
void storeSorted(Node *root, int arr[], int &i){
if (root != NULL) {
storeSorted(root->left, arr, i);
arr[i++] = root->key;
storeSorted(root->right, arr, i);
}
}
Node* insert(Node* node, int key){
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
int getMax(int arr[], int n){
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
void swap(int *xp, int *yp){
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void heapify(int arr[], int n, int i){
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void merge(int *a, int low, int high, int mid){
int i, j, k, temp[high - low + 1];
i = low;
k = 0;
j = mid + 1;
while(i <= mid && j <= high){
if(a[i] < a[j]){
temp[k] = a[i];
k++;
i++;
} else {
temp[k] = a[j];
k++;
j++;
}
}
while(i <= mid){
temp[k] = a[i];
k++;
i++;
}
while(j <= high){
temp[k] = a[j];
k++;
j++;
}
for (i = low; i <= high; i++){
a[i] = temp[i-low];
}
}
void mergeSort(int *a, int low, int high){
int mid;
if (low < high) {
mid=(low+high)/2;
mergeSort(a, low, mid);
mergeSort(a, mid+1, high);
merge(a, low, high, mid);
}
// https://www.geeksforgeeks.org/merge-sort/
}
int partition (int arr[], int low, int high){
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++){
if (arr[j] < pivot){
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void bubbleSort(int array[], int n){
for(int i = 0; i < n - 1; i++){
for(int j = 0; j < n - i - 1; j++){
if(array[j] > array[j+1]){
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
//obtenido de mis códigos realizados en otra clase
}
void cocktailSort(int a[], int n){
bool swapped = true;
int start = 0;
int end = n - 1;
while (swapped) {
swapped = false;
for (int i = start; i < end; ++i) {
if (a[i] > a[i + 1]) {
swap(a[i], a[i + 1]);
swapped = true;
}
}
if (!swapped)
break;
swapped = false;
--end;
for (int i = end - 1; i >= start; --i) {
if (a[i] > a[i + 1]) {
swap(a[i], a[i + 1]);
swapped = true;
}
}
++start;
}
// https://www.geeksforgeeks.org/cpp-program-for-cocktail-sort/
}
void insertionSort(int array[], int n){
for (int i = 1; i < n; i ++){
int temp = array[i];
for(int j = i - 1; j>= 0 && array[j] > temp; j--){
array[j + 1]= array[j];
array[j] = temp;
}
}
//https://www.geeksforgeeks.org/insertion-sort/
}
void bucketSort(int array[],int n){
struct bucket buckets[3];
int i, j, k;
for (i = 0; i < 3; i++){
buckets[i].count = 0;
buckets[i].value = (int*)malloc(sizeof(int) * n);
}
for (i = 0; i < n; i++){
if (array[i] < 0){
buckets[0].value[buckets[0].count++] = array[i];
}
else if (array[i] > 10){
buckets[2].value[buckets[2].count++] = array[i];
}
else{
buckets[1].value[buckets[1].count++] = array[i];
}
}
for (k = 0, i = 0; i < 3; i++){
qsort(buckets[i].value, buckets[i].count, sizeof(int), &compareIntegers);
for (j = 0; j < buckets[i].count; j++){
array[k + j] = buckets[i].value[j];
}
k += buckets[i].count;
free(buckets[i].value);
}
//https://www.geeksforgeeks.org/bucket-sort-2/
}
void countingSort(vector <int>& arr){
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
int range = max - min + 1;
vector<int> count(range), output(arr.size());
for(int i = 0; i < arr.size(); i++)
count[arr[i]-min]++;
for(int i = 1; i < count.size(); i++)
count[i] += count[i-1];
for(int i = arr.size()-1; i >= 0; i--)
{
output[ count[arr[i]-min] -1 ] = arr[i];
count[arr[i]-min]--;
}
for(int i=0; i < arr.size(); i++)
arr[i] = output[i];
//https://www.geeksforgeeks.org/counting-sort/
}
void binaryTreeSort(int arr[], int n){
struct Node *root = NULL;
root = insert(root, arr[0]);
for (int i=1; i<n; i++)
insert(root, arr[i]);
int i = 0;
storeSorted(root, arr, i);
//https://www.geeksforgeeks.org/tree-sort/
}
void countSort(int arr[], int n, int exp){
int output[n];
int i, count[10] = {0};
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--) {
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
void radixSort(int arr[], int n){
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
//https://www.geeksforgeeks.org/radix-sort/
}
void shellSort(int arr[], int n){
for (int gap = n/2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i += 1){
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}
}
//https://www.geeksforgeeks.org/shellsort/
}
void selectionSort(int arr[], int n){
int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
//obtenido de mis códigos realizados en clases anteriores
}
void heapSort(int arr[], int n){
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
//https://www.geeksforgeeks.org/cpp-program-for-heap-sort/
}
void quickSort(int arr[], int low, int high){
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
//https://www.geeksforgeeks.org/quick-sort/
}
int main(){
int size = 0;
int algorithm = 12;
cout << "Type in the size of your array. Choose from the following list: " << endl;
cout << "1. 10\n2. 100\n3. 1 000\n4. 10 000\n5. 100 000\n6. 200 000\n";
cin >> size;
//creating the array with random numbers
int array[size+1];
for(int i = 0; i < size; i++){
array[i] = rand() % 200 + 1;
}
cout << "\nSORTING ALGORITHM\t ELAPSED TIME (ms)\n" << "____________________________________________" << endl;
for(int i = 1; i <= algorithm; i++){
//creating a copy of they original array
int arrayCopy[size+1];
for(int i = 0; i < size; i++){
arrayCopy[i] = array[i];
}
switch(i){
case 1: //BubbleSort
{
auto start = chrono::steady_clock::now();
bubbleSort(array, size);
auto end = chrono::steady_clock::now();
cout << "\nBubble Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 2: //CocktailSort
{
auto start = chrono::steady_clock::now();
cocktailSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Cocktail Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 3://Insertion Sort
{
auto start = chrono::steady_clock::now();
insertionSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Insertion Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 4: //Bucket Sort
{
auto start = chrono::steady_clock::now();
bucketSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Bucket Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 5: //Counting Sort
{
//array into vector
vector<int> vec;
for(int i = 0; i < size; ++i){
vec.push_back(array[i]);
}
auto start = chrono::steady_clock::now();
countingSort(vec);
auto end = chrono::steady_clock::now();
cout << "Counting Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 6: //Merge sort
{
auto start = chrono::steady_clock::now();
mergeSort(array, 0, size-1);
auto end = chrono::steady_clock::now();
cout << "Merge Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 7: //Binary Tree sort
{
auto start = chrono::steady_clock::now();
binaryTreeSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Binary Tree Sort\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 8: //Radix sort
{
auto start = chrono::steady_clock::now();
radixSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Radix Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 9: //Shell sort
{
auto start = chrono::steady_clock::now();
shellSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Shell Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 10: //Selection Sort
{
auto start = chrono::steady_clock::now();
selectionSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Selection Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 11: //Heap sort
{
auto start = chrono::steady_clock::now();
heapSort(array, size);
auto end = chrono::steady_clock::now();
cout << "Heap Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
case 12: //Quick sort
{
auto start = chrono::steady_clock::now();
quickSort(array, 0, size - 1);
auto end = chrono::steady_clock::now();
cout << "Quick Sort\t\t\t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
}
break;
}
}
return 0;
}
<file_sep>/Homework 5 - Computational Geometry/arcos.cpp
#include "arcos.h"
#include "ui_arcos.h"
#include <QMessageBox>
#define PI 3.14159265
Arcos::Arcos(QWidget *parent):QDialog(parent), ui(new Ui::Arcos){
this->setFixedSize(521, 333); //Size of window
ui->setupUi(this);
xCentro = 345.0; // values so the first drawn figure is centered
yCentro = 170.0;
QTransform center;
center.translate(xCentro,yCentro);
vecTrans.push_back(center);
}
Arcos::~Arcos() {
delete ui;
}
void puntosDelCirculo(QPainter & painter) {
int xc,yc,x,y,p,r;
xc=300;
yc=200;
r=100;
x = 0;
y = r;
p = 1-r;
while(x <= y) {
if(p < 0) {
x++;
p += 2*x +1;
}
else {
x++;
y--;
p += 2*x - 2*y +1;
}
painter.drawPoint(xc+x,yc+y);
painter.drawPoint(xc+y,yc+x);
painter.drawPoint(xc+x,yc-y);
painter.drawPoint(xc+y,yc-x);
}
}
void dibujarArco(QPainter & painter) {
int xc,yc,x,y,p,r;
xc=0;
yc=0;
r=100;
x = 0;
y = r;
p = 1-r;
while(x<=y) {
if(p<0) {
x++;
p += 2*x +1;
}
else{
x++;
y--;
p += 2*x - 2*y +1;
}
painter.drawPoint(xc+x,yc+y);
painter.drawPoint(xc+y,yc+x);
painter.drawPoint(xc+x,yc-y);
painter.drawPoint(xc+y,yc-x);
}
}
void Arcos::paintEvent(QPaintEvent *event) {
QPainter painter(this);
QPen pointPen(Qt::black);
pointPen.setWidth(2);
painter.setPen(pointPen);
if (dibuja) {
for(int i=0; i<vecTrans.size(); ++i) {
painter.setTransform(vecTrans[i],true);
dibujarArco(painter);;
}
}
}
//These are the buttons
void Arcos::on_dibujar_clicked() {
trans.dibujar(dibuja,vecTrans,xCentro,yCentro);
update();
}
void Arcos::on_trasladar_clicked() {
QString x = ui->boxXinicio->toPlainText();
QString y = ui->boxYinicio->toPlainText();
if(!x.isEmpty() && !y.isEmpty()) {
trans.trasladar(x, y, vecTrans);
update();
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the values for x and y");
msgBox.exec();
}
}
void Arcos::on_rotar_clicked() {
QString gradosStr = ui->boxGrados->toPlainText();
if(!gradosStr.isEmpty()) {
trans.rotar(gradosStr, vecTrans);
update();
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the degree for rotation");
msgBox.exec();
}
}
void Arcos::on_zoom_in_clicked() {
trans.zoomIn(vecTrans);
update();
}
void Arcos::on_zoom_out_clicked() {
trans.zoomOut(vecTrans);
update();
}
void Arcos::on_horizontal_clicked() {
trans.reflexHorizontal(vecTrans);
update();
}
void Arcos::on_vertical_clicked() {
trans.reflexVertical(vecTrans);
update();
}
<file_sep>/Project 1 - Balanced Trees/TwoThreeTree.h
#include "TwoThreeNode.h"
#include <iomanip>
#include <queue>
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class TwoThreeTree {
protected:
TwoThreeNode<T> * root = nullptr;
std::vector<T> leafLevel;
public:
TwoThreeTree() { }
~TwoThreeTree();
bool empty();
void clear();
void clear(TwoThreeNode<T> * node);
TwoThreeNode<T> * getRoot() const;
void setRoot(const T info);
void setRoot(TwoThreeNode<T> * node);
bool isRoot(TwoThreeNode<T> * node);
void insert23(T info);
void insert23(TwoThreeNode<T> * info);
void insert23(TwoThreeNode<T> * parent, TwoThreeNode<T> * info);
void insert23(TwoThreeNode<T> * parent, T info);
void printAsc(TwoThreeNode<T> * node, int level);
void printAsc();
void printDesc(TwoThreeNode<T> * node, int level);
void printDesc();
void assignRoot(TwoThreeNode<T>* root);
bool isTwoTree ();
bool isTwoTree(TwoThreeNode<T>* node);
void redistributeChildren(TwoThreeNode<T>* container, TwoThreeNode<T>* node1, TwoThreeNode<T>* node2);
void divide(TwoThreeNode<T>* container);
bool checkTwoNode(TwoThreeNode<T>* node);
bool checkThreeNode(TwoThreeNode<T>* node);
bool freeChildren(TwoThreeNode<T>* node);
TwoThreeNode<T>* searchNode(const T info, TwoThreeNode<T> * node);
bool search23(const T info);
TwoThreeNode<T>* findNodeToDelete(TwoThreeNode<T>*, T info);
bool deleteNode(TwoThreeNode<T>* node);
bool delete23(T info);
void fix(TwoThreeNode<T>* node);
TwoThreeNode<T>* getSucesorInorder(TwoThreeNode<T>* node);
void getleafLevel(TwoThreeNode<T>* node);
bool getKeysNode(TwoThreeNode<T>* node);
bool getChildrenNode(TwoThreeNode<T>* node);
bool findNode(TwoThreeNode<T>*, T info);
void isLeaf() ;
bool isLeaf(TwoThreeNode<T> * node) ;
void ancestor(TwoThreeNode<T> * node) const;
int getHeight() const;
int getHeight(TwoThreeNode<T> * node) const ;
int getDepth() const;
int getDepth(TwoThreeNode<T> * node) const;
int getLevel() const;
int getLevel(TwoThreeNode<T> * node) const;
void order(T a[], int N);
void printHeight23(T x);
void printDepth23(T x);
void printLevel23(T x);
bool hasPath(TwoThreeNode<T>*& root, vector<T>&arr, T x);
};
template <class T>
TwoThreeTree<T>::~TwoThreeTree() {
clear();
}
template <class T>
bool TwoThreeTree<T>::empty() {
return root == nullptr;
}
template <class T>
void TwoThreeTree<T>::clear() {
clear(root);
}
template <class T>
void TwoThreeTree<T>::clear(TwoThreeNode<T> * node) {
if (node) {
clear(node->getLeft());
clear(node->getRight());
delete node;
}
}
template <class T>
TwoThreeNode<T> * TwoThreeTree<T>::getRoot() const {
return root;
}
template <class T>
void TwoThreeTree<T>::setRoot(const T info) {
TwoThreeNode<T> * node = new TwoThreeNode<T>(info);
setRoot(node);
}
template <class T>
void TwoThreeTree<T>::setRoot(TwoThreeNode<T> * node) {
if (!empty()) {
node->setLeft(root);
root->setParent(node);
root = node;
}
else {
root = node;
}
}
template <class T>
bool TwoThreeTree<T>::isRoot(TwoThreeNode<T> * node) {
return node == this->root;
}
template <class T>
void TwoThreeTree<T>::insert23(T info) {
insert23(this->root, info);
}
template <class T>
void TwoThreeTree<T>::insert23(TwoThreeNode<T> * info) {
insert23(this->root, info);
}
template <class T>
void TwoThreeTree<T>::assignRoot(TwoThreeNode<T>* node) {
root = node;
}
template <class T>
void TwoThreeTree<T>::redistributeChildren(TwoThreeNode<T>* container, TwoThreeNode<T>* node1, TwoThreeNode<T>* node2) {
node1->setLeft(container->getLeft());
node1->setRight(container->getMiddle());
node2->setLeft(container->getTemp());
node2->setRight(container->getRight());
node1->getLeft()->setParent(node1);
node1->getRight()->setParent(node1);
node2->getLeft()->setParent(node2);
node2->getRight()->setParent(node2);
}
template <class T>
void TwoThreeTree<T>::divide(TwoThreeNode<T>* container) {
if(isRoot(container)) {
TwoThreeNode<T>* newRoot = new TwoThreeNode<T>(container->getTempMiddle());
assignRoot(newRoot);
TwoThreeNode<T>* node1 = new TwoThreeNode<T>(container->getSmall());
TwoThreeNode<T>* node2 = new TwoThreeNode<T>(container->getBig());
if(container->getTemp()!=nullptr)
redistributeChildren(container, node1, node2);
newRoot->setLeft(node1);
newRoot->setRight(node2);
newRoot->getLeft()->setParent(newRoot);
newRoot->getRight()->setParent(newRoot);
delete container;
}
else if(container->getParent() != nullptr) {
TwoThreeNode<T>* parent = container->getParent();
if(parent->isFull()) {
parent->setInfoMiddle(container->getTempMiddle());
if(parent->getRight() == container) {
TwoThreeNode<T>* node1 = new TwoThreeNode<T>(container->getSmall());
TwoThreeNode<T>* node2 = new TwoThreeNode<T>(container->getBig());
if(container->getTemp()!=nullptr)
redistributeChildren(container, node1, node2);
parent->setRight(node2);
parent->setTemp(node1);
parent->getRight()->setParent(parent);
parent->getTemp()->setParent(parent);
delete container;
}
else if(parent->getLeft() == container) {
TwoThreeNode<T>* node1 = new TwoThreeNode<T>(container->getSmall());
TwoThreeNode<T>* node2 = new TwoThreeNode<T>(container->getBig());
if(container->getTemp()!=nullptr)
redistributeChildren(container, node1, node2);
parent->setLeft(node1);
parent->setTemp(parent->getMiddle());
parent->setMiddle(node2);
parent->getLeft()->setParent(parent);
parent->getMiddle()->setParent(parent);
parent->getTemp()->setParent(parent);
delete container;
}
else {
TwoThreeNode<T>* node1 = new TwoThreeNode<T>(container->getSmall());
TwoThreeNode<T>* node2 = new TwoThreeNode<T>(container->getBig());
if(container->getTemp()!=nullptr)
redistributeChildren(container, node1, node2);
parent->setMiddle(node1);
parent->setTemp(node2);
parent->getMiddle()->setParent(parent);
parent->getTemp()->setParent(parent);
delete container;
}
divide(parent);
}
else {
parent->setInfo(container->getTempMiddle());
if(parent->getRight() == container)
{
TwoThreeNode<T>* node1 = new TwoThreeNode<T>(container->getSmall());
TwoThreeNode<T>* node2 = new TwoThreeNode<T>(container->getBig());
if(container->getTemp()!=nullptr)
redistributeChildren(container, node1, node2);
parent->setRight(node2);
parent->setMiddle(node1);
parent->getRight()->setParent(parent);
parent->getMiddle()->setParent(parent);
delete container;
}
else if(parent->getLeft() == container) {
TwoThreeNode<T>* node1 = new TwoThreeNode<T>(container->getSmall());
TwoThreeNode<T>* node2 = new TwoThreeNode<T>(container->getBig());
if(container->getTemp()!=nullptr)
redistributeChildren(container, node1, node2);
parent->setLeft(node1);
parent->setMiddle(node2);
parent->getLeft()->setParent(parent);
parent->getMiddle()->setParent(parent);
delete container;
}
if(parent->hasThreeKeys())
divide(parent);
}
}
}
template <class T>
bool TwoThreeTree<T>:: checkTwoNode(TwoThreeNode<T>* node) {
if((node->hasLower() && !node->hasHigher()) || (!node->hasLower() && node->hasHigher()))
return true;
else
return false;
}
template <class T>
bool TwoThreeTree<T>:: checkThreeNode(TwoThreeNode<T>* node) {
if(node->hasLower() && node->hasHigher())
return true;
else
return false;
}
template <class T>
bool TwoThreeTree<T>::freeChildren(TwoThreeNode<T>* node) {
if(node->getLeft() == nullptr || node->getMiddle() == nullptr || node->getRight() == nullptr)
return true;
else
return false;
}
template <class T>
void TwoThreeTree<T>::insert23(TwoThreeNode<T> * parent, T info) {
TwoThreeNode<T>* container = new TwoThreeNode<T>();
if(root == nullptr)
{
assignRoot(new TwoThreeNode<T>(info));
return;
}
container = searchNode(info, root);
if(checkTwoNode(container))
{
container->setInfo(info);
container->deleteTempMiddle();
}
else if(checkThreeNode(container))
{
container->setInfoMiddle(info);
divide(container);
}
}
template <class T>
bool TwoThreeTree<T>::search23(const T info) {
bool found;
if (searchNode(info, root) != nullptr) {
found = true;
}
else {
found = false;
}
return found;
}
template <class T>
TwoThreeNode<T>* TwoThreeTree<T>::searchNode(const T info, TwoThreeNode<T> * node) {
if(node == nullptr)
return nullptr;
if(isLeaf(node))
return node;
else if(checkTwoNode(node)) {
if(info <= node->getSmall())
return searchNode(info, node->getLeft());
else
return searchNode(info, node->getRight());
}
else if(checkThreeNode(node)) {
if(info <= node->getSmall())
return searchNode(info, node->getLeft());
else if(info > node->getBig())
return searchNode(info, node->getRight());
else
return searchNode(info, node->getMiddle());
}
return node;
}
template <class T>
void TwoThreeTree<T>::printAsc() {
printAsc(root, 0);
cout << " " << endl;
}
template <class T>
void TwoThreeTree<T>::printAsc(TwoThreeNode<T> * node, int lv) {
if(node == nullptr)
return;
if(isLeaf(node)) {
if(checkTwoNode(node)) {
cout << node->getSmall() << " "<< flush;
}
else if(checkThreeNode(node)) {
cout << node->getSmall() << " " << node->getBig();
}
}
else if(checkTwoNode(node)) {
printAsc(node->getLeft(), lv);
cout << node->getSmall() << " "<< flush;
printAsc(node->getRight(), lv);
}
else if(checkThreeNode(node)) {
printAsc(node->getLeft(), lv);
cout << node->getSmall() << " "<< flush;
printAsc(node->getMiddle(), lv);
cout << node->getBig() << " "<< flush;
printAsc(node->getRight(), lv);
}
}
template <class T>
void TwoThreeTree<T>::printDesc() {
printDesc(root, 0);
cout << " " << endl;
}
template <class T>
void TwoThreeTree<T>::printDesc(TwoThreeNode<T> * node, int lv) {
if(node == nullptr)
return;
if(isLeaf(node)) {
if(checkTwoNode(node)) {
cout << node->getSmall() << " "<< flush;
}
else if(checkThreeNode(node)) {
cout << node->getBig() << " " << node->getSmall() << " ";
}
}
else if(checkTwoNode(node)) {
printDesc(node->getRight(), lv);
cout << node->getSmall() << " "<< flush;
printDesc(node->getLeft(), lv);
}
else if(checkThreeNode(node)) {
printDesc(node->getRight(), lv);
cout << node->getBig() << " "<< flush;
printDesc(node->getMiddle(), lv);
cout << node->getSmall() << " "<< flush;
printDesc(node->getLeft(), lv);
}
}
template <class T>
void TwoThreeTree<T>::fix(TwoThreeNode<T>* node) {
if(isRoot(node)) {
assignRoot(node->getMiddle());
delete node;
}
else {
bool threeKeys = false;
TwoThreeNode<T>* parent = node->getParent();
if(checkTwoNode(parent)) {
TwoThreeNode<T>* sibiling = new TwoThreeNode<T>();
if(parent->getRight() == node)
sibiling = parent->getLeft();
else
sibiling = parent->getRight();
if(parent->getRight() == node) {
if(checkThreeNode(parent->getLeft())){
threeKeys = true;
T sibilingLower = sibiling->getSmall();
T sibilingHigher = sibiling->getBig();
T parentVal = parent->getSmall();
T keys[3] = {sibilingLower,sibilingHigher,parentVal};
order(keys,3);
T low = keys[0];
T mid = keys[1];
T high = keys[2];
node->setInfo(high);
parent->deleteKeys();
parent->setInfo(mid);
sibiling->deleteKeys();
sibiling->setInfo(low);
if(!isLeaf(node)) {
node->setRight(node->getMiddle());
node->setMiddle(nullptr);
node->setLeft(sibiling->getRight());
node->getLeft()->setParent(node);
sibiling->setRight(sibiling->getMiddle());
sibiling->setMiddle(nullptr);
}
}
}
else {
if(checkThreeNode(parent->getRight()))
{
threeKeys = true;
T sibilingLower = sibiling->getSmall();
T sibilingHigher = sibiling->getBig();
T parentVal = parent->getSmall();
T keys[3] = {sibilingLower,sibilingHigher,parentVal};
order(keys,3);
T low = keys[0];
T mid = keys[1];
T high = keys[2];
node->setInfo(low);
parent->deleteKeys();
parent->setInfo(mid);
sibiling->deleteKeys();
sibiling->setInfo(high);
if(!isLeaf(node)) {
node->setLeft(node->getMiddle());
node->setMiddle(nullptr);
node->setRight(sibiling->getLeft());
node->getRight()->setParent(node);
sibiling->setLeft(sibiling->getMiddle());
sibiling->setMiddle(nullptr);
}
}
}
}
else if(checkThreeNode(parent)) {
TwoThreeNode<T>* sibiling = new TwoThreeNode<T>();
if(parent->getRight() == node) {
if(checkThreeNode(parent->getMiddle())) {
threeKeys = true;
sibiling = parent->getMiddle();
node->setInfo(parent->getBig());
parent->setBig(sibiling->getBig());
sibiling->deleteBig();
if(!isLeaf(node)) {
node->setRight(node->getMiddle());
node->setLeft(sibiling->getRight());
node->getLeft()->setParent(node);
sibiling->setRight(sibiling->getMiddle());
sibiling->setMiddle(nullptr);
}
}
}
else if(parent->getMiddle() == node) {
if(checkThreeNode(parent->getLeft())) {
threeKeys = true;
sibiling = parent->getLeft();
node->setInfo(parent->getSmall());
parent->setSmall(sibiling->getBig());
sibiling->deleteBig();
if(!isLeaf(node)) {
node->setRight(node->getMiddle());
node->setLeft(sibiling->getRight());
node->getLeft()->setParent(node);
sibiling->setRight(sibiling->getMiddle());
sibiling->setMiddle(nullptr);
}
}
}
else {
if(checkThreeNode(parent->getMiddle())) {
threeKeys = true;
sibiling = parent->getMiddle();
node->setInfo(parent->getSmall());
parent->setSmall(sibiling->getSmall());
sibiling->changeBigToSmall();
if(!isLeaf(node)) {
node->setLeft(node->getMiddle());
node->setRight(sibiling->getLeft());
node->getRight()->setParent(node);
sibiling->setLeft(sibiling->getMiddle());
sibiling->setMiddle(nullptr);
}
}
}
}
if(!threeKeys) {
TwoThreeNode<T>* sibiling = new TwoThreeNode<T>();
if(checkTwoNode(parent)) {
if(parent->getRight() == node) {
sibiling = parent->getLeft();
sibiling->setInfo(parent->getSmall());
if(!isLeaf(node)) {
sibiling->setMiddle(sibiling->getRight());
sibiling->setRight(node->getMiddle());
}
parent->setMiddle(sibiling);
parent->getMiddle()->setParent(parent);
parent->setLeft(nullptr);
parent->setRight(nullptr);
parent->deleteKeys();
delete node;
}
else {
sibiling = parent->getRight();
sibiling->setInfo(parent->getSmall());
if(!isLeaf(node))
{
sibiling->setMiddle(sibiling->getLeft());
sibiling->setLeft(node->getMiddle());
sibiling->getLeft()->setParent(sibiling);
}
parent->setMiddle(sibiling);
parent->getMiddle()->setParent(parent);
parent->setLeft(nullptr);
parent->setRight(nullptr);
parent->deleteKeys();
delete node;
}
}
else if(checkThreeNode(parent)) {
if(parent->getRight() == node) {
sibiling = parent->getMiddle();
sibiling->setInfo(parent->getBig());
if(!isLeaf(node)) {
sibiling->setMiddle(sibiling->getRight());
sibiling->setRight(node->getMiddle());
sibiling->getRight()->setParent(sibiling);
}
parent->setRight(sibiling);
parent->getRight()->setParent(parent);
parent->setMiddle(nullptr);
parent->deleteBig();
delete node;
}
else if(parent->getMiddle() == node) {
sibiling = parent->getLeft();
sibiling->setInfo(parent->getSmall());
if(!isLeaf(node)) {
sibiling->setMiddle(sibiling->getRight());
sibiling->setRight(node->getMiddle());
sibiling->getRight()->setParent(sibiling);
}
parent->setLeft(sibiling);
parent->getLeft()->setParent(parent);
parent->setMiddle(nullptr);
parent->deleteSmall();
parent->changeBigToSmall();
delete node;
}
else {
sibiling = parent->getMiddle();
sibiling->setInfo(parent->getSmall());
if(!isLeaf(node)) {
sibiling->setMiddle(sibiling->getLeft());
sibiling->setLeft(node->getMiddle());
sibiling->getLeft()->setParent(sibiling);
}
parent->setLeft(sibiling);
parent->getLeft()->setParent(parent);
parent->setMiddle(nullptr);
parent->deleteSmall();
parent->changeBigToSmall();
delete node;
}
}
if(parent->noKeys()) {
sibiling->setParent(parent);
fix(parent);
}
}
}
}
template <class T>
bool TwoThreeTree<T>::delete23(T info) {
TwoThreeNode<T>* node = new TwoThreeNode<T>();
node = findNodeToDelete(root, info);
if(node) {
TwoThreeNode<T>* leafNode = new TwoThreeNode<T>();
if(!isLeaf(node)) {
leafNode = getSucesorInorder(node);
T swapVal = leafNode->getSmall();
node->setSmall(swapVal);
}
else {
if(node->getBig() == info) {
node->deleteBig();
return true;
}
}
leafNode->deleteSmall();
if(leafNode->noKeys()) {
fix(leafNode);
}
return true;
}
else
return false;
}
template <class T>
TwoThreeNode<T>* TwoThreeTree<T>::getSucesorInorder(TwoThreeNode<T>* node) {
if (node) {
TwoThreeNode<T> * workingNode = node->getLeft();
if(workingNode){
while (workingNode->getRight() != nullptr) {
workingNode = workingNode->getRight();
}
return workingNode;
}
return nullptr;
} else {
return nullptr;
}
}
template <class T>
TwoThreeNode<T>* TwoThreeTree<T>::findNodeToDelete(TwoThreeNode<T>* node, T info) {
if(node == nullptr)
return nullptr;
if(isLeaf(node)) {
if(checkTwoNode(node)) {
if(node->getSmall() == info){
return node;
}
}
else if(checkThreeNode(node)) {
if(node->getSmall() == info || node->getBig() == info) {
return node;
}
}
return nullptr;
}
else if(checkTwoNode(node)) {
if(info == node->getSmall()) {
return node;
}
if(info < node->getSmall())
return findNodeToDelete(node->getLeft(), info);
else
return findNodeToDelete( node->getRight(), info);
}
else if(checkThreeNode(node))
{
if(node->getSmall() == info || node->getBig() == info) {
return node;
}
if(info < node->getSmall())
return findNodeToDelete(node->getLeft(), info);
else if(info > node->getBig())
return findNodeToDelete(node->getRight(), info);
else
return findNodeToDelete(node->getMiddle(), info);
}
return nullptr;
}
template <class T>
bool TwoThreeTree<T>::findNode(TwoThreeNode<T>* node, T info) {
if(node == nullptr)
return false;
if(isLeaf(node)) {
if(checkTwoNode(node)) {
if(node->getSmall() == info)
{
return true;
}
}
else if(checkThreeNode(node)) {
if(node->getSmall() == info || node->getBig() == info) {
return true;
}
}
return false;
}
else if(checkTwoNode(node)) {
if(info == node->getSmall()) {
return true;
}
if(info < node->getSmall())
return findNode(node->getLeft(), info);
else
return findNode( node->getRight(), info);
}
else if(checkThreeNode(node)) {
if(node->getSmall() == info || node->getBig() == info) {
return true;
}
if(info < node->getSmall())
return findNode(node->getLeft(), info);
else if(info > node->getBig())
return findNode(node->getRight(), info);
else
return findNode(node->getMiddle(), info);
}
return false;
}
template <class T>
bool TwoThreeTree<T>::isTwoTree() {
return isTwoTree(root);
}
template <class T>
bool TwoThreeTree<T>::isTwoTree(TwoThreeNode<T>* node) {
leafLevel.clear();
getleafLevel(root);
T cmp = leafLevel[0];
bool leafs = true;
for(int i=1; i<leafLevel.size(); i++) {
if(leafLevel[i] != cmp)
leafs = false;
}
return leafs;
}
template <class T>
void TwoThreeTree<T>::getleafLevel(TwoThreeNode<T>* node) {
if(node == nullptr)
return;
if(isLeaf(node)) {
leafLevel.push_back(getLevel(node));
}
else if(checkTwoNode(node)) {
getleafLevel(node->getLeft());
getleafLevel(node->getRight());
}
else if(checkThreeNode(node)) {
getleafLevel(node->getLeft());
getleafLevel(node->getMiddle());
getleafLevel(node->getRight());
}
}
template <class T>
void TwoThreeTree<T>::isLeaf() {
isLeaf(root);
}
template <class T>
bool TwoThreeTree<T>::isLeaf(TwoThreeNode<T> * node) {
if(node->getLeft() == nullptr && node->getMiddle() == nullptr && node->getRight() == nullptr)
return true;
else
return false;
}
template <class T>
void TwoThreeTree<T>::ancestor(TwoThreeNode<T> * node) const {
if (node) {
cout << *node << " -> ";
ancestor(node->getParent());
}
}
template <class T>
int TwoThreeTree<T>::getHeight() const {
return getHeight(root);
}
template <class T>
int TwoThreeTree<T>::getHeight(TwoThreeNode<T> * node) const {
if (!node)
return -1;
return 1 + std::max(getHeight(node->getLeft()), getHeight(node->getRight()));
}
template <class T>
int TwoThreeTree<T>::getDepth() const {
return getDepth(root);
}
template <class T>
int TwoThreeTree<T>::getDepth(TwoThreeNode<T> * node) const {
if (node == nullptr) {
return 0;
}
else {
return getDepth(node->getParent())+1;
}
}
template <class T>
int TwoThreeTree<T>::getLevel() const {
return getLevel(root);
}
template <class T>
int TwoThreeTree<T>::getLevel(TwoThreeNode<T> * node) const {
int level = 0;
while (node != nullptr && node->getParent() != nullptr) {
level++;
node = node->getParent();
}
return level;
}
template <class T>
void TwoThreeTree<T>::order(T a[], int N) {
int i, j, flag = 1;
int temp;
int numLength = N;
for(i = 1; (i <= numLength) && flag; i++) {
flag = 0;
for (j=0; j < (numLength -1); j++) {
if (a[j+1] < a[j]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
flag = 1;
}
}
}
return;
}
template<class T>
// HEIGHT: LONGEST PATH FROM THAT NODE TO A LEAF
bool TwoThreeTree<T>::hasPath(TwoThreeNode<T>*& root, vector<T>& arr, T x){
if(root == NULL) return false;
arr.push_back(x); //save the nodes value in vector
if(x == x) return true;
if(hasPath(root->left, arr, x) || hasPath(root->right, arr, x)) return true;
arr.pop_back();
return false;
}
template<class T>
void TwoThreeTree<T>::printHeight23(T x){
TwoThreeNode<T> *y = root;
vector<T> arr;
int h = 1;
cout << "Printing path: \n";
if(hasPath(root, arr, x)){
for(int i = 0; i < arr.size() - 1; ++i){
cout << arr[i] << " -> ";
h = (h + 4 * 3) * 4;
}
cout << arr[arr.size() - 1];
} else
cout << "There's no path of " << x << endl;
cout << "\nHeight of node " << x << " is " << h << endl;
}
template<class T>
void TwoThreeTree<T>::printDepth23(T x){
TwoThreeNode<T> *y = root;
vector<T> arr;
int d = 1;
cout << "Printing path: \n";
if(hasPath(root, arr, x)){
for(int i = arr.size() - 1; i > 0 ; --i){
cout << arr[i] << " -> ";
d = (d + 4) * 5;
}
cout << arr[0];
} else
cout << "There's no path of " << x << endl;
cout << "\nDepth of node " << x << " to root is " << d << endl;
}
template<class T>
void TwoThreeTree<T>::printLevel23(T x){
TwoThreeNode<T> *y = root;
vector<T> arr;
int l = 1;
cout << "Printing path: \n";
if(hasPath(root, arr, x)){
for(int i = arr.size() - 1; i > 0 ; --i){
cout << arr[i] << " -> ";
l = (l + 4) * 5;
}
cout << arr[0];
} else
cout << "There's no path of " << x << endl;
cout << "\nLevel of node " << x << " is " << l + 1 << endl;
}
<file_sep>/Homework 5 - Computational Geometry/argo.cpp
#include "argo.h"
#include "ui_argo.h"
argo::argo(QWidget *parent) :
QDialog(parent),
ui(new Ui::argo)
{
ui->setupUi(this);
}
argo::~argo()
{
delete ui;
}
<file_sep>/Project 3 - Parallel vs Sequential/secuencial/sudoku.cpp
#include <iostream>
#include <vector>
#include <algorithm> // for count
#include <assert.h>
#include <time.h>
using namespace std;
// Possible values that can be entered in a cell
// Elimination
class PossibleValues{
vector<bool> b; // Each boolean uses 1 bit, very optimal
public:
PossibleValues(): b(9, true) {} //9 cells
bool activeVal(int v) const { return b[v - 1]; }
void deleteVal(int v) { b[v - 1] = false; }
int numActiveVal() const { return count(b.begin(), b.end(), true); } // Check how many values are on "true" (usable values)
int valueInCell() const {
// simply check if there's only one value in true, then that's the value for the cell
// this returns an iterator to where the true value is positioned on
vector<bool>::const_iterator it = find(b.begin(), b.end(), true);
return 1 + (it - b.begin());
}
string str(int width) const;
};
// concatenate possible values
string PossibleValues::str(int width) const {
string s(width, ' '); //this is simply for the printing part
int j = 0;
for(int i = 1; i <= 9; i++){
if(activeVal(i)) s[j++] = ('0' + i);
}
return s;
}
class Sudoku {
vector<PossibleValues> cells;
// Groups (for lines, columns and subgrids) that will have to apply the rules
// GropusOf: Which groups does a certain cell belong to
// Neighbors: All of the cells a certain cell is related to
static vector < vector <int> > groups, groupsOf, neighbors;
public:
Sudoku(string s); //representation of sudoku
static void initialize();
PossibleValues possibleVal(int k) const { return cells[k]; } // know the possible values of k
bool solved() const; // know if a sudoku is solved or not
bool assign(int k, int val); // to cell k, assign value val, bool return value is to know if we have succeeded or failed
bool deleteVal(int k, int val); // to cell k, delete value val, bool return value is to know if we have succeeded or failed
void print(ostream& o) const;
int lessPossibilites() const; //will return the value of the cell that has the less possibilites, when they have 2 or more possible values
};
vector < vector <int> > Sudoku::groups(27), Sudoku::groupsOf(81), Sudoku::neighbors(81);
void Sudoku::initialize() {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
const int k = i * 9 + j; //Getting the value of a cell
const int g[3] = { i, 9 + j, 18 + (i/3)*3 + (j/3) }; // index of groups the k cell belongs to
//filling the groups and groupsOf of a cell k
for(int x = 0; x < 3; ++x) {
groups[g[x]].push_back(k);
groupsOf[k].push_back(g[x]);
}
}
}
for(int k = 0; k < 81; ++k) {
for(int x = 0; x < 3; ++x) {
const int g = groupsOf[k][x];
for(int i = 0; i < 9; ++i) {
const int k2 = groups[g][i];
if(k2 != k) {
neighbors[k].push_back(k2);
}
}
}
}
}
// using numActiveVal we can easily know if the sudoku has been solved or not. If, for each cell the numActiveVal = 1, then it is solved
bool Sudoku::solved() const {
for(int k = 0; k < cells.size(); ++k){
if(cells[k].numActiveVal() != 1){
return false;
}
}
return true;
}
bool Sudoku::assign(int k, int val) {
// cout << "Assign value (" << k << ", " << val << ")" << endl;
for(int i = 1; i <= 9; ++i) {
if(val != i) {
if(!deleteVal(k, i)) return false; // erase all the other values in the cell that are not the given value, if it cannot delete a value, return false --> there's an error
}
}
return true;
}
bool Sudoku::deleteVal(int k, int val) {
//cout << "Delete value (" << k << ", " << val << ")" << endl;
if(!cells[k].activeVal(val)) {
return true; // We can easily delete a value because it wasn't active
}
cells[k].deleteVal(val);
const int N = cells[k].numActiveVal();
if(N == 0) { // If there are 0 possible values --> error
return false;
} else if(N == 1) { // If there is only 1 possible values, delete the value in the neighbors
const int v2 = cells[k].valueInCell();
for(int i = 0; i < neighbors[i].size(); i++) {
if(!deleteVal(neighbors[k][i], v2)) return false; // propagate the false values when something fails
}
}
for(int x = 0; x < 3; x++) {
const int g = groupsOf[k][x]; // the group we're currently analyzing
int n = 0, k2;
for(int i = 0; i < 9; i++) {
const int kp = groups[g][i];
if(cells[kp].activeVal(val)) {
n++, k2 = kp;
}
}
if(n == 0) {
return false; // if a value has been deleted but it isn't present in any other of the neighbors, there's an error
} else if (n == 1) { // simply assign a value if it's an onl value
if(!assign(k2, val)) return false;
}
}
return true;
}
int Sudoku::lessPossibilites() const {
int kMin = -1, min;
for(int k = 0; k < cells.size(); k++) {
const int possNums = cells[k].numActiveVal();
if(possNums > 1 && (kMin == -1 || possNums < min)) {
min = possNums;
kMin = k; // cell with less possibilites
}
}
return kMin;
}
void Sudoku::print(ostream& o) const {
int width = 2;
for(int k = 0; k < cells.size(); ++k) {
width = max(width, 1 + cells[k].numActiveVal());
}
string separator(3*width, '-');
cout << endl;
for(int i = 0; i < 9; i++) {
if(i == 3 || i == 6) {
cout << separator << "+-" << separator << "+-"<< separator << endl;
}
for(int j = 0; j < 9; j++) {
const int k = i*9 + j;
if(j == 3 || j == 6) {
cout << "| ";
}
cout << cells[k].str(width);
}
cout << endl;
}
}
Sudoku::Sudoku(string s): cells(81) { //initialize with default values
int k = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] >= '1' && s[i] <= '9') {
if (!assign(k, s[i] - '0')){//reduce ASCII so we get a NUMBER
cout << "Error trying to read the Sudoku. Check input" << endl;
// we're checking in case we the input value doesn't follow the rules
}
k++;
} else if (s[i] == '0' || s[i] == '.') {
k++;
}
}
assert(k == 81); //program will break if k != of 81
}
// This function is used to "guess" a value when there are multiple possibilites to choose from resulting in an unsolved Sudoku. It forms a "tree" os possibilites, erasing branches as soon as they aren't working
Sudoku *solve(Sudoku* S) {
if(S == NULL || S->solved()) { // Base case, either it's solved or it's empty
return S;
}
const int k = S->lessPossibilites();
const PossibleValues pV = S->possibleVal(k);
for(int i = 1; i <= 9; i++) {
if(pV.activeVal(i)) {
Sudoku *S1 = new Sudoku(*S); //Reference to a copy of a Sudoku
if(S1->assign(k, i)) {
Sudoku *S2 = solve(S1);
if(S2 != NULL) {
if(S2 != S1) delete S1; // the solution is another one, it's not S1
return S2;
}
}
delete S1; //the "tree" branch is not this one; erease it completely
}
}
return NULL;
}
int main() {
clock_t startTimer, endTimer;
Sudoku::initialize();
string s, line;
while(getline(cin, line)) s += line; //reading from a file
startTimer = clock();
Sudoku *S = solve(new Sudoku(s));
endTimer = clock();
S->print(cout);
double timeTaken = (double)(endTimer - startTimer)/(double)(CLOCKS_PER_SEC);
cout << "\nTime taken by program is : " << timeTaken << " seconds\n";
}
<file_sep>/Homework 5 - Computational Geometry/prismarec.cpp
#include "prismarec.h"
#include "ui_prismarec.h"
#include <math.h>
#include <QMessageBox>
prismarec::prismarec(QWidget *parent):QDialog(parent), ui(new Ui::prismarec) {
this->setFixedSize(521, 333); //Size of window
ui->setupUi(this);
xCentro = 345.0; // values so the first drawn figure is centered
yCentro = 170.0;
QTransform center;
center.translate(xCentro,yCentro);
vecTrans.push_back(center);
}
prismarec::~prismarec() {
delete ui;
}
void prismarec::paintEvent(QPaintEvent *e) {
QPainter painter(this);
QPen pointPen(Qt::black);
pointPen.setWidth(2);
painter.setPen(pointPen);
if (dibuja){
for(int i=0; i<vecTrans.size(); ++i){
painter.setTransform(vecTrans[i],true);
drawPrismarec(painter);
}
}
}
void prismarec::drawPrismarec(QPainter &painter){
//Base
painter.drawLine(0,50,30,0);
painter.drawLine(30,0,80,0);
painter.drawLine(30,-150,30,0);
painter.drawLine(50,50,80,0);
// "Height"
painter.drawLine(0,-100, 30,-150);
painter.drawLine(50,-100, 80,-150);
painter.drawLine(0, 50, 50, 50);
painter.drawLine(0,-100, 50, -100);
painter.drawLine(0, -100, 0, 50);
painter.drawLine(50,-100, 50, 50);
painter.drawLine(30,-150, 80,-150);
painter.drawLine(80,-150, 80, 0);
}
void prismarec::on_dibujar_clicked() {
vecTrans.clear();
QTransform centro;
centro.translate(xCentro,yCentro);
vecTrans.push_back(centro);
dibuja = !dibuja;
update();
}
void prismarec::on_trasladar_clicked() {
QString x = ui->boxXinicio->toPlainText();
QString y = ui->boxYinicio->toPlainText();
if(!x.isEmpty() && !y.isEmpty()) {
int xS = x.toInt();
int yS = y.toInt();
QTransform t;
t.translate(xS, yS);
vecTrans.push_back(t);
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the values for x and y");
msgBox.exec();
}
update();
}
void prismarec::on_zoom_in_clicked() {
QTransform zIn;
zIn.scale(2,2);
vecTrans.push_back(zIn);
update();
}
void prismarec::on_zoom_out_clicked() {
QTransform zOut;
zOut.scale(0.5,0.5);
vecTrans.push_back(zOut);
update();
}
void prismarec::on_rotar_clicked() {
QString r = ui->boxGrados->toPlainText();
if(!r.isEmpty()) {
int rS = r.toInt();
QTransform r;
r.rotate(rS);
vecTrans.push_back(r);
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the degree for rotation");
msgBox.exec();
}
update();
}
void prismarec::on_vertical_clicked() {
QTransform rv;
rv.scale(1,-1);
vecTrans.push_back(rv);
update();
}
void prismarec::on_horizontal_clicked() {
QTransform rh;
rh.scale(-1,1);
vecTrans.push_back(rh);
update();
}
<file_sep>/Homework 5 - Computational Geometry/poligonos.cpp
#include "poligonos.h"
#include "ui_poligonos.h"
#include <QMessageBox>
#include <math.h>
Poligonos::Poligonos(QWidget *parent): QDialog(parent), ui(new Ui::Poligonos) {
this->setFixedSize(521, 333); //Size of window
ui->setupUi(this);
xCentro = 345.0; // values so the first drawn figure is centered
yCentro = 170.0;
QTransform centro;
centro.translate(xCentro,yCentro);
vecTrans.push_back(centro);
}
Poligonos::~Poligonos() {
delete ui;
}
void dibujarPoligono(int lados, QPainter & painter) {
double radio = 100;
double angulo = (double)360.0/(double)lados;
int xi,yi,xf,yf;
double val = M_PI / 180;
angulo *= val;
int a = 0;
for(a = 1; a <= lados; a++) {
xi = (radio * cos(angulo*a));
yi = (radio * sin(angulo*a));
xf = (radio * cos(angulo*(a+1)));
yf = (radio * sin(angulo*(a+1)));
painter.drawLine(xi, yi, xf, yf);
}
}
void Poligonos::paintEvent(QPaintEvent *event) {
QPainter painter(this);
QPen pointPen(Qt::black);
pointPen.setWidth(2);
painter.setPen(pointPen);
if (dibuja) {
QString ladosStr = ui->boxXfin->toPlainText();
if (!ladosStr.isEmpty()) {
int lados = ladosStr.toInt();
for(int i=0; i<vecTrans.size(); ++i) {
painter.setTransform(vecTrans[i],true);
dibujarPoligono(lados, painter);
}
}
}
}
//Buttons...
void Poligonos::on_dibujar_clicked() {
trans.dibujar(dibuja,vecTrans,xCentro,yCentro);
update();
}
void Poligonos::on_trasladar_clicked() {
QString xStr = ui->boxXinicio->toPlainText();
QString yStr = ui->boxYinicio->toPlainText();
QString x = ui->boxXinicio->toPlainText();
QString y = ui->boxYinicio->toPlainText();
if(!x.isEmpty() && !y.isEmpty()) {
trans.trasladar(x, y, vecTrans);
update();
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the values for x and y");
msgBox.exec();
}
}
void Poligonos::on_rotar_clicked() {
QString gradosStr = ui->boxGrados->toPlainText();
if(!gradosStr.isEmpty()) {
trans.rotar(gradosStr, vecTrans);
update();
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the degree for rotation");
msgBox.exec();
}
}
void Poligonos::on_zoom_out_clicked() {
trans.zoomOut(vecTrans);
update();
}
void Poligonos::on_zoom_in_clicked() {
trans.zoomIn(vecTrans);
update();
}
void Poligonos::on_horizontal_clicked() {
trans.reflexHorizontal(vecTrans);
update();
}
void Poligonos::on_vertical_clicked() {
trans.reflexVertical(vecTrans);
update();
}
<file_sep>/Exercises/Dynamic Programming/main.cpp
#include <iostream>
#include <chrono>
using namespace std;
int FibIterativo(int n){
int suma, x, y;
if(n <= 1)
return 1;
else {
x = 1;
y = 1;
for(int i = 2; i < n; ++i){
suma = x + y;
y = x;
x = suma;
}
return suma;
}
}
int Fib(int n){
if(n == 0 || n == 1){
return 1;
}
else {
return Fib(n - 1) + Fib(n - 2);
}
return -1;
}
int main(){
int n, technique, answer;
clock_t start, end;
cout << "Input the value to calculate\n";
cin >> n;
cout << "1. Recursive Fibonacci\n2. Iterative Fibonacci\n";
cin >> technique;
switch(technique){
case 1:
{
auto start = chrono::steady_clock::now();
answer = Fib(n);
auto end = chrono::steady_clock::now();
cout << "Time taken by Recursive Fibonacci of " << n << " is \t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
cout << "Fibonacci of: " << answer << endl;
}
break;
case 2:
{
auto start = chrono::steady_clock::now();
answer = FibIterativo(n);
auto end = chrono::steady_clock::now();
cout << "Time taken by Iterative Fibonacci of " << n << " is \t" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms\n" << endl;
cout << "Fibonacci of: " << answer << endl;
}
break;
}
return 0;
}
<file_sep>/Homework 5 - Computational Geometry/cubo.cpp
#include "cubo.h"
#include "ui_cubo.h"
#include <QPainter>
#include <QMessageBox>
#include <math.h>
cubo::cubo(QWidget *parent):QDialog(parent), ui(new Ui::cubo) {
this->setFixedSize(521, 333); //Size of window
ui->setupUi(this);
xCentro = 345.0; // values so the first drawn figure is centered
yCentro = 170.0;
QTransform center;
center.translate(xCentro,yCentro);
vecTrans.push_back(center);
}
cubo::~cubo()
{
delete ui;
}
void cubo::paintEvent(QPaintEvent *e){
QPainter painter(this);
QPen pointPen(Qt::black);
pointPen.setWidth(2);
painter.setPen(pointPen);
if (dibuja){
for(int i=0; i<vecTrans.size(); ++i){
painter.setTransform(vecTrans[i],true);
drawCubo(painter);
}
}
}
void cubo::drawCubo(QPainter &painter){
painter.drawLine(-40, 40, 40, 40);
painter.drawLine(-40, 40, -40, -40);
painter.drawLine(40, 40, 40, -40);
painter.drawLine(-40, -40, 40, -40);
painter.drawLine(0, 0, 80, 0);
painter.drawLine(0, 0, 0, -80);
painter.drawLine(80, 0, 80, -80);
painter.drawLine(0, -80, 80, -80);
painter.drawLine(-40, 40, 0, 0);
painter.drawLine(40, 40, 80, 0);
painter.drawLine(-40, -40, 0, -80);
painter.drawLine(40, -40, 80, -80);
}
void cubo::on_dibujar_clicked() {
vecTrans.clear();
QTransform centro;
centro.translate(xCentro,yCentro);
vecTrans.push_back(centro);
dibuja = !dibuja;
update();
}
void cubo::on_trasladar_clicked() {
QString x = ui->boxXinicio->toPlainText();
QString y = ui->boxYinicio->toPlainText();
if(!x.isEmpty() && !y.isEmpty()) {
int xS = x.toInt();
int yS = y.toInt();
QTransform t;
t.translate(xS, yS);
vecTrans.push_back(t);
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the values for x and y");
msgBox.exec();
}
update();
}
void cubo::on_zoom_out_clicked() {
QTransform zIn;
zIn.scale(2,2);
vecTrans.push_back(zIn);
update();
}
void cubo::on_zoom_in_clicked() {
QTransform zOut;
zOut.scale(0.5,0.5);
vecTrans.push_back(zOut);
update();
}
void cubo::on_rotar_clicked() {
QString r = ui->boxGrados->toPlainText();
if(!r.isEmpty()) {
int rS = r.toInt();
QTransform r;
r.rotate(rS);
vecTrans.push_back(r);
} else {
QMessageBox msgBox;
msgBox.setText("Please type in the degree for rotation");
msgBox.exec();
}
update();
}
void cubo::on_vertical_clicked() {
QTransform rv;
rv.scale(1,-1);
vecTrans.push_back(rv);
update();
}
void cubo::on_horizontal_clicked() {
QTransform rh;
rh.scale(-1,1);
vecTrans.push_back(rh);
update();
}
<file_sep>/Homework 5 - Computational Geometry/prismatri.h
#ifndef PRISMATRI_H
#define PRISMATRI_H
#include <QDialog>
#include <QtGui>
#include <QtCore>
namespace Ui {
class PrismaTri;
}
class PrismaTri : public QDialog
{
Q_OBJECT
public:
explicit PrismaTri(QWidget *parent = 0);
~PrismaTri();
protected:
void paintEvent(QPaintEvent *e);
void drawPrismaTri(QPainter &painter);
private slots:
void on_dibujar_clicked();
void on_trasladar_clicked();
void on_rotar_clicked();
void on_zoom_in_clicked();
void on_zoom_out_clicked();
void on_horizontal_clicked();
void on_vertical_clicked();
private:
Ui::PrismaTri *ui;
bool dibuja = false;
double xCentro;
double yCentro;
QVector<QTransform> vecTrans;
};
#endif // PRISMATRI_H
<file_sep>/Project 1 - Balanced Trees/RBTNode.h
//RBTNode.h
enum RBTColor { Black, Red };
template<class KeyType>
struct RBTNode
{
KeyType key;
RBTColor color;
RBTNode<KeyType> * left;
RBTNode<KeyType> * right;
RBTNode<KeyType> * parent;
RBTNode(KeyType k, RBTColor c, RBTNode* p, RBTNode*l, RBTNode*r) :
key(k), color(c), parent(p), left(l), right(r) { };
};
<file_sep>/Homework 5 - Computational Geometry/dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include "poligonos.h"
#include "arcos.h"
#include "cubo.h"
#include "cono.h"
#include "prismarec.h"
#include "prismatri.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
private slots:
void on_poligono_clicked();
void on_arco_clicked();
void on_cubo_clicked();
void on_cono_clicked();
void on_prismarec_clicked();
void on_prismatri_clicked();
private:
Ui::Dialog *ui;
};
#endif
<file_sep>/Homework 4 - Graph Processing/main.c.cpp
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <ctime>
#include <chrono>
using namespace std;
typedef PNGraph DGraph;
void GraphML(DGraph graph) {
ofstream file ("wiki_vote.graphml");
if (file.is_open()) {
file << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
file << "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n";
file << "<graph id=\"G\" edgedefault=\"directed\">\n";
for (DGraph::TObj::TNodeI NI = graph->BegNI(); NI < graph->EndNI(); NI++)
file << "<node id=\"" << NI.GetId() << "\"/>\n";
int i = 1;
for (DGraph::TObj::TEdgeI EI = graph->BegEI(); EI < graph->EndEI(); EI++, ++i)
file << "<edge id=\"e" << i << "\" source=\"" << EI.GetSrcNId() << "\" target=\"" << EI.GetDstNId() << "\"/>\n";
file << "</graph>\n";
file << "</graphml>\n";
file.close();
}
}
void GEXF(DGraph graph) {
ofstream file ("wiki_vote.gexf");
if (file.is_open()) {
file << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
file << "<gexf xmlns=\"http://www.gexf.net/1.2draft\" version=\"1.2\">\n";
file << "<graph mode=\"static\" defaultedgetype=\"directed\">\n";
file << "<nodes>\n";
for (DGraph::TObj::TNodeI NI = graph->BegNI(); NI < graph->EndNI(); NI++)
file << "<node id=\"" << NI.GetId() << "\" />\n";
file << "</nodes>\n";
file << "<edges>\n";
int i = 1;
for (DGraph::TObj::TEdgeI EI = graph->BegEI(); EI < graph->EndEI(); EI++, ++i)
file << "<edge id=\"" << i << "\" source=\"" << EI.GetSrcNId() << "\" target=\"" << EI.GetDstNId() << "\" />\n";
file << "</edges>\n";
file << "</graph>\n";
file << "</gexf>\n";
file.close();
}
}
void GDF(DGraph graph) {
ofstream file ("wiki_vote.gdf");
if (file.is_open()) {
file << "nodedef>id VARCHAR\n";
for (DGraph::TObj::TNodeI NI = graph->BegNI(); NI < graph->EndNI(); NI++)
file << NI.GetId() << "\n";
file << "edgedef>source VARCHAR, destination VARCHAR\n";
for (DGraph::TObj::TEdgeI EI = graph->BegEI(); EI < graph->EndEI(); EI++)
file << EI.GetSrcNId() << ", " << EI.GetDstNId() << "\n";
file.close();
}
}
void JSON(DGraph graph) {
ofstream file ("wiki_vote.json");
if (file.is_open()) {
file << "{ \"graph\": {\n";
file << "\"nodes\": [\n";
for (DGraph::TObj::TNodeI NI = graph->BegNI(); NI < graph->EndNI();) {
file << "{ \"id\": \"" << NI.GetId() << "\" }";
if (NI++ == graph->EndNI())
file << " ],\n";
else
file << ",\n";
}
file << "\"edges\": [\n";
for (DGraph::TObj::TEdgeI EI = graph->BegEI(); EI < graph->EndEI();) {
file << "{ \"source\": \"" << EI.GetSrcNId() << "\", \"target\": \"" << EI.GetDstNId() << "\" }";
if (EI++ == graph->EndEI())
file << " ]\n";
else
file << ",\n";
}
file << "} }";
file.close();
}
}
int main() {
DGraph graph = TSnap::LoadEdgeList<DGraph>("wiki-Vote.txt",0,1);
cout << "\nThe Wiki-Vote dataset has been imported succesfully\nExporting...\n" << endl;
cout << "Format\tExecution Time (ms)" << endl;
for(int i = 0; i < 4; ++i) {
switch(i){
case 0:
{
auto start = chrono::steady_clock::now();
GraphML(graph);
auto end = chrono::steady_clock::now();
cout << "GraphML\t " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl;
}
break;
case 1:
{
auto start = chrono::steady_clock::now();
GEXF(graph);
auto end = chrono::steady_clock::now();
cout << "GEFX\t " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl;
}
break;
case 2:
{
auto start = chrono::steady_clock::now();
GDF(graph);
auto end = chrono::steady_clock::now();
cout << "GDF\t " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl;
}
break;
case 3:
{
auto start = chrono::steady_clock::now();
JSON(graph);
auto end = chrono::steady_clock::now();
cout << "JSON\t " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl;
}
break;
}
}
return 0;
}
<file_sep>/Homework 3 - Algorithm Design Techniques/driverTruck.cpp
/*
<NAME>
A01021698
Exercise 1: Driver truck
Technique: Greedy algorithm
It makes a greedy choice when filling up the tank at the farthest reachable gas station
Complexity: O(n) because there's only one for loop going through the n distances of the gas stations
*/
#include <iostream>
using namespace std;
int main() {
int tank = 95, distanceTravelled = 0, refill = 0, n = 6;
int gasStation [n]= {58, 49, 25, 78, 94, 76};
cout << "\nCDMX Acapulco" << endl;
cout << "|-----|-----|-----|-----|-----|-----|" << endl;
cout << "0----58----107---132---210---304---380 km\n\n";
cout << "Tank capacity: " << tank << endl << endl;
int usedGas = tank;
for(int i = 0; i <= n - 1; ++i){
usedGas -= gasStation[i];
distanceTravelled += gasStation[i];
if(usedGas < gasStation[i + 1]){
cout << "Stopping at gas station located at km " << distanceTravelled << endl;
usedGas = tank;
refill++;
}
}
cout << "\nThe driver must stop to refill " << refill << " times"<< endl;
refill = 0;
return 0;
}
<file_sep>/Homework 5 - Computational Geometry/argo.h
#ifndef ARGO_H
#define ARGO_H
#include <QDialog>
namespace Ui {
class argo;
}
class argo : public QDialog
{
Q_OBJECT
public:
explicit argo(QWidget *parent = nullptr);
~argo();
private:
Ui::argo *ui;
};
#endif // ARGO_H
<file_sep>/Project 2 - Graphs Algorithms/README.md
Busque en Internet las bibliotecas para la implementación de grafos (Boost Graph Library y SNAP) e implemente un programa que haciendo uso de cada biblioteca permita:
Insertar vértices en el grafo
Insertar arista en el grafo
Eliminar vértices del grafo
Eliminar aristas del grafo
Realizar un recorrido en profundidad (DFS)
Realizar un recorrido en amplitud (BFS)
Obtener el árbol de recubrimiento mínimo correspondiente utilizando el algoritmo de Prim
Obtener el árbol de recubrimiento mínimo correspondiente utilizando el algoritmo de Kruskal
Determinar la ruta mínima para llegar de un vértice origen a todos los demás vértices del grafo (Dijkstra)
Determinar la ruta mínima para llegar de cualquier vértice origen a todos los demás vértices del grafo (Floyd-Warshall)
Posteriormente modele en cada programa el grafo que aparece a continuación y mida los tiempos de ejecución de la implementación de cada algoritmo (de los anteriores) utilizando cada una de las bibliotecas tanto en su laptop como en una RPi. Para cada uno de los algoritmos utilizados, analice su complejidad temporal y espacial.
Finalmente, genere un reporte como resultado de la investigación donde analice los resultados obtenidos y en caso de haber diferencias entre los tiempos de ejecución utilizando una biblioteca u otra, realice una reflexión personal donde mencione con sus palabras cuáles son los factores que ocasionan dichas diferencias de tiempo.
Como parte de la respuesta de este ejercicio debe incluir en el reporte de investigación, lo siguiente:
Tabla con los tiempos de ejecución de cada algoritmo utilizado de cada biblioteca, tanto en la RPi como en la laptop / escritorio.
Para cada algoritmo, una gráfica comparativa con sus tiempos de ejecución en la RPi y en la laptop / escritorio para cada biblioteca.
Análisis e interpretación de los resultados (con sus palabras).
| 6a155b7d60765dc778704ceb06766c6c334a7468 | [
"C#",
"C",
"C++",
"Markdown"
] | 34 | C++ | dvigleo/algorithms-design | c4e73129ee240fb4b8c51f8bb788869096f7d281 | 3a60607b1fdd0c7612209f944b162110f45d99d8 | |
refs/heads/master | <repo_name>jazzyshi/WEIFUWU<file_sep>/sysprovider/src/main/java/com/weifuwu/sysprovider/SysServiceImpl.java
package com.weifuwu.sysprovider;
import com.weifuwu.sysapi.SysService;
/**
* Created by jzshi on 2018/12/21.
*/
public class SysServiceImpl implements SysService {
@Override
public String getPersonInfo() {
return null;
}
}
<file_sep>/sysapi/src/main/java/com/weifuwu/sysapi/SysService.java
package com.weifuwu.sysapi;
/**
* Created by jzshi on 2018/12/21.
*/
public interface SysService {
String getPersonInfo1();
String testlocal();
String testlocal1();
}
| d55ad73d321a570a66d1661d836c8501b7186aad | [
"Java"
] | 2 | Java | jazzyshi/WEIFUWU | ae644a4c9fc0b29bf8c48c728b17af92907fb262 | ae944255126813b26091c9760a6e0048688a44ba | |
refs/heads/master | <file_sep>package com.naive.toosimple.dao;
import com.naive.toosimple.domain.entity.Author;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AuthorDao {
int add(Author author);
int update(Author author);
int delete(Long id);
Author findAuthor(Long id);
List<Author> findAuthorList();
}
<file_sep># springboot-mysql-jdbc
sample of spring-boot-jdbc
use manually dataSource ctrl and jdbc data persistence
尝试手动配置数据源的jdbc案例
| a5d9df5cea88dac550eaa91d98c2298052f8d92c | [
"Markdown",
"Java"
] | 2 | Java | KeanuAscent/springboot-mysql-jdbc | 4e16f83a5d29be1d3803ad241c00785249754593 | 77da9df120f6c3ad2cbd3b807c4e43e81f3f60f8 | |
refs/heads/master | <repo_name>geyaowei/kafak-test<file_sep>/src/main/java/kafka/ProducerInstance.java
package kafka;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import java.util.Properties;
public class ProducerInstance {
public Producer<String, String> producer;
public ProducerInstance(Properties props) {
Properties properties = new Properties();
properties.put("bootstrap.servers", props.get("bootstrap.server"));
properties.put("acks", "all");
properties.put("retries", 0);
properties.put("batch.size", 16384);
properties.put("linger.ms", 1);
properties.put("buffer.memory", 33554432);
properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
producer = new KafkaProducer<String, String>(properties);
}
public void close(){
this.producer.close();
}
}
<file_sep>/src/main/java/kafka/ConsumerInstance.java
package kafka;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.Producer;
import java.util.Arrays;
import java.util.Properties;
public class ConsumerInstance {
/**
* 自动提交offset
* @param prop
*/
public static KafkaConsumer<String, String> autoSubmitOffset(Properties prop) {
Properties props = new Properties();
//必须要加,如果要读旧数据.默认是largest
props.put("auto.offset.reset", "smallest");
/* 定义kakfa 服务的地址,不需要将所有broker指定上 */
props.put("bootstrap.servers", prop.get("bootstrap.server"));
/* 制定consumer group */
props.put("group.id", "test1");
/* 是否自动确认offset */
props.put("enable.auto.commit", "true");
/* 自动确认offset的时间间隔 */
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
/* key的序列化类 */
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
/* value的序列化类 */
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("test"));
return consumer;
}
/**
* 手动提交offset
* @param prop
*/
public static KafkaConsumer<String, String> manualSubmitOffset(Properties prop) {
Properties props = new Properties();
/* 定义kakfa 服务的地址,不需要将所有broker指定上 */
props.put("bootstrap.servers", prop.get("bootstrap.server"));
/* 制定consumer group */
props.put("group.id", "test1");
/* 是否自动确认offset */
props.put("enable.auto.commit", "false");
/* 自动确认offset的时间间隔 */
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
/* key的序列化类 */
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
/* value的序列化类 */
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("test"));
return consumer;
}
}
| 3612cdb38518869196a78106d49951da4aa6653d | [
"Java"
] | 2 | Java | geyaowei/kafak-test | a2bbb9ce73ba33feb1717466ebc01762719aa8f2 | 798bc344b9f9caecc4c9f7b736ed1cd35c66d348 | |
refs/heads/master | <file_sep>package com.spm.projectws.controller;
import com.spm.projectws.model.FileDetails;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
/**
*
* @author IT17119122
*/
@RestController
@CrossOrigin
public class FileReadAndWriteController {
@RequestMapping(value = "/sendfile", method = RequestMethod.POST)
public ResponseEntity<Object> getFile(@RequestParam("file") MultipartFile file){
FileDetails fileDetails = new FileDetails();
try {
fileDetails.setFile(file.getBytes());
String s = new String(fileDetails.getFile());
System.out.println("TTTTTTTTTTTTTTTTTTTTTTTTTT: " + s);
System.out.println(fileDetails.getFile());
return new ResponseEntity<>(fileDetails, HttpStatus.OK);
} catch (IOException ex) {
Logger.getLogger(FileReadAndWriteController.class.getName()).log(Level.SEVERE, null, ex);
return new ResponseEntity<>(HttpStatus.OK);
}
}
}
| 04e29266c473f62d8a4565f795dc92ede3692aa0 | [
"Java"
] | 1 | Java | shainitenuwara/Program-complexity-measurement-tool | 69bdfb1ad56f2333962a9ce0ccfe13c5ae3a80cb | 330fa6f0b8f24d1cd930535b40b7a52ac5655222 | |
refs/heads/main | <file_sep># dddd
xiaojiba
<file_sep>package com.test.selfstudyroom.entity;
public class Admins {
private String user_name;
private String passwords;
public String getPasswords() {
return passwords;
}
public void setPasswords(String passwords) {
this.passwords = passwords;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
<file_sep>package com.test.selfstudyroom.service;
import com.test.selfstudyroom.entity.Order;
import java.util.List;
public interface OrderService {
public List<Order> selectAll (int before, int after);
public int findOrderCount();
public Order selectById(String id);
public int delById(String id);
public int deleteBatch(List<String> ids);
}
<file_sep>package com.test.selfstudyroom.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.selfstudyroom.entity.Opinion;
import com.test.selfstudyroom.service.OpinionService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
public class OpinionController {
@Autowired
private OpinionService opinionService;
/*查询所有*/
@GetMapping("/selectAllOpinion")
@ResponseBody
public String selectAll(@RequestParam(value = "page",required = true) int page,
@RequestParam(value = "limit",required = true) int limit){
int before = limit*(page-1);
int after = page*limit;
List<Opinion> opinions= opinionService.selectAll(before,after);
int count= opinionService.findOpinionCount();
JSONArray json = JSONArray.fromObject(opinions);
String js=json.toString();
String jso="{\"code\":0,\"msg\":\"\",\"count\":"+count+",\"data\":"+js+"}";
for (Opinion it:opinions){
System.out.println(it.toString());
}
return jso;
}
/*根据id查找*/
@RequestMapping(value = "/findOpinion",method = RequestMethod.GET)
@ResponseBody
public String selectById(@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit,
@RequestParam(value = "username") String id){
int before = limit*(page-1)+1;
int after = page*limit;
if(id.isEmpty()) return selectAll(before,after);
int b = Integer.valueOf(id).intValue();
Opinion opinion =opinionService.selectById(b);
String js=null,jso;
if (opinion!=null){
JSONArray json= JSONArray.fromObject(opinion);
js=json.toString();
jso="{\"code\":0,\"msg\":\"\",\"count\":"+1+",\"data\":"+js+"}";
}
else {
jso="{\"code\":0,\"msg\":\"\",\"count\":"+0+",\"data\":"+js+"}";
}
return jso;
}
@PostMapping("/deleteOpinion")
public String delById(@RequestParam(value = "student_id") String id){
int b = Integer.valueOf(id).intValue();
int a=opinionService.delById(b);
if (a>0){
System.out.println("删除成功");
return "OK";
}
else {
System.out.println("删除失败");
return "NO";
}
}
@PostMapping("/deleteBatchOpinion")
public String deleteBatch(@RequestParam(value = "list") String list) throws JsonProcessingException {
//创建jackson对象
ObjectMapper mapper = new ObjectMapper();
//使用Jackson将json转为List<User>
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class,String.class);
List<String> delIds = (List<String>) mapper.readValue(list, javaType);
List<Integer> nums = new ArrayList<>();
for (String x : delIds) {
Integer z = Integer.parseInt(x);
System.out.println(z);
nums.add(z);
}
int i= opinionService.deleteBatch(nums);
if (i>0){
System.out.println("删除成功");
return "OK";
}
else {
System.out.println("删除失败");
return "NO";
}
}
}
<file_sep>package com.test.selfstudyroom.entity;
public class Opinion {
private int student_id;
private String content;
private String release_date;
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
}
<file_sep>package com.test.selfstudyroom.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.selfstudyroom.entity.Opinion;
import com.test.selfstudyroom.entity.Order;
import com.test.selfstudyroom.service.OrderService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
public class OrderCOntroller {
@Autowired
private OrderService orderService;
/*查询所有*/
@GetMapping("/selectAllOrder")
@ResponseBody
public String selectAll(@RequestParam(value = "page",required = true) int page,
@RequestParam(value = "limit",required = true) int limit){
int before = limit*(page-1);
int after = page*limit;
List<Order> Orders= orderService.selectAll(before,after);
int count= orderService.findOrderCount();
JSONArray json = JSONArray.fromObject(Orders);
String js=json.toString();
String jso="{\"code\":0,\"msg\":\"\",\"count\":"+count+",\"data\":"+js+"}";
for (Order it:Orders){
System.out.println(it.toString());
}
return jso;
}
/*根据id查找*/
@RequestMapping(value = "/findOrder",method = RequestMethod.GET)
@ResponseBody
public String selectById(@RequestParam(value = "page") int page,
@RequestParam(value = "limit") int limit,
@RequestParam(value = "username") String id){
int before = limit*(page-1)+1;
int after = page*limit;
if(id.isEmpty()) return selectAll(before,after);
// int b = Integer.valueOf(id).intValue();
Order Order =orderService.selectById(id);
String js=null,jso;
if (Order!=null){
JSONArray json= JSONArray.fromObject(Order);
js=json.toString();
jso="{\"code\":0,\"msg\":\"\",\"count\":"+1+",\"data\":"+js+"}";
}
else {
jso="{\"code\":0,\"msg\":\"\",\"count\":"+0+",\"data\":"+js+"}";
}
return jso;
}
@PostMapping("/deleteOrder")
public String delById(@RequestParam(value = "order_id") String id){
// int b = Integer.valueOf(id).intValue();
int a=orderService.delById(id);
if (a>0){
System.out.println("删除成功");
return "OK";
}
else {
System.out.println("删除失败");
return "NO";
}
}
@PostMapping("/deleteBatchOrder")
public String deleteBatch(@RequestParam(value = "list") String list) throws JsonProcessingException {
//创建jackson对象
ObjectMapper mapper = new ObjectMapper();
//使用Jackson将json转为List<User>
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class,String.class);
List<String> delIds = (List<String>) mapper.readValue(list, javaType);
for (String x : delIds) {
// Integer z = Integer.parseInt(x);
System.out.println(x);
// nums.add(x);
}
int i= orderService.deleteBatch(delIds);
if (i>0){
System.out.println("删除成功");
return "OK";
}
else {
System.out.println("删除失败");
return "NO";
}
}
}
<file_sep>package com.test.selfstudyroom.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.selfstudyroom.entity.RoomEntity;
import com.test.selfstudyroom.service.RoomService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class RoomController {
@Autowired
private RoomService roomService;
/**
* 添加教室
* @param room_id
* @param room_state
* @param room_number
* @param room_address
* @param room_time
* @return
*/
@RequestMapping(value = "/addRoom",method=RequestMethod.POST)
@ResponseBody
public Map<String, String> RoomEntitySubmit(@RequestParam(value = "id",required = true) String room_id,
@RequestParam(value = "static",required = true) String room_state,
@RequestParam(value = "member") String room_number,
@RequestParam(value = "address") String room_address,
@RequestParam(value = "time") String room_time
){
Map<String, String> ret = new HashMap<String, String>();
System.out.println(room_id);
System.out.println(room_state);
System.out.println(room_number);
System.out.println(room_address);
System.out.println(room_time);
RoomEntity roomEntity = new RoomEntity();
roomEntity.setRoom_id(room_id);
if(room_state.equals("启用")){
roomEntity.setState(true);
}
if(room_state.equals("禁用")){
roomEntity.setState(false);
}
roomEntity.setRoom_num(room_number);
roomEntity.setRoom_address(room_address);
roomEntity.setRoom_time(room_time);
System.out.println(roomEntity.toString());
if(roomService.findRoomById(room_id)!=null){
ret.put("type", "error");
ret.put("msg", "该员工ID已注册,添加失败");
return ret;
}
if(roomService.addRoom(roomEntity)<=0){
ret.put("type", "error");
ret.put("msg", "员工信息添加失败");
return ret;
}
ret.put("type", "success");
ret.put("msg", "员工信息添加成功");
return ret;
}
/**
* 更新教室信息
* @param oldRoomId
* @param room_id
* @param room_state
* @param room_number
* @param room_address
* @param room_time
* @return
*/
@RequestMapping(value = "/updateRoom",method = RequestMethod.POST)
@ResponseBody
public Map<String, String> updateRoom(
@RequestParam(value = "oldRoomId",required = true) String oldRoomId,
@RequestParam(value = "id",required = true) String room_id,
@RequestParam(value = "static",required = true) String room_state,
@RequestParam(value = "member") String room_number,
@RequestParam(value = "address") String room_address,
@RequestParam(value = "time") String room_time
){
Map<String, String> ret = new HashMap<>();
RoomEntity newRoom = new RoomEntity();
newRoom.setRoom_id(room_id);
newRoom.setRoom_time(room_time);
newRoom.setRoom_num(room_number);
newRoom.setRoom_address(room_address);
if(room_state.equals("启用"))
newRoom.setState(true);
if(room_state.equals("禁用"))
newRoom.setState(false);
System.out.println(oldRoomId);
System.out.println(newRoom.toString());
if(roomService.updateRoom(oldRoomId,newRoom)<=0){
ret.put("type", "error");
ret.put("msg", "该教室更新数据失败");
return ret;
}
ret.put("type", "success");
ret.put("msg", "该教室更新数据成功");
return ret;
}
/**
* 查找所有的教室
* @return
*/
@RequestMapping(value = "/findRooms",method = RequestMethod.GET)
@ResponseBody
public String findRooms(
@RequestParam(value = "page",required = true) int page,
@RequestParam(value = "limit",required = true) int limit){
int before = limit*(page-1);
int after = page*limit;
List<RoomEntity> sum=roomService.findRooms(before,after);
int count = roomService.findRoomsCount();
JSONArray json=JSONArray.fromObject(sum);
String js=json.toString();
String jso="{\"code\":0,\"msg\":\"\",\"count\":"+count+",\"data\":"+js+"}";
for(RoomEntity it:sum){
System.out.println(it.toString());
}
return jso;
}
/**
*删除教室ById
* @param room_id
* @return
*/
@RequestMapping(value = "/deleteRoom",method = RequestMethod.POST)
@ResponseBody
public Map<String, String> deleteRoom(
@RequestParam(value = "room_id",required = true) String room_id)
{
System.out.println(room_id);
Map<String,String> sum= new HashMap<>();
if(roomService.deleteRoomsById(room_id)<=0){
sum.put("type", "error");
sum.put("msg", "该员工不存在,删除失败");
}else{
sum.put("type", "success");
sum.put("msg", "信息删除成功");
}
return sum;
}
/**
* 删除多个教室
* @param
* @return
*/
@RequestMapping(value = "/deleteRooms",method = RequestMethod.POST)
@ResponseBody
public Map<String, String> deleteRooms(
@RequestParam(value = "ids",required = true) String ids) throws JsonProcessingException {
Map<String, String> ret = new HashMap<>();
//jackson对象
ObjectMapper mapper = new ObjectMapper();
//使用jackson将json转为List<User>
JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, String.class);
List<String> delIds = (List<String>)mapper.readValue(ids, jt);
if(roomService.deleteRooms(delIds)<=0){
ret.put("type", "error");
ret.put("msg", "删除该教室数据失败");
return ret;
}
ret.put("type", "success");
ret.put("msg", "删除"+delIds.size()+"个教室数据成功");
return ret;
}
/**
* 搜寻教室
*/
@RequestMapping(value = "/searchRoom",method = RequestMethod.GET)
@ResponseBody
public String searchRoom(
@RequestParam(value = "page",required = true) int page,
@RequestParam(value = "limit",required = true) int limit,
@RequestParam(value = "username",required = true) String room_id)
{
int before = limit*(page-1)+1;
int after = page*limit;
if(room_id.isEmpty()) return findRooms(before,after);
RoomEntity roomEntity = roomService.findRoomById(room_id);
JSONArray json;
String js=null,jso;
if(roomEntity!=null){
json=JSONArray.fromObject(roomEntity);
js=json.toString();
jso="{\"code\":0,\"msg\":\"\",\"count\":"+1+",\"data\":"+js+"}";
}
else{
jso="{\"code\":0,\"msg\":\"\",\"count\":"+0+",\"data\":"+js+"}";
}
return jso;
}
}
| 4e90c77e1baa3304f6f14f4a3f8eff8253802d45 | [
"Markdown",
"Java"
] | 7 | Markdown | lonelyb/dddd | 84f696c686effacf958bdeb3cb6fdeb07659174f | d8c684edf5b29005868a095b3b96f4e8e14f4c77 | |
refs/heads/main | <file_sep>//
// Models.swift
// LearningApp
//
// Created by <NAME> on 2021-06-30.
//
import Foundation
class Module : Identifiable, Decodable {
var id : Int
var category : String
var content : Content
var test : Test
}
class Content : Decodable, Identifiable {
var id : Int
var image : String
var time: String
var description : String
var lessons : [Lesson]
}
struct Lesson : Decodable, Identifiable {
var id : Int
var title : String
var video : String
var duration : String
var explanation : String
}
struct Test : Decodable, Identifiable {
var id : Int
var image : String
var time : String
var description : String
var questions : [Question]
}
struct Question : Decodable, Identifiable {
var id : Int
var content : String
var correctIndex : Int
var answers : [String]
}
<file_sep>//
// HomeViewRow.swift
// LearningApp
//
// Created by <NAME> on 2021-07-07.
//
import SwiftUI
struct HomeViewRow: View {
var image: String
var title: String
var description: String
var count: String
var time: String
var body: some View {
// Learning Card
ZStack {
Rectangle()
.foregroundColor(.white)
.cornerRadius(10)
.shadow(radius: 5)
.aspectRatio(CGSize(width: 335, height: 175), contentMode: .fit)
HStack(spacing: 30) {
//Image
Image(image)
.resizable()
.frame(width: 120, height: 120, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.clipShape(/*@START_MENU_TOKEN@*/Circle()/*@END_MENU_TOKEN@*/)
// Text
VStack(alignment: .leading, spacing: 10) {
// Headline
Text(title)
.font(.headline)
// Description
Text(description)
.padding(.bottom)
.font(.caption)
// Icons
HStack(spacing: 10) {
HStack(spacing: 3) {
Image(systemName: "book.closed")
Text(count)
.font(Font.system(size: 10))
}
HStack(spacing: 3) {
Image(systemName: "clock")
Text(time)
.font(Font.system(size: 10))
}
}
}
.padding(.horizontal, 10)
}.padding(.horizontal, 20)
}
}
}
struct HomeViewRow_Previews: PreviewProvider {
static var previews: some View {
HomeViewRow(image: "swift", title: "Learn Swift", description: "Some description", count: "20 Lessons", time: "42 hours")
}
}
| 9a6085529b3f5ab2d7b74d570630c3c24ab09240 | [
"Swift"
] | 2 | Swift | LuckyTemitope/LearningApp | 5907749f1a38fbff35a9cfa3642912e0646d0cbc | 96502141883d01b19286da835d47712e0ffe7218 | |
refs/heads/master | <repo_name>Artyko/Cheatmeal<file_sep>/test_DB.py
import pytest
from datetime import datetime, timedelta
from app import app, db
from app.models import User, Recipe
class TestBD:
def setup(self):
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
db.create_all()
def teardown(self):
db.session.remove()
db.drop_all()
def test_password_hashing(self):
u = User(username='susan')
u.set_password('cat')
assert u.check_password('dog') is False
assert u.check_password('cat') is True
def test_add_users(self):
user_1 = User(username='john', email='<EMAIL>')
user_2 = User(username='susan', email='<EMAIL>')
db.session.add(user_1)
db.session.add(user_2)
db.session.commit()
assert user_1.recipe.all() == []
assert user_2.recipe.all() == []
def test_add_and_remove_recipe_to_user(self):
user_1 = User(username='john', email='<EMAIL>')
db.session.add(user_1)
db.session.commit()
recipe_1 = Recipe(title='Strawberry pie')
user_1.add_recipe(recipe_1)
assert user_1.recipe.count() == 1
user_1.remove_recipe(recipe_1)
db.session.commit()
assert user_1.recipe.count() == 0
<file_sep>/app/main/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField
from wtforms.validators import ValidationError, DataRequired, EqualTo, Length
from flask_babel import _, lazy_gettext as _l
from app.models import User
class EditProfileForm(FlaskForm):
username = StringField(_l('Username'), validators=[DataRequired()])
submit = SubmitField(_l('Submit'))
def __init__(self, original_username, *args, **kwargs):
super(EditProfileForm, self).__init__(*args, **kwargs)
self.original_username = original_username
def validate_username(self, username):
if username.data != self.original_username:
user = User.query.filter_by(username=self.username.date)
if user is not None:
raise ValidationError('Please use a different username')
class RecipeForm(FlaskForm):
title = StringField(_l('Recipe name'), validators=[DataRequired()])
ingredients = TextAreaField(_l('Ingredient name'))
description = TextAreaField(_l('Describe your recipe'))
submit = SubmitField(_l('Submit'))
class EmptyForm(FlaskForm):
submit = SubmitField('Submit')
<file_sep>/app/models.py
from datetime import datetime
from app import db, login
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
recipe_ingredient = db.Table('recipe_ingredient',
db.Column('recipe_id', db.Integer, db.ForeignKey('recipe.id')),
db.Column('measure_id', db.Integer, db.ForeignKey('measure.id')),
db.Column('measure_qty_id', db.Integer, db.ForeignKey('measure_qty.id')),
db.Column('ingredient_id', db.Integer, db.ForeignKey('ingredient.id')))
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
recipe = db.relationship('Recipe', backref='user', lazy='dynamic')
def __repr__(self):
return '<User {}>'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
@login.user_loader
def load_user(id):
return User.query.get(int(id))
def show_recipes(self):
return Recipe.query.filter_by(user_id=self.id)
def recipe_exist(self, recipe):
return self.recipe.filter(recipe_ingredient.c.recipe_id == recipe.id).count() > 0
def add_recipe(self, recipe):
if not self.recipe_exist(recipe):
self.recipe.append(recipe)
def remove_recipe(self, recipe):
if not self.recipe_exist(recipe):
self.recipe.remove(recipe)
class Recipe(db.Model):
__tablename__ = 'recipe'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(120))
description = db.Column(db.String(840))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
recipes = db.relationship('Ingredient', secondary=recipe_ingredient,
primaryjoin=(recipe_ingredient.c.recipe_id == id),
secondaryjoin=(recipe_ingredient.c.ingredient_id == id),
backref=db.backref('ingredient', lazy='dynamic'), cascade="all")
def __repr__(self):
return f'<Recipe {self.title}>'
class Measure(db.Model):
__tablename__ = 'measure'
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(120))
recipe_ingredient = db.relationship('Recipe', secondary=recipe_ingredient,
backref=db.backref('recipes_names', lazy='dynamic'), cascade="all")
class MeasureQty(db.Model):
__tablename__ = 'measure_qty'
id = db.Column(db.Integer, primary_key=True)
amount = db.Column(db.Integer)
recipe_ingredient = db.relationship('Recipe', secondary=recipe_ingredient,
backref=db.backref('recipes_1', lazy='dynamic'), cascade="all")
class Ingredient(db.Model):
__tablename__ = 'ingredient'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120))
calories = db.Column(db.Integer)
recipe_ingredient = db.relationship('Recipe', secondary=recipe_ingredient,
backref=db.backref('recipes_2', lazy='dynamic'), cascade="all")
<file_sep>/migrations/versions/51f732aa5466_.py
"""empty message
Revision ID: <KEY>
Revises: <KEY>
Create Date: 2020-12-25 21:47:27.090205
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('ingredient',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=120), nullable=True),
sa.Column('calories', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('measure',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('description', sa.String(length=120), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('measure_qty',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('amount', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('recipe',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=120), nullable=True),
sa.Column('description', sa.String(length=840), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_recipe_timestamp'), 'recipe', ['timestamp'], unique=False)
op.create_table('recipe_ingredient',
sa.Column('recipe_id', sa.Integer(), nullable=True),
sa.Column('measure_id', sa.Integer(), nullable=True),
sa.Column('measure_qty_id', sa.Integer(), nullable=True),
sa.Column('ingredient_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['ingredient_id'], ['ingredient.id'], ),
sa.ForeignKeyConstraint(['measure_id'], ['measure.id'], ),
sa.ForeignKeyConstraint(['measure_qty_id'], ['measure_qty.id'], ),
sa.ForeignKeyConstraint(['recipe_id'], ['recipe.id'], )
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('recipe_ingredient')
op.drop_index(op.f('ix_recipe_timestamp'), table_name='recipe')
op.drop_table('recipe')
op.drop_table('measure_qty')
op.drop_table('measure')
op.drop_table('ingredient')
# ### end Alembic commands ###
<file_sep>/README.md
# Cheatmeal
A cookbook for awesome recipes
<file_sep>/app/main/routes.py
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, g, current_app
from flask_login import current_user, login_required
from flask_babel import _, get_locale
from app import db
from app.main.forms import EditProfileForm, RecipeForm
from app.models import User, Recipe
from app.main import bp
@bp.before_request
def before_request():
if current_user.is_authenticated:
current_user.last_seen = datetime.utcnow()
db.session.commit()
g.locale = str(get_locale())
@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
@login_required
def index():
form = RecipeForm()
if form.validate_on_submit():
recipe = Recipe(title=form.title.data,
description=form.description.data,
user_id=current_user.id)
db.session.add(recipe)
db.session.commit()
flash(_('Your recipe is now live!'))
return redirect(url_for('main.index'))
page = request.args.get('page', 1, type=int)
recipes = current_user.show_recipes().paginate(
page, current_app.config['RECIPES_PER_PAGE'], False)
next_url = url_for('main.index', page=recipes.next_num) \
if recipes.has_next else None
prev_url = url_for('main.index', page=recipes.prev_num) \
if recipes.has_prev else None
return render_template('index.html', title='Home',
form=form, recipes=recipes.items,
next_url=next_url, prev_url=prev_url)
@bp.route('/user/<username>')
@login_required
def user(username):
user = User.query.filter_by(username=username).first_or_404()
page = request.args.get('page', 1, type=int)
recipes = user.recipe.order_by(Recipe.timestamp.desc()).paginate(
page, current_app.config['RECIPES_PER_PAGE'], False)
next_url = url_for('main.user', page=recipes.next_num) \
if recipes.has_next else None
prev_url = url_for('main.user', page=recipes.prev_num) \
if recipes.has_prev else None
return render_template('user.html', user=user, recipes=recipes.items,
next_url=next_url, prev_url=prev_url)
@bp.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(current_user.username)
if form.validate_on_submit():
current_user.username = form.username.data
db.session.commit()
flash(_('Your changes have been saved.'))
return redirect(url_for('main.edit_profile'))
elif request.method == 'GET':
form.username.data = current_user.username
return render_template('edit_profile.html', title=_('Edit Profile'),
form=form)
@bp.route('/explore')
@login_required
def explore():
page = request.args.get('page', 1, type=int)
recipes = Recipe.query.order_by(Recipe.timestamp.desc()).paginate(
page, current_app.config['RECIPES_PER_PAGE'], False)
next_url = url_for('main.index', page=recipes.next_num) \
if recipes.has_next else None
prev_url = url_for('main.index', page=recipes.prev_num) \
if recipes.has_prev else None
return render_template('index.html', title=_('Explore'), recipes=recipes.items,
next_url=next_url, prev_url=prev_url)
<file_sep>/requirements.txt
alembic==1.4.3
attrs==20.3.0
Babel==2.9.0
click==7.1.2
dominate==2.6.0
Flask==1.1.2
Flask-Babel==2.0.0
Flask-Bootstrap==3.3.7.1
Flask-Login==0.5.0
Flask-Migrate==2.5.3
Flask-Moment==0.11.0
Flask-SQLAlchemy==2.4.4
Flask-WTF==0.14.3
importlib-metadata==3.4.0
iniconfig==1.1.1
itsdangerous==1.1.0
Jinja2==2.11.2
Mako==1.1.3
MarkupSafe==1.1.1
packaging==20.8
pluggy==0.13.1
py==1.10.0
pyparsing==2.4.7
pytest==6.2.2
python-dateutil==2.8.1
python-editor==1.0.4
pytz==2021.1
six==1.15.0
SQLAlchemy==1.3.22
toml==0.10.2
typing-extensions==3.7.4.3
visitor==0.1.3
Werkzeug==1.0.1
WTForms==2.3.3
zipp==3.4.0
python-dotenv~=0.15.0 | 85b92c686a8717a67be31a499f6e7a87f5f74f1a | [
"Markdown",
"Python",
"Text"
] | 7 | Python | Artyko/Cheatmeal | b043fd05120aafceb58f2d173e2215fc352777e4 | 290692025772beb76f4662672001274dc22ebade | |
refs/heads/master | <file_sep>import { ActionModel } from '../actions/actions.model'
export interface DogModel {
id: number
name: string
breed: string
age: number
actionIds: number[]
actions?: ActionModel[]
}
<file_sep>import morgan from 'morgan'
import { Request, Response, NextFunction } from 'express'
import { LoggerStream } from 'Src/pkg/log/log'
let format: string | null = null
export function morganLoggerMiddleware(
req: Request,
res: Response,
next: NextFunction,
): Function {
if (!format) {
format = process.env.NODE_ENV === 'production' ? 'combined' : 'tiny'
}
return morgan(format, { stream: new LoggerStream() })(req, res, next)
}
<file_sep>FROM node:10.16.0-alpine
WORKDIR /app
COPY . ./
RUN yarn
EXPOSE 8000<file_sep>interface ActionEntity {
id: number
name: string
}
const actions: ActionEntity[] = [
{ id: 1, name: 'sit' },
{ id: 2, name: 'bark' },
{ id: 3, name: 'salute' },
{ id: 4, name: 'stand' },
{ id: 5, name: 'jump' },
{ id: 6, name: 'roll' },
{ id: 7, name: 'crawl' },
]
type FindAllResponse = Array<ActionEntity>
type FindByIdResponse = ActionEntity
export class ActionsRepository {
findAll(): FindAllResponse {
return actions
}
findById(id: number): FindByIdResponse | null {
const action = actions.find((a) => a.id === id)
if (!action) {
return null
}
return action
}
}
<file_sep>import { DogsService } from './dog.service'
import { DogsRepository } from '../storage/memory/dog.repository'
import { ActionsRepository } from '../storage/memory/actions.repository'
import { DogModel } from './dog.model'
describe('DogsService', () => {
let dogsService: DogsService
beforeEach(() => {
const actionsRepository = new ActionsRepository()
const dogsRepository = new DogsRepository()
dogsService = new DogsService(actionsRepository, dogsRepository)
})
it('should be defined', () => {
expect(dogsService).toBeDefined()
})
describe('getAll', () => {
it('On success: should return a list of dogs', () => {
const response = dogsService.getAll()
const objectMatcher: DogModel = {
id: expect.any(Number),
name: expect.any(String),
breed: expect.any(String),
age: expect.any(Number),
actionIds: expect.arrayContaining([expect.any(Number)]),
}
expect(response).toBeTruthy()
expect(response).toHaveProperty('length')
expect(response.length).toBeGreaterThan(0)
expect(response[0]).toMatchObject(objectMatcher)
})
})
})
<file_sep>module.exports = {
arrowParens: 'always',
bracketSpacing: true,
endOfLine: 'lf',
inserPragma: false,
printWidth: 80,
quoteProps: 'consistent',
requirePragma: false,
semi: false,
singleQuote: true,
tabWidth: 2,
trailingComma: 'all',
useTabs: true,
}
<file_sep>import { Express } from 'express'
import request from 'supertest'
import { bootstrapRestServer } from '../../src/cmd/server/rest'
describe.only('REST: Actions', () => {
let app: Express
beforeAll(async () => {
app = await bootstrapRestServer()
})
describe('GET: /api/actions', () => {
it('on success: should return a list of actions', async () => {
const response = await request(app).get('/api/actions')
console.log(response.body)
const itemsMatcher = {
items: expect.arrayContaining([
expect.objectContaining({
id: expect.any(Number),
name: expect.any(String),
}),
]),
}
expect(response.status).toBe(200)
expect(response.body.count).toBeGreaterThanOrEqual(0)
expect(response.body.items).toMatchObject(itemsMatcher.items)
})
})
})
<file_sep>import { Express } from 'express'
import { DogsRepository } from 'Src/pkg/storage/memory/dog.repository'
import { DogsService } from 'Src/pkg/dogs/dog.service'
import { createRestServer } from 'Src/pkg/http/rest'
import { ActionsRepository } from 'Src/pkg/storage/memory/actions.repository'
import { ActionsService } from 'Src/pkg/actions/actions.service'
export async function bootstrapRestServer(): Promise<Express> {
const actionsRepository = new ActionsRepository()
const dogsRepository = new DogsRepository()
const actionsService = new ActionsService(actionsRepository)
const dogService = new DogsService(actionsRepository, dogsRepository)
const server = createRestServer(actionsService, dogService)
return server
}
bootstrapRestServer()
.then((server) =>
server.listen(3000, () => {
console.log('server listening on port: 3000')
}),
)
.catch((error) => console.log(error))
<file_sep>import { Request, Response, NextFunction } from 'express'
import { logger } from 'Src/pkg/log/log'
export function routeNotFoundMiddleware(
req: Request,
res: Response,
next: NextFunction, // eslint-disable-line
): Response {
logger.info(`Route: ${req.originalUrl}, not found`)
return res.status(404).send("Sorry can't find that!") // eslint-disable-line
}
<file_sep>interface DogEntity {
id: number
name: string
breed: string
age: number
actionIds: number[]
}
const dogs: DogEntity[] = [
{
id: 1,
name: 'Stormy',
breed: '<NAME>',
age: 6,
actionIds: [2, 3],
},
{
id: 2,
name: 'Stormy',
breed: '<NAME>',
age: 9,
actionIds: [1, 2, 3, 4, 5, 6],
},
]
type FindAllResponse = Array<DogEntity>
type FindByIdResponse = DogEntity
export class DogsRepository {
public findAll(): FindAllResponse {
return dogs
}
public findById(id: number): FindByIdResponse | null {
const dog = dogs.find((d) => d.id === id)
if (!dog) {
return null
}
return dog
}
}
<file_sep>import { ErrorRequestHandler, Request, Response, NextFunction } from 'express'
import { logger } from 'Src/pkg/log/log'
export function errorHandlerMiddleware(
err: ErrorRequestHandler,
req: Request,
res: Response,
next: NextFunction, // eslint-disable-line
): Response {
logger.error(err)
return res.status(500).send(err)
}
<file_sep>FROM node:10.12.0-alpine as base
WORKDIR /app
COPY package.json yarn.lock babel.config.js tsconfig.json ./
RUN yarn
COPY src /app/src
RUN yarn build
FROM node:10.12.0-alpine
COPY package.json yarn.lock ./
RUN yarn --production
COPY --from=base /app/dist /app/dist
EXPOSE 8000
<file_sep>import { Router, Request, Response } from 'express'
import { DogsService } from 'Src/pkg/dogs/dog.service'
function getAllDogsHandler(dogsService: DogsService) {
return (req: Request, res: Response) => {
const dogs = dogsService.getAll()
return res.json({
count: dogs.length,
items: dogs,
})
}
}
function getActionsByDog(dogsService: DogsService) {
return (req: Request, res: Response) => {
const params = req.params as { dogId: string }
if (!params.dogId) {
return res.status(400).json({
error: 'BAD REQUEST',
message: 'Missing dog ID in params',
})
}
const actions = dogsService.getActionsByDog(parseInt(params.dogId, 10))
if (!actions) {
return res.status(404).json({
error: 'NOT FOUND',
message: 'The dog with the specified id does not exist',
})
}
return res.json({
data: actions,
})
}
}
export function createDogsHandler(
router: Router,
dogsService: DogsService,
): void {
router.get('/api/dogs', getAllDogsHandler(dogsService))
router.get('/api/dogs/:dogId/actions', getActionsByDog(dogsService))
}
<file_sep>import { Router, Request, Response } from 'express'
import { ActionsService } from 'Src/pkg/actions/actions.service'
function getAllActionsHandler(actionsService: ActionsService) {
return (req: Request, res: Response) => {
const actions = actionsService.getAll()
return res.json({
count: actions.length,
items: actions,
})
}
}
export function createActionsHandler(
router: Router,
actionsService: ActionsService,
): void {
router.get('/api/actions', getAllActionsHandler(actionsService))
}
<file_sep># Express Boilerplate App
## A simple express app for quickly getting started with new projects
- Simple folder/project structure
- Dockerfiles and docker-compose for quick starting the app
- Editor and prettier config files for code styling
- Vscode config file
- Typescript 3.5
- Babel 7
- Testing with Jest
- Logging with Winston
## Useful commands
1. yarn dev: build in development and watch for changes with nodemon
2. yarn build: build the app and output it to the dist folder
3. yarn test: run jest
4. yarn type-check: use typescript type checks
<file_sep>import { ActionsRepository } from 'Src/pkg/storage/memory/actions.repository'
import { DogsRepository } from 'Src/pkg/storage/memory/dog.repository'
import { ActionModel } from '../actions/actions.model'
import { DogModel } from './dog.model'
export class DogsService {
constructor(
private readonly actionsRepository: ActionsRepository,
private readonly dogsRepository: DogsRepository,
) {}
private makeDog(data: any): DogModel {
return {
id: data.id,
name: data.name,
breed: data.breed,
age: data.age,
actionIds: data.actionIds,
}
}
public getAll(): DogModel[] {
const dogs = this.dogsRepository.findAll()
return dogs.map((d) => this.makeDog(d))
}
public getActionsByDog(id: number): ActionModel[] | null {
const dog = this.dogsRepository.findById(id)
if (!dog) {
return null
}
const actions = this.actionsRepository.findAll()
const response = actions.filter((a) => dog.actionIds.includes(a.id))
return response
}
}
<file_sep>import { Request, Response, NextFunction } from 'express'
export function noSniffMiddleware(
req: Request,
res: Response,
next: NextFunction,
): void {
res.setHeader('X-Content-Type-Options', 'nosniff')
next()
}
<file_sep>import { ActionsService } from './actions.service'
import { ActionsRepository } from '../storage/memory/actions.repository'
import { ActionModel } from './actions.model'
describe('ActionsService', () => {
let actionsService: ActionsService
beforeEach(() => {
const actionsRepository = new ActionsRepository()
actionsService = new ActionsService(actionsRepository)
})
it('Should be defined', () => {
expect(actionsService).toBeDefined()
})
describe('getAll', () => {
it('On success: should return a list of actions', () => {
const response = actionsService.getAll()
const objectMatcher: ActionModel = {
id: expect.any(Number),
name: expect.any(String),
}
expect(response).toBeTruthy()
expect(response).toHaveProperty('length')
expect(response.length).toBeGreaterThan(0)
expect(response[0]).toMatchObject(objectMatcher)
})
})
})
<file_sep>import { ActionsRepository } from 'Src/pkg/storage/memory/actions.repository'
import { ActionModel } from './actions.model'
export class ActionsService {
constructor(private readonly actionsRepository: ActionsRepository) {}
getAll(): ActionModel[] {
return this.actionsRepository.findAll()
}
}
<file_sep>import express, { Express } from 'express'
import cors from 'cors'
import helmet from 'helmet'
import { DogsService } from 'Src/pkg/dogs/dog.service'
import { createDogsHandler } from './handlers/dog.handler'
import { ActionsService } from 'Src/pkg/actions/actions.service'
import { createActionsHandler } from './handlers/actions.handler'
import { noSniffMiddleware } from 'Src/pkg/http/middleware/noSniff'
// eslint-disable-next-line max-len
import { morganLoggerMiddleware } from 'Src/pkg/http/middleware/morgan'
// eslint-disable-next-line max-len
import { errorHandlerMiddleware } from 'Src/pkg/http/middleware/error'
// eslint-disable-next-line max-len
import { routeNotFoundMiddleware } from 'Src/pkg/http/middleware/routeNotFound'
export function createRestServer(
actionsService: ActionsService,
dogsService: DogsService,
): Express {
const app = express()
app.use(cors())
app.use(helmet())
app.use(noSniffMiddleware)
app.use(morganLoggerMiddleware)
const router = express.Router()
createDogsHandler(router, dogsService)
createActionsHandler(router, actionsService)
app.use('/', router)
app.use(errorHandlerMiddleware)
app.use(routeNotFoundMiddleware)
return app
}
| 114a3d58f59a3987cd96b251f61ec790d3542ab3 | [
"JavaScript",
"TypeScript",
"Dockerfile",
"Markdown"
] | 20 | TypeScript | javier-gs00/express_boilerplate | b42735d3a4f49ae2d99560a10de1d4494cd448e1 | 48d5250a8cc128fef0b8b747c02353f187db049c | |
refs/heads/master | <file_sep>// Copyright(c) 2015-2020, NVIDIA CORPORATION. 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.
#include <cassert>
#include <algorithm>
#include <fstream>
#include <functional>
#include <iterator>
#include <exception>
#include <regex>
#include <iterator>
#include "VulkanHppGenerator.hpp"
void appendArgumentCount(std::string & str, size_t vectorIndex, std::string const& vectorName, std::string const& counterName, size_t returnParamIndex, size_t templateParamIndex, bool twoStep, bool singular);
std::string appendFunctionBodyEnhancedLocalReturnVariableSingular(std::string & str, std::string const& indentation, std::string const& returnName, std::string const& typeName, bool isStructureChain);
void appendReinterpretCast(std::string & str, bool leadingConst, std::string const& type, bool trailingPointerToConst);
void appendTypesafeStuff(std::string &str, std::string const& typesafeCheck);
void appendVersionCheck(std::string & str, std::string const& version);
bool beginsWith(std::string const& text, std::string const& prefix);
bool endsWith(std::string const& text, std::string const& postfix);
void check(bool condition, int line, std::string const& message);
void checkAttributes(int line, std::map<std::string, std::string> const& attributes, std::map<std::string, std::set<std::string>> const& required, std::map<std::string, std::set<std::string>> const& optional);
void checkElements(int line, std::vector<tinyxml2::XMLElement const*> const& elements, std::map<std::string, bool> const& required, std::set<std::string> const& optional = {});
void cleanup(std::stringstream & ss);
std::string constructArraySize(std::vector<std::string> const& sizes);
std::string constructStandardArray(std::string const& type, std::vector<std::string> const& sizes);
std::string createEnumValueName(std::string const& name, std::string const& prefix, std::string const& postfix, bool bitmask, std::string const& tag);
std::string createSuccessCode(std::string const& code, std::set<std::string> const& tags);
std::string determineCommandName(std::string const& vulkanCommandName, std::string const& firstArgumentType);
std::set<size_t> determineSkippedParams(size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices);
bool determineStructureChaining(std::string const& structType, std::set<std::string> const& extendedStructs, std::map<std::string, std::string> const& structureAliases);
std::string extractTag(int line, std::string const& name, std::set<std::string> const& tags);
std::string findTag(std::set<std::string> const& tags, std::string const& name, std::string const& postfix = "");
std::pair<bool, std::string> generateFunctionBodyStandardReturn(std::string const& returnType);
std::map<std::string, std::string> getAttributes(tinyxml2::XMLElement const* element);
template <typename ElementContainer> std::vector<tinyxml2::XMLElement const*> getChildElements(ElementContainer const* element);
std::string getEnumPostfix(std::string const& name, std::set<std::string> const& tags, std::string & prefix);
std::string getEnumPrefix(int line, std::string const& name, bool bitmask);
std::string readTypePostfix(tinyxml2::XMLNode const* node);
std::string readTypePrefix(tinyxml2::XMLNode const* node);
std::string replaceWithMap(std::string const &input, std::map<std::string, std::string> replacements);
std::string startLowerCase(std::string const& input);
std::string startUpperCase(std::string const& input);
std::string stripPostfix(std::string const& value, std::string const& postfix);
std::string stripPluralS(std::string const& name);
std::string stripPrefix(std::string const& value, std::string const& prefix);
std::string toCamelCase(std::string const& value);
std::string toUpperCase(std::string const& name);
std::vector<std::string> tokenize(std::string tokenString, char separator);
std::string trim(std::string const& input);
std::string trimEnd(std::string const& input);
void warn(bool condition, int line, std::string const& message);
const std::set<std::string> nonConstSTypeStructs = { "VkBaseInStructure", "VkBaseOutStructure" };
void appendArgumentCount(std::string & str, size_t vectorIndex, std::string const& vectorName, std::string const& counterName, size_t returnParamIndex, size_t templateParamIndex, bool twoStep, bool singular)
{
// this parameter is a count parameter for a vector parameter
if ((returnParamIndex == vectorIndex) && twoStep)
{
// the corresponding vector parameter is the return parameter and it's a two-step algorithm
// -> use the pointer to a local variable named like the counter parameter without leading 'p'
assert((counterName[0] == 'p') && isupper(counterName[1]));
str += "&" + startLowerCase(stripPrefix(counterName, "p"));
}
else
{
// the corresponding vector parameter is not the return parameter, or it's not a two-step algorithm
if (singular)
{
// for the singular version, the count is just 1.
str += "1 ";
}
else
{
// for the non-singular version, the count is the size of the vector parameter
// -> use the vector parameter name without leading 'p' to get the size (in number of elements, not in bytes)
assert(vectorName[0] == 'p');
str += startLowerCase(stripPrefix(vectorName, "p")) + ".size() ";
}
if (templateParamIndex == vectorIndex)
{
// if the vector parameter is templatized -> multiply by the size of that type to get the size in bytes
str += "* sizeof( T ) ";
}
}
}
std::string appendFunctionBodyEnhancedLocalReturnVariableSingular(std::string & str, std::string const& indentation, std::string const& returnName, std::string const& typeName, bool isStructureChain)
{
std::string strippedReturnName = stripPluralS(returnName);
if (isStructureChain)
{
// For StructureChains use the template parameters
str +=
"StructureChain<X, Y, Z...> structureChain;\n" +
indentation + " " + typeName + "& " + strippedReturnName + " = structureChain.template get<" + typeName + ">()";
strippedReturnName = "structureChain";
}
else
{
// in singular case, just use the return parameters pure type for the return variable
str += typeName + " " + strippedReturnName;
}
return strippedReturnName;
}
void appendReinterpretCast(std::string & str, bool leadingConst, std::string const& type, bool trailingPointerToConst)
{
str += "reinterpret_cast<";
if (leadingConst)
{
str += "const ";
}
str += type;
if (trailingPointerToConst)
{
str += "* const";
}
str += "*>";
}
void appendTypesafeStuff(std::string & str, std::string const& typesafeCheck)
{
str += "// 32-bit vulkan is not typesafe for handles, so don't allow copy constructors on this platform by default.\n"
"// To enable this feature on 32-bit platforms please define VULKAN_HPP_TYPESAFE_CONVERSION\n"
+ typesafeCheck + "\n"
"# if !defined( VULKAN_HPP_TYPESAFE_CONVERSION )\n"
"# define VULKAN_HPP_TYPESAFE_CONVERSION\n"
"# endif\n"
"#endif\n";
}
void appendVersionCheck(std::string & str, std::string const& version)
{
str += "static_assert( VK_HEADER_VERSION == " + version + " , \"Wrong VK_HEADER_VERSION!\" );\n"
"\n";
}
bool beginsWith(std::string const& text, std::string const& prefix)
{
return prefix.empty() || text.substr(0, prefix.length()) == prefix;
}
bool endsWith(std::string const& text, std::string const& postfix)
{
return postfix.empty() || ((postfix.length() <= text.length()) && (text.substr(text.length() - postfix.length()) == postfix));
}
void check(bool condition, int line, std::string const& message)
{
if (!condition)
{
throw std::runtime_error("Spec error on line " + std::to_string(line) + ": " + message);
}
}
// check the validity of an attributes map
// line : the line in the xml file where the attributes are listed
// attributes : the map of name/value pairs of the encountered attributes
// required : the required attributes, with a set of allowed values per attribute
// optional : the optional attributes, with a set of allowed values per attribute
void checkAttributes(int line, std::map<std::string, std::string> const& attributes, std::map<std::string, std::set<std::string>> const& required, std::map<std::string, std::set<std::string>> const& optional)
{
// check if all required attributes are included and if there is a set of allowed values, check if the actual value is part of that set
for (auto const& r : required)
{
auto attributesIt = attributes.find(r.first);
check(attributesIt != attributes.end(), line, "missing attribute <" + r.first + ">");
check(r.second.empty() || (r.second.find(attributesIt->second) != r.second.end()), line, "unexpected attribute value <" + attributesIt->second + "> in attribute <" + r.first + ">");
}
// check if all not required attributes or optional, and if there is a set of allowed values, check if the actual value is part of that set
for (auto const& a : attributes)
{
if (required.find(a.first) == required.end())
{
auto optionalIt = optional.find(a.first);
if (optionalIt == optional.end())
{
warn(false, line, "unknown attribute <" + a.first + ">");
continue;
}
if (!optionalIt->second.empty())
{
std::vector<std::string> values = tokenize(a.second, ',');
for (auto const& v : values)
{
check(optionalIt->second.find(v) != optionalIt->second.end(), line, "unexpected attribute value <" + v + "> in attribute <" + a.first + ">");
}
}
}
}
}
void checkElements(int line, std::vector<tinyxml2::XMLElement const*> const& elements, std::map<std::string, bool> const& required, std::set<std::string> const& optional)
{
std::map<std::string, size_t> encountered;
for (auto const& e : elements)
{
std::string value = e->Value();
encountered[value]++;
warn((required.find(value) != required.end()) || (optional.find(value) != optional.end()), e->GetLineNum(), "unknown element <" + value + ">");
}
for (auto const& r : required)
{
auto encounteredIt = encountered.find(r.first);
check(encounteredIt != encountered.end(), line, "missing required element <" + r.first + ">");
// check: r.second (means: required excactly once) => (encouteredIt->second == 1)
check(!r.second || (encounteredIt->second == 1), line, "required element <" + r.first + "> is supposed to be listed exactly once, but is listed " + std::to_string(encounteredIt->second));
}
}
void cleanup(std::string &str)
{
std::map<std::string,std::string> replacements =
{
{ "\n\n\n", "\n\n" },
{ "{\n\n", "{\n" },
{ "\n\n }", "\n }" }
};
for (auto const& repl : replacements)
{
std::string::size_type pos = str.find(repl.first);
while (pos != std::string::npos)
{
str.replace(pos, repl.first.length(), repl.second);
pos = str.find(repl.first, pos);
}
}
}
std::string constructArraySize(std::vector<std::string> const& sizes)
{
std::string arraySize;
for (auto const& s : sizes)
{
arraySize += s + " * ";
}
return arraySize.substr(0, arraySize.length() - 3);
}
std::string constructCArraySizes(std::vector<std::string> const& sizes)
{
std::string arraySizes;
for (auto const& s : sizes)
{
arraySizes += "[" + s + "]";
}
return arraySizes;
}
std::string constructStandardArray(std::string const& type, std::vector<std::string> const& sizes)
{
std::string arrayString = "std::array<" + type + "," + sizes.back() + ">";
for (size_t i = sizes.size() - 2; i < sizes.size(); i--)
{
arrayString = "std::array<" + arrayString + "," + sizes[i] + ">";
}
return arrayString;
}
std::string createEnumValueName(std::string const& name, std::string const& prefix, std::string const& postfix, bool bitmask, std::string const& tag)
{
std::string result = "e" + toCamelCase(stripPostfix(stripPrefix(name, prefix), postfix));
if (bitmask)
{
size_t pos = result.find("Bit");
if (pos != std::string::npos)
{
result.erase(pos, 3);
}
}
if (!tag.empty() && (result.substr(result.length() - tag.length()) == toCamelCase(tag)))
{
result = result.substr(0, result.length() - tag.length()) + tag;
}
return result;
}
std::string createSuccessCode(std::string const& code, std::set<std::string> const& tags)
{
std::string tag = findTag(tags, code);
// on each success code: prepend 'e', strip "VK_" and a tag, convert it to camel case, and add the tag again
return "e" + toCamelCase(stripPostfix(stripPrefix(code, "VK_"), tag)) + tag;
}
std::string determineCommandName(std::string const& vulkanCommandName, std::string const& firstArgumentType)
{
std::string commandName(startLowerCase(stripPrefix(vulkanCommandName, "vk")));
std::string searchName = stripPrefix(firstArgumentType, "Vk");
size_t pos = commandName.find(searchName);
if ((pos == std::string::npos) && isupper(searchName[0]))
{
searchName[0] = static_cast<char>(tolower(searchName[0]));
pos = commandName.find(searchName);
}
if (pos != std::string::npos)
{
commandName.erase(pos, searchName.length());
}
else if ((searchName == "commandBuffer") && beginsWith(commandName, "cmd"))
{
commandName.erase(0, 3);
pos = 0;
}
if ((pos == 0) && isupper(commandName[0]))
{
commandName[0] = static_cast<char>(tolower(commandName[0]));
}
return commandName;
}
std::set<size_t> determineSkippedParams(size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices)
{
std::set<size_t> skippedParams;
// the size-parameters of vector parameters are not explicitly used in the enhanced API
std::for_each(vectorParamIndices.begin(), vectorParamIndices.end(), [&skippedParams](std::pair<size_t, size_t> const& vp) { if (vp.second != INVALID_INDEX) skippedParams.insert(vp.second); });
// and the return parameter is also skipped
if (returnParamIndex != INVALID_INDEX)
{
skippedParams.insert(returnParamIndex);
}
return skippedParams;
}
bool determineStructureChaining(std::string const& structType, std::set<std::string> const& extendedStructs, std::map<std::string, std::string> const& structureAliases)
{
bool isStructureChained = (extendedStructs.find(structType) != extendedStructs.end());
if (!isStructureChained)
{
auto aliasIt = structureAliases.find(structType);
if ((aliasIt != structureAliases.end()))
{
isStructureChained = (extendedStructs.find(aliasIt->second) != extendedStructs.end());
}
}
return isStructureChained;
}
std::string findTag(std::set<std::string> const& tags, std::string const& name, std::string const& postfix)
{
auto tagIt = std::find_if(tags.begin(), tags.end(), [&name, &postfix](std::string const& t) { return endsWith(name, t + postfix); });
return (tagIt != tags.end()) ? *tagIt : "";
}
std::pair<bool, std::string> generateFunctionBodyStandardReturn(std::string const& returnType)
{
bool castReturn = false;
std::string ret;
if (returnType != "void")
{
// there's something to return...
ret = "return ";
castReturn = beginsWith(returnType, "Vk");
if (castReturn)
{
// the return-type is a vulkan type -> need to cast to VULKAN_HPP_NAMESPACE-type
ret += "static_cast<" + stripPrefix(returnType, "Vk") + ">( ";
}
}
return std::make_pair(castReturn, ret);
}
std::map<std::string, std::string> getAttributes(tinyxml2::XMLElement const* element)
{
std::map<std::string, std::string> attributes;
for (auto attribute = element->FirstAttribute(); attribute; attribute = attribute->Next())
{
assert(attributes.find(attribute->Name()) == attributes.end());
attributes[attribute->Name()] = attribute->Value();
}
return attributes;
}
template <typename ElementContainer>
std::vector<tinyxml2::XMLElement const*> getChildElements(ElementContainer const* element)
{
std::vector<tinyxml2::XMLElement const*> childElements;
for (tinyxml2::XMLElement const* childElement = element->FirstChildElement(); childElement; childElement = childElement->NextSiblingElement())
{
childElements.push_back(childElement);
}
return childElements;
}
std::string getEnumPostfix(std::string const& name, std::set<std::string> const& tags, std::string & prefix)
{
std::string postfix;
if (name != "VkResult")
{
// if the enum name contains a tag move it from the prefix to the postfix to generate correct enum value names.
for (auto const& tag : tags)
{
if (endsWith(prefix, tag + "_"))
{
prefix.erase(prefix.length() - tag.length() - 1);
postfix = "_" + tag;
break;
}
else if (endsWith(name, tag))
{
postfix = "_" + tag;
break;
}
}
}
return postfix;
}
std::string getEnumPrefix(int line, std::string const& name, bool bitmask)
{
std::string prefix;
if (name == "VkResult")
{
prefix = "VK_";
}
else if (bitmask)
{
// for a bitmask enum, start with "VK", cut off the trailing "FlagBits", and convert that name to upper case
// end that with "Bit"
size_t pos = name.find("FlagBits");
check(pos != std::string::npos, line, "bitmask <" + name + "> does not contain <FlagBits>");
prefix = toUpperCase(name.substr(0, pos)) + "_";
}
else
{
// for a non-bitmask enum, convert the name to upper case
prefix = toUpperCase(name) + "_";
}
return prefix;
}
std::string extractTag(int line, std::string const& name, std::set<std::string> const& tags)
{
// extract the tag from the name, which is supposed to look like VK_<tag>_<other>
size_t tagStart = name.find('_');
check(tagStart != std::string::npos, line, "name <" + name + "> is missing an underscore '_'");
size_t tagEnd = name.find('_', tagStart + 1);
check(tagEnd != std::string::npos, line, "name <" + name + "> is missing an underscore '_'");
std::string tag = name.substr(tagStart + 1, tagEnd - tagStart - 1);
check(tags.find(tag) != tags.end(), line, "name <" + name + "> is using an unknown tag <" + tag + ">");
return tag;
}
std::pair<std::vector<std::string>, std::string> readModifiers(tinyxml2::XMLNode const* node)
{
std::vector<std::string> arraySizes;
std::string bitCount;
if (node && node->ToText())
{
// following the name there might be some array size
std::string value = node->Value();
assert(!value.empty());
if (value[0] == '[')
{
std::string::size_type endPos = 0;
while (endPos + 1 != value.length())
{
std::string::size_type startPos = value.find('[', endPos);
check(startPos != std::string::npos, node->GetLineNum(), "could not find '[' in <" + value + ">");
endPos = value.find(']', startPos);
check(endPos != std::string::npos, node->GetLineNum(), "could not find ']' in <" + value + ">");
check(startPos + 2 <= endPos, node->GetLineNum(), "missing content between '[' and ']' in <" + value + ">");
arraySizes.push_back(value.substr(startPos + 1, endPos - startPos - 1));
}
}
else if (value[0] == ':')
{
bitCount = value.substr(1);
}
else
{
check((value[0] == ';') || (value[0] == ')'), node->GetLineNum(), "unknown modifier <" + value + ">");
}
}
return std::make_pair(arraySizes, bitCount);;
}
std::string readTypePostfix(tinyxml2::XMLNode const* node)
{
std::string postfix;
if (node && node->ToText())
{
postfix = trimEnd(node->Value());
}
return postfix;
}
std::string readTypePrefix(tinyxml2::XMLNode const* node)
{
std::string prefix;
if (node && node->ToText())
{
prefix = trim(node->Value());
}
return prefix;
}
std::string replaceWithMap(std::string const &input, std::map<std::string, std::string> replacements)
{
// This will match ${someVariable} and contain someVariable in match group 1
std::regex re(R"(\$\{([^\}]+)\})");
auto it = std::sregex_iterator(input.begin(), input.end(), re);
auto end = std::sregex_iterator();
// No match, just return the original string
if (it == end)
{
return input;
}
std::string result = "";
while (it != end)
{
std::smatch match = *it;
auto itReplacement = replacements.find(match[1].str());
assert(itReplacement != replacements.end());
result += match.prefix().str() + ((itReplacement != replacements.end()) ? itReplacement->second : match[0].str());
++it;
// we've passed the last match. Append the rest of the orignal string
if (it == end)
{
result += match.suffix().str();
}
}
return result;
}
std::string startLowerCase(std::string const& input)
{
return input.empty() ? "" : static_cast<char>(tolower(input[0])) + input.substr(1);
}
std::string startUpperCase(std::string const& input)
{
return input.empty() ? "" : static_cast<char>(toupper(input[0])) + input.substr(1);
}
std::string stripPostfix(std::string const& value, std::string const& postfix)
{
std::string strippedValue = value;
if (endsWith(strippedValue, postfix))
{
strippedValue.erase(strippedValue.length() - postfix.length());
}
return strippedValue;
}
std::string stripPluralS(std::string const& name)
{
std::string strippedName(name);
size_t pos = strippedName.rfind('s');
assert(pos != std::string::npos);
strippedName.erase(pos, 1);
return strippedName;
}
std::string stripPrefix(std::string const& value, std::string const& prefix)
{
std::string strippedValue = value;
if (beginsWith(strippedValue, prefix))
{
strippedValue.erase(0, prefix.length());
}
return strippedValue;
}
std::string toCamelCase(std::string const& value)
{
assert(!value.empty() && (isupper(value[0]) || isdigit(value[0])));
std::string result;
result.reserve(value.size());
bool keepUpper = true;
for (auto c : value)
{
if (c == '_')
{
keepUpper = true;
}
else if (isdigit(c))
{
keepUpper = true;
result.push_back(c);
}
else if (keepUpper)
{
result.push_back(c);
keepUpper = false;
}
else
{
result.push_back(static_cast<char>(tolower(c)));
}
}
return result;
}
std::string toUpperCase(std::string const& name)
{
std::string convertedName;
convertedName.reserve(name.size());
bool lowerOrDigit = false;
for (auto c : name)
{
if (islower(c) || isdigit(c))
{
lowerOrDigit = true;
}
else if (lowerOrDigit)
{
convertedName.push_back('_');
lowerOrDigit = false;
}
convertedName.push_back(static_cast<char>(toupper(c)));
}
return convertedName;
}
std::vector<std::string> tokenize(std::string tokenString, char separator)
{
std::vector<std::string> tokens;
size_t start = 0, end;
do
{
end = tokenString.find(separator, start);
if (start != end)
{
tokens.push_back(tokenString.substr(start, end - start));
}
start = end + 1;
} while (end != std::string::npos);
return tokens;
}
std::string trim(std::string const& input)
{
std::string result = input;
result.erase(result.begin(), std::find_if(result.begin(), result.end(), [](char c) { return !std::isspace(c); }));
result.erase(std::find_if(result.rbegin(), result.rend(), [](char c) { return !std::isspace(c); }).base(), result.end());
return result;
}
std::string trimEnd(std::string const& input)
{
std::string result = input;
result.erase(std::find_if(result.rbegin(), result.rend(), [](char c) { return !std::isspace(c); }).base(), result.end());
return result;
}
void warn(bool condition, int line, std::string const& message)
{
if (!condition)
{
std::cerr << "Spec warning on line " << std::to_string(line) << " " << message << "!" << std::endl;
}
}
VulkanHppGenerator::VulkanHppGenerator(tinyxml2::XMLDocument const& document)
{
m_handles.insert(std::make_pair("", HandleData({}, 0))); // insert the default "handle" without class (for createInstance, and such)
int line = document.GetLineNum();
std::vector<tinyxml2::XMLElement const*> elements = getChildElements(&document);
checkElements(line, elements, { { "registry", true } });
check(elements.size() == 1, line, "encountered " + std::to_string(elements.size()) + " elments named <registry> but only one is allowed");
readRegistry(elements[0]);
checkCorrectness();
}
void VulkanHppGenerator::appendArgumentPlainType(std::string & str, ParamData const& paramData) const
{
// this parameter is just a plain type
if (!paramData.type.postfix.empty())
{
assert(paramData.type.postfix.back() == '*');
// it's a pointer
std::string parameterName = startLowerCase(stripPrefix(paramData.name, "p"));
if (paramData.type.prefix.find("const") != std::string::npos)
{
// it's a const pointer
if (paramData.type.type == "char")
{
// it's a const pointer to char -> it's a string -> get the data via c_str()
str += parameterName + (paramData.optional ? (" ? " + parameterName + "->c_str() : nullptr") : ".c_str()");
}
else
{
// it's const pointer to something else -> just use the name
assert(!paramData.optional);
str += paramData.name;
}
}
else
{
// it's a non-const pointer, and char is the only type that occurs -> use the address of the parameter
assert(paramData.type.type.find("char") == std::string::npos);
str += "&" + parameterName;
}
}
else
{
// it's a plain parameter -> just use its name
str += paramData.name;
}
}
void VulkanHppGenerator::appendArguments(std::string & str, CommandData const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool firstCall, bool singular, size_t from, size_t to) const
{
assert(from <= to);
bool encounteredArgument = false;
for (size_t i = from; i < to; i++)
{
if (encounteredArgument)
{
str += ", ";
}
auto it = vectorParamIndices.find(i);
if (it != vectorParamIndices.end())
{
appendArgumentVector(str, it->first, commandData.params[it->first], returnParamIndex, templateParamIndex, twoStep, firstCall, singular);
}
else
{
it = find_if(vectorParamIndices.begin(), vectorParamIndices.end(), [i](std::pair<size_t, size_t> const& vpi) { return vpi.second == i; });
if (it != vectorParamIndices.end())
{
appendArgumentCount(str, it->first, commandData.params[it->first].name, commandData.params[it->second].name, returnParamIndex, templateParamIndex, twoStep, singular);
}
else if (beginsWith(commandData.params[i].type.type, "Vk"))
{
appendArgumentVulkanType(str, commandData.params[i]);
}
else
{
appendArgumentPlainType(str, commandData.params[i]);
}
}
encounteredArgument = true;
}
}
void VulkanHppGenerator::appendArgumentVector(std::string & str, size_t paramIndex, ParamData const& paramData, size_t returnParamIndex, size_t templateParamIndex, bool twoStep, bool firstCall, bool singular) const
{
// this parameter is a vector parameter
assert(paramData.type.postfix.back() == '*');
if ((returnParamIndex == paramIndex) && twoStep && firstCall)
{
// this parameter is the return parameter, and it's the first call of a two-step algorithm -> just just nullptr
str += "nullptr";
}
else
{
std::string parameterName = startLowerCase(stripPrefix(paramData.name, "p"));
if (beginsWith(paramData.type.type, "Vk") || (paramIndex == templateParamIndex))
{
// CHECK for !commandData.params[it->first].optional
// this parameter is a vulkan type or a templated type -> need to reinterpret cast
appendReinterpretCast(str, paramData.type.prefix.find("const") == 0, paramData.type.type, paramData.type.postfix.rfind("* const") != std::string::npos);
str += "( " + (singular ? ("&" + stripPluralS(parameterName)) : (parameterName + ".data()")) + " )";
}
else if (paramData.type.type == "char")
{
// the parameter is a vector to char -> it might be optional
// besides that, the parameter now is a std::string -> get the pointer via c_str()
str += parameterName + (paramData.optional ? (" ? " + parameterName + "->c_str() : nullptr") : ".c_str()");
}
else
{
// this parameter is just a vetor -> get the pointer to its data
str += parameterName + ".data()";
}
}
}
void VulkanHppGenerator::appendArgumentVulkanType(std::string & str, ParamData const& paramData) const
{
// this parameter is a vulkan type
if (!paramData.type.postfix.empty())
{
assert(paramData.type.postfix.back() == '*');
// it's a pointer -> needs a reinterpret cast to the vulkan type
std::string parameterName = startLowerCase(stripPrefix(paramData.name, "p"));
appendReinterpretCast(str, paramData.type.prefix.find("const") != std::string::npos, paramData.type.type, false);
str += "( ";
if (paramData.optional)
{
// for an optional parameter, we need also a static_cast from optional type to const-pointer to pure type
str += "static_cast<const " + stripPrefix(paramData.type.type, "Vk") + "*>( " + parameterName + " )";
}
else
{
// other parameters can just use the pointer
str += "&" + parameterName;
}
str += " )";
}
else
{
// a non-pointer parameter needs a static_cast from VULKAN_HPP_NAMESPACE-type to vulkan type
str += "static_cast<" + paramData.type.type + ">( " + paramData.name + " )";
}
}
void VulkanHppGenerator::appendBaseTypes(std::string & str) const
{
assert(!m_baseTypes.empty());
for (auto const& baseType : m_baseTypes)
{
if ((baseType.first != "VkFlags") && (baseType.first != "VkFlags64")) // filter out VkFlags and VkFlags64, as they are mapped to our own Flags class
{
str += " using " + stripPrefix(baseType.first, "Vk") + " = " + baseType.second.type + ";\n";
}
}
}
void VulkanHppGenerator::appendBitmasks(std::string & str) const
{
for (auto const& bitmask : m_bitmasks)
{
auto bitmaskBits = m_enums.find(bitmask.second.requirements);
bool hasBits = (bitmaskBits != m_enums.end());
check(bitmask.second.requirements.empty() || hasBits, bitmask.second.xmlLine, "bitmask <" + bitmask.first + "> references the undefined requires <" + bitmask.second.requirements + ">");
std::string strippedBitmaskName = stripPrefix(bitmask.first, "Vk");
std::string strippedEnumName = hasBits ? stripPrefix(bitmaskBits->first, "Vk") : "";
str += "\n";
appendPlatformEnter(str, !bitmask.second.alias.empty(), bitmask.second.platform);
appendBitmask(str, strippedBitmaskName, bitmask.second.type, bitmask.second.alias, strippedEnumName, hasBits ? bitmaskBits->second.values : std::vector<EnumValueData>());
appendBitmaskToStringFunction(str, strippedBitmaskName, strippedEnumName, hasBits ? bitmaskBits->second.values : std::vector<EnumValueData>());
appendPlatformLeave(str, !bitmask.second.alias.empty(), bitmask.second.platform);
}
}
void VulkanHppGenerator::appendBitmask(std::string & str, std::string const& bitmaskName, std::string const& bitmaskType, std::string const& bitmaskAlias, std::string const& enumName, std::vector<EnumValueData> const& enumValues) const
{
// each Flags class is using the class 'Flags' with the corresponding FlagBits enum as the template parameter
// if there's no enum for the FlagBits, introduce an artificial empty one
std::string emptyEnumName;
if (enumName.empty())
{
emptyEnumName = bitmaskName;
size_t pos = emptyEnumName.rfind("Flags");
assert(pos != std::string::npos);
emptyEnumName.replace(pos, 5, "FlagBits");
// if this emptyEnumName is not in the list of enums, list it here
if (m_enums.find("Vk" + emptyEnumName) == m_enums.end())
{
const std::string templateString = R"x( enum class ${enumName} : ${bitmaskType}
{};
VULKAN_HPP_INLINE std::string to_string( ${enumName} )
{
return "(void)";
}
)x";
str += replaceWithMap(templateString, { { "enumName", emptyEnumName }, { "bitmaskType", bitmaskType } });
}
}
std::string name = (enumName.empty() ? emptyEnumName : enumName);
str += "\n"
" using " + bitmaskName + " = Flags<" + name + ">;\n";
if (!enumValues.empty())
{
std::string allFlags;
for (auto const& value : enumValues)
{
if (!allFlags.empty())
{
allFlags += " | ";
}
allFlags += bitmaskType + "(" + enumName + "::" + value.vkValue + ")";
}
static const std::string bitmaskOperatorsTemplate = R"(
template <> struct FlagTraits<${enumName}>
{
enum : ${bitmaskType}
{
allFlags = ${allFlags}
};
};
VULKAN_HPP_INLINE VULKAN_HPP_CONSTEXPR ${bitmaskName} operator|( ${enumName} bit0, ${enumName} bit1 ) VULKAN_HPP_NOEXCEPT
{
return ${bitmaskName}( bit0 ) | bit1;
}
VULKAN_HPP_INLINE VULKAN_HPP_CONSTEXPR ${bitmaskName} operator&( ${enumName} bit0, ${enumName} bit1 ) VULKAN_HPP_NOEXCEPT
{
return ${bitmaskName}( bit0 ) & bit1;
}
VULKAN_HPP_INLINE VULKAN_HPP_CONSTEXPR ${bitmaskName} operator^( ${enumName} bit0, ${enumName} bit1 ) VULKAN_HPP_NOEXCEPT
{
return ${bitmaskName}( bit0 ) ^ bit1;
}
VULKAN_HPP_INLINE VULKAN_HPP_CONSTEXPR ${bitmaskName} operator~( ${enumName} bits ) VULKAN_HPP_NOEXCEPT
{
return ~( ${bitmaskName}( bits ) );
}
)";
str += replaceWithMap(bitmaskOperatorsTemplate, { { "bitmaskName", bitmaskName }, { "bitmaskType", bitmaskType }, { "enumName", enumName }, { "allFlags", allFlags } });
}
if (!bitmaskAlias.empty())
{
str += "\n"
" using " + stripPrefix(bitmaskAlias, "Vk") + " = " + bitmaskName + ";\n";
}
}
void VulkanHppGenerator::appendBitmaskToStringFunction(std::string & str, std::string const& bitmaskName, std::string const& enumName, std::vector<EnumValueData> const& enumValues) const
{
str += "\n"
" VULKAN_HPP_INLINE std::string to_string( " + bitmaskName + (enumValues.empty() ? " " : " value ") + " )\n"
" {\n";
if (enumValues.empty())
{
str += "\n return \"{}\";\n";
}
else
{
// 'or' together all the bits in the value
str += "\n"
" if ( !value ) return \"{}\";\n"
" std::string result;\n";
for (auto const& evd : enumValues)
{
if (evd.singleBit)
{
str += "\n"
" if ( value & " + enumName + "::" + evd.vkValue + " ) result += \"" + evd.vkValue.substr(1) + " | \";";
}
}
str += "\n"
" return \"{ \" + result.substr(0, result.size() - 3) + \" }\";\n";
}
str += " }\n";
}
void VulkanHppGenerator::appendCall(std::string & str, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool firstCall, bool singular) const
{
// the original function call
str += "d." + commandData.first + "( ";
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
if (!handle.empty())
{
// if it's member of a class -> the first argument is the member variable, starting with "m_"
assert(handle == commandData.second.params[0].type.type);
str += "m_" + startLowerCase(stripPrefix(handle, "Vk"));
if (1 < commandData.second.params.size())
{
str += ", ";
}
}
appendArguments(str, commandData.second, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, firstCall, singular, handle.empty() ? 0 : 1, commandData.second.params.size());
str += " )";
}
void VulkanHppGenerator::appendCommand(std::string & str, std::string const& indentation, std::string const& name, std::pair<std::string, CommandData> const& commandData, bool definition) const
{
bool twoStep = isTwoStepAlgorithm(commandData.second.params);
std::map<size_t, size_t> vectorParamIndices = determineVectorParamIndices(commandData.second.params);
size_t returnParamIndex = determineReturnParamIndex(commandData.second, vectorParamIndices, twoStep);
bool isStructureChain = (returnParamIndex != INVALID_INDEX) && determineStructureChaining(commandData.second.params[returnParamIndex].type.type, m_extendedStructs, m_structureAliases);
std::string enhancedReturnType = determineEnhancedReturnType(commandData.second, returnParamIndex, vectorParamIndices, twoStep, false); // get the enhanced return type without structureChain
size_t templateParamIndex = determineTemplateParamIndex(commandData.second.params, vectorParamIndices);
// first create the standard version of the function
std::string standard;
appendFunction(standard, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, definition, false, false, false, false, false);
// then the enhanced version, composed by up to eight parts
std::string enhanced;
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, definition, true, false, false, false, false);
if (enhancedReturnType.find("Allocator") != std::string::npos)
{
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, definition, true, false, false, false, true);
}
if (isStructureChain)
{
std::string enhancedReturnTypeWithStructureChain = determineEnhancedReturnType(commandData.second, returnParamIndex, vectorParamIndices, twoStep, true);
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnTypeWithStructureChain, definition, true, false, false, true, false);
if (enhancedReturnTypeWithStructureChain.find("Allocator") != std::string::npos)
{
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnTypeWithStructureChain, definition, true, false, false, true, true);
}
}
// then a singular version, if a sized vector would be returned
std::map<size_t, size_t>::const_iterator returnVector = vectorParamIndices.find(returnParamIndex);
bool singular = (returnVector != vectorParamIndices.end()) &&
(returnVector->second != INVALID_INDEX) &&
(commandData.second.params[returnVector->first].type.type != "void") &&
(commandData.second.params[returnVector->second].type.postfix.empty() || (commandData.second.params[returnVector->second].type.postfix.back() != '*'));
if (singular)
{
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, definition, true, true, false, false, false);
}
// special handling for createDevice and createInstance !
bool specialWriteUnique = (commandData.first == "vkCreateDevice") || (commandData.first == "vkCreateInstance");
// and then the same for the Unique* versions (a deleteCommand is available for the commandData's class, and the function starts with 'allocate' or 'create')
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
auto handleIt = m_handles.find(m_commandToHandle.find(commandData.first)->second);
assert(handleIt != m_handles.end());
if ((!handleIt->second.deleteCommand.empty() || specialWriteUnique)
&& ((commandData.first.substr(2, 8) == "Allocate") || (commandData.first.substr(2, 6) == "Create")
|| ((commandData.first.substr(2, 8) == "Register") && (returnParamIndex + 1 == commandData.second.params.size()))))
{
enhanced += "#ifndef VULKAN_HPP_NO_SMART_HANDLE\n";
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, definition, true, false, true, false, false);
if (enhancedReturnType.find("Allocator") != std::string::npos)
{
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, definition, true, false, true, false, true);
}
if (singular)
{
appendFunction(enhanced, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, definition, true, true, true, false, false);
}
enhanced += "#endif /*VULKAN_HPP_NO_SMART_HANDLE*/\n";
}
// and append one or both of them
if (standard == enhanced)
{
// standard and enhanced string are equal -> just use one of them and we're done
str += standard;
}
else
{
// standard and enhanced string differ -> use both, wrapping the enhanced by !VULKAN_HPP_DISABLE_ENHANCED_MODE
// determine the argument list of that standard, and compare it with that of the enhanced
// if they are equal -> need to have just one; if they differ -> need to have both
size_t standardStart = standard.find('(');
size_t standardCount = standard.find(')', standardStart) - standardStart;
size_t enhancedStart = enhanced.find('(');
bool unchangedInterface = (standard.substr(standardStart, standardCount) == enhanced.substr(enhancedStart, standardCount));
if (unchangedInterface)
{
str += "#ifdef VULKAN_HPP_DISABLE_ENHANCED_MODE\n";
}
str += standard
+ (unchangedInterface ? "#else" : "#ifndef VULKAN_HPP_DISABLE_ENHANCED_MODE") + "\n"
+ enhanced
+ "#endif /*VULKAN_HPP_DISABLE_ENHANCED_MODE*/\n";
}
}
void VulkanHppGenerator::appendDispatchLoaderDynamic(std::string & str)
{
str += R"(
#if VULKAN_HPP_ENABLE_DYNAMIC_LOADER_TOOL
class DynamicLoader
{
public:
#ifdef VULKAN_HPP_NO_EXCEPTIONS
DynamicLoader() VULKAN_HPP_NOEXCEPT : m_success( false )
#else
DynamicLoader() : m_success( false )
#endif
{
#if defined(__linux__)
m_library = dlopen( "libvulkan.so", RTLD_NOW | RTLD_LOCAL );
#elif defined(__APPLE__)
m_library = dlopen( "libvulkan.dylib", RTLD_NOW | RTLD_LOCAL );
#elif defined(_WIN32)
m_library = LoadLibrary( TEXT( "vulkan-1.dll" ) );
#else
VULKAN_HPP_ASSERT( false && "unsupported platform" );
#endif
m_success = m_library != 0;
#ifndef VULKAN_HPP_NO_EXCEPTIONS
if ( !m_success )
{
// NOTE there should be an InitializationFailedError, but msvc insists on the symbol does not exist within the scope of this function.
throw std::runtime_error( "Failed to load vulkan library!" );
}
#endif
}
DynamicLoader( DynamicLoader const& ) = delete;
DynamicLoader( DynamicLoader && other ) VULKAN_HPP_NOEXCEPT
: m_success(other.m_success)
, m_library(other.m_library)
{
other.m_library = nullptr;
}
DynamicLoader &operator=( DynamicLoader const& ) = delete;
DynamicLoader &operator=( DynamicLoader && other ) VULKAN_HPP_NOEXCEPT
{
m_success = other.m_success;
std::swap(m_library, other.m_library);
return *this;
}
~DynamicLoader() VULKAN_HPP_NOEXCEPT
{
if ( m_library )
{
#if defined(__linux__) || defined(__APPLE__)
dlclose( m_library );
#elif defined(_WIN32)
FreeLibrary( m_library );
#endif
}
}
template <typename T>
T getProcAddress( const char* function ) const VULKAN_HPP_NOEXCEPT
{
#if defined(__linux__) || defined(__APPLE__)
return (T)dlsym( m_library, function );
#elif defined(_WIN32)
return (T)GetProcAddress( m_library, function );
#endif
}
bool success() const VULKAN_HPP_NOEXCEPT { return m_success; }
private:
bool m_success;
#if defined(__linux__) || defined(__APPLE__)
void *m_library;
#elif defined(_WIN32)
HMODULE m_library;
#else
#error unsupported platform
#endif
};
#endif
)";
str += R"(
class DispatchLoaderDynamic
{
public:
)";
for (auto const& handle : m_handles)
{
for (auto const& command : handle.second.commands)
{
std::string enter, leave;
appendPlatformEnter(enter, !command.second.aliases.empty(), command.second.platform);
appendPlatformLeave(leave, !command.second.aliases.empty(), command.second.platform);
str += enter + " PFN_" + command.first + " " + command.first + " = 0;\n" + leave;
for (auto const& alias : command.second.aliases)
{
assert(enter.empty() && leave.empty());
str += " PFN_" + alias + " " + alias + " = 0;\n";
}
}
}
std::string emptyFunctions;
std::string strDeviceFunctions;
std::string strDeviceFunctionsInstance;
std::string strInstanceFunctions;
for (auto const& handle : m_handles)
{
for (auto const& command : handle.second.commands)
{
if ((command.first != "vkGetInstanceProcAddr"))
{
std::string enter, leave;
appendPlatformEnter(enter, !command.second.aliases.empty(), command.second.platform);
appendPlatformLeave(leave, !command.second.aliases.empty(), command.second.platform);
if (handle.first.empty())
{
assert(command.second.aliases.empty());
emptyFunctions += enter;
emptyFunctions += " " + command.first + " = PFN_" + command.first + "( vkGetInstanceProcAddr( NULL, \"" + command.first + "\" ) );\n";
emptyFunctions += leave;
}
else if (!command.second.params.empty()
&& m_handles.find(command.second.params[0].type.type) != m_handles.end()
&& command.second.params[0].type.type != "VkInstance"
&& command.second.params[0].type.type != "VkPhysicalDevice")
{
strDeviceFunctions += enter;
strDeviceFunctions += " " + command.first + " = PFN_" + command.first + "( vkGetDeviceProcAddr( device, \"" + command.first + "\" ) );\n";
strDeviceFunctions += leave;
strDeviceFunctionsInstance += enter;
strDeviceFunctionsInstance += " " + command.first + " = PFN_" + command.first + "( vkGetInstanceProcAddr( instance, \"" + command.first + "\" ) );\n";
strDeviceFunctionsInstance += leave;
for (auto const& alias : command.second.aliases)
{
assert(enter.empty() && leave.empty());
strDeviceFunctions += " " + alias + " = PFN_" + alias + "( vkGetDeviceProcAddr( device, \"" + alias + "\" ) );\n";
strDeviceFunctionsInstance += " " + alias + " = PFN_" + alias + "( vkGetInstanceProcAddr( instance, \"" + alias + "\" ) );\n";
}
}
else
{
strInstanceFunctions += enter;
strInstanceFunctions += " " + command.first + " = PFN_" + command.first + "( vkGetInstanceProcAddr( instance, \"" + command.first + "\" ) );\n";
strInstanceFunctions += leave;
for (auto const& alias : command.second.aliases)
{
assert(enter.empty() && leave.empty());
strInstanceFunctions += " " + alias + " = PFN_" + alias + "( vkGetInstanceProcAddr( instance, \"" + alias + "\" ) );\n";
}
}
}
}
}
// append initialization function to fetch function pointers
str += R"(
public:
DispatchLoaderDynamic() VULKAN_HPP_NOEXCEPT = default;
#if !defined(VK_NO_PROTOTYPES)
// This interface is designed to be used for per-device function pointers in combination with a linked vulkan library.
template <typename DynamicLoader>
void init(VULKAN_HPP_NAMESPACE::Instance const& instance, VULKAN_HPP_NAMESPACE::Device const& device, DynamicLoader const& dl) VULKAN_HPP_NOEXCEPT
{
PFN_vkGetInstanceProcAddr getInstanceProcAddr = dl.template getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr");
PFN_vkGetDeviceProcAddr getDeviceProcAddr = dl.template getProcAddress<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr");
init(static_cast<VkInstance>(instance), getInstanceProcAddr, static_cast<VkDevice>(device), device ? getDeviceProcAddr : nullptr);
}
// This interface is designed to be used for per-device function pointers in combination with a linked vulkan library.
template <typename DynamicLoader
#if VULKAN_HPP_ENABLE_DYNAMIC_LOADER_TOOL
= vk::DynamicLoader
#endif
>
void init(VULKAN_HPP_NAMESPACE::Instance const& instance, VULKAN_HPP_NAMESPACE::Device const& device) VULKAN_HPP_NOEXCEPT
{
static DynamicLoader dl;
init(instance, device, dl);
}
#endif // !defined(VK_NO_PROTOTYPES)
DispatchLoaderDynamic(PFN_vkGetInstanceProcAddr getInstanceProcAddr) VULKAN_HPP_NOEXCEPT
{
init(getInstanceProcAddr);
}
void init( PFN_vkGetInstanceProcAddr getInstanceProcAddr ) VULKAN_HPP_NOEXCEPT
{
VULKAN_HPP_ASSERT(getInstanceProcAddr);
vkGetInstanceProcAddr = getInstanceProcAddr;
)";
str += emptyFunctions;
str += R"( }
// This interface does not require a linked vulkan library.
DispatchLoaderDynamic( VkInstance instance, PFN_vkGetInstanceProcAddr getInstanceProcAddr, VkDevice device = VK_NULL_HANDLE, PFN_vkGetDeviceProcAddr getDeviceProcAddr = nullptr ) VULKAN_HPP_NOEXCEPT
{
init( instance, getInstanceProcAddr, device, getDeviceProcAddr );
}
// This interface does not require a linked vulkan library.
void init( VkInstance instance, PFN_vkGetInstanceProcAddr getInstanceProcAddr, VkDevice device = VK_NULL_HANDLE, PFN_vkGetDeviceProcAddr /*getDeviceProcAddr*/ = nullptr ) VULKAN_HPP_NOEXCEPT
{
VULKAN_HPP_ASSERT(instance && getInstanceProcAddr);
vkGetInstanceProcAddr = getInstanceProcAddr;
init( VULKAN_HPP_NAMESPACE::Instance(instance) );
if (device) {
init( VULKAN_HPP_NAMESPACE::Device(device) );
}
}
void init( VULKAN_HPP_NAMESPACE::Instance instanceCpp ) VULKAN_HPP_NOEXCEPT
{
VkInstance instance = static_cast<VkInstance>(instanceCpp);
)";
str += strInstanceFunctions;
str += strDeviceFunctionsInstance;
str += " }\n\n";
str += " void init( VULKAN_HPP_NAMESPACE::Device deviceCpp ) VULKAN_HPP_NOEXCEPT\n {\n";
str += " VkDevice device = static_cast<VkDevice>(deviceCpp);\n";
str += strDeviceFunctions;
str += R"( }
};
)";
}
void VulkanHppGenerator::appendDispatchLoaderStatic(std::string & str)
{
str += R"(
#if !defined(VK_NO_PROTOTYPES)
class DispatchLoaderStatic
{
public:)";
for (auto const& handle : m_handles)
{
for (auto const& command : handle.second.commands)
{
std::string parameterList, parameters;
bool firstParam = true;
for (auto param : command.second.params)
{
if (!firstParam)
{
parameterList += ", ";
parameters += ", ";
}
parameterList += param.type.prefix + (param.type.prefix.empty() ? "" : " ") + param.type.type + param.type.postfix + " " + param.name + constructCArraySizes(param.arraySizes);
parameters += param.name;
firstParam = false;
}
std::string commandName = stripPrefix(command.first, "vk");
str += "\n";
appendPlatformEnter(str, !command.second.aliases.empty(), command.second.platform);
str += " " + command.second.returnType + " vk" + commandName + "( " + parameterList + " ) const VULKAN_HPP_NOEXCEPT\n"
" {\n"
" return ::vk" + commandName + "( " + parameters + " );\n"
" }\n";
appendPlatformLeave(str, !command.second.aliases.empty(), command.second.platform);
for (auto const& alias : command.second.aliases)
{
commandName = stripPrefix(alias, "vk");
str += "\n"
" " + command.second.returnType + " vk" + commandName + "( " + parameterList + " ) const VULKAN_HPP_NOEXCEPT\n"
" {\n"
" return ::vk" + commandName + "( " + parameters + " );\n"
" }\n";
}
}
}
str += " };\n#endif\n";
}
void VulkanHppGenerator::appendDispatchLoaderDefault(std::string & str)
{
str += "\n"
R"( class DispatchLoaderDynamic;
#if !defined(VULKAN_HPP_DISPATCH_LOADER_DYNAMIC)
# if defined(VK_NO_PROTOTYPES)
# define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
# else
# define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 0
# endif
#endif
#if !defined(VULKAN_HPP_DEFAULT_DISPATCHER)
# if VULKAN_HPP_DISPATCH_LOADER_DYNAMIC == 1
# define VULKAN_HPP_DEFAULT_DISPATCHER ::VULKAN_HPP_NAMESPACE::defaultDispatchLoaderDynamic
# define VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE namespace VULKAN_HPP_NAMESPACE { DispatchLoaderDynamic defaultDispatchLoaderDynamic; }
extern DispatchLoaderDynamic defaultDispatchLoaderDynamic;
# else
# define VULKAN_HPP_DEFAULT_DISPATCHER ::VULKAN_HPP_NAMESPACE::DispatchLoaderStatic()
# define VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
# endif
#endif
#if !defined(VULKAN_HPP_DEFAULT_DISPATCHER_TYPE)
# if VULKAN_HPP_DISPATCH_LOADER_DYNAMIC == 1
#define VULKAN_HPP_DEFAULT_DISPATCHER_TYPE ::VULKAN_HPP_NAMESPACE::DispatchLoaderDynamic
# else
# define VULKAN_HPP_DEFAULT_DISPATCHER_TYPE ::VULKAN_HPP_NAMESPACE::DispatchLoaderStatic
# endif
#endif
)";
}
void VulkanHppGenerator::appendEnum(std::string & str, std::pair<std::string, EnumData> const& enumData) const
{
str += " enum class " + stripPrefix(enumData.first, "Vk");
if (enumData.second.isBitmask)
{
auto bitmaskIt = std::find_if(m_bitmasks.begin(), m_bitmasks.end(), [&enumData](auto const& bitmask){ return bitmask.second.requirements == enumData.first; });
assert(bitmaskIt != m_bitmasks.end());
str += " : " + bitmaskIt->first;
}
str += "\n"
" {";
bool first = true;
for (auto const& value : enumData.second.values)
{
if (!first)
{
str += ",";
}
str += "\n " + value.vkValue + " = " + value.vulkanValue;
first = false;
}
for (auto const& value : enumData.second.aliases)
{
// make sure to only list alias values that differ from all non-alias values
if (std::find_if(enumData.second.values.begin(), enumData.second.values.end(), [&value](EnumValueData const& evd) { return value.second == evd.vkValue; }) == enumData.second.values.end())
{
if (!first)
{
str += ",";
}
str += "\n " + value.second + " = " + value.first;
first = false;
}
}
if (!first)
{
str += "\n ";
}
str += "};\n";
if (!enumData.second.alias.empty())
{
str += " using " + stripPrefix(enumData.second.alias, "Vk") + " = " + stripPrefix(enumData.first, "Vk") + ";\n";
}
}
void VulkanHppGenerator::appendEnums(std::string & str) const
{
for (auto const& e : m_enums)
{
str += "\n";
appendPlatformEnter(str, !e.second.alias.empty(), e.second.platform);
appendEnum(str, e);
appendEnumToString(str, e);
if (e.second.alias.empty()) // enums with an alias are not protected anymore !
{
appendPlatformLeave(str, !e.second.alias.empty(), e.second.platform);
}
}
}
void VulkanHppGenerator::appendEnumToString(std::string & str, std::pair<std::string, EnumData> const& enumData) const
{
std::string enumName = stripPrefix(enumData.first, "Vk");
str += "\n"
" VULKAN_HPP_INLINE std::string to_string( " + enumName + (enumData.second.values.empty() ? "" : " value") + " )\n"
" {";
if (enumData.second.values.empty())
{
str += "\n"
" return \"(void)\";\n";
}
else
{
str += "\n"
" switch ( value )\n"
" {\n";
for (auto const& value : enumData.second.values)
{
str += " case " + enumName + "::" + value.vkValue + " : return \"" + value.vkValue.substr(1) + "\";\n";
}
str += " default: return \"invalid\";\n"
" }\n";
}
str += " }\n";
}
void VulkanHppGenerator::appendForwardDeclarations(std::string & str) const
{
str += "\n";
for (auto const& structure : m_structures)
{
appendPlatformEnter(str, !structure.second.aliases.empty(), structure.second.platform);
str += std::string(" ") + (structure.second.isUnion ? "union" : "struct") + " " + stripPrefix(structure.first, "Vk") + ";\n";
for (std::string const& alias : structure.second.aliases)
{
str += " using " + stripPrefix(alias, "Vk") + " = " + stripPrefix(structure.first, "Vk") + ";\n";
}
appendPlatformLeave(str, !structure.second.aliases.empty(), structure.second.platform);
}
}
bool needsMultiVectorSizeCheck(size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices)
{
for (std::map<size_t, size_t>::const_iterator it0 = vectorParamIndices.begin(); it0 != vectorParamIndices.end(); ++it0)
{
if (it0->first != returnParamIndex)
{
for (std::map<size_t, size_t>::const_iterator it1 = std::next(it0); it1 != vectorParamIndices.end(); ++it1)
{
if ((it1->first != returnParamIndex) && (it0->second == it1->second))
{
return true;
}
}
}
}
return false;
}
void VulkanHppGenerator::appendFunction(std::string & str, std::string const& indentation, std::string const& name, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, std::string const& enhancedReturnType, bool definition, bool enhanced, bool singular, bool unique, bool isStructureChain, bool withAllocator) const
{
appendFunctionHeaderTemplate(str, indentation, returnParamIndex, templateParamIndex, enhancedReturnType, enhanced, singular, unique, !definition, isStructureChain);
str += indentation + (definition ? "VULKAN_HPP_INLINE " : "");
appendFunctionHeaderReturnType(str, commandData.second, returnParamIndex, vectorParamIndices, enhancedReturnType, enhanced, twoStep, singular, unique, isStructureChain);
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
if (definition && !handle.empty())
{
str += stripPrefix(handle, "Vk") + "::";
}
// append the function header name
str += (singular ? stripPluralS(name) : name);
if (unique)
{
str += "Unique";
}
appendFunctionHeaderArguments(str, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, enhanced, singular, !definition, withAllocator);
// Any function that originally does not return VkResult can be marked noexcept,
// if it is enhanced it must not include anything with an Allocator or needs size checks on multiple vectors
bool hasAllocator = enhancedReturnType.find("Allocator") != std::string::npos;
if (!enhanced || (commandData.second.returnType != "VkResult" && !(enhanced && (hasAllocator || needsMultiVectorSizeCheck(returnParamIndex, vectorParamIndices)))))
{
str += " VULKAN_HPP_NOEXCEPT";
}
str += std::string(definition ? "" : ";") + "\n";
if (definition)
{
// append the function body
str += indentation + "{\n";
if (enhanced)
{
appendFunctionBodyEnhanced(str, indentation, name, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, enhancedReturnType, singular, unique, isStructureChain, withAllocator);
}
else
{
appendFunctionBodyStandard(str, indentation, commandData);
}
str += indentation + "}\n";
}
}
void VulkanHppGenerator::appendFunctionBodyEnhanced(std::string & str, std::string const& indentation, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, std::string const& enhancedReturnType, bool singular, bool unique, bool isStructureChain, bool withAllocator) const
{
if (unique && !singular && (vectorParamIndices.find(returnParamIndex) != vectorParamIndices.end())) // returns a vector of UniqueStuff
{
appendFunctionBodyEnhancedVectorOfUniqueHandles(str, indentation, commandName, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, singular, withAllocator);
}
else if (isStructureChain && (vectorParamIndices.find(returnParamIndex) != vectorParamIndices.end()))
{
appendFunctionBodyEnhancedVectorOfStructureChain(str, indentation, commandData, returnParamIndex, vectorParamIndices, withAllocator);
}
else
{
if (1 < vectorParamIndices.size())
{
appendFunctionBodyEnhancedMultiVectorSizeCheck(str, indentation, commandName, commandData, returnParamIndex, vectorParamIndices);
}
std::string returnName;
if (returnParamIndex != INVALID_INDEX)
{
returnName = appendFunctionBodyEnhancedLocalReturnVariable(str, indentation, commandData.second, returnParamIndex, vectorParamIndices, twoStep, enhancedReturnType, singular, isStructureChain, withAllocator);
}
if (twoStep)
{
appendFunctionBodyEnhancedTwoStep(str, indentation, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, singular, returnName);
}
else
{
appendFunctionBodyEnhancedSingleStep(str, indentation, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, singular);
}
if ((commandData.second.returnType == "VkResult") || !commandData.second.successCodes.empty())
{
appendFunctionBodyEnhancedReturnResultValue(str, indentation, returnName, commandName, commandData, returnParamIndex, twoStep, singular, unique);
}
else if ((returnParamIndex != INVALID_INDEX) && (stripPrefix(commandData.second.returnType, "Vk") != enhancedReturnType))
{
// for the other returning cases, when the return type is somhow enhanced, just return the local returnVariable
str += indentation + " return " + returnName + ";\n";
}
}
}
std::string VulkanHppGenerator::appendFunctionBodyEnhancedLocalReturnVariable(std::string & str, std::string const& indentation, CommandData const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, std::string const& enhancedReturnType, bool singular, bool isStructureChain, bool withAllocator) const
{
std::string pureReturnType = stripPrefix(commandData.params[returnParamIndex].type.type, "Vk");
std::string returnName = startLowerCase(stripPrefix(commandData.params[returnParamIndex].name, "p"));
// there is a returned parameter -> we need a local variable to hold that value
if (stripPrefix(commandData.returnType, "Vk") != enhancedReturnType)
{
// the returned parameter is somehow enhanced by us
str += indentation + " ";
if (singular)
{
returnName = appendFunctionBodyEnhancedLocalReturnVariableSingular(str, indentation, returnName, pureReturnType, isStructureChain);
}
else
{
// in non-singular case, use the enhanced type for the return variable (like vector<...>)
if (isStructureChain && vectorParamIndices.empty())
{
// For StructureChains use the template parameters
str += "StructureChain<X, Y, Z...> structureChain;\n"
+ indentation + " " + enhancedReturnType + "& " + returnName + " = structureChain.template get<" + enhancedReturnType + ">()";
returnName = "structureChain";
}
else
{
str += enhancedReturnType + " " + returnName;
}
std::map<size_t, size_t>::const_iterator vpiIt = vectorParamIndices.find(returnParamIndex);
if (vpiIt != vectorParamIndices.end() && !twoStep)
{
appendFunctionBodyEnhancedLocalReturnVariableVectorSize(str, commandData.params, *vpiIt, returnParamIndex, vectorParamIndices, withAllocator);
}
else if (withAllocator)
{
str += "( vectorAllocator )";
}
}
str += ";\n";
}
else
{
// the return parameter is not enhanced -> the type is supposed to be a Result and there are more than one success codes!
assert((commandData.returnType == "VkResult") && (1 < commandData.successCodes.size()));
str += indentation + " " + pureReturnType + " " + returnName + ";\n";
}
return returnName;
}
void VulkanHppGenerator::appendFunctionBodyEnhancedLocalReturnVariableVectorSize(std::string & str, std::vector<ParamData> const& params, std::pair<size_t, size_t> const& vectorParamIndex, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool withAllocator) const
{
// if the return parameter is a vector parameter, and not part of a two-step algorithm, initialize its size
std::string size;
if (vectorParamIndex.second == INVALID_INDEX)
{
assert(!params[returnParamIndex].len.empty());
// the size of the vector is not given by an other parameter, but by some member of a parameter, described as 'parameter::member'
// -> replace the '::' by '.' and filter out the leading 'p' to access that value
size = startLowerCase(stripPrefix(params[returnParamIndex].len, "p"));
size_t pos = size.find("::");
assert(pos != std::string::npos);
size.replace(pos, 2, ".");
}
else
{
// the size of the vector is given by an other parameter
// first check, if that size has become the size of some other vector parameter
// -> look for it and get it's actual size
for (auto const& vpi : vectorParamIndices)
{
if ((vpi.first != vectorParamIndex.first) && (vpi.second == vectorParamIndex.second))
{
size = startLowerCase(stripPrefix(params[vpi.first].name, "p")) + ".size()";
break;
}
}
if (size.empty())
{
// otherwise, just use that parameter
size = params[vectorParamIndex.second].name;
}
}
assert(!size.empty());
str += "( " + size + (withAllocator ? ", vectorAllocator" : "") + " )";
}
void VulkanHppGenerator::appendFunctionBodyEnhancedMultiVectorSizeCheck(std::string & str, std::string const& indentation, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices) const
{
std::string const sizeCheckTemplate =
R"#(#ifdef VULKAN_HPP_NO_EXCEPTIONS
${i} VULKAN_HPP_ASSERT( ${firstVectorName}.size() == ${secondVectorName}.size() );
#else
${i} if ( ${firstVectorName}.size() != ${secondVectorName}.size() )
${i} {
${i} throw LogicError( VULKAN_HPP_NAMESPACE_STRING "::${className}::${commandName}: ${firstVectorName}.size() != ${secondVectorName}.size()" );
${i} }
#endif /*VULKAN_HPP_NO_EXCEPTIONS*/
)#";
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
// add some error checks if multiple vectors need to have the same size
for (std::map<size_t, size_t>::const_iterator it0 = vectorParamIndices.begin(); it0 != vectorParamIndices.end(); ++it0)
{
if (it0->first != returnParamIndex)
{
for (std::map<size_t, size_t>::const_iterator it1 = std::next(it0); it1 != vectorParamIndices.end(); ++it1)
{
if ((it1->first != returnParamIndex) && (it0->second == it1->second))
{
str += replaceWithMap(sizeCheckTemplate, std::map<std::string, std::string>({
{ "firstVectorName", startLowerCase(stripPrefix(commandData.second.params[it0->first].name, "p")) },
{ "secondVectorName", startLowerCase(stripPrefix(commandData.second.params[it1->first].name, "p")) },
{ "className", handle },
{ "commandName", commandName },
{ "i", indentation }
}));
}
}
}
}
}
void VulkanHppGenerator::appendFunctionBodyEnhancedReturnResultValue(std::string & str, std::string const& indentation, std::string const& returnName, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, bool twoStep, bool singular, bool unique) const
{
std::string type = (returnParamIndex != INVALID_INDEX) ? commandData.second.params[returnParamIndex].type.type : "";
std::string returnVectorName = (returnParamIndex != INVALID_INDEX) ? stripPostfix(stripPrefix(commandData.second.params[returnParamIndex].name, "p"), "s") : "";
if (commandData.second.returnType == "void") {
std::cerr << "warning: skipping appendFunctionBodyEnhancedReturnResultValue for function " << commandName << " because the returnType is void";
return;
}
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
if (unique)
{
// the unique version needs a Deleter object for destruction of the newly created stuff
// get the DeleterData corresponding to the returned type
// special handling for "createDevice", as Device is created from PhysicalDevice, but destroyed on its own
bool noParent = handle.empty() || (commandData.first == "vkCreateDevice");
str += "\n"
+ indentation + ((commandData.first == "vkAllocateMemory") ? " ObjectFree<" : " ObjectDestroy<") + (noParent ? "NoParent" : stripPrefix(handle, "Vk")) + ",Dispatch> deleter( " + (noParent ? "" : "*this, ") + "allocator, d );\n"
+ indentation + " return createResultValue<" + stripPrefix(type, "Vk") + ",Dispatch>( result, ";
}
else
{
str += indentation + " return createResultValue( result, ";
}
// if the return type is "Result" or there is at least one success code, create the Result/Value construct to return
if (returnParamIndex != INVALID_INDEX)
{
// if there's a return parameter, list it in the Result/Value constructor
str += returnName + ", ";
}
// now the function name (with full namespace) as a string
str += "VULKAN_HPP_NAMESPACE_STRING\"::" + (handle.empty() ? "" : stripPrefix(handle, "Vk") + "::") + (singular ? stripPluralS(commandName) : commandName) + (unique ? "Unique" : "") + "\"";
if (!twoStep && (1 < commandData.second.successCodes.size()))
{
// and for the single-step algorithms with more than one success code list them all
str += ", { Result::" + createSuccessCode(commandData.second.successCodes[0], m_tags);
for (size_t i = 1; i < commandData.second.successCodes.size(); i++)
{
str += ", Result::" + createSuccessCode(commandData.second.successCodes[i], m_tags);
}
str += " }";
}
if (unique)
{
str += ", deleter";
}
str += " );\n";
}
void VulkanHppGenerator::appendFunctionBodyEnhancedSingleStep(std::string & str, std::string const& indentation, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool singular) const
{
str += indentation + " ";
if (commandData.second.returnType == "VkResult")
{
str += "Result result = static_cast<Result>( ";
}
else if (commandData.second.returnType != "void")
{
str += "return ";
}
appendCall(str, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, false, true, singular);
if (commandData.second.returnType == "VkResult")
{
str += " )";
}
str += ";\n";
}
void VulkanHppGenerator::appendFunctionBodyEnhancedTwoStep(std::string & str, std::string const& indentation, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool singular, std::string const& returnName) const
{
assert(!singular);
assert((commandData.second.returnType == "VkResult") || (commandData.second.returnType == "void"));
assert(returnParamIndex != INVALID_INDEX);
// local count variable to hold the size of the vector to fill
std::map<size_t, size_t>::const_iterator returnit = vectorParamIndices.find(returnParamIndex);
assert(returnit != vectorParamIndices.end() && (returnit->second != INVALID_INDEX));
// take the pure type of the size parameter; strip the leading 'p' from its name for its local name
std::string sizeName = startLowerCase(stripPrefix(commandData.second.params[returnit->second].name, "p"));
str += indentation + " " + stripPrefix(commandData.second.params[returnit->second].type.type, "Vk") + " " + sizeName + ";\n";
std::string const multiSuccessTemplate =
R"(${i} Result result;
${i} do
${i} {
${i} result = static_cast<Result>( ${call1} );
${i} if ( ( result == Result::eSuccess ) && ${sizeName} )
${i} {
${i} ${returnName}.resize( ${sizeName} );
${i} result = static_cast<Result>( ${call2} );
${i} }
${i} } while ( result == Result::eIncomplete );
${i} if ( result == Result::eSuccess )
${i} {
${i} VULKAN_HPP_ASSERT( ${sizeName} <= ${returnName}.size() );
${i} ${returnName}.resize( ${sizeName} );
${i} }
)";
std::string const singleSuccessTemplate =
R"(${i} Result result = static_cast<Result>( ${call1} );
${i} if ( ( result == Result::eSuccess ) && ${sizeName} )
${i} {
${i} ${returnName}.resize( ${sizeName} );
${i} result = static_cast<Result>( ${call2} );
${i} }
)";
std::string const voidMultiCallTemplate =
R"(${i} ${call1};
${i} ${returnName}.resize( ${sizeName} );
${i} ${call2};
)";
std::string const& selectedTemplate = (commandData.second.returnType == "VkResult") ? ((1 < commandData.second.successCodes.size()) ? multiSuccessTemplate : singleSuccessTemplate) : voidMultiCallTemplate;
std::string call1, call2;
appendCall(call1, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, true, true, false);
appendCall(call2, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, true, false, false);
str += replaceWithMap(selectedTemplate,
{
{ "sizeName", sizeName },
{ "returnName", returnName },
{ "call1", call1 },
{ "call2", call2 },
{ "i", indentation }
});
}
void VulkanHppGenerator::appendFunctionBodyEnhancedVectorOfStructureChain(std::string & str, std::string const& indentation, std::pair<std::string,CommandData> const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool withAllocator) const
{
std::string const stringTemplate =
R"(${i} std::vector<StructureChain,Allocator> ${returnName}${vectorAllocator};
${i} uint32_t ${sizeName};
${i} d.${commandName}( m_${handleName}, &${sizeName}, nullptr );
${i} ${returnName}.resize( ${sizeName} );
${i} std::vector<VULKAN_HPP_NAMESPACE::${returnType}> localVector( ${sizeName} );
${i} for ( uint32_t i = 0; i < ${sizeName} ; i++ )
${i} {
${i} localVector[i].pNext = ${returnName}[i].template get<VULKAN_HPP_NAMESPACE::${returnType}>().pNext;
${i} }
${i} d.${commandName}( m_${handleName}, &${sizeName}, reinterpret_cast<${VkReturnType}*>( localVector.data() ) );
${i} for ( uint32_t i = 0; i < ${sizeName} ; i++ )
${i} {
${i} ${returnName}[i].template get<VULKAN_HPP_NAMESPACE::${returnType}>() = localVector[i];
${i} }
${i} return ${returnName};
)";
// local count variable to hold the size of the vector to fill
std::map<size_t, size_t>::const_iterator returnit = vectorParamIndices.find(returnParamIndex);
assert(returnit != vectorParamIndices.end() && (returnit->second != INVALID_INDEX));
assert(m_commandToHandle.find(commandData.first)->second == commandData.second.params[0].type.type); // make sure, the first argument is the handle
assert(commandData.second.params.size() == 3); // make sure, there are three args: the handle, the pointer to size, and the data pointer
str += replaceWithMap(stringTemplate,
{
{ "commandName", commandData.first},
{ "handleName", startLowerCase(stripPrefix(commandData.second.params[0].type.type, "Vk")) },
{ "i", indentation },
{ "returnName", startLowerCase(stripPrefix(commandData.second.params[returnParamIndex].name, "p")) },
{ "returnType", stripPrefix(commandData.second.params[returnParamIndex].type.type, "Vk")},
{ "sizeName", startLowerCase(stripPrefix(commandData.second.params[returnit->second].name, "p"))},
{ "vectorAllocator", withAllocator ? "( vectorAllocator )" : "" },
{ "VkReturnType", commandData.second.params[returnParamIndex].type.type}
});
}
void VulkanHppGenerator::appendFunctionBodyEnhancedVectorOfUniqueHandles(std::string & str, std::string const& indentation, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool singular, bool withAllocator) const
{
std::string const stringTemplate =
R"(${i} static_assert( sizeof( ${type} ) <= sizeof( UniqueHandle<${type}, Dispatch> ), "${type} is greater than UniqueHandle<${type}, Dispatch>!" );
${i} std::vector<UniqueHandle<${type}, Dispatch>, Allocator> ${typeVariable}s${allocator};
${i} ${typeVariable}s.reserve( ${vectorSize} );
${i} ${type}* buffer = reinterpret_cast<${type}*>( reinterpret_cast<char*>( ${typeVariable}s.data() ) + ${vectorSize} * ( sizeof( UniqueHandle<${type}, Dispatch> ) - sizeof( ${type} ) ) );
${i} Result result = static_cast<Result>(d.vk${command}( m_device, ${arguments}, reinterpret_cast<Vk${type}*>( buffer ) ) );
${i} if ( ${successChecks} )
${i} {
${i} ${Deleter}<${DeleterTemplate},Dispatch> deleter( *this, ${deleterArg}, d );
${i} for ( size_t i=0 ; i<${vectorSize} ; i++ )
${i} {
${i} ${typeVariable}s.push_back( UniqueHandle<${type}, Dispatch>( buffer[i], deleter ) );
${i} }
${i} }
${i} return createResultValue( result, ${typeVariable}s, VULKAN_HPP_NAMESPACE_STRING "::${class}::${commandName}Unique"${successCodes} );
)";
std::string type = (returnParamIndex != INVALID_INDEX) ? commandData.second.params[returnParamIndex].type.type : "";
std::string typeVariable = startLowerCase(stripPrefix(type, "Vk"));
std::string arguments;
appendArguments(arguments, commandData.second, returnParamIndex, templateParamIndex, vectorParamIndices, twoStep, true, singular, 1, commandData.second.params.size() - 1);
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
auto handleIt = m_handles.find(type);
assert(handleIt != m_handles.end());
assert(!commandData.second.successCodes.empty());
std::string successChecks = "result == VULKAN_HPP_NAMESPACE::Result::" + createSuccessCode(commandData.second.successCodes[0], m_tags);
std::string successCodes;
if (1 < commandData.second.successCodes.size())
{
successChecks = "( " + successChecks + " )";
successCodes = ", { VULKAN_HPP_NAMESPACE::Result::" + createSuccessCode(commandData.second.successCodes[0], m_tags);
for (size_t i = 1; i < commandData.second.successCodes.size(); i++)
{
successChecks += " || ( result == VULKAN_HPP_NAMESPACE::Result::" + createSuccessCode(commandData.second.successCodes[i], m_tags) + " )";
successCodes += ", VULKAN_HPP_NAMESPACE::Result::" + createSuccessCode(commandData.second.successCodes[i], m_tags);
}
successCodes += " }";
}
bool isCreateFunction = (commandData.first.substr(2, 6) == "Create");
str += replaceWithMap(stringTemplate, std::map<std::string, std::string>
{
{ "allocator", withAllocator ? "( vectorAllocator )" : "" },
{ "arguments", arguments },
{ "class", stripPrefix(handle, "Vk") },
{ "command", stripPrefix(commandData.first, "vk") },
{ "commandName", commandName },
{ "Deleter", handleIt->second.deletePool.empty() ? "ObjectDestroy" : "PoolFree" },
{ "deleterArg", handleIt->second.deletePool.empty() ? "allocator" : "allocateInfo." + startLowerCase(stripPrefix(handleIt->second.deletePool, "Vk")) },
{ "DeleterTemplate", stripPrefix(handle, "Vk") + (handleIt->second.deletePool.empty() ? "" : "," + stripPrefix(handleIt->second.deletePool, "Vk")) },
{ "i", indentation },
{ "successChecks", successChecks },
{ "successCodes", successCodes },
{ "type", stripPrefix(type, "Vk") },
{ "typeVariable", typeVariable },
{ "vectorSize", isCreateFunction ? "createInfos.size()" : "allocateInfo." + typeVariable + "Count" }
});
}
void VulkanHppGenerator::appendFunctionBodyStandard(std::string & str, std::string const& indentation, std::pair<std::string, CommandData> const& commandData) const
{
std::pair<bool, std::string> returnData = generateFunctionBodyStandardReturn(commandData.second.returnType);
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
assert(handle.empty() || (handle == commandData.second.params[0].type.type));
str += indentation + " " + returnData.second + "d." + commandData.first + "( " + (handle.empty() ? "" : ("m_" + startLowerCase(stripPrefix(handle, "Vk"))));
for (size_t i = handle.empty() ? 0 : 1; i < commandData.second.params.size(); i++)
{
if (0 < i)
{
str += ", ";
}
appendFunctionBodyStandardArgument(str, commandData.second.params[i].type, commandData.second.params[i].name);
}
str += std::string(" )") + (returnData.first ? " )" : "") + ";\n";
}
void VulkanHppGenerator::appendFunctionBodyStandardArgument(std::string & str, TypeData const& typeData, std::string const& name) const
{
if (beginsWith(typeData.type, "Vk"))
{
// the parameter is a vulkan type
if (!typeData.postfix.empty())
{
assert(typeData.postfix.back() == '*');
// it's a pointer -> need to reinterpret_cast it
appendReinterpretCast(str, typeData.prefix.find("const") == 0, typeData.type, typeData.postfix.find("* const") != std::string::npos);
}
else
{
// it's a value -> need to static_cast ist
str += "static_cast<" + typeData.type + ">";
}
str += "( " + name + " )";
}
else
{
// it's a non-vulkan type -> just use it
str += name;
}
}
bool VulkanHppGenerator::appendFunctionHeaderArgumentEnhanced(std::string & str, ParamData const& param, size_t paramIndex, std::map<size_t, size_t> const& vectorParamIndices, bool skip, bool argEncountered, bool isTemplateParam, bool isLastArgument, bool singular, bool withDefaults, bool withAllocator) const
{
if (!skip)
{
if (argEncountered)
{
str += ", ";
}
std::string strippedParameterName = startLowerCase(stripPrefix(param.name, "p"));
std::map<size_t, size_t>::const_iterator it = vectorParamIndices.find(paramIndex);
if (it == vectorParamIndices.end())
{
// the argument ist not a vector
if (param.type.postfix.empty())
{
// and its not a pointer -> just use its type and name here
appendFunctionHeaderArgumentEnhancedSimple(str, param, isLastArgument, withDefaults, withAllocator);
}
else
{
// the argument is not a vector, but a pointer
assert(param.type.postfix.back() == '*');
appendFunctionHeaderArgumentEnhancedPointer(str, param, strippedParameterName, withDefaults, withAllocator);
}
}
else
{
// the argument is a vector
appendFunctionHeaderArgumentEnhancedVector(str, param, strippedParameterName, it->second != INVALID_INDEX, isTemplateParam, singular, withDefaults, withAllocator);
}
argEncountered = true;
}
return argEncountered;
}
void VulkanHppGenerator::appendFunctionHeaderArgumentEnhancedPointer(std::string & str, ParamData const& param, std::string const& strippedParameterName, bool withDefaults, bool withAllocator) const
{
assert(param.type.postfix.back() == '*');
if (param.optional)
{
// for an optional argument, trim the leading 'p' from the name
str += "Optional<" + param.type.prefix + (param.type.prefix.empty() ? "" : " ") + stripPrefix(param.type.type, "Vk") + "> " + strippedParameterName;
if (withDefaults && !withAllocator)
{
str += " = nullptr";
}
}
else if (param.type.type == "void")
{
// for void-pointer, just use type and name
str += param.type.compose() + " " + param.name;
}
else if (param.type.type != "char")
{
// for non-char-pointer, change to reference
assert(param.type.postfix == "*");
str += param.type.prefix + (param.type.prefix.empty() ? "" : " ") + stripPrefix(param.type.type, "Vk") + " & " + strippedParameterName;
}
else
{
// for char-pointer, change to const reference to std::string
str += "const std::string & " + strippedParameterName;
}
}
void VulkanHppGenerator::appendFunctionHeaderArgumentEnhancedSimple(std::string & str, ParamData const& param, bool lastArgument, bool withDefaults, bool withAllocator) const
{
str += param.type.compose() + " " + param.name + constructCArraySizes(param.arraySizes);
if (withDefaults && lastArgument && !withAllocator)
{
// check if the very last argument is a flag without any bits -> provide some empty default for it
std::map<std::string, BitmaskData>::const_iterator bitmasksIt = m_bitmasks.find(param.type.type);
if (bitmasksIt != m_bitmasks.end())
{
// get the enum corresponding to this flag, to check if it's empty
std::string strippedBitmaskName = stripPrefix(bitmasksIt->first, "Vk");
std::map<std::string, EnumData>::const_iterator enumIt = m_enums.find(bitmasksIt->second.requirements);
assert((enumIt == m_enums.end()) || (enumIt->second.isBitmask));
if ((enumIt == m_enums.end()) || (enumIt->second.values.empty()))
{
// there are no bits in this flag -> provide the default
str += " = " + stripPrefix(param.type.type, "Vk") + "()";
}
}
}
}
void VulkanHppGenerator::appendFunctionHeaderArgumentEnhancedVector(std::string & str, ParamData const& param, std::string const& strippedParameterName, bool hasSizeParam, bool isTemplateParam, bool singular, bool withDefaults, bool withAllocator) const
{
assert(param.type.postfix.back() == '*');
// it's optional, if it's marked as optional and there's no size specified
bool optional = param.optional && !hasSizeParam;
if (param.type.type.find("char") != std::string::npos)
{
// it's a char-vector -> use a std::string (either optional or a const-reference
if (optional)
{
str += "Optional<const std::string> " + strippedParameterName;
if (withDefaults && !withAllocator)
{
str += " = nullptr";
}
}
else
{
str += "const std::string & " + strippedParameterName;
}
}
else
{
// it's a non-char vector (they are never optional)
assert(!optional);
if (singular)
{
// in singular case, change from pointer to reference
str += param.type.prefix + (param.type.prefix.empty() ? "" : " ") + stripPrefix(param.type.type, "Vk") + " & " + stripPluralS(strippedParameterName);
}
else
{
// otherwise, use our ArrayProxy
bool isConst = (param.type.prefix.find("const") != std::string::npos);
str += "ArrayProxy<" + (isTemplateParam ? (isConst ? "const T" : "T") : stripPostfix(param.type.compose(), "*")) + "> " + strippedParameterName;
}
}
}
void VulkanHppGenerator::appendFunctionHeaderArguments(std::string & str, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool enhanced, bool singular, bool withDefaults, bool withAllocator) const
{
str += "(";
if (enhanced)
{
appendFunctionHeaderArgumentsEnhanced(str, commandData, returnParamIndex, templateParamIndex, vectorParamIndices, singular, withDefaults, withAllocator);
}
else
{
appendFunctionHeaderArgumentsStandard(str, commandData, withDefaults);
}
str += ")";
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
if (!m_commandToHandle.find(commandData.first)->second.empty())
{
str += " const";
}
}
void VulkanHppGenerator::appendFunctionHeaderArgumentsEnhanced(std::string & str, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool singular, bool withDefaults, bool withAllocator) const
{
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
// check if there's at least one argument left to put in here
std::set<size_t> skippedParams = determineSkippedParams(returnParamIndex, vectorParamIndices);
if (skippedParams.size() + (handle.empty() ? 0 : 1) < commandData.second.params.size())
{
// determine the last argument, where we might provide some default for
size_t lastArgument = INVALID_INDEX;
for (size_t i = commandData.second.params.size() - 1; i < commandData.second.params.size(); i--)
{
if (skippedParams.find(i) == skippedParams.end())
{
lastArgument = i;
break;
}
}
str += " ";
bool argEncountered = false;
for (size_t i = handle.empty() ? 0 : 1; i < commandData.second.params.size(); i++)
{
argEncountered = appendFunctionHeaderArgumentEnhanced(str, commandData.second.params[i], i, vectorParamIndices, skippedParams.find(i) != skippedParams.end(), argEncountered,
(templateParamIndex == i), (lastArgument == i), singular, withDefaults, withAllocator);
}
if (argEncountered)
{
str += ", ";
}
}
if (withAllocator)
{
str += "Allocator const& vectorAllocator, ";
}
str += "Dispatch const &d";
if (withDefaults && !withAllocator)
{
str += " = VULKAN_HPP_DEFAULT_DISPATCHER";
}
str += " ";
}
void VulkanHppGenerator::appendFunctionHeaderArgumentsStandard(std::string & str, std::pair<std::string, CommandData> const& commandData, bool withDefaults) const
{
// for the standard case, just list all the arguments as we've got them
// determine the last argument, where we might provide some default for
size_t lastArgument = commandData.second.params.size() - 1;
assert(m_commandToHandle.find(commandData.first) != m_commandToHandle.end());
std::string const& handle = m_commandToHandle.find(commandData.first)->second;
bool argEncountered = false;
for (size_t i = handle.empty() ? 0 : 1; i < commandData.second.params.size(); i++)
{
argEncountered = appendFunctionHeaderArgumentStandard(str, commandData.second.params[i], argEncountered, lastArgument == i, withDefaults);
}
if (argEncountered)
{
str += ", ";
}
str += "Dispatch const &d";
if (withDefaults)
{
str += " = VULKAN_HPP_DEFAULT_DISPATCHER ";
}
}
bool VulkanHppGenerator::appendFunctionHeaderArgumentStandard(std::string & str, ParamData const& param, bool argEncountered, bool isLastArgument, bool withDefaults) const
{
if (argEncountered)
{
str += ",";
}
str += " " + param.type.compose() + " " + param.name + constructCArraySizes(param.arraySizes);
if (withDefaults && isLastArgument)
{
// check if the very last argument is a flag without any bits -> provide some empty default for it
std::map<std::string, BitmaskData>::const_iterator bitmasksIt = m_bitmasks.find(param.type.type);
if (bitmasksIt != m_bitmasks.end())
{
// get the enum corresponding to this flag, to check if it's empty
std::string strippedBitmaskName = stripPrefix(bitmasksIt->first, "Vk");
std::map<std::string, EnumData>::const_iterator enumIt = m_enums.find(bitmasksIt->second.requirements);
assert((enumIt == m_enums.end()) || (enumIt->second.isBitmask));
if ((enumIt == m_enums.end()) || (enumIt->second.values.empty()))
{
// there are no bits in this flag -> provide the default
str += " = " + stripPrefix(param.type.type, "Vk") + "()";
}
}
}
return true;
}
void VulkanHppGenerator::appendFunctionHeaderReturnType(std::string & str, CommandData const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, std::string const& enhancedReturnType, bool enhanced, bool twoStep, bool singular, bool unique, bool isStructureChain) const
{
if (enhanced)
{
bool useTypename = ((commandData.successCodes.size() == 1) || ((commandData.successCodes.size() == 2) && (commandData.successCodes[1] == "VK_INCOMPLETE") && twoStep));
// the enhanced function might return some pretty complex return stuff
bool isVector = (enhancedReturnType.find("Allocator") != std::string::npos);
if (unique)
{
// the unique version returns something prefixed with 'Unique'; potentially a vector of that stuff
// it's a vector, if it's not the singular version and the return parameter is a vector parameter
bool returnsVector = !singular && (vectorParamIndices.find(returnParamIndex) != vectorParamIndices.end());
std::string returnType = isStructureChain ? "StructureChain<X, Y, Z...>" : stripPrefix(commandData.params[returnParamIndex].type.type, "Vk");
str += useTypename ? "typename ResultValueType<" : "ResultValue<";
str += returnsVector ? "std::vector<UniqueHandle<" + returnType + ",Dispatch>,Allocator>>" : "UniqueHandle<" + returnType + ",Dispatch>>";
str += useTypename ? "::type " : " ";
}
else if ((enhancedReturnType != stripPrefix(commandData.returnType, "Vk")) && (commandData.returnType != "void"))
{
// if the enhanced return type differs from the original return type, and it's not void, we return a ResultValueType<...>::type
assert(commandData.returnType == "VkResult");
// in singular case, we create the ResultValueType from the pure return type, otherwise from the enhanced return type
std::string returnType = isStructureChain ? "StructureChain<X, Y, Z...>" : (singular ? stripPrefix(commandData.params[returnParamIndex].type.type, "Vk") : enhancedReturnType);
// for the non-singular case with allocation, we need to prepend with 'typename' to keep compilers happy
str += (useTypename ? "typename ResultValueType<" : "ResultValue<") + returnType + ">" + (useTypename ? "::type " : " ");
}
else if ((returnParamIndex != INVALID_INDEX) && (1 < commandData.successCodes.size()))
{
// if there is a return parameter at all, and there are multiple success codes, we return a ResultValue<...> with the pure return type
assert(commandData.returnType == "VkResult");
str += "ResultValue<" + (isStructureChain ? "StructureChain<X, Y, Z...>" : stripPrefix(commandData.params[returnParamIndex].type.type, "Vk")) + "> ";
}
else
{
// and in every other case, we just return the enhanced return type.
str += (isStructureChain && !isVector ? "StructureChain<X, Y, Z...>" : enhancedReturnType) + " ";
}
}
else
{
// the non-enhanced function just uses the return type
str += stripPrefix(commandData.returnType, "Vk") + " ";
}
}
void VulkanHppGenerator::appendFunctionHeaderTemplate(std::string & str, std::string const& indentation, size_t returnParamIndex, size_t templateParamIndex, std::string const& enhancedReturnType, bool enhanced, bool singular, bool unique, bool withDefault, bool isStructureChain) const
{
bool withAllocator = (enhancedReturnType.find("Allocator") != std::string::npos);
str += indentation + "template<";
if (enhanced)
{
if (isStructureChain)
{
str += std::string("typename ") + (withAllocator ? "StructureChain" : "X, typename Y, typename ...Z") + ", ";
}
else if ((templateParamIndex != INVALID_INDEX) && ((templateParamIndex != returnParamIndex) || (enhancedReturnType == "Result")))
{
assert(!withAllocator);
str += "typename T, ";
}
if (!singular && withAllocator)
{
// otherwise, if there's an Allocator used in the enhanced return type, we templatize on that Allocator
assert((enhancedReturnType.substr(0, 12) == "std::vector<") && (enhancedReturnType.find(',') != std::string::npos) && (12 < enhancedReturnType.find(',')));
str += "typename Allocator";
if (withDefault)
{
// for the default type get the type from the enhancedReturnType, which is of the form 'std::vector<Type,Allocator>'
assert(!isStructureChain || !unique);
str += " = std::allocator<" + (isStructureChain ? "StructureChain" : (unique ? "Unique" : "") + enhancedReturnType.substr(12, enhancedReturnType.find(',') - 12)) + ">";
}
str += ", ";
}
}
str += std::string("typename Dispatch") + (withDefault ? " = VULKAN_HPP_DEFAULT_DISPATCHER_TYPE" : "") + ">\n";
}
void VulkanHppGenerator::appendHandle(std::string & str, std::pair<std::string, HandleData> const& handleData, std::set<std::string> & listedHandles) const
{
if (listedHandles.find(handleData.first) == listedHandles.end())
{
listedHandles.insert(handleData.first);
// first check for any handle that needs to be listed before this one
for (auto const& command : handleData.second.commands)
{
for (auto const& parameter : command.second.params)
{
std::string typeName = parameter.type.type;
auto handlesIt = m_handles.find(typeName);
if ((handlesIt != m_handles.end()) && (listedHandles.find(typeName) == listedHandles.end()))
{
appendHandle(str, *handlesIt, listedHandles);
}
}
}
if (handleData.first.empty())
{
for (auto const& command : handleData.second.commands)
{
std::string commandName = determineCommandName(command.first, command.second.params[0].type.type);
if (command.first == "vkCreateInstance")
{
// special handling for createInstance, as we need to explicitly place the forward declarations and the deleter classes here
#if !defined(NDEBUG)
auto handleIt = m_handles.find("");
assert((handleIt != m_handles.end()) && (handleIt->second.childrenHandles.size() == 2));
assert(handleIt->second.childrenHandles.find("VkInstance") != handleIt->second.childrenHandles.end());
#endif
appendUniqueTypes(str, "", { "VkInstance" });
}
str += "\n";
appendPlatformEnter(str, !command.second.aliases.empty(), command.second.platform);
appendCommand(str, " ", commandName, command, false);
appendPlatformLeave(str, !command.second.aliases.empty(), command.second.platform);
for (auto const& alias : command.second.aliases)
{
appendCommand(str, " ", determineCommandName(alias, command.second.params[0].type.type), command, false);
}
}
}
else
{
// then append any forward declaration of Deleters used by this handle
if (!handleData.second.childrenHandles.empty())
{
appendUniqueTypes(str, handleData.first, handleData.second.childrenHandles);
}
else if (handleData.first == "VkPhysicalDevice")
{
// special handling for class Device, as it's created from PhysicalDevice, but destroys itself
appendUniqueTypes(str, "", { "VkDevice" });
}
std::string commands;
// list all the commands that are mapped to members of this class
for (auto const& command : handleData.second.commands)
{
std::string enter, leave, commandString;
appendPlatformEnter(enter, !command.second.aliases.empty(), command.second.platform);
appendPlatformLeave(leave, !command.second.aliases.empty(), command.second.platform);
commands += "\n" + enter;
std::string commandName = determineCommandName(command.first, command.second.params[0].type.type);
appendCommand(commands, " ", commandName, command, false);
for (auto const& alias : command.second.aliases)
{
assert(enter.empty() && leave.empty());
commands += "\n";
std::string aliasCommandName = determineCommandName(alias, command.second.params[0].type.type);
appendCommand(commands, " ", aliasCommandName, command, false);
}
// special handling for destroy functions
bool platformLeft = false;
if (((command.first.substr(2, 7) == "Destroy") && (commandName != "destroy")) || (command.first.substr(2, 4) == "Free"))
{
assert(1 < command.second.params.size());
auto handleIt = m_handles.find(command.second.params[1].type.type);
assert(handleIt != m_handles.end());
if (!handleIt->second.alias.empty())
{
commands += leave;
platformLeft = true;
}
commandName = (command.first.substr(2, 7) == "Destroy") ? "destroy" : "free";
std::string destroyCommandString;
appendCommand(destroyCommandString, " ", commandName, command, false);
commands += "\n" + destroyCommandString;
}
if (!platformLeft)
{
commands += leave;
}
}
static const std::string templateString = R"(
${enter} class ${className}
{
public:
using CType = Vk${className};
static VULKAN_HPP_CONST_OR_CONSTEXPR ObjectType objectType = ObjectType::e${className};
public:
VULKAN_HPP_CONSTEXPR ${className}() VULKAN_HPP_NOEXCEPT
: m_${memberName}(VK_NULL_HANDLE)
{}
VULKAN_HPP_CONSTEXPR ${className}( std::nullptr_t ) VULKAN_HPP_NOEXCEPT
: m_${memberName}(VK_NULL_HANDLE)
{}
VULKAN_HPP_TYPESAFE_EXPLICIT ${className}( Vk${className} ${memberName} ) VULKAN_HPP_NOEXCEPT
: m_${memberName}( ${memberName} )
{}
#if defined(VULKAN_HPP_TYPESAFE_CONVERSION)
${className} & operator=(Vk${className} ${memberName}) VULKAN_HPP_NOEXCEPT
{
m_${memberName} = ${memberName};
return *this;
}
#endif
${className} & operator=( std::nullptr_t ) VULKAN_HPP_NOEXCEPT
{
m_${memberName} = VK_NULL_HANDLE;
return *this;
}
#if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR)
auto operator<=>( ${className} const& ) const = default;
#else
bool operator==( ${className} const & rhs ) const VULKAN_HPP_NOEXCEPT
{
return m_${memberName} == rhs.m_${memberName};
}
bool operator!=(${className} const & rhs ) const VULKAN_HPP_NOEXCEPT
{
return m_${memberName} != rhs.m_${memberName};
}
bool operator<(${className} const & rhs ) const VULKAN_HPP_NOEXCEPT
{
return m_${memberName} < rhs.m_${memberName};
}
#endif
${commands}
VULKAN_HPP_TYPESAFE_EXPLICIT operator Vk${className}() const VULKAN_HPP_NOEXCEPT
{
return m_${memberName};
}
explicit operator bool() const VULKAN_HPP_NOEXCEPT
{
return m_${memberName} != VK_NULL_HANDLE;
}
bool operator!() const VULKAN_HPP_NOEXCEPT
{
return m_${memberName} == VK_NULL_HANDLE;
}
private:
Vk${className} m_${memberName};
};
static_assert( sizeof( ${className} ) == sizeof( Vk${className} ), "handle and wrapper have different size!" );
template <>
struct cpp_type<ObjectType::e${className}>
{
using type = ${className};
};
)";
std::string enter, leave;
appendPlatformEnter(enter, !handleData.second.alias.empty(), handleData.second.platform);
appendPlatformLeave(leave, !handleData.second.alias.empty(), handleData.second.platform);
str += replaceWithMap(templateString, {
{ "className", stripPrefix(handleData.first, "Vk") },
{ "commands", commands },
{ "enter", enter },
{ "memberName", startLowerCase(stripPrefix(handleData.first, "Vk")) }
});
if (!handleData.second.alias.empty())
{
str += " using " + stripPrefix(handleData.second.alias, "Vk") + " = " + stripPrefix(handleData.first, "Vk") + ";\n";
}
str += leave;
}
}
}
void VulkanHppGenerator::appendHandles(std::string & str) const
{
std::set<std::string> listedHandles;
for (auto const& handle : m_handles)
{
appendHandle(str, handle, listedHandles);
}
}
void VulkanHppGenerator::appendHandlesCommandDefintions(std::string & str) const
{
for (auto const& handle : m_handles)
{
// finally the commands, that are member functions of this handle
for (auto const& command : handle.second.commands)
{
std::string commandName = determineCommandName(command.first, command.second.params[0].type.type);
std::string strippedName = startLowerCase(stripPrefix(command.first, "vk"));
str += "\n";
appendPlatformEnter(str, !command.second.aliases.empty(), command.second.platform);
appendCommand(str, " ", commandName, command, true);
for (auto const& alias : command.second.aliases)
{
str += "\n";
appendCommand(str, " ", determineCommandName(alias, command.second.params[0].type.type), command, true);
}
// special handling for destroy functions
bool platformLeft = false;
if (((command.first.substr(2, 7) == "Destroy") && (commandName != "destroy")) || (command.first.substr(2, 4) == "Free"))
{
assert(1 < command.second.params.size());
auto handleIt = m_handles.find(command.second.params[1].type.type);
assert(handleIt != m_handles.end());
if (!handleIt->second.alias.empty())
{
appendPlatformLeave(str, !command.second.aliases.empty(), command.second.platform);
platformLeft = true;
}
commandName = (command.first.substr(2, 7) == "Destroy") ? "destroy" : "free";
str += "\n";
appendCommand(str, " ", commandName, command, true);
}
if (!platformLeft)
{
appendPlatformLeave(str, !command.second.aliases.empty(), command.second.platform);
}
}
}
str += "\n";
}
// Intended only for `enum class Result`!
void VulkanHppGenerator::appendResultExceptions(std::string & str) const
{
std::string templateString = R"(
class ${className} : public SystemError
{
public:
${className}( std::string const& message )
: SystemError( make_error_code( ${enumName}::${enumMemberName} ), message ) {}
${className}( char const * message )
: SystemError( make_error_code( ${enumName}::${enumMemberName} ), message ) {}
};
)";
auto enumData = m_enums.find("VkResult");
for (auto const& value : enumData->second.values)
{
if (beginsWith(value.vkValue, "eError"))
{
str += replaceWithMap(templateString,
{
{ "className", stripPrefix(value.vkValue, "eError") + "Error" },
{ "enumName", stripPrefix(enumData->first, "Vk") },
{ "enumMemberName", value.vkValue }
});
}
}
str += "\n";
}
void VulkanHppGenerator::appendPlatformEnter(std::string & str, bool isAliased, std::string const& platform) const
{
if (!isAliased && !platform.empty())
{
auto it = m_platforms.find(platform);
assert((it != m_platforms.end()) && !it->second.empty());
str += "#ifdef " + it->second + "\n";
}
}
void VulkanHppGenerator::appendPlatformLeave(std::string & str, bool isAliased, std::string const& platform) const
{
if (!isAliased && !platform.empty())
{
auto it = m_platforms.find(platform);
assert((it != m_platforms.end()) && !it->second.empty());
str += "#endif /*" + it->second + "*/\n";
}
}
void VulkanHppGenerator::appendStruct(std::string & str, std::pair<std::string, StructureData> const& structure, std::set<std::string> & listedStructures) const
{
if (listedStructures.find(structure.first) == listedStructures.end())
{
listedStructures.insert(structure.first);
for (auto const& member : structure.second.members)
{
auto structureIt = m_structures.find(member.type.type);
if ((structureIt != m_structures.end()) && (listedStructures.find(member.type.type) == listedStructures.end()))
{
appendStruct(str, *structureIt, listedStructures);
}
}
if (!structure.second.subStruct.empty())
{
auto structureIt = m_structures.find(structure.second.subStruct);
if ((structureIt != m_structures.end()) && (listedStructures.find(structureIt->first) == listedStructures.end()))
{
appendStruct(str, *structureIt, listedStructures);
}
}
if (structure.second.isUnion)
{
appendUnion(str, structure);
}
else
{
appendStructure(str, structure);
}
}
}
void VulkanHppGenerator::appendStructAssignmentOperator(std::string &str, std::pair<std::string, StructureData> const& structData, std::string const& prefix) const
{
// we need an assignment operator if there is constant sType in this struct
std::string copyTemplate;
if ((nonConstSTypeStructs.find(structData.first) == nonConstSTypeStructs.end()) && !structData.second.members.empty() && (structData.second.members.front().name == "sType"))
{
assert((2 <= structData.second.members.size()) && (structData.second.members[1].name == "pNext"));
copyTemplate = "memcpy( &pNext, &rhs.pNext, sizeof( ${structName} ) - offsetof( ${structName}, pNext ) )";
}
else
{
copyTemplate = "memcpy( static_cast<void*>(this), &rhs, sizeof( ${structName} ) )";
}
std::string structName = stripPrefix(structData.first, "Vk");
std::string operation = replaceWithMap(copyTemplate, { { "structName", structName } });
static const std::string stringTemplate = R"(
${prefix}${structName} & operator=( ${structName} const & rhs ) VULKAN_HPP_NOEXCEPT
${prefix}{
${prefix} ${operation};
${prefix} return *this;
${prefix}}
)";
str += replaceWithMap(stringTemplate, { { "operation", operation }, {"prefix", prefix }, { "structName", structName } });
}
void VulkanHppGenerator::appendStructCompareOperators(std::string & str, std::pair<std::string, StructureData> const& structData) const
{
// two structs are compared by comparing each of the elements
std::string compareMembers;
std::string intro = "";
for (size_t i = 0; i < structData.second.members.size(); i++)
{
MemberData const& member = structData.second.members[i];
compareMembers += intro;
if (member.arraySizes.empty())
{
compareMembers += "( " + member.name + " == rhs." + member.name + " )";
}
else
{
std::string arraySize = constructArraySize(member.arraySizes);
if ((0 < i) && ((stripPostfix(member.name, "s") + "Count") == structData.second.members[i - 1].name))
{
assert(structData.second.members[i - 1].type.type == "uint32_t"); // make sure, it's an unsigned type, so we don't need to clamp here
arraySize = "std::min<" + structData.second.members[i-1].type.type + ">( " + arraySize + ", " + structData.second.members[i - 1].name + " )";
}
compareMembers += "( memcmp( " + member.name + ", rhs." + member.name + ", " + arraySize + " * sizeof( " + member.type.compose() + " ) ) == 0 )";
}
intro = "\n && ";
}
static const std::string compareTemplate = R"(
#if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR)
auto operator<=>( ${name} const& ) const = default;
#else
bool operator==( ${name} const& rhs ) const VULKAN_HPP_NOEXCEPT
{
return ${compareMembers};
}
bool operator!=( ${name} const& rhs ) const VULKAN_HPP_NOEXCEPT
{
return !operator==( rhs );
}
#endif
)";
str += replaceWithMap(compareTemplate, { { "name", stripPrefix(structData.first, "Vk") }, { "compareMembers", compareMembers } });
}
std::string VulkanHppGenerator::constructConstexprString(std::pair<std::string, StructureData> const& structData) const
{
// structs with a union (and VkBaseInStructure and VkBaseOutStructure) can't be a constexpr!
bool isConstExpression = !containsUnion(structData.first) && (structData.first != "VkBaseInStructure") && (structData.first != "VkBaseOutStructure");
return isConstExpression ? (std::string("VULKAN_HPP_CONSTEXPR") + (containsArray(structData.first) ? "_14 " : " ")) : "";
}
void VulkanHppGenerator::appendStructConstructor(std::string &str, std::pair<std::string, StructureData> const& structData, std::string const& prefix) const
{
// the constructor with all the elements as arguments, with defaults
std::string constexprString = constructConstexprString(structData);
std::string ctorOpening = prefix + constexprString + stripPrefix(structData.first, "Vk");
std::string indentation(ctorOpening.size() + 2, ' ');
std::string arguments, initializers, copyOps;
bool listedArgument = false;
bool firstArgument = true;
for (auto const& member : structData.second.members)
{
// gather the arguments
listedArgument = appendStructConstructorArgument(arguments, listedArgument, indentation, member);
// gather the initializers; skip members 'pNext' and 'sType', they are directly set by initializers
if ((member.name != "pNext") && (member.name != "sType"))
{
if (member.arraySizes.empty())
{
// here, we can only handle non-array arguments
initializers += prefix + " " + (firstArgument ? ":" : ",") + " " + member.name + "( " + member.name + "_ )\n";
firstArgument = false;
}
else
{
// here we can handle the arrays, copying over from argument (with trailing '_') to member
initializers += prefix + " " + (firstArgument ? ":" : ",") + " " + member.name + "{}\n"; // need to initialize the array
firstArgument = false;
std::string type = (member.type.type.substr(0, 2) == "Vk") ? ("VULKAN_HPP_NAMESPACE::" + stripPrefix(member.type.type, "Vk")) : member.type.type;
std::string arraySizes;
for (auto const& as : member.arraySizes)
{
arraySizes += "," + as;
}
copyOps += prefix + " VULKAN_HPP_NAMESPACE::ConstExpression" + std::to_string(member.arraySizes.size()) + "DArrayCopy<" + type + arraySizes + ">::copy( " + member.name + ", " + member.name + "_ );\n";
}
}
}
str += ctorOpening + (arguments.empty() ? "()" : std::string("( " + arguments + " )")) + " VULKAN_HPP_NOEXCEPT\n" + initializers;
if (copyOps.empty())
{
str += prefix + "{}\n";
}
else
{
str += prefix + "{\n" + copyOps + prefix + "}\n";
}
}
void VulkanHppGenerator::appendStructCopyConstructor(std::string &str, std::pair<std::string, StructureData> const& structData, std::string const& prefix) const
{
// the constructor with all the elements as arguments, with defaults
std::string constexprString = constructConstexprString(structData);
std::string ctorOpening = prefix + constexprString + stripPrefix(structData.first, "Vk");
std::string indentation(ctorOpening.size() + 2, ' ');
std::string initializers, copyOps;
bool firstArgument = true;
for (auto const& member : structData.second.members)
{
if (member.name == "pNext")
{
assert(firstArgument);
initializers += prefix + " : pNext( rhs.pNext )\n";
firstArgument = false;
}
else if (member.name != "sType")
{
// gather the initializers; skip member 'sType', which is directly set by initializer
if (member.arraySizes.empty())
{
// here, we can only handle non-array arguments
initializers += prefix + " " + (firstArgument ? ":" : ",") + " " + member.name + "( rhs." + member.name + " )\n";
firstArgument = false;
}
else
{
// here we can handle the arrays, copying over from argument (with trailing '_') to member
initializers += prefix + " " + (firstArgument ? ":" : ",") + " " + member.name + "{}\n"; // need to initialize the array
firstArgument = false;
std::string type = (member.type.type.substr(0, 2) == "Vk") ? ("VULKAN_HPP_NAMESPACE::" + stripPrefix(member.type.type, "Vk")) : member.type.type;
std::string arraySizes;
for (auto const& as : member.arraySizes)
{
arraySizes += "," + as;
}
copyOps += "\n" + prefix + " VULKAN_HPP_NAMESPACE::ConstExpression" + std::to_string(member.arraySizes.size()) + "DArrayCopy<" + type + arraySizes + ">::copy( " + member.name + ", rhs." + member.name + " );";
}
}
}
if (!copyOps.empty())
{
copyOps += "\n" + prefix;
}
static std::string constructorTemplate = R"(
${prefix}${constexpr}${structName}( ${structName} const& rhs ) VULKAN_HPP_NOEXCEPT
${initializers}${prefix}{${copyOps}}
)";
str += replaceWithMap(constructorTemplate, { { "prefix", prefix }, { "constexpr", constexprString }, { "structName", stripPrefix(structData.first, "Vk") }, { "initializers", initializers }, { "copyOps", copyOps } });
}
bool VulkanHppGenerator::appendStructConstructorArgument(std::string & str, bool listedArgument, std::string const& indentation, MemberData const& memberData) const
{
// skip members 'pNext' and 'sType', as they are never explicitly set
if ((memberData.name != "pNext") && (memberData.name != "sType"))
{
str += (listedArgument ? (",\n" + indentation) : "");
if (memberData.arraySizes.empty())
{
str += memberData.type.compose() + " ";
}
else
{
str += constructStandardArray(memberData.type.compose(), memberData.arraySizes) + " const& ";
}
str += memberData.name + "_ = ";
auto enumIt = m_enums.find(memberData.type.type);
if (enumIt != m_enums.end() && memberData.type.postfix.empty())
{
// enum arguments might need special initialization
assert(memberData.type.prefix.empty() && memberData.arraySizes.empty() && !enumIt->second.values.empty());
str += "VULKAN_HPP_NAMESPACE::" + stripPrefix(memberData.type.type, "Vk") + "::" + enumIt->second.values.front().vkValue;
}
else
{
// all the rest can be initialized with just {}
str += "{}";
}
listedArgument = true;
}
return listedArgument;
}
void VulkanHppGenerator::appendStructCopyConstructors(std::string & str, std::string const& name) const
{
static const std::string templateString = R"(
${name}( Vk${name} const & rhs ) VULKAN_HPP_NOEXCEPT
{
*this = rhs;
}
${name}& operator=( Vk${name} const & rhs ) VULKAN_HPP_NOEXCEPT
{
*this = *reinterpret_cast<VULKAN_HPP_NAMESPACE::${name} const *>(&rhs);
return *this;
}
)";
str += replaceWithMap(templateString, { { "name", name } });
}
void VulkanHppGenerator::appendStructMembers(std::string & str, std::pair<std::string,StructureData> const& structData, std::string const& prefix) const
{
for (auto const& member : structData.second.members)
{
str += prefix;
if ((member.name == "sType") && (nonConstSTypeStructs.find(structData.first) == nonConstSTypeStructs.end())) // special handling for sType and some nasty little structs that don't get a const sType
{
str += "const ";
}
if (!member.bitCount.empty() && beginsWith(member.type.type, "Vk"))
{
assert(member.type.prefix.empty() && member.type.postfix.empty()); // never encounterd a different case
str += member.type.type;
}
else
{
str += member.type.compose();
}
str += " " + member.name;
if (member.name == "sType") // special handling for sType
{
auto enumIt = m_enums.find("VkStructureType");
assert(enumIt != m_enums.end());
if (!member.values.empty())
{
assert(beginsWith(member.values, "VK_STRUCTURE_TYPE"));
auto nameIt = std::find_if(enumIt->second.values.begin(), enumIt->second.values.end(), [&member](EnumValueData const& evd) { return member.values == evd.vulkanValue; });
assert(nameIt != enumIt->second.values.end());
str += " = StructureType::" + nameIt->vkValue;
}
else
{
// special handling for those nasty structs with an unspecified value for sType
str += " = {}";
}
}
else
{
// as we don't have any meaningful default initialization values, everything can be initialized by just '{}' !
assert(member.arraySizes.empty() || member.bitCount.empty());
if (!member.bitCount.empty())
{
str += " : " + member.bitCount; // except for bitfield members, where no default member initializatin is supported (up to C++20)
}
else
{
auto enumIt = m_enums.find(member.type.type);
if (enumIt != m_enums.end() && member.type.postfix.empty())
{
// enum arguments might need special initialization
assert(member.type.prefix.empty() && member.arraySizes.empty() && !enumIt->second.values.empty());
str += " = VULKAN_HPP_NAMESPACE::" + stripPrefix(member.type.type, "Vk") + "::" + enumIt->second.values.front().vkValue;
}
else
{
str += constructCArraySizes(member.arraySizes) + " = {}";
}
}
}
str += ";\n";
}
}
void VulkanHppGenerator::appendStructs(std::string & str) const
{
std::set<std::string> listedStructures;
for (auto const& structure : m_structures)
{
appendStruct(str, structure, listedStructures);
}
}
void VulkanHppGenerator::appendStructSetter(std::string & str, std::string const& structureName, MemberData const& memberData) const
{
if (memberData.type.type != "VkStructureType") // filter out StructureType, which is supposed to be immutable !
{
std::string memberType;
if (memberData.arraySizes.empty())
{
memberType = memberData.type.compose();
}
else
{
memberType = constructStandardArray(memberData.type.compose(), memberData.arraySizes);
}
// copy over the argument, either by assigning simple data, or by memcpy array data
str += "\n"
" " + structureName + " & set" + startUpperCase(memberData.name) + "( " + memberType + " " + memberData.name + "_ ) VULKAN_HPP_NOEXCEPT\n"
" {\n"
" ";
if (memberData.arraySizes.empty())
{
if (!memberData.bitCount.empty() && beginsWith(memberData.type.type, "Vk"))
{
str += memberData.name + " = " + "*reinterpret_cast<" + memberData.type.type + "*>(&" + memberData.name + "_)";
}
else
{
str += memberData.name + " = " + memberData.name + "_";
}
}
else
{
str += "memcpy( " + memberData.name + ", " + memberData.name + "_.data(), " + constructArraySize(memberData.arraySizes) + " * sizeof( " + memberData.type.compose() + " ) )";
}
str += ";\n"
" return *this;\n"
" }\n";
}
}
void VulkanHppGenerator::appendStructSubConstructor(std::string &str, std::pair<std::string, StructureData> const& structData, std::string const& prefix) const
{
if (!structData.second.subStruct.empty())
{
auto const& subStruct = m_structures.find(structData.second.subStruct);
assert(subStruct != m_structures.end());
std::string subStructArgumentName = startLowerCase(stripPrefix(subStruct->first, "Vk"));
std::string ctorOpening = prefix + "explicit " + stripPrefix(structData.first, "Vk") + "( ";
std::string indentation = std::string(ctorOpening.size(), ' ');
std::string subCopies;
bool firstArgument = true;
for (size_t i = 0; i < subStruct->second.members.size(); i++)
{
assert(structData.second.members[i].arraySizes.empty());
subCopies += prefix + " " + (firstArgument ? ":" : ",") + " " + structData.second.members[i].name + "( " + subStructArgumentName + "." + subStruct->second.members[i].name + " )\n";
firstArgument = false;
}
std::string subArguments;
bool listedArgument = true;
for (size_t i = subStruct->second.members.size(); i < structData.second.members.size(); i++)
{
listedArgument = appendStructConstructorArgument(subArguments, listedArgument, indentation, structData.second.members[i]);
assert(structData.second.members[i].arraySizes.empty());
subCopies += prefix + " , " + structData.second.members[i].name + "( " + structData.second.members[i].name + "_ )\n";
}
str += "\n"
" explicit " + stripPrefix(structData.first, "Vk") + "( " + stripPrefix(subStruct->first, "Vk") + " const& " + subStructArgumentName + subArguments + " )\n"
+ subCopies +
" {}\n";
}
}
void VulkanHppGenerator::appendStructure(std::string & str, std::pair<std::string, StructureData> const& structure) const
{
str += "\n";
appendPlatformEnter(str, !structure.second.aliases.empty(), structure.second.platform);
std::string constructorAndSetters;
appendStructConstructor(constructorAndSetters, structure, " ");
appendStructCopyConstructor(constructorAndSetters, structure, " ");
appendStructSubConstructor(constructorAndSetters, structure, " ");
appendStructAssignmentOperator(constructorAndSetters, structure, " ");
appendStructCopyConstructors(constructorAndSetters, stripPrefix(structure.first, "Vk"));
if (!structure.second.returnedOnly)
{
// only structs that are not returnedOnly get setters!
for (auto const& member : structure.second.members)
{
appendStructSetter(constructorAndSetters, stripPrefix(structure.first, "Vk"), member);
}
}
// operator==() and operator!=()
// only structs without a union as a member can have a meaningfull == and != operation; we filter them out
std::string compareOperators;
if (!containsUnion(structure.first))
{
appendStructCompareOperators(compareOperators, structure);
}
// the member variables
std::string members = "\n public:\n";
appendStructMembers(members, structure, " ");
static const std::string structureTemplate = R"( struct ${name}
{
${constructorAndSetters}
operator ${vkName} const&() const VULKAN_HPP_NOEXCEPT
{
return *reinterpret_cast<const ${vkName}*>( this );
}
operator ${vkName} &() VULKAN_HPP_NOEXCEPT
{
return *reinterpret_cast<${vkName}*>( this );
}
${compareOperators}
${members}
};
static_assert( sizeof( ${name} ) == sizeof( ${vkName} ), "struct and wrapper have different size!" );
static_assert( std::is_standard_layout<${name}>::value, "struct wrapper is not a standard layout!" );
)";
str += replaceWithMap(structureTemplate,
{
{ "name", stripPrefix(structure.first, "Vk") },
{ "constructorAndSetters", constructorAndSetters },
{ "vkName", structure.first },
{ "compareOperators", compareOperators },
{ "members", members }
});
appendPlatformLeave(str, !structure.second.aliases.empty(), structure.second.platform);
}
void VulkanHppGenerator::appendStructureChainValidation(std::string & str)
{
// append all template functions for the structure pointer chain validation
for (auto const& structure : m_structures)
{
if (!structure.second.structExtends.empty())
{
appendPlatformEnter(str, !structure.second.aliases.empty(), structure.second.platform);
// append out allowed structure chains
for (auto extendName : structure.second.structExtends)
{
std::map<std::string, StructureData>::const_iterator itExtend = m_structures.find(extendName);
if (itExtend == m_structures.end())
{
// look if the extendName acutally is an alias of some other structure
itExtend = std::find_if(m_structures.begin(), m_structures.end(), [extendName](auto const& sd) { return sd.second.aliases.find(extendName) != sd.second.aliases.end(); });
}
if (itExtend == m_structures.end())
{
std::string errorString;
errorString = "<" + extendName + "> does not specify a struct in structextends field.";
// check if symbol name is an alias to a struct
auto itAlias = std::find_if(m_structures.begin(), m_structures.end(), [&extendName](std::pair<std::string, StructureData> const &it) -> bool {return std::find(it.second.aliases.begin(), it.second.aliases.end(), extendName) != it.second.aliases.end(); });
if (itAlias != m_structures.end())
{
errorString += " The symbol is an alias and maps to <" + itAlias->first + ">.";
}
check(false, structure.second.xmlLine, errorString);
}
if (structure.second.platform != itExtend->second.platform)
{
appendPlatformEnter(str, !itExtend->second.aliases.empty(), itExtend->second.platform);
}
str += " template <> struct isStructureChainValid<" + stripPrefix(extendName, "Vk") + ", " + stripPrefix(structure.first, "Vk") + ">{ enum { value = true }; };\n";
if (structure.second.platform != itExtend->second.platform)
{
appendPlatformLeave(str, !itExtend->second.aliases.empty(), itExtend->second.platform);
}
}
appendPlatformLeave(str, !structure.second.aliases.empty(), structure.second.platform);
}
}
}
void VulkanHppGenerator::appendThrowExceptions(std::string & str) const
{
auto enumData = m_enums.find("VkResult");
str += "\n"
" [[noreturn]] static void throwResultException( Result result, char const * message )\n"
" {\n"
" switch ( result )\n"
" {\n";
for (auto const& value : enumData->second.values)
{
if (beginsWith(value.vkValue, "eError"))
{
str += " case Result::" + value.vkValue + ": throw " + stripPrefix(value.vkValue, "eError") + "Error( message );\n";
}
}
str += " default: throw SystemError( make_error_code( result ) );\n"
" }\n"
" }\n";
}
void VulkanHppGenerator::appendUnion(std::string & str, std::pair<std::string, StructureData> const& structure) const
{
str += "\n";
appendPlatformEnter(str, !structure.second.aliases.empty(), structure.second.platform);
std::string unionName = stripPrefix(structure.first, "Vk");
str +=
" union " + unionName + "\n"
" {\n"
" " + unionName + "( VULKAN_HPP_NAMESPACE::" + unionName + " const& rhs ) VULKAN_HPP_NOEXCEPT\n"
" {\n"
" memcpy( static_cast<void*>(this), &rhs, sizeof( VULKAN_HPP_NAMESPACE::" + unionName + " ) );\n"
" }\n";
bool firstMember = true;
for (auto const& member : structure.second.members)
{
// VkBool32 is aliased to uint32_t. Don't create a VkBool32 constructor if the union also contains a uint32_t constructor.
auto compareBool32Alias = [](MemberData const& member) { return member.type.type == std::string("uint32_t"); };
if (member.type.type == "VkBool32") {
if (std::find_if(structure.second.members.begin(), structure.second.members.end(), compareBool32Alias) != structure.second.members.end())
{
continue;
}
}
static const std::string constructorTemplate = R"(
${unionName}( ${memberType} ${memberName}_${defaultAssignment} )
{
${memberAssignment};
}
)";
std::string memberAssignment, memberType;
if (member.arraySizes.empty())
{
memberAssignment = member.name + " = " + member.name + "_";
memberType = member.type.compose();
}
else
{
std::string arraySize = constructArraySize(member.arraySizes);
memberAssignment = "memcpy( " + member.name + ", " + member.name + "_.data(), " + arraySize + " * sizeof( " + member.type.compose() + " ) )";
memberType = "const " + constructStandardArray(member.type.compose(), member.arraySizes) + "&";
}
str += replaceWithMap(constructorTemplate,
{
{ "defaultAssignment", firstMember ? " = {}" : "" },
{ "memberAssignment", memberAssignment },
{ "memberName", member.name },
{ "memberType", memberType },
{ "unionName", stripPrefix(structure.first, "Vk") }
});
firstMember = false;
}
// one setter per union element
for (auto const& member : structure.second.members)
{
appendStructSetter(str, stripPrefix(structure.first, "Vk"), member);
}
// assignment operator
static const std::string operatorsTemplate = R"(
VULKAN_HPP_NAMESPACE::${unionName} & operator=( VULKAN_HPP_NAMESPACE::${unionName} const & rhs ) VULKAN_HPP_NOEXCEPT
{
memcpy( static_cast<void*>(this), &rhs, sizeof( VULKAN_HPP_NAMESPACE::${unionName} ) );
return *this;
}
operator Vk${unionName} const&() const
{
return *reinterpret_cast<const Vk${unionName}*>(this);
}
operator Vk${unionName} &()
{
return *reinterpret_cast<Vk${unionName}*>(this);
}
)";
str += replaceWithMap(operatorsTemplate, { { "unionName", stripPrefix(structure.first, "Vk") } });
// the union member variables
// if there's at least one Vk... type in this union, check for unrestricted unions support
bool needsUnrestrictedUnions = (std::find_if(structure.second.members.begin(), structure.second.members.end(), [](MemberData const& member) { return beginsWith(member.type.type, "Vk"); }) != structure.second.members.end());
if (needsUnrestrictedUnions)
{
str += "#ifdef VULKAN_HPP_HAS_UNRESTRICTED_UNIONS\n";
}
for (auto const& member : structure.second.members)
{
str += " " + member.type.compose() + " " + member.name + constructCArraySizes(member.arraySizes) + ";\n";
}
if (needsUnrestrictedUnions)
{
str += "#else\n";
for (auto const& member : structure.second.members)
{
str += " " + member.type.prefix + (member.type.prefix.empty() ? "" : " ") + member.type.type + member.type.postfix + " " + member.name + constructCArraySizes(member.arraySizes) + ";\n";
}
str += "#endif /*VULKAN_HPP_HAS_UNRESTRICTED_UNIONS*/\n";
}
str += " };\n";
appendPlatformLeave(str, !structure.second.aliases.empty(), structure.second.platform);
}
void VulkanHppGenerator::appendUniqueTypes(std::string & str, std::string const& parentType, std::set<std::string> const& childrenTypes) const
{
str += "\n"
"#ifndef VULKAN_HPP_NO_SMART_HANDLE\n";
if (!parentType.empty())
{
str += " class " + stripPrefix(parentType, "Vk") + ";\n";
}
for (auto const& childType : childrenTypes)
{
auto handleIt = m_handles.find(childType);
assert(handleIt != m_handles.end());
std::string type = stripPrefix(childType, "Vk");
std::string deleterType = handleIt->second.deletePool.empty() ? "Object" : "Pool";
std::string deleterAction = (handleIt->second.deleteCommand.substr(2, 4) == "Free") ? "Free" : "Destroy";
std::string deleterParent = parentType.empty() ? "NoParent" : stripPrefix(parentType, "Vk");
std::string deleterPool = handleIt->second.deletePool.empty() ? "" : ", " + stripPrefix(handleIt->second.deletePool, "Vk");
appendPlatformEnter(str, !handleIt->second.alias.empty(), handleIt->second.platform);
str += " template <typename Dispatch> class UniqueHandleTraits<" + type + ", Dispatch> { public: using deleter = " + deleterType + deleterAction + "<" + deleterParent + deleterPool + ", Dispatch>; };\n"
" using Unique" + type + " = UniqueHandle<" + type + ", VULKAN_HPP_DEFAULT_DISPATCHER_TYPE>;\n";
if (!handleIt->second.alias.empty())
{
str += " using Unique" + stripPrefix(handleIt->second.alias, "Vk") + " = UniqueHandle<" + type + ", VULKAN_HPP_DEFAULT_DISPATCHER_TYPE>;\n";
}
appendPlatformLeave(str, !handleIt->second.alias.empty(), handleIt->second.platform);
}
str += "#endif /*VULKAN_HPP_NO_SMART_HANDLE*/\n";
}
void VulkanHppGenerator::EnumData::addEnumValue(int line, std::string const &valueName, bool bitmask, bool bitpos, std::string const& prefix, std::string const& postfix, std::string const& tag)
{
std::string translatedName = createEnumValueName(valueName, prefix, postfix, bitmask, tag);
auto it = std::find_if(values.begin(), values.end(), [&translatedName](EnumValueData const& evd) { return evd.vkValue == translatedName; });
if (it == values.end())
{
values.push_back(EnumValueData(valueName, translatedName, bitpos));
}
else
{
check(it->vulkanValue == valueName, line, "enum value <" + valueName + "> maps to same C++-name as <" + it->vulkanValue + ">");
}
}
void VulkanHppGenerator::checkCorrectness()
{
check(!m_vulkanLicenseHeader.empty(), -1, "missing license header");
for (auto const& baseType : m_baseTypes)
{
check(m_types.find(baseType.second.type) != m_types.end(), baseType.second.xmlLine, "basetype type <" + baseType.second.type + "> not specified");
}
for (auto const& bitmask : m_bitmasks)
{
if (!bitmask.second.requirements.empty())
{
check(m_enums.find(bitmask.second.requirements) != m_enums.end(), bitmask.second.xmlLine, "bitmask requires unknown <" + bitmask.second.requirements + ">");
}
}
for (auto const& extension : m_extensions)
{
if (!extension.second.deprecatedBy.empty())
{
check((m_extensions.find(extension.second.deprecatedBy) != m_extensions.end()) || (m_features.find(extension.second.deprecatedBy) != m_features.end())
, extension.second.xmlLine, "extension deprecated by to unknown extension/version <" + extension.second.promotedTo + ">");
}
if (!extension.second.obsoletedBy.empty())
{
check((m_extensions.find(extension.second.obsoletedBy) != m_extensions.end()) || (m_features.find(extension.second.obsoletedBy) != m_features.end())
, extension.second.xmlLine, "extension obsoleted by unknown extension/version <" + extension.second.promotedTo + ">");
}
if (!extension.second.promotedTo.empty())
{
check((m_extensions.find(extension.second.promotedTo) != m_extensions.end()) || (m_features.find(extension.second.promotedTo) != m_features.end())
, extension.second.xmlLine, "extension promoted to unknown extension/version <" + extension.second.promotedTo + ">");
}
for (auto const& require : extension.second.requirements)
{
check(m_extensions.find(require.first) != m_extensions.end(), require.second, "unknown extension requires <" + require.first + ">");
}
}
for (auto const& funcPointer : m_funcPointers)
{
if (!funcPointer.second.requirements.empty())
{
check(m_types.find(funcPointer.second.requirements) != m_types.end(), funcPointer.second.xmlLine, "funcpointer requires unknown <" + funcPointer.second.requirements + ">");
}
}
for (auto const& structure : m_structures)
{
for (auto const& extend : structure.second.structExtends)
{
check(m_types.find(extend) != m_types.end(), structure.second.xmlLine, "struct extends unknown <" + extend + ">");
}
for (auto const& member : structure.second.members)
{
check(m_types.find(member.type.type) != m_types.end(), member.xmlLine, "struct member uses unknown type <" + member.type.type + ">");
if (!member.usedConstant.empty())
{
check(m_constants.find(member.usedConstant) != m_constants.end(), member.xmlLine, "struct member array size uses unknown constant <" + member.usedConstant + ">");
}
}
}
auto resultIt = m_enums.find("VkResult");
assert(resultIt != m_enums.end());
std::set<std::string> resultCodes;
for (auto rc : resultIt->second.values)
{
resultCodes.insert(rc.vulkanValue);
}
for (auto rc : resultIt->second.aliases)
{
resultCodes.insert(rc.first);
}
for (auto const& handle : m_handles)
{
for (auto const& parent : handle.second.parents)
{
check(m_handles.find(parent) != m_handles.end(), handle.second.xmlLine, "handle with unknown parent <" + parent + ">");
}
for (auto const& command : handle.second.commands)
{
for (auto const& ec : command.second.errorCodes)
{
check(resultCodes.find(ec) != resultCodes.end(), command.second.xmlLine, "command uses unknown error code <" + ec + ">");
}
for (auto const& sc : command.second.successCodes)
{
check(resultCodes.find(sc) != resultCodes.end(), command.second.xmlLine, "command uses unknown success code <" + sc + ">");
}
// check that functions returning a VkResult specify successcodes
check((command.second.returnType != "VkResult") || !command.second.successCodes.empty(), command.second.xmlLine, "missing successcodes on command <" + command.first + "> returning VkResult!");
}
}
}
bool VulkanHppGenerator::checkLenAttribute(std::string const& len, std::vector<ParamData> const& params)
{
// simple: "null-terminated" or previously encountered parameter
if ((len == "null-terminated") || (std::find_if(params.begin(), params.end(), [&len](ParamData const& pd) { return pd.name == len; }) != params.end()))
{
return true;
}
// check if len specifies a member of a struct
std::vector<std::string> lenParts = tokenize(len, ':');
if (lenParts.size() == 2)
{
auto paramIt = std::find_if(params.begin(), params.end(), [&l = lenParts[0]](ParamData const& pd){ return pd.name == l; });
if (paramIt != params.end())
{
auto structureIt = m_structures.find(paramIt->type.type);
if ((structureIt != m_structures.end()) && (std::find_if(structureIt->second.members.begin(), structureIt->second.members.end(), [&n = lenParts[1]](MemberData const& md){ return md.name == n; }) != structureIt->second.members.end()))
{
return true;
}
}
}
return false;
}
bool VulkanHppGenerator::containsArray(std::string const& type) const
{
// a simple recursive check if a type is or contains an array
auto structureIt = m_structures.find(type);
bool found = false;
if (structureIt != m_structures.end())
{
for (auto memberIt = structureIt->second.members.begin(); memberIt != structureIt->second.members.end() && !found; ++memberIt)
{
found = !memberIt->arraySizes.empty() || containsArray(memberIt->type.type);
}
}
return found;
}
bool VulkanHppGenerator::containsUnion(std::string const& type) const
{
// a simple recursive check if a type is or contains a union
auto structureIt = m_structures.find(type);
bool found = (structureIt != m_structures.end());
if (found)
{
found = structureIt->second.isUnion;
for (auto memberIt = structureIt->second.members.begin(); memberIt != structureIt->second.members.end() && !found; ++memberIt)
{
found = memberIt->type.prefix.empty() && memberIt->type.postfix.empty() && containsUnion(memberIt->type.type);
}
}
return found;
}
std::string VulkanHppGenerator::determineEnhancedReturnType(CommandData const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool isStructureChain) const
{
assert((returnParamIndex == INVALID_INDEX) || (returnParamIndex < commandData.params.size()));
for (auto vpi : vectorParamIndices)
{
assert((vpi.first != vpi.second) && (vpi.first < commandData.params.size()) && ((vpi.second == INVALID_INDEX) || (vpi.second < commandData.params.size())));
}
std::string enhancedReturnType;
// if there is a return parameter of type void or Result, and if it's of type Result it either has just one success code
// or two success codes, where the second one is of type VK_INCOMPLETE and it's a two-step process
// -> we can return that parameter
if ((returnParamIndex != INVALID_INDEX)
&& ((commandData.returnType == "void")
|| ((commandData.returnType == "VkResult")
&& ((commandData.successCodes.size() == 1)
|| ((commandData.successCodes.size() == 2) && (commandData.successCodes[1] == "VK_INCOMPLETE") && twoStep)
|| ((commandData.successCodes.size() == 3) && (commandData.successCodes[1] == "VK_OPERATION_DEFERRED_KHR") && (commandData.successCodes[2] == "VK_OPERATION_NOT_DEFERRED_KHR"))))))
{
assert(commandData.successCodes.empty() || (commandData.successCodes[0] == "VK_SUCCESS"));
if (vectorParamIndices.find(returnParamIndex) != vectorParamIndices.end())
{
enhancedReturnType = (commandData.params[returnParamIndex].type.type == "void")
? "std::vector<uint8_t,Allocator>" // the return parameter is a vector-type parameter
: isStructureChain
? "std::vector<StructureChain,Allocator>" // for structureChain returns, it's just a vector of StrutureChains
: "std::vector<" + stripPrefix(commandData.params[returnParamIndex].type.type, "Vk") + ",Allocator>"; // for the other parameters, we use a vector of the pure type
}
else
{
// it's a simple parameter -> get the type and just remove the trailing '*' (originally, it's a pointer)
assert(commandData.params[returnParamIndex].type.postfix.back() == '*');
assert((commandData.params[returnParamIndex].type.prefix.find("const") == std::string::npos) && (commandData.params[returnParamIndex].type.postfix.find("const") == std::string::npos));
enhancedReturnType = stripPostfix(commandData.params[returnParamIndex].type.compose(), "*");
}
}
else if ((commandData.returnType == "VkResult") && (commandData.successCodes.size() == 1))
{
// an original return of type "Result" with just one successCode is changed to void, errors throw an exception
enhancedReturnType = "void";
}
else
{
// the return type just stays the original return type
enhancedReturnType = stripPrefix(commandData.returnType, "Vk");
}
return enhancedReturnType;
}
size_t VulkanHppGenerator::determineReturnParamIndex(CommandData const& commandData, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep) const
{
for (auto vpi : vectorParamIndices)
{
assert((vpi.first != vpi.second) && (vpi.first < commandData.params.size()) && ((vpi.second == INVALID_INDEX) || (vpi.second < commandData.params.size())));
}
size_t returnParamIndex = INVALID_INDEX;
// for return types of type VkResult or void, we can determine a parameter to return
if ((commandData.returnType == "VkResult") || (commandData.returnType == "void"))
{
for (size_t i = 0; i < commandData.params.size(); i++)
{
if ((commandData.params[i].type.postfix.find('*') != std::string::npos)
&& ((commandData.params[i].type.type != "void") || twoStep || (commandData.params[i].type.postfix.find("**") != std::string::npos))
&& (commandData.params[i].type.prefix.find("const") == std::string::npos)
&& std::find_if(vectorParamIndices.begin(), vectorParamIndices.end(), [i](std::pair<size_t, size_t> const& vpi) { return vpi.second == i; }) == vectorParamIndices.end())
{
// it's a non-const pointer and not a vector-size parameter
std::map<size_t, size_t>::const_iterator vpit = vectorParamIndices.find(i);
if ((vpit == vectorParamIndices.end()) || twoStep || (vectorParamIndices.size() > 1) || (vpit->second == INVALID_INDEX) || (commandData.params[vpit->second].type.postfix.find('*') != std::string::npos))
{
// it's not a vector parameter, or a two-step process, or there is at least one more vector parameter, or the size argument of this vector parameter is not an argument, or the size argument of this vector parameter is provided by a pointer
// -> look for another non-cost pointer argument
auto paramIt = std::find_if(commandData.params.begin() + i + 1, commandData.params.end(), [](ParamData const& pd)
{
return (pd.type.postfix.find('*') != std::string::npos) && (pd.type.postfix.find("const") == std::string::npos);
});
// if there is another such argument, we can't decide which one to return -> return INVALID_INDEX
// otherwise return the index of the selcted parameter
returnParamIndex = paramIt != commandData.params.end() ? INVALID_INDEX : i;
}
}
}
}
return returnParamIndex;
}
std::string VulkanHppGenerator::determineSubStruct(std::pair<std::string, StructureData> const& structure) const
{
for (auto const& s : m_structures)
{
if ((s.first != structure.first) && (s.second.members.size() < structure.second.members.size()) && (s.second.members[0].name != "sType"))
{
bool equal = true;
for (size_t i = 0; i < s.second.members.size() && equal; i++)
{
equal = (s.second.members[i].type == structure.second.members[i].type) && (s.second.members[i].name == structure.second.members[i].name);
}
if (equal)
{
return s.first;
}
}
}
return "";
}
size_t VulkanHppGenerator::determineTemplateParamIndex(std::vector<ParamData> const& params, std::map<size_t, size_t> const& vectorParamIndices) const
{
size_t templateParamIndex = INVALID_INDEX;
for (size_t i = 0; i < params.size(); i++)
{
// any vector parameter on the pure type void is templatized in the enhanced API
if ((vectorParamIndices.find(i) != vectorParamIndices.end()) && (params[i].type.type == "void"))
{
#if !defined(NDEBUG)
for (size_t j = i + 1; j < params.size(); j++)
{
assert((vectorParamIndices.find(j) == vectorParamIndices.end()) || (params[j].type.type != "void"));
}
#endif
templateParamIndex = i;
break;
}
}
assert((templateParamIndex == INVALID_INDEX) || (vectorParamIndices.find(templateParamIndex) != vectorParamIndices.end()));
return templateParamIndex;
}
std::map<size_t, size_t> VulkanHppGenerator::determineVectorParamIndices(std::vector<ParamData> const& params) const
{
std::map<size_t, size_t> vectorParamIndices;
// look for the parameters whose len equals the name of an other parameter
for (auto it = params.begin(); it != params.end(); ++it)
{
if (!it->len.empty())
{
auto findLambda = [it](ParamData const& pd) { return pd.name == it->len; };
auto findIt = std::find_if(params.begin(), it, findLambda); // look for a parameter named as the len of this parameter
assert((std::count_if(params.begin(), params.end(), findLambda) == 0) || (findIt < it)); // make sure, there is no other parameter like that
// add this parameter as a vector parameter, using the len-name parameter as the second value (or INVALID_INDEX if there is nothing like that)
vectorParamIndices.insert(std::make_pair(std::distance(params.begin(), it), (findIt < it) ? std::distance(params.begin(), findIt) : INVALID_INDEX));
assert((vectorParamIndices[std::distance(params.begin(), it)] != INVALID_INDEX)
|| (it->len == "null-terminated")
|| (it->len == "pAllocateInfo::descriptorSetCount")
|| (it->len == "pAllocateInfo::commandBufferCount"));
}
}
return vectorParamIndices;
}
std::string const& VulkanHppGenerator::getTypesafeCheck() const
{
return m_typesafeCheck;
}
std::string const& VulkanHppGenerator::getVersion() const
{
return m_version;
}
std::string const& VulkanHppGenerator::getVulkanLicenseHeader() const
{
return m_vulkanLicenseHeader;
}
bool VulkanHppGenerator::isTwoStepAlgorithm(std::vector<ParamData> const& params) const
{
// we generate a two-step algorithm for functions returning a vector of stuff, where the length is specified as a pointer as well
// for those functions, the size can be queried first, and then used
bool isTwoStep = false;
for (auto paramIt = params.begin(); paramIt != params.end() && !isTwoStep; ++paramIt)
{
if (!paramIt->len.empty())
{
auto lenIt = std::find_if(params.begin(), paramIt, [paramIt](ParamData const& pd) { return paramIt->len == pd.name; });
if (lenIt != paramIt)
{
isTwoStep = (lenIt->type.postfix.find('*') != std::string::npos);
}
}
}
return isTwoStep;
}
void VulkanHppGenerator::linkCommandToHandle(int line, std::string const& name, CommandData const& commandData)
{
// first, find the handle named like the type of the first argument
// if there is no such handle, look for the unnamed "handle", that gathers all the functions not tied to a specific handle
check(!commandData.params.empty(), line, "command <" + name + "> with no params");
std::map<std::string, HandleData>::iterator handleIt = m_handles.find(commandData.params[0].type.type);
if (handleIt == m_handles.end())
{
handleIt = m_handles.find("");
}
check(handleIt != m_handles.end(), line, "could not find a handle to hold command <" + name + ">");
// put the command into the handle's list of commands
check(handleIt->second.commands.find(name) == handleIt->second.commands.end(), line, "command list of handle <" + handleIt->first + "> already holds a commnand <" + name + ">");
handleIt->second.commands.insert(std::make_pair(name, commandData));
// and store the handle in the command-to-handle map
check(m_commandToHandle.find(name) == m_commandToHandle.end(), line, "command to handle mapping already holds the command <" + name + ">");
m_commandToHandle[name] = handleIt->first;
}
void VulkanHppGenerator::readBaseType(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "category",{ "basetype" } } }, {});
NameData nameData;
TypeData typeData;
std::tie(nameData, typeData) = readNameAndType(element);
check(beginsWith(nameData.name, "Vk"), line, "name <" + nameData.name + "> does not begin with <Vk>");
check(nameData.arraySizes.empty(), line, "name <" + nameData.name + "> with unsupported arraySizes");
check(nameData.bitCount.empty(), line, "name <" + nameData.name + "> with unsupported bitCount <" + nameData.bitCount + ">");
check(typeData.prefix == "typedef", line, "unexpected type prefix <" + typeData.prefix + ">");
check(typeData.postfix.empty(), line, "unexpected type postfix <" + typeData.postfix + ">");
check(m_baseTypes.insert(std::make_pair(nameData.name, BaseTypeData(typeData.type, line))).second, line, "basetype <" + nameData.name + "> already specified");
check(m_types.insert(nameData.name).second, line, "basetype <" + nameData.name + "> already specified as a type");
}
void VulkanHppGenerator::readBitmask(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
auto aliasIt = attributes.find("alias");
if (aliasIt != attributes.end())
{
readBitmaskAlias(element, attributes);
}
else
{
checkAttributes(line, attributes, { { "category",{ "bitmask" } } }, { { "requires",{} } });
std::string requirements;
for (auto const& attribute : attributes)
{
if (attribute.first == "requires")
{
requirements = attribute.second;
}
}
NameData nameData;
TypeData typeData;
std::tie(nameData, typeData) = readNameAndType(element);
check(beginsWith(nameData.name, "Vk"), line, "name <" + nameData.name + "> does not begin with <Vk>");
check(nameData.arraySizes.empty(), line, "name <" + nameData.name + "> with unsupported arraySizes");
check(nameData.bitCount.empty(), line, "name <" + nameData.name + "> with unsupported bitCount <" + nameData.bitCount + ">");
warn((typeData.type == "VkFlags") || (typeData.type == "VkFlags64"), line, "unexpected bitmask type <" + typeData.type + ">");
check(typeData.prefix == "typedef", line, "unexpected type prefix <" + typeData.prefix + ">");
check(typeData.postfix.empty(), line, "unexpected type postfix <" + typeData.postfix + ">");
check(m_commandToHandle.find(nameData.name) == m_commandToHandle.end(), line, "command <" + nameData.name + "> already specified");
m_bitmasks.insert(std::make_pair(nameData.name, BitmaskData(requirements, typeData.type, line)));
check(m_types.insert(nameData.name).second, line, "bitmask <" + nameData.name + "> already specified as a type");
}
}
void VulkanHppGenerator::readBitmaskAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "alias",{} },{ "category",{ "bitmask" } },{ "name",{} } }, {});
checkElements(line, getChildElements(element), {});
std::string alias, name;
for (auto const& attribute : attributes)
{
if (attribute.first == "alias")
{
alias = attribute.second;
}
else if (attribute.first == "name")
{
name = attribute.second;
}
}
auto bitmasksIt = m_bitmasks.find(alias);
check(bitmasksIt != m_bitmasks.end(), line, "missing alias <" + alias + ">.");
check(bitmasksIt->second.alias.empty(), line, "alias for bitmask <" + bitmasksIt->first + "> already specified as <" + bitmasksIt->second.alias + ">");
bitmasksIt->second.alias = name;
check(m_types.insert(name).second, line, "aliased bitmask <" + name + "> already specified as a type");
}
void VulkanHppGenerator::readCommand(tinyxml2::XMLElement const* element)
{
std::map<std::string, std::string> attributes = getAttributes(element);
auto aliasIt = attributes.find("alias");
if (aliasIt != attributes.end())
{
readCommandAlias(element, attributes);
}
else
{
readCommand(element, attributes);
}
}
void VulkanHppGenerator::readCommand(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, {},
{
{ "cmdbufferlevel",{ "primary", "secondary" } },
{ "comment",{} },
{ "errorcodes",{} },
{ "pipeline",{ "compute", "graphics", "transfer" } },
{ "queues",{ "compute", "graphics", "sparse_binding", "transfer" } },
{ "renderpass",{ "both", "inside", "outside" } },
{ "successcodes",{} }
});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "param", false }, { "proto", true } }, { "implicitexternsyncparams" });
CommandData commandData(line);
for (auto const& attribute : attributes)
{
if (attribute.first == "errorcodes")
{
commandData.errorCodes = tokenize(attribute.second, ',');
// errorCodes are checked in checkCorrectness after complete reading
}
else if (attribute.first == "successcodes")
{
commandData.successCodes = tokenize(attribute.second, ',');
// successCodes are checked in checkCorrectness after complete reading
}
}
std::string name;
for (auto child : children)
{
std::string value = child->Value();
if (value == "param")
{
commandData.params.push_back(readCommandParam(child, commandData.params));
}
else if (value == "proto")
{
std::tie(name, commandData.returnType) = readCommandProto(child);
}
}
assert(!name.empty());
registerDeleter(name, std::make_pair(name, commandData));
linkCommandToHandle(line, name, commandData);
}
void VulkanHppGenerator::readCommandAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
// for command aliases, create a copy of the aliased command
int line = element->GetLineNum();
checkAttributes(line, attributes, {}, { { "alias",{} }, { "name",{} }, });
checkElements(line, getChildElements(element), {});
std::string alias, name;
for (auto const& attribute : attributes)
{
if (attribute.first == "alias")
{
alias = attribute.second;
}
else if (attribute.first == "name")
{
name = attribute.second;
check(beginsWith(name, "vk"), line, "name <" + name + "> should begin with <vk>");
}
}
auto commandToHandleIt = m_commandToHandle.find(alias);
check(commandToHandleIt != m_commandToHandle.end(), line, "missing command <" + alias + ">");
auto handleIt = m_handles.find(commandToHandleIt->second);
check(handleIt != m_handles.end(), line, "missing handle <" + commandToHandleIt->second + ">");
auto commandsIt = handleIt->second.commands.find(alias);
if (commandsIt == handleIt->second.commands.end())
{
// look, if this command is aliases and already aliased command
commandsIt = std::find_if(handleIt->second.commands.begin(), handleIt->second.commands.end(), [&alias](auto const& cd) { return cd.second.aliases.find(alias) != cd.second.aliases.end(); });
}
check(commandsIt != handleIt->second.commands.end(), line, "missing command <" + alias + "> in handle <" + handleIt->first + ">");
check(commandsIt->second.aliases.insert(name).second, line, "alias <" + name + "> for command <" + alias + "> already specified");
// and store the alias in the command-to-handle map
check(m_commandToHandle.find(name) == m_commandToHandle.end(), line, "command to handle mapping already holds the command <" + name + ">");
m_commandToHandle[name] = handleIt->first;
}
VulkanHppGenerator::ParamData VulkanHppGenerator::readCommandParam(tinyxml2::XMLElement const* element, std::vector<ParamData> const& params)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, {}, { { "externsync",{} },{ "len",{} },{ "noautovalidity",{ "true" } },{ "optional",{ "false", "true" } } });
ParamData paramData;
for (auto attribute : attributes)
{
if (attribute.first == "len")
{
paramData.len = attribute.second;
check(checkLenAttribute(paramData.len, params), line, "command param len <" + paramData.len + "> is not recognized as a valid len value");
}
else if (attribute.first == "optional")
{
paramData.optional = (attribute.second == "true");
}
}
NameData nameData;
std::tie(nameData, paramData.type) = readNameAndType(element);
check(nameData.bitCount.empty(), line, "name <" + nameData.name + "> with unsupported bitCount <" + nameData.bitCount + ">");
check(m_types.find(paramData.type.type) != m_types.end(), line, "unknown type <" + paramData.type.type + ">");
check(paramData.type.prefix.empty() || (paramData.type.prefix == "const") || (paramData.type.prefix == "const struct") || (paramData.type.prefix == "struct"), line, "unexpected type prefix <" + paramData.type.prefix + ">");
check(paramData.type.postfix.empty() || (paramData.type.postfix == "*") || (paramData.type.postfix == "**") || (paramData.type.postfix == "* const*"), line, "unexpected type postfix <" + paramData.type.postfix + ">");
check(std::find_if(params.begin(), params.end(), [&name = nameData.name](ParamData const& pd) { return pd.name == name; }) == params.end(), line, "command param <" + nameData.name + "> already used");
paramData.name = nameData.name;
paramData.arraySizes = nameData.arraySizes;
return paramData;
}
std::pair<std::string, std::string> VulkanHppGenerator::readCommandProto(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, {});
NameData nameData;
TypeData typeData;
std::tie(nameData, typeData) = readNameAndType(element);
check(beginsWith(nameData.name, "vk"), line, "name <" + nameData.name + "> does not begin with <vk>");
check(nameData.arraySizes.empty(), line, "name <" + nameData.name + "> with unsupported arraySizes");
check(nameData.bitCount.empty(), line, "name <" + nameData.name + "> with unsupported bitCount <" + nameData.bitCount + ">");
check(m_types.find(typeData.type) != m_types.end(), line, "unknown type <" + typeData.type + ">");
check(typeData.prefix.empty(), line, "unexpected type prefix <" + typeData.prefix + ">");
check(typeData.postfix.empty(), line, "unexpected type postfix <" + typeData.postfix + ">");
check(m_commandToHandle.find(nameData.name) == m_commandToHandle.end(), line, "command <" + nameData.name + "> already specified");
return std::make_pair(nameData.name, typeData.type);
}
void VulkanHppGenerator::readCommands(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, { { "comment",{} } });
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "command", false } });
for (auto child : children)
{
readCommand(child);
}
}
std::string VulkanHppGenerator::readComment(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, {});
checkElements(line, getChildElements(element), {});
return element->GetText();
}
void VulkanHppGenerator::readDefine(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "category",{ "define" } } }, { { "name",{} } });
auto nameIt = attributes.find("name");
if (nameIt != attributes.end())
{
check(!element->FirstChildElement(), line, "unknown formatting of type category=define name <" + nameIt->second + ">");
check(nameIt->second == "VK_DEFINE_NON_DISPATCHABLE_HANDLE", line, "unknown type category=define name <" + nameIt->second + ">");
check(element->LastChild() && element->LastChild()->ToText() && element->LastChild()->ToText()->Value(), line, "unknown formatting of type category=define named <" + nameIt->second + ">");
// filter out the check for the different types of VK_DEFINE_NON_DISPATCHABLE_HANDLE
std::string text = element->LastChild()->ToText()->Value();
size_t start = text.find("#if defined(__LP64__)");
check(start != std::string::npos, line, "unexpected text in type category=define named <" + nameIt->second + ">");
size_t end = text.find_first_of("\r\n", start + 1);
check(end != std::string::npos, line, "unexpected text in type category=define named <" + nameIt->second + ">");
m_typesafeCheck = text.substr(start, end - start);
}
else if (element->GetText())
{
std::string text = element->GetText();
if ((text.find("class") != std::string::npos) || (text.find("struct") != std::string::npos))
{
// here are a couple of structs as defines, which really are types!
tinyxml2::XMLElement const* child = element->FirstChildElement();
check(child && (strcmp(child->Value(), "name") == 0) && child->GetText(), line, "unexpected formatting of type category=define");
text = child->GetText();
check(m_types.insert(text).second, line, "type <" + text + "> has already been speficied");
}
else
{
tinyxml2::XMLElement const* child = element->FirstChildElement();
check(child && !child->FirstAttribute() && (strcmp(child->Value(), "name") == 0) && child->GetText(), line, "unknown formatting of type category define");
text = trim(child->GetText());
if (text == "VK_HEADER_VERSION")
{
m_version = trimEnd(element->LastChild()->ToText()->Value());
}
// ignore all the other defines
warn(!child->NextSiblingElement() || (child->NextSiblingElement() && !child->NextSiblingElement()->FirstAttribute() && (strcmp(child->NextSiblingElement()->Value(), "type") == 0) && !child->NextSiblingElement()->NextSiblingElement()), line, "unknown formatting of type category define");
}
}
}
void VulkanHppGenerator::readEnum(tinyxml2::XMLElement const* element, EnumData & enumData, bool bitmask, std::string const& prefix, std::string const& postfix)
{
std::map<std::string, std::string> attributes = getAttributes(element);
auto aliasIt = attributes.find("alias");
if (aliasIt != attributes.end())
{
readEnumAlias(element, attributes, enumData, bitmask, prefix, postfix);
}
else
{
readEnum(element, attributes, enumData, bitmask, prefix, postfix);
}
}
void VulkanHppGenerator::readEnum(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, EnumData & enumData, bool bitmask, std::string const& prefix, std::string const& postfix)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "name",{} } }, { { "bitpos",{} },{ "comment",{} },{ "value",{} } });
checkElements(line, getChildElements(element), {});
std::string alias, bitpos, name, value;
for (auto const& attribute : attributes)
{
if (attribute.first == "bitpos")
{
bitpos = attribute.second;
check(!bitpos.empty(), line, "enum with empty bitpos");
}
else if (attribute.first == "name")
{
name = attribute.second;
check(!name.empty(), line, "enum with empty name");
}
else if (attribute.first == "value")
{
value = attribute.second;
check(!value.empty(), line, "enum with empty value");
}
}
assert(!name.empty());
std::string tag = findTag(m_tags, name, postfix);
check(bitpos.empty() ^ value.empty(), line, "invalid set of attributes for enum <" + name + ">");
enumData.addEnumValue(line, name, bitmask, !bitpos.empty(), prefix, postfix, tag);
}
void VulkanHppGenerator::readEnumAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, EnumData & enumData, bool bitmask, std::string const& prefix, std::string const& postfix)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "alias",{} }, { "name",{} } }, { { "comment", {} } });
checkElements(line, getChildElements(element), {});
std::string alias, bitpos, name, value;
for (auto const& attribute : attributes)
{
if (attribute.first == "alias")
{
alias = attribute.second;
check(!alias.empty(), line, "enum with empty alias");
}
else if (attribute.first == "name")
{
name = attribute.second;
check(!name.empty(), line, "enum with empty name");
}
}
assert(!name.empty());
std::string tag = findTag(m_tags, name, postfix);
check(std::find_if(enumData.values.begin(), enumData.values.end(), [&alias](EnumValueData const& evd) { return evd.vulkanValue == alias; }) != enumData.values.end(),
line, "enum alias <" + alias + "> not listed in set of enum values");
enumData.aliases.push_back(std::make_pair(name, createEnumValueName(name, prefix, postfix, bitmask, tag)));
}
void VulkanHppGenerator::readEnumConstant(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "name",{} } }, { { "alias",{} },{ "comment",{} }, { "value", {} } });
checkElements(line, getChildElements(element), {});
for (auto const& attribute : attributes)
{
if (attribute.first == "alias")
{
check(m_constants.find(attribute.second) != m_constants.end(), line, "unknown enum constant alias <" + attribute.second + ">");
}
else if (attribute.first == "name")
{
check(m_constants.insert(attribute.second).second, line, "already specified enum constant <" + attribute.second + ">");
}
}
}
void VulkanHppGenerator::readEnums(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "name",{} } }, { { "comment",{} },{ "type",{ "bitmask", "enum" } } });
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
std::string name, type;
for (auto const& attribute : attributes)
{
if (attribute.first == "name")
{
name = attribute.second;
check(!name.empty(), line, "enum with empty name");
}
else if (attribute.first == "type")
{
type = attribute.second;
check(!type.empty(), line, "enum with empty type");
}
}
assert(!name.empty());
if (name == "API Constants")
{
checkElements(line, children, { { "enum", false } }, {});
for (auto const& child : children)
{
readEnumConstant(child);
}
}
else
{
checkElements(line, children, {}, { "comment", "enum", "unused" });
check(!type.empty(), line, "enum without type");
// get the EnumData entry in enum map
std::map<std::string, EnumData>::iterator it = m_enums.find(name);
if (it == m_enums.end())
{
// well, some enums are not listed in the <types> section
warn(false, line, "enum <" + name + "> is not listed as enum in the types section");
it = m_enums.insert(std::make_pair(name, EnumData())).first;
}
check(it->second.values.empty(), line, "enum <" + name + "> already holds values");
// mark it as a bitmask, if it is one
bool bitmask = (type == "bitmask");
it->second.isBitmask = bitmask;
if (bitmask)
{
// look for the corresponding bitmask and set the requirements if needed!
auto bitmaskIt = std::find_if(m_bitmasks.begin(), m_bitmasks.end(), [&name](auto const& bitmask) { return bitmask.second.requirements == name; });
if (bitmaskIt == m_bitmasks.end())
{
warn(false, line, "enum <" + name + "> is not listed as an requires for any bitmask in the types section");
std::string bitmaskName = name;
size_t pos = bitmaskName.rfind("FlagBits");
check(pos != std::string::npos, line, "enum <" + name + "> does not contain <FlagBits> as substring");
bitmaskName.replace(pos, 8, "Flags");
bitmaskIt = m_bitmasks.find(bitmaskName);
check(bitmaskIt != m_bitmasks.end(), line, "enum <" + name + "> has not corresponding bitmask <" + bitmaskName + "> listed in the types section");
assert(bitmaskIt->second.requirements.empty());
bitmaskIt->second.requirements = name;
}
}
std::string prefix = getEnumPrefix(line, name, bitmask);
std::string postfix = getEnumPostfix(name, m_tags, prefix);
// read the names of the enum values
for (auto child : children)
{
std::string value = child->Value();
if (value == "comment")
{
readComment(child);
}
else if (value == "enum")
{
readEnum(child, it->second, bitmask, prefix, postfix);
}
}
}
}
void VulkanHppGenerator::readExtension(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes,
{
{ "name",{} },
{ "number",{} },
{ "supported",{ "disabled", "enabled", "vulkan" } }
},
{
{ "author",{} },
{ "comment",{} },
{ "contact",{} },
{ "deprecatedby",{} },
{ "obsoletedby",{} },
{ "platform",{} },
{ "promotedto",{} },
{ "provisional", { "true" } },
{ "requires",{} },
{ "requiresCore",{} },
{ "type",{ "device", "instance" } }
});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, {}, { "require" });
std::string deprecatedBy, name, obsoletedBy, platform, promotedTo, supported;
std::vector<std::string> requirements;
for (auto const& attribute : attributes)
{
if (attribute.first == "deprecatedby")
{
deprecatedBy = attribute.second;
}
else if (attribute.first == "name")
{
name = attribute.second;
}
else if (attribute.first == "obsoletedby")
{
obsoletedBy = attribute.second;
}
else if (attribute.first == "platform")
{
platform = attribute.second;
check(m_platforms.find(platform) != m_platforms.end(), line, "unknown platform <" + platform + ">");
}
else if (attribute.first == "promotedto")
{
promotedTo = attribute.second;
}
else if (attribute.first == "requires")
{
requirements = tokenize(attribute.second, ',');
}
else if (attribute.first == "requiresCore")
{
std::string const& requiresCore = attribute.second;
check(std::find_if(m_features.begin(), m_features.end(), [&requiresCore](std::pair<std::string, std::string> const& nameNumber){ return nameNumber.second == requiresCore; }) != m_features.end(),
line, "unknown feature number <" + attribute.second + ">");
}
else if (attribute.first == "supported")
{
supported = attribute.second;
}
}
if (supported == "disabled")
{
// kick out all the disabled stuff we've read before !!
for (auto const& child : children)
{
readExtensionDisabledRequire(name, child);
}
}
else
{
auto pitb = m_extensions.insert(std::make_pair(name, ExtensionData(line)));
check(pitb.second, line, "already encountered extension <" + name + ">");
pitb.first->second.deprecatedBy = deprecatedBy;
pitb.first->second.obsoletedBy = obsoletedBy;
pitb.first->second.promotedTo = promotedTo;
for (auto const& r : requirements)
{
check(pitb.first->second.requirements.insert(std::make_pair(r, line)).second, line, "required extension <" + r + "> already listed");
}
std::string tag = extractTag(line, name, m_tags);
for (auto child : children)
{
readExtensionRequire(child, platform, tag, pitb.first->second.requirements);
}
}
}
void VulkanHppGenerator::readExtensionDisabledCommand(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "name",{} } }, {});
checkElements(line, getChildElements(element), {});
std::string name = attributes.find("name")->second;
std::string strippedName = startLowerCase(stripPrefix(name, "vk"));
// first unlink the command from its class
auto commandToHandleIt = m_commandToHandle.find(name);
check(commandToHandleIt != m_commandToHandle.end(), line, "try to remove unknown command <" + name + ">");
auto handlesIt = m_handles.find(m_commandToHandle.find(name)->second);
check(handlesIt != m_handles.end(), line, "cannot find handle corresponding to command <" + name + ">");
auto it = handlesIt->second.commands.find(name);
check(it != handlesIt->second.commands.end(), line, "cannot find command <" + name + "> in commands associated with handle <" + handlesIt->first + ">");
handlesIt->second.commands.erase(it);
// then remove the command from the command-to-handle map
m_commandToHandle.erase(commandToHandleIt);
}
void VulkanHppGenerator::readExtensionDisabledEnum(std::string const& extensionName, tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "name",{} } }, { { "bitpos",{} },{ "extends",{} },{ "offset",{} },{ "value",{} } });
checkElements(line, getChildElements(element), {});
std::string extends, name;
for (auto const& attribute : attributes)
{
if (attribute.first == "extends")
{
extends = attribute.second;
}
else if (attribute.first == "name")
{
name = attribute.second;
}
}
if (!extends.empty())
{
auto enumIt = m_enums.find(extends);
check(enumIt != m_enums.end(), line, "disabled extension <" + extensionName + "> references unknown enum <" + extends + ">");
check(std::find_if(enumIt->second.values.begin(), enumIt->second.values.end(), [&name](EnumValueData const& evd) { return evd.vulkanValue == name; }) == enumIt->second.values.end(), line, "disabled extension <" + extensionName + "> references known enum value <" + name + ">");
}
}
void VulkanHppGenerator::readExtensionDisabledRequire(std::string const& extensionName, tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, {});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "enum", false } }, { "command", "comment", "type" });
for (auto child : children)
{
std::string value = child->Value();
if (value == "command")
{
readExtensionDisabledCommand(child);
}
else if (value == "comment")
{
readComment(child);
}
else if (value == "enum")
{
readExtensionDisabledEnum(extensionName, child);
}
else
{
assert(value == "type");
readExtensionDisabledType(child);
}
}
}
void VulkanHppGenerator::readExtensionDisabledType(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "name",{} } }, {});
checkElements(line, getChildElements(element), {});
std::string name = attributes.find("name")->second;
std::string strippedName = stripPrefix(name, "Vk");
// a type simply needs to be removed from the structs, bitmasks, or enums
check(m_bitmasks.erase(name) + m_enums.erase(name) + m_structures.erase(name) == 1, line, "element <" + name + "> was removed from more than one set of elements");
}
void VulkanHppGenerator::readExtensionRequire(tinyxml2::XMLElement const* element, std::string const& platform, std::string const& tag, std::map<std::string, int> & requirements)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, {}, { { "extension",{} },{ "feature",{} } });
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, {}, { "command", "comment", "enum", "type" });
for (auto const& attribute : attributes)
{
if (attribute.first == "extension")
{
check(requirements.insert(std::make_pair(attribute.second, line)).second, line, "required extension <" + attribute.second + "> already listed");
}
else
{
assert(attribute.first == "feature");
check(m_features.find(attribute.second) != m_features.end(), line, "unknown feature <" + attribute.second + ">");
}
}
for (auto child : children)
{
std::string value = child->Value();
if (value == "command")
{
readExtensionRequireCommand(child, platform);
}
else if (value == "comment")
{
readComment(child);
}
else if (value == "enum")
{
readRequireEnum(child, tag);
}
else if (value == "type")
{
readExtensionRequireType(child, platform);
}
}
}
void VulkanHppGenerator::readExtensionRequireCommand(tinyxml2::XMLElement const* element, std::string const& platform)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "name",{} } }, {});
checkElements(line, getChildElements(element), {});
// just add the protect string to the CommandData
if (!platform.empty())
{
std::string name = attributes.find("name")->second;
check(m_platforms.find(platform) != m_platforms.end(), line, "unknown platform <" + platform + ">");
auto commandToHandleIt = m_commandToHandle.find(name);
check(commandToHandleIt != m_commandToHandle.end(), line, "unknown command <" + name + ">");
auto const& handlesIt = m_handles.find(commandToHandleIt->second);
check(handlesIt != m_handles.end(), line, "unknown handle for command <" + name + ">");
auto const& commandsIt = handlesIt->second.commands.find(name);
check(commandsIt != handlesIt->second.commands.end(), line, "unknown command <" + name + "> for handle <" + handlesIt->first + ">");
commandsIt->second.platform = platform;
}
}
void VulkanHppGenerator::readExtensionRequireType(tinyxml2::XMLElement const* element, std::string const& platform)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "name",{} } }, {});
checkElements(line, getChildElements(element), {});
// add the protect-string to the appropriate type: enum, flag, handle, scalar, or struct
std::string name = attributes.find("name")->second;
auto handleIt = m_handles.find(name);
if (handleIt != m_handles.end())
{
assert(beginsWith(name, "Vk"));
auto objectTypeIt = m_enums.find("VkObjectType");
assert(objectTypeIt != m_enums.end());
std::string objectTypeName = "e" + stripPrefix(handleIt->first, "Vk");
auto valueIt = std::find_if(objectTypeIt->second.values.begin(), objectTypeIt->second.values.end(), [objectTypeName](EnumValueData const& evd) {return evd.vkValue == objectTypeName; });
check(valueIt != objectTypeIt->second.values.end(), line, "missing entry in VkObjectType enum for handle <" + name + ">.");
}
if (!platform.empty())
{
auto bmit = m_bitmasks.find(name);
if (bmit != m_bitmasks.end())
{
check(bmit->second.platform.empty(), line, "platform already specified for bitmask <" + name + ">");
bmit->second.platform = platform;
assert((m_enums.find(bmit->second.requirements) == m_enums.end()) || (m_enums.find(bmit->second.requirements)->second.isBitmask));
}
else
{
auto eit = m_enums.find(name);
if (eit != m_enums.end())
{
check(eit->second.platform.empty(), line, "platform already specified for enum <" + name + ">");
eit->second.platform = platform;
}
else
{
auto hit = m_handles.find(name);
if (hit != m_handles.end())
{
check(hit->second.platform.empty(), line, "platform already specified for handle <" + name + ">");
hit->second.platform = platform;
}
else
{
auto stit = m_structures.find(name);
if (stit != m_structures.end())
{
assert(m_handles.find(name) == m_handles.end());
check(stit->second.platform.empty(), line, "platform already specified for structure <" + name + ">");
stit->second.platform = platform;
}
else
{
assert((m_types.find(name) != m_types.end()));
}
}
}
}
}
}
void VulkanHppGenerator::readExtensions(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), { { "comment",{} } }, {});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "extension", false } });
for (auto child : children)
{
readExtension(child);
}
}
void VulkanHppGenerator::readFeature(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "api",{ "vulkan" } },{ "comment",{} },{ "name",{} },{ "number",{} } }, {});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "require", false } });
std::string name, number, modifiedNumber;
for (auto const& attribute : attributes)
{
if (attribute.first == "name")
{
name = attribute.second;
}
else if (attribute.first == "number")
{
number = attribute.second;
modifiedNumber = number;
std::replace(modifiedNumber.begin(), modifiedNumber.end(), '.', '_');
}
}
assert(!name.empty() && !number.empty());
check(name == "VK_VERSION_" + modifiedNumber, line, "unexpected formatting of name <" + name + ">");
check(m_features.insert(std::make_pair(name, number)).second, line, "already specified feature <" + name + ">");
for (auto child : children)
{
readFeatureRequire(child);
}
}
void VulkanHppGenerator::readFeatureRequire(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, { { "comment",{} } });
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, {}, { "command", "comment", "enum", "type" });
for (auto child : children)
{
std::string value = child->Value();
if (value == "command")
{
readRequireCommand(child);
}
else if (value == "comment")
{
readComment(child);
}
else if (value == "enum")
{
readRequireEnum(child, "");
}
else if (value == "type")
{
readRequireType(child);
}
}
}
void VulkanHppGenerator::readFuncpointer(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "category",{ "funcpointer" } } }, { { "requires",{} } });
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "name", true } }, { "type" });
std::string requirements;
for (auto const& attribute : attributes)
{
if (attribute.first == "requires")
{
requirements = attribute.second;
}
}
for (auto const& child : children)
{
std::string value = child->Value();
int childLine = child->GetLineNum();
if (value == "name")
{
std::string name = child->GetText();
check(!name.empty(), childLine, "funcpointer with empty name");
check(m_funcPointers.insert(std::make_pair(name, FuncPointerData(requirements, line))).second, childLine, "funcpointer <" + name + "> already specified");
check(m_types.insert(name).second, childLine, "funcpointer <" + name + "> already specified as a type");
}
else if (value == "type")
{
std::string type = child->GetText();
check(!type.empty(), childLine, "funcpointer argument with empty type");
check((m_types.find(type) != m_types.end()) || (type == requirements), childLine, "funcpointer argument of unknown type <" + type + ">");
}
}
}
void VulkanHppGenerator::readHandle(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
auto aliasIt = attributes.find("alias");
if (aliasIt != attributes.end())
{
checkAttributes(line, attributes, { { "alias",{} },{ "category",{ "handle" } },{ "name",{} } }, {});
checkElements(line, getChildElements(element), {});
auto handlesIt = m_handles.find(aliasIt->second);
check(handlesIt != m_handles.end(), line, "using unspecified alias <" + aliasIt->second + ">.");
check(handlesIt->second.alias.empty(), line, "handle <" + handlesIt->first + "> already has an alias <" + handlesIt->second.alias + ">");
handlesIt->second.alias = attributes.find("name")->second;
check(m_types.insert(handlesIt->second.alias).second, line, "handle alias <" + handlesIt->second.alias + "> already specified as a type");
}
else
{
checkAttributes(line, attributes, { { "category",{ "handle" } } }, { { "parent",{} }});
std::string parent;
for (auto const& attribute : attributes)
{
if (attribute.first == "parent")
{
parent = attribute.second;
check(!parent.empty(), line, "handle with empty parent");
}
}
NameData nameData;
TypeData typeData;
std::tie(nameData, typeData) = readNameAndType(element);
check(beginsWith(nameData.name, "Vk"), line, "name <" + nameData.name + "> does not begin with <Vk>");
check(nameData.arraySizes.empty(), line, "name <" + nameData.name + "> with unsupported arraySizes");
check(nameData.bitCount.empty(), line, "name <" + nameData.name + "> with unsupported bitCount <" + nameData.bitCount + ">");
check((typeData.type == "VK_DEFINE_HANDLE") || (typeData.type == "VK_DEFINE_NON_DISPATCHABLE_HANDLE"), line, "handle with invalid type <" + typeData.type + ">");
check(typeData.prefix.empty(), line, "unexpected type prefix <" + typeData.prefix + ">");
check(typeData.postfix == "(", line, "unexpected type postfix <" + typeData.postfix + ">");
check(m_handles.insert(std::make_pair(nameData.name, HandleData(tokenize(parent, ','), line))).second, line, "handle <" + nameData.name + "> already specified");
check(m_types.insert(nameData.name).second, line, "handle <" + nameData.name + "> already specified as a type");
}
}
std::pair<VulkanHppGenerator::NameData, VulkanHppGenerator::TypeData> VulkanHppGenerator::readNameAndType(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "name", true }, { "type", true } });
NameData nameData;
TypeData typeData;
for (auto child : children)
{
line = child->GetLineNum();
checkAttributes(line, getAttributes(child), {}, {});
checkElements(line, getChildElements(child), {});
std::string value = child->Value();
if (value == "name")
{
nameData.name = child->GetText();
std::tie(nameData.arraySizes, nameData.bitCount) = readModifiers(child->NextSibling());
}
else if (value == "type")
{
typeData.prefix = readTypePrefix(child->PreviousSibling());
typeData.type = child->GetText();
typeData.postfix = readTypePostfix(child->NextSibling());
}
}
return std::make_pair(nameData, typeData);
}
void VulkanHppGenerator::readPlatform(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "comment",{} },{ "name",{} },{ "protect",{} } }, {});
checkElements(line, getChildElements(element), {});
std::string name, protect;
for (auto const& attribute : attributes)
{
if (attribute.first == "name")
{
name = attribute.second;
check(!name.empty(), line, "attribute <name> is empty");
}
else if (attribute.first == "protect")
{
protect = attribute.second;
check(!protect.empty(), line, "attribute <protect> is empty");
}
}
assert(!name.empty() && !protect.empty());
check(m_platforms.find(name) == m_platforms.end(), line, "platform name <" + name + "> already specified");
check(std::find_if(m_platforms.begin(), m_platforms.end(), [&protect](std::pair<std::string, std::string> const& p) { return p.second == protect; }) == m_platforms.end(), line, "platform protect <" + protect + "> already specified");
m_platforms[name] = protect;
}
void VulkanHppGenerator::readPlatforms(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), { { "comment",{} } }, {});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "platform", false } });
for (auto child : children)
{
readPlatform(child);
}
}
void VulkanHppGenerator::readRegistry(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, {});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "commands", true }, { "comment", false }, { "enums", false }, { "extensions", true }, { "feature", false }, { "platforms", true }, { "tags", true }, { "types", true } });
for (auto child : children)
{
const std::string value = child->Value();
if (value == "commands")
{
readCommands(child);
}
else if (value == "comment")
{
std::string comment = readComment(child);
if (comment.find("\nCopyright") == 0)
{
setVulkanLicenseHeader(child->GetLineNum(), comment);
}
}
else if (value == "enums")
{
readEnums(child);
}
else if (value == "extensions")
{
readExtensions(child);
}
else if (value == "feature")
{
readFeature(child);
}
else if (value == "platforms")
{
readPlatforms(child);
}
else if (value == "tags")
{
readTags(child);
}
else if (value == "types")
{
readTypes(child);
}
}
}
void VulkanHppGenerator::readRequireCommand(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, {}, { { "name",{} } });
std::string command = attributes.find("name")->second;
check(m_commandToHandle.find(command) != m_commandToHandle.end(), line, "feature requires unknown command <" + command + ">");
}
void VulkanHppGenerator::readRequireEnum(tinyxml2::XMLElement const* element, std::string const& tag)
{
std::map<std::string, std::string> attributes = getAttributes(element);
if (attributes.find("alias") != attributes.end())
{
readRequireEnumAlias(element, attributes, tag);
}
else
{
readRequireEnum(element, attributes, tag);
}
}
void VulkanHppGenerator::readRequireEnum(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, std::string const& tag)
{
int line = element->GetLineNum();
checkAttributes(line, attributes,
{
{ "name",{} }
},
{
{ "bitpos",{} },
{ "comment",{} },
{ "extends",{} },
{ "dir",{ "-" } },
{ "extnumber",{} },
{ "offset",{} },
{ "value",{} }
});
checkElements(line, getChildElements(element), {});
std::string bitpos, name, extends, extnumber, offset, value;
for (auto const& attribute : attributes)
{
if (attribute.first == "bitpos")
{
bitpos = attribute.second;
}
else if (attribute.first == "extends")
{
extends = attribute.second;
}
else if (attribute.first == "name")
{
name = attribute.second;
}
else if (attribute.first == "offset")
{
offset = attribute.second;
}
else if (attribute.first == "value")
{
value = attribute.second;
}
}
if (!extends.empty())
{
auto enumIt = m_enums.find(extends);
check(enumIt != m_enums.end(), line, "feature extends unknown enum <" + extends + ">");
std::string prefix = getEnumPrefix(element->GetLineNum(), enumIt->first, enumIt->second.isBitmask);
std::string postfix = getEnumPostfix(enumIt->first, m_tags, prefix);
// add this enum name to the list of values
check(bitpos.empty() + offset.empty() + value.empty() == 2, line, "exactly one out of bitpos = <" + bitpos + ">, offset = <" + offset + ">, and value = <" + value + "> are supposed to be empty");
enumIt->second.addEnumValue(element->GetLineNum(), name, enumIt->second.isBitmask, !bitpos.empty(), prefix, postfix, tag);
}
else if (value.empty())
{
check(m_constants.find(name) != m_constants.end(), line, "unknown required enum <" + name + ">");
}
}
void VulkanHppGenerator::readRequireEnumAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, std::string const& tag)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "alias",{} }, { "extends",{} }, { "name",{} } }, { { "comment",{} } });
checkElements(line, getChildElements(element), {});
std::string alias, bitpos, name, extends, extnumber, offset, value;
for (auto const& attribute : attributes)
{
if (attribute.first == "alias")
{
alias = attribute.second;
}
else if (attribute.first == "extends")
{
extends = attribute.second;
}
else if (attribute.first == "name")
{
name = attribute.second;
}
}
auto enumIt = m_enums.find(extends);
check(enumIt != m_enums.end(), line, "feature extends unknown enum <" + extends + ">");
std::string prefix = getEnumPrefix(element->GetLineNum(), enumIt->first, enumIt->second.isBitmask);
std::string postfix = getEnumPostfix(enumIt->first, m_tags, prefix);
// add this enum name to the list of aliases
std::string valueName = createEnumValueName(name, prefix, postfix, enumIt->second.isBitmask, tag);
if (!enumIt->second.alias.empty())
{
prefix = getEnumPrefix(element->GetLineNum(), enumIt->second.alias, enumIt->second.isBitmask);
postfix = getEnumPostfix(enumIt->second.alias, m_tags, prefix);
if (endsWith(name, postfix))
{
valueName = createEnumValueName(name, prefix, postfix, enumIt->second.isBitmask, tag);
}
}
check(std::find_if(enumIt->second.aliases.begin(), enumIt->second.aliases.end(), [&valueName](std::pair<std::string, std::string> const& aliasPair) { return valueName == aliasPair.second; }) == enumIt->second.aliases.end(),
line, "alias <" + valueName + "> already specified");
if (std::find_if(enumIt->second.values.begin(), enumIt->second.values.end(), [&valueName](EnumValueData const& evd) { return evd.vkValue == valueName; }) == enumIt->second.values.end())
{
enumIt->second.aliases.push_back(std::make_pair(name, valueName));
}
}
void VulkanHppGenerator::readRequires(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { {"name", {}}, { "requires", {}} }, {});
checkElements(line, getChildElements(element), {});
for (auto attribute : attributes)
{
if (attribute.first == "name")
{
check(m_types.insert(attribute.second).second, line, "type named <" + attribute.second + "> already specified");
}
else
{
assert(attribute.first == "requires");
check(m_includes.find(attribute.second) != m_includes.end(), line, "type requires unknown include <" + attribute.second + ">");
}
}
}
void VulkanHppGenerator::readRequireType(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), { { "name", {} } }, {});
checkElements(line, getChildElements(element), {});
}
void VulkanHppGenerator::readStruct(tinyxml2::XMLElement const* element, bool isUnion, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
if (attributes.find("alias") != attributes.end())
{
readStructAlias(element, attributes);
}
else
{
checkAttributes(line, attributes,
{
{ "category",{ isUnion ? "union" : "struct" } },
{ "name",{} }
},
{
{ "comment",{} },
{ "returnedonly",{ "true" } },
{ "structextends",{} }
});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, {}, { "member", "comment" });
std::string name;
std::vector<std::string> structExtends;
bool returnedOnly = false;
for (auto const& attribute : attributes)
{
if (attribute.first == "name")
{
name = attribute.second;
}
else if (attribute.first == "returnedonly")
{
check(attribute.second == "true", line, "unknown value for attribute returnedonly: <" + attribute.second + ">");
returnedOnly = true;
}
else if (attribute.first == "structextends")
{
structExtends = tokenize(attribute.second, ',');
}
}
assert(!name.empty());
check(m_structures.find(name) == m_structures.end(), line, "struct <" + name + "> already specfied");
std::map<std::string, StructureData>::iterator it = m_structures.insert(std::make_pair(name, StructureData(structExtends, line))).first;
it->second.returnedOnly = returnedOnly;
it->second.isUnion = isUnion;
for (auto child : children)
{
std::string value = child->Value();
if (value == "comment")
{
readComment(child);
}
else if (value == "member")
{
readStructMember(child, it->second.members);
}
}
it->second.subStruct = determineSubStruct(*it);
m_extendedStructs.insert(structExtends.begin(), structExtends.end());
check(m_types.insert(name).second, line, "struct <" + name + "> already specified as a type"); // log type and alias in m_types
}
}
void VulkanHppGenerator::readStructAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "alias",{} },{ "category",{ "struct" } },{ "name",{} } }, {});
checkElements(line, getChildElements(element), {}, {});
std::string alias, name;
for (auto const& attribute : attributes)
{
if (attribute.first == "alias")
{
alias = attribute.second;
}
else if (attribute.first == "name")
{
name = attribute.second;
}
}
auto structIt = m_structures.find(alias);
check(structIt != m_structures.end(), line, "missing alias <" + alias + ">.");
check(structIt->second.aliases.insert(name).second, line, "struct <" + alias + "> already uses alias <" + name + ">");
check(m_structureAliases.insert(std::make_pair(name, alias)).second, line, "structure alias <" + name + "> already used");
check(m_types.insert(name).second, line, "struct <" + name + "> already specified as a type");
}
void VulkanHppGenerator::readStructMember(tinyxml2::XMLElement const* element, std::vector<MemberData> & members)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, {},
{
{ "altlen",{} },
{ "externsync",{ "true" } },
{ "len",{} },
{ "noautovalidity",{ "true" } },
{ "optional",{ "false", "true" } },
{ "values",{} }
});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "name", true }, { "type", true } }, { "comment", "enum" });
members.push_back(MemberData(line));
MemberData & memberData = members.back();
auto valuesIt = attributes.find("values");
if (valuesIt != attributes.end())
{
memberData.values = valuesIt->second;
}
for (auto child : children)
{
std::string value = child->Value();
if (value == "enum")
{
readStructMemberEnum(child, memberData);
}
else if (value == "name")
{
readStructMemberName(child, memberData, members);
}
else if (value == "type")
{
readStructMemberType(child, memberData);
}
}
}
void VulkanHppGenerator::readStructMemberEnum(tinyxml2::XMLElement const* element, MemberData & memberData)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, {});
checkElements(line, getChildElements(element), {}, {});
std::string enumString = element->GetText();
check(element->PreviousSibling() && (strcmp(element->PreviousSibling()->Value(), "[") == 0) && element->NextSibling() && (strcmp(element->NextSibling()->Value(), "]") == 0),
line, std::string("structure member array specifiation is ill-formatted: <") + enumString + ">");
memberData.arraySizes.push_back(enumString);
check(memberData.usedConstant.empty(), line, "struct already holds a constant <" + memberData.usedConstant + ">");
memberData.usedConstant = enumString;
}
void VulkanHppGenerator::readStructMemberName(tinyxml2::XMLElement const* element, MemberData & memberData, std::vector<MemberData> const& members)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, {});
checkElements(line, getChildElements(element), {}, {});
std::string name = element->GetText();
check(std::find_if(members.begin(), members.end(), [&name](MemberData const& md) { return md.name == name; }) == members.end(), line, "structure member name <" + name + "> already used");
memberData.name = name;
std::tie(memberData.arraySizes, memberData.bitCount) = readModifiers(element->NextSibling());
}
void VulkanHppGenerator::readStructMemberType(tinyxml2::XMLElement const* element, MemberData & memberData)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), {}, {});
checkElements(line, getChildElements(element), {}, {});
memberData.type.prefix = readTypePrefix(element->PreviousSibling());
memberData.type.type = element->GetText();
memberData.type.postfix = readTypePostfix(element->NextSibling());
}
void VulkanHppGenerator::readTag(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
checkAttributes(line, attributes, { { "author",{} },{ "contact",{} },{ "name",{} } }, {});
checkElements(line, getChildElements(element), {});
for (auto const& attribute : attributes)
{
if (attribute.first == "name")
{
check(m_tags.find(attribute.second) == m_tags.end(), line, "tag named <" + attribute.second + "> has already been specified");
m_tags.insert(attribute.second);
}
else
{
check((attribute.first == "author") || (attribute.first == "contact"), line, "unknown attribute <" + attribute.first + ">");
}
}
}
void VulkanHppGenerator::readTags(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), { { "comment",{} } }, {});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "tag", false } });
for (auto child : children)
{
readTag(child);
}
}
void VulkanHppGenerator::readType(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
std::map<std::string, std::string> attributes = getAttributes(element);
auto categoryIt = attributes.find("category");
if (categoryIt != attributes.end())
{
if (categoryIt->second == "basetype")
{
readBaseType(element, attributes);
}
else if (categoryIt->second == "bitmask")
{
readBitmask(element, attributes);
}
else if (categoryIt->second == "define")
{
readDefine(element, attributes);
}
else if (categoryIt->second == "enum")
{
readTypeEnum(element, attributes);
}
else if (categoryIt->second == "funcpointer")
{
readFuncpointer(element, attributes);
}
else if (categoryIt->second == "handle")
{
readHandle(element, attributes);
}
else if (categoryIt->second == "include")
{
readTypeInclude(element, attributes);
}
else if (categoryIt->second == "struct")
{
readStruct(element, false, attributes);
}
else
{
check(categoryIt->second == "union", element->GetLineNum(), "unknown type category <" + categoryIt->second + ">");
readStruct(element, true, attributes);
}
}
else
{
auto requiresIt = attributes.find("requires");
if (requiresIt != attributes.end())
{
readRequires(element, attributes);
}
else
{
check((attributes.size() == 1) && (attributes.begin()->first == "name") && (attributes.begin()->second == "int"), line, "unknown type");
check(m_types.insert(attributes.begin()->second).second, line, "type <" + attributes.begin()->second + "> already specified");
}
}
}
void VulkanHppGenerator::readTypeEnum(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "category",{ "enum" } }, { "name",{} } }, { { "alias",{} }});
checkElements(line, getChildElements(element), {});
std::string alias, name;
for (auto const& attribute : attributes)
{
if (attribute.first == "alias")
{
alias = attribute.second;
check(!alias.empty(), line, "enum with empty alias");
}
else if (attribute.first == "name")
{
name = attribute.second;
check(!name.empty(), line, "enum with empty name");
check(m_enums.find(name) == m_enums.end(), line, "enum <" + name + "> already specified");
}
}
assert(!name.empty());
if (alias.empty())
{
check(m_enums.insert(std::make_pair(name, EnumData())).second, line, "enum <" + name + "> already specified");
}
else
{
auto enumIt = m_enums.find(alias);
check(enumIt != m_enums.end(), line, "enum with unknown alias <" + alias + ">");
check(enumIt->second.alias.empty(), line, "enum <" + enumIt->first + "> already has an alias <" + enumIt->second.alias + ">");
enumIt->second.alias = name;
}
check(m_types.insert(name).second, line, "enum <" + name + "> already specified as a type");
}
void VulkanHppGenerator::readTypeInclude(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes)
{
int line = element->GetLineNum();
checkAttributes(line, attributes, { { "category", { "include" } }, { "name",{} } }, {});
checkElements(line, getChildElements(element), {});
std::string name = attributes.find("name")->second;
check(m_includes.insert(name).second, element->GetLineNum(), "include named <" + name + "> already specified");
}
void VulkanHppGenerator::readTypes(tinyxml2::XMLElement const* element)
{
int line = element->GetLineNum();
checkAttributes(line, getAttributes(element), { { "comment",{} } }, {});
std::vector<tinyxml2::XMLElement const*> children = getChildElements(element);
checkElements(line, children, { { "comment", false }, { "type", false } });
for (auto child : children)
{
std::string value = child->Value();
if (value == "comment")
{
readComment(child);
}
else
{
assert(value == "type");
readType(child);
}
}
}
void VulkanHppGenerator::registerDeleter(std::string const& name, std::pair<std::string, CommandData> const& commandData)
{
if ((commandData.first.substr(2, 7) == "Destroy") || (commandData.first.substr(2, 4) == "Free"))
{
std::string key;
size_t valueIndex;
switch (commandData.second.params.size())
{
case 2:
case 3:
assert(commandData.second.params.back().type.type == "VkAllocationCallbacks");
key = (commandData.second.params.size() == 2) ? "" : commandData.second.params[0].type.type;
valueIndex = commandData.second.params.size() - 2;
break;
case 4:
key = commandData.second.params[0].type.type;
valueIndex = 3;
assert(m_handles.find(commandData.second.params[valueIndex].type.type) != m_handles.end());
m_handles.find(commandData.second.params[valueIndex].type.type)->second.deletePool = commandData.second.params[1].type.type;
break;
default:
assert(false);
valueIndex = 0;
}
auto keyHandleIt = m_handles.find(key);
assert((keyHandleIt != m_handles.end()) && (keyHandleIt->second.childrenHandles.find(commandData.second.params[valueIndex].type.type) == keyHandleIt->second.childrenHandles.end()));
keyHandleIt->second.childrenHandles.insert(commandData.second.params[valueIndex].type.type);
auto handleIt = m_handles.find(commandData.second.params[valueIndex].type.type);
assert(handleIt != m_handles.end());
handleIt->second.deleteCommand = name;
}
}
void VulkanHppGenerator::setVulkanLicenseHeader(int line, std::string const& comment)
{
check(m_vulkanLicenseHeader.empty(), line, "second encounter of a Copyright comment");
m_vulkanLicenseHeader = comment;
// replace any '\n' with "\n// "
for (size_t pos = m_vulkanLicenseHeader.find('\n'); pos != std::string::npos; pos = m_vulkanLicenseHeader.find('\n', pos + 1))
{
m_vulkanLicenseHeader.replace(pos, 1, "\n// ");
}
// and add a little message on our own
m_vulkanLicenseHeader += "\n\n// This header is generated from the Khronos Vulkan XML API Registry.";
m_vulkanLicenseHeader = trim(m_vulkanLicenseHeader) + "\n";
}
std::string VulkanHppGenerator::TypeData::compose() const
{
return prefix + (prefix.empty() ? "" : " ") + ((type.substr(0, 2) == "Vk") ? "VULKAN_HPP_NAMESPACE::" : "") + stripPrefix(type, "Vk") + postfix;
}
std::string to_string(tinyxml2::XMLError error)
{
switch (error)
{
case tinyxml2::XML_SUCCESS : return "XML_SUCCESS";
case tinyxml2::XML_NO_ATTRIBUTE : return "XML_NO_ATTRIBUTE";
case tinyxml2::XML_WRONG_ATTRIBUTE_TYPE : return "XML_WRONG_ATTRIBUTE_TYPE";
case tinyxml2::XML_ERROR_FILE_NOT_FOUND : return "XML_ERROR_FILE_NOT_FOUND";
case tinyxml2::XML_ERROR_FILE_COULD_NOT_BE_OPENED : return "XML_ERROR_FILE_COULD_NOT_BE_OPENED";
case tinyxml2::XML_ERROR_FILE_READ_ERROR : return "XML_ERROR_FILE_READ_ERROR";
case tinyxml2::XML_ERROR_PARSING_ELEMENT : return "XML_ERROR_PARSING_ELEMENT";
case tinyxml2::XML_ERROR_PARSING_ATTRIBUTE : return "XML_ERROR_PARSING_ATTRIBUTE";
case tinyxml2::XML_ERROR_PARSING_TEXT : return "XML_ERROR_PARSING_TEXT";
case tinyxml2::XML_ERROR_PARSING_CDATA : return "XML_ERROR_PARSING_CDATA";
case tinyxml2::XML_ERROR_PARSING_COMMENT : return "XML_ERROR_PARSING_COMMENT";
case tinyxml2::XML_ERROR_PARSING_DECLARATION : return "XML_ERROR_PARSING_DECLARATION";
case tinyxml2::XML_ERROR_PARSING_UNKNOWN : return "XML_ERROR_PARSING_UNKNOWN";
case tinyxml2::XML_ERROR_EMPTY_DOCUMENT : return "XML_ERROR_EMPTY_DOCUMENT";
case tinyxml2::XML_ERROR_MISMATCHED_ELEMENT : return "XML_ERROR_MISMATCHED_ELEMENT";
case tinyxml2::XML_ERROR_PARSING : return "XML_ERROR_PARSING";
case tinyxml2::XML_CAN_NOT_CONVERT_TEXT : return "XML_CAN_NOT_CONVERT_TEXT";
case tinyxml2::XML_NO_TEXT_NODE : return "XML_NO_TEXT_NODE";
default : return "unknown error code <" + std::to_string(error) + ">";
}
}
int main(int argc, char **argv)
{
static const std::string classArrayProxy = R"(
#if !defined(VULKAN_HPP_DISABLE_ENHANCED_MODE)
template <typename T>
class ArrayProxy
{
public:
VULKAN_HPP_CONSTEXPR ArrayProxy(std::nullptr_t) VULKAN_HPP_NOEXCEPT
: m_count(0)
, m_ptr(nullptr)
{}
ArrayProxy(typename std::remove_reference<T>::type & ptr) VULKAN_HPP_NOEXCEPT
: m_count(1)
, m_ptr(&ptr)
{}
ArrayProxy(uint32_t count, T * ptr) VULKAN_HPP_NOEXCEPT
: m_count(count)
, m_ptr(ptr)
{}
template <size_t N>
ArrayProxy(std::array<typename std::remove_const<T>::type, N> & data) VULKAN_HPP_NOEXCEPT
: m_count(N)
, m_ptr(data.data())
{}
template <size_t N>
ArrayProxy(std::array<typename std::remove_const<T>::type, N> const& data) VULKAN_HPP_NOEXCEPT
: m_count(N)
, m_ptr(data.data())
{}
template <class Allocator = std::allocator<typename std::remove_const<T>::type>>
ArrayProxy(std::vector<typename std::remove_const<T>::type, Allocator> & data) VULKAN_HPP_NOEXCEPT
: m_count(static_cast<uint32_t>(data.size()))
, m_ptr(data.data())
{}
template <class Allocator = std::allocator<typename std::remove_const<T>::type>>
ArrayProxy(std::vector<typename std::remove_const<T>::type, Allocator> const& data) VULKAN_HPP_NOEXCEPT
: m_count(static_cast<uint32_t>(data.size()))
, m_ptr(data.data())
{}
ArrayProxy(std::initializer_list<typename std::remove_reference<T>::type> const& data) VULKAN_HPP_NOEXCEPT
: m_count(static_cast<uint32_t>(data.end() - data.begin()))
, m_ptr(data.begin())
{}
const T * begin() const VULKAN_HPP_NOEXCEPT
{
return m_ptr;
}
const T * end() const VULKAN_HPP_NOEXCEPT
{
return m_ptr + m_count;
}
const T & front() const VULKAN_HPP_NOEXCEPT
{
VULKAN_HPP_ASSERT(m_count && m_ptr);
return *m_ptr;
}
const T & back() const VULKAN_HPP_NOEXCEPT
{
VULKAN_HPP_ASSERT(m_count && m_ptr);
return *(m_ptr + m_count - 1);
}
bool empty() const VULKAN_HPP_NOEXCEPT
{
return (m_count == 0);
}
uint32_t size() const VULKAN_HPP_NOEXCEPT
{
return m_count;
}
T * data() const VULKAN_HPP_NOEXCEPT
{
return m_ptr;
}
private:
uint32_t m_count;
T * m_ptr;
};
#endif
)";
static const std::string classFlags = R"(
template <typename FlagBitsType> struct FlagTraits
{
enum { allFlags = 0 };
};
template <typename BitType>
class Flags
{
public:
using MaskType = typename std::underlying_type<BitType>::type;
// constructors
VULKAN_HPP_CONSTEXPR Flags() VULKAN_HPP_NOEXCEPT
: m_mask(0)
{}
VULKAN_HPP_CONSTEXPR Flags(BitType bit) VULKAN_HPP_NOEXCEPT
: m_mask(static_cast<MaskType>(bit))
{}
VULKAN_HPP_CONSTEXPR Flags(Flags<BitType> const& rhs) VULKAN_HPP_NOEXCEPT
: m_mask(rhs.m_mask)
{}
VULKAN_HPP_CONSTEXPR explicit Flags(MaskType flags) VULKAN_HPP_NOEXCEPT
: m_mask(flags)
{}
// relational operators
#if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR)
auto operator<=>(Flags<BitType> const&) const = default;
#else
VULKAN_HPP_CONSTEXPR bool operator<(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return m_mask < rhs.m_mask;
}
VULKAN_HPP_CONSTEXPR bool operator<=(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return m_mask <= rhs.m_mask;
}
VULKAN_HPP_CONSTEXPR bool operator>(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return m_mask > rhs.m_mask;
}
VULKAN_HPP_CONSTEXPR bool operator>=(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return m_mask >= rhs.m_mask;
}
VULKAN_HPP_CONSTEXPR bool operator==(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return m_mask == rhs.m_mask;
}
VULKAN_HPP_CONSTEXPR bool operator!=(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return m_mask != rhs.m_mask;
}
#endif
// logical operator
VULKAN_HPP_CONSTEXPR bool operator!() const VULKAN_HPP_NOEXCEPT
{
return !m_mask;
}
// bitwise operators
VULKAN_HPP_CONSTEXPR Flags<BitType> operator&(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return Flags<BitType>(m_mask & rhs.m_mask);
}
VULKAN_HPP_CONSTEXPR Flags<BitType> operator|(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return Flags<BitType>(m_mask | rhs.m_mask);
}
VULKAN_HPP_CONSTEXPR Flags<BitType> operator^(Flags<BitType> const& rhs) const VULKAN_HPP_NOEXCEPT
{
return Flags<BitType>(m_mask ^ rhs.m_mask);
}
VULKAN_HPP_CONSTEXPR Flags<BitType> operator~() const VULKAN_HPP_NOEXCEPT
{
return Flags<BitType>(m_mask ^ FlagTraits<BitType>::allFlags);
}
// assignment operators
Flags<BitType> & operator=(Flags<BitType> const& rhs) VULKAN_HPP_NOEXCEPT
{
m_mask = rhs.m_mask;
return *this;
}
Flags<BitType> & operator|=(Flags<BitType> const& rhs) VULKAN_HPP_NOEXCEPT
{
m_mask |= rhs.m_mask;
return *this;
}
Flags<BitType> & operator&=(Flags<BitType> const& rhs) VULKAN_HPP_NOEXCEPT
{
m_mask &= rhs.m_mask;
return *this;
}
Flags<BitType> & operator^=(Flags<BitType> const& rhs) VULKAN_HPP_NOEXCEPT
{
m_mask ^= rhs.m_mask;
return *this;
}
// cast operators
explicit VULKAN_HPP_CONSTEXPR operator bool() const VULKAN_HPP_NOEXCEPT
{
return !!m_mask;
}
explicit VULKAN_HPP_CONSTEXPR operator MaskType() const VULKAN_HPP_NOEXCEPT
{
return m_mask;
}
private:
MaskType m_mask;
};
#if !defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR)
// relational operators only needed for pre C++20
template <typename BitType>
VULKAN_HPP_CONSTEXPR bool operator<(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags > bit;
}
template <typename BitType>
VULKAN_HPP_CONSTEXPR bool operator<=(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags >= bit;
}
template <typename BitType>
VULKAN_HPP_CONSTEXPR bool operator>(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags < bit;
}
template <typename BitType>
VULKAN_HPP_CONSTEXPR bool operator>=(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags <= bit;
}
template <typename BitType>
VULKAN_HPP_CONSTEXPR bool operator==(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags == bit;
}
template <typename BitType>
VULKAN_HPP_CONSTEXPR bool operator!=(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags != bit;
}
#endif
// bitwise operators
template <typename BitType>
VULKAN_HPP_CONSTEXPR Flags<BitType> operator&(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags & bit;
}
template <typename BitType>
VULKAN_HPP_CONSTEXPR Flags<BitType> operator|(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags | bit;
}
template <typename BitType>
VULKAN_HPP_CONSTEXPR Flags<BitType> operator^(BitType bit, Flags<BitType> const& flags) VULKAN_HPP_NOEXCEPT
{
return flags ^ bit;
}
)";
static const std::string classObjectDestroy = R"(
struct AllocationCallbacks;
template <typename OwnerType, typename Dispatch>
class ObjectDestroy
{
public:
ObjectDestroy()
: m_owner()
, m_allocationCallbacks( nullptr )
, m_dispatch( nullptr )
{}
ObjectDestroy( OwnerType owner, Optional<const AllocationCallbacks> allocationCallbacks = nullptr, Dispatch const &dispatch = VULKAN_HPP_DEFAULT_DISPATCHER ) VULKAN_HPP_NOEXCEPT
: m_owner( owner )
, m_allocationCallbacks( allocationCallbacks )
, m_dispatch( &dispatch )
{}
OwnerType getOwner() const VULKAN_HPP_NOEXCEPT { return m_owner; }
Optional<const AllocationCallbacks> getAllocator() const VULKAN_HPP_NOEXCEPT { return m_allocationCallbacks; }
protected:
template <typename T>
void destroy(T t) VULKAN_HPP_NOEXCEPT
{
VULKAN_HPP_ASSERT( m_owner && m_dispatch );
m_owner.destroy( t, m_allocationCallbacks, *m_dispatch );
}
private:
OwnerType m_owner;
Optional<const AllocationCallbacks> m_allocationCallbacks;
Dispatch const* m_dispatch;
};
class NoParent;
template <typename Dispatch>
class ObjectDestroy<NoParent,Dispatch>
{
public:
ObjectDestroy()
: m_allocationCallbacks( nullptr )
, m_dispatch( nullptr )
{}
ObjectDestroy( Optional<const AllocationCallbacks> allocationCallbacks, Dispatch const &dispatch = VULKAN_HPP_DEFAULT_DISPATCHER ) VULKAN_HPP_NOEXCEPT
: m_allocationCallbacks( allocationCallbacks )
, m_dispatch( &dispatch )
{}
Optional<const AllocationCallbacks> getAllocator() const VULKAN_HPP_NOEXCEPT { return m_allocationCallbacks; }
protected:
template <typename T>
void destroy(T t) VULKAN_HPP_NOEXCEPT
{
VULKAN_HPP_ASSERT( m_dispatch );
t.destroy( m_allocationCallbacks, *m_dispatch );
}
private:
Optional<const AllocationCallbacks> m_allocationCallbacks;
Dispatch const* m_dispatch;
};
)";
static const std::string classObjectFree = R"(
template <typename OwnerType, typename Dispatch>
class ObjectFree
{
public:
ObjectFree()
: m_owner()
, m_allocationCallbacks( nullptr )
, m_dispatch( nullptr )
{}
ObjectFree( OwnerType owner, Optional<const AllocationCallbacks> allocationCallbacks, Dispatch const &dispatch ) VULKAN_HPP_NOEXCEPT
: m_owner( owner )
, m_allocationCallbacks( allocationCallbacks )
, m_dispatch( &dispatch )
{}
OwnerType getOwner() const VULKAN_HPP_NOEXCEPT { return m_owner; }
Optional<const AllocationCallbacks> getAllocator() const VULKAN_HPP_NOEXCEPT { return m_allocationCallbacks; }
protected:
template <typename T>
void destroy(T t) VULKAN_HPP_NOEXCEPT
{
VULKAN_HPP_ASSERT( m_owner && m_dispatch );
m_owner.free( t, m_allocationCallbacks, *m_dispatch );
}
private:
OwnerType m_owner;
Optional<const AllocationCallbacks> m_allocationCallbacks;
Dispatch const* m_dispatch;
};
)";
static const std::string classOptional = R"(
template <typename RefType>
class Optional
{
public:
Optional(RefType & reference) VULKAN_HPP_NOEXCEPT { m_ptr = &reference; }
Optional(RefType * ptr) VULKAN_HPP_NOEXCEPT { m_ptr = ptr; }
Optional(std::nullptr_t) VULKAN_HPP_NOEXCEPT { m_ptr = nullptr; }
operator RefType*() const VULKAN_HPP_NOEXCEPT { return m_ptr; }
RefType const* operator->() const VULKAN_HPP_NOEXCEPT { return m_ptr; }
explicit operator bool() const VULKAN_HPP_NOEXCEPT { return !!m_ptr; }
private:
RefType *m_ptr;
};
)";
static const std::string classPoolFree = R"(
template <typename OwnerType, typename PoolType, typename Dispatch>
class PoolFree
{
public:
PoolFree( OwnerType owner = OwnerType(), PoolType pool = PoolType(), Dispatch const &dispatch = VULKAN_HPP_DEFAULT_DISPATCHER ) VULKAN_HPP_NOEXCEPT
: m_owner( owner )
, m_pool( pool )
, m_dispatch( &dispatch )
{}
OwnerType getOwner() const VULKAN_HPP_NOEXCEPT { return m_owner; }
PoolType getPool() const VULKAN_HPP_NOEXCEPT { return m_pool; }
protected:
template <typename T>
void destroy(T t) VULKAN_HPP_NOEXCEPT
{
m_owner.free( m_pool, t, *m_dispatch );
}
private:
OwnerType m_owner;
PoolType m_pool;
Dispatch const* m_dispatch;
};
)";
static const std::string classStructureChain = R"(
template <typename X, typename Y> struct isStructureChainValid { enum { value = false }; };
template <typename P, typename T>
struct TypeList
{
using list = P;
using last = T;
};
template <typename List, typename X>
struct extendCheck
{
static const bool valid = isStructureChainValid<typename List::last, X>::value || extendCheck<typename List::list,X>::valid;
};
template <typename T, typename X>
struct extendCheck<TypeList<void,T>,X>
{
static const bool valid = isStructureChainValid<T, X>::value;
};
template <typename X>
struct extendCheck<void,X>
{
static const bool valid = true;
};
template<typename Type, class...>
struct isPartOfStructureChain
{
static const bool valid = false;
};
template<typename Type, typename Head, typename... Tail>
struct isPartOfStructureChain<Type, Head, Tail...>
{
static const bool valid = std::is_same<Type, Head>::value || isPartOfStructureChain<Type, Tail...>::valid;
};
template <class Element>
class StructureChainElement
{
public:
explicit operator Element&() VULKAN_HPP_NOEXCEPT { return value; }
explicit operator const Element&() const VULKAN_HPP_NOEXCEPT { return value; }
private:
Element value;
};
template<typename ...StructureElements>
class StructureChain : private StructureChainElement<StructureElements>...
{
public:
StructureChain() VULKAN_HPP_NOEXCEPT
{
link<void, StructureElements...>();
}
StructureChain(StructureChain const &rhs) VULKAN_HPP_NOEXCEPT
{
linkAndCopy<void, StructureElements...>(rhs);
}
StructureChain(StructureElements const &... elems) VULKAN_HPP_NOEXCEPT
{
linkAndCopyElements<void, StructureElements...>(elems...);
}
StructureChain& operator=(StructureChain const &rhs) VULKAN_HPP_NOEXCEPT
{
linkAndCopy<void, StructureElements...>(rhs);
return *this;
}
template<typename ClassType> ClassType& get() VULKAN_HPP_NOEXCEPT { return static_cast<ClassType&>(*this);}
template<typename ClassType> const ClassType& get() const VULKAN_HPP_NOEXCEPT { return static_cast<const ClassType&>(*this);}
template<typename ClassTypeA, typename ClassTypeB, typename ...ClassTypes>
std::tuple<ClassTypeA&, ClassTypeB&, ClassTypes&...> get()
{
return std::tie(get<ClassTypeA>(), get<ClassTypeB>(), get<ClassTypes>()...);
}
template<typename ClassTypeA, typename ClassTypeB, typename ...ClassTypes>
std::tuple<const ClassTypeA&, const ClassTypeB&, const ClassTypes&...> get() const
{
return std::tie(get<ClassTypeA>(), get<ClassTypeB>(), get<ClassTypes>()...);
}
template<typename ClassType>
void unlink() VULKAN_HPP_NOEXCEPT
{
static_assert(isPartOfStructureChain<ClassType, StructureElements...>::valid, "Can't unlink Structure that's not part of this StructureChain!");
static_assert(!std::is_same<ClassType, typename std::tuple_element<0, std::tuple<StructureElements...>>::type>::value, "It's not allowed to unlink the first element!");
VkBaseOutStructure * ptr = reinterpret_cast<VkBaseOutStructure*>(&get<ClassType>());
VULKAN_HPP_ASSERT(ptr != nullptr);
VkBaseOutStructure ** ppNext = &(reinterpret_cast<VkBaseOutStructure*>(this)->pNext);
VULKAN_HPP_ASSERT(*ppNext != nullptr);
while (*ppNext != ptr)
{
ppNext = &(*ppNext)->pNext;
VULKAN_HPP_ASSERT(*ppNext != nullptr); // fires, if the ClassType member has already been unlinked !
}
VULKAN_HPP_ASSERT(*ppNext == ptr);
*ppNext = (*ppNext)->pNext;
}
template <typename ClassType>
void relink() VULKAN_HPP_NOEXCEPT
{
static_assert(isPartOfStructureChain<ClassType, StructureElements...>::valid, "Can't relink Structure that's not part of this StructureChain!");
static_assert(!std::is_same<ClassType, typename std::tuple_element<0, std::tuple<StructureElements...>>::type>::value, "It's not allowed to have the first element unlinked!");
VkBaseOutStructure * ptr = reinterpret_cast<VkBaseOutStructure*>(&get<ClassType>());
VULKAN_HPP_ASSERT(ptr != nullptr);
VkBaseOutStructure ** ppNext = &(reinterpret_cast<VkBaseOutStructure*>(this)->pNext);
VULKAN_HPP_ASSERT(*ppNext != nullptr);
#if !defined(NDEBUG)
while (*ppNext)
{
VULKAN_HPP_ASSERT(*ppNext != ptr); // fires, if the ClassType member has not been unlinked before
ppNext = &(*ppNext)->pNext;
}
ppNext = &(reinterpret_cast<VkBaseOutStructure*>(this)->pNext);
#endif
ptr->pNext = *ppNext;
*ppNext = ptr;
}
private:
template<typename List, typename X>
void link() VULKAN_HPP_NOEXCEPT
{
static_assert(extendCheck<List, X>::valid, "The structure chain is not valid!");
}
template<typename List, typename X, typename Y, typename ...Z>
void link() VULKAN_HPP_NOEXCEPT
{
static_assert(extendCheck<List,X>::valid, "The structure chain is not valid!");
X& x = static_cast<X&>(*this);
Y& y = static_cast<Y&>(*this);
x.pNext = &y;
link<TypeList<List, X>, Y, Z...>();
}
template<typename List, typename X>
void linkAndCopy(StructureChain const &rhs) VULKAN_HPP_NOEXCEPT
{
static_assert(extendCheck<List, X>::valid, "The structure chain is not valid!");
static_cast<X&>(*this) = static_cast<X const &>(rhs);
}
template<typename List, typename X, typename Y, typename ...Z>
void linkAndCopy(StructureChain const &rhs) VULKAN_HPP_NOEXCEPT
{
static_assert(extendCheck<List, X>::valid, "The structure chain is not valid!");
X& x = static_cast<X&>(*this);
Y& y = static_cast<Y&>(*this);
x = static_cast<X const &>(rhs);
x.pNext = &y;
linkAndCopy<TypeList<List, X>, Y, Z...>(rhs);
}
template<typename List, typename X>
void linkAndCopyElements(X const &xelem) VULKAN_HPP_NOEXCEPT
{
static_assert(extendCheck<List, X>::valid, "The structure chain is not valid!");
static_cast<X&>(*this) = xelem;
}
template<typename List, typename X, typename Y, typename ...Z>
void linkAndCopyElements(X const &xelem, Y const &yelem, Z const &... zelem) VULKAN_HPP_NOEXCEPT
{
static_assert(extendCheck<List, X>::valid, "The structure chain is not valid!");
X& x = static_cast<X&>(*this);
Y& y = static_cast<Y&>(*this);
x = xelem;
x.pNext = &y;
linkAndCopyElements<TypeList<List, X>, Y, Z...>(yelem, zelem...);
}
};
)";
static const std::string classUniqueHandle = R"(
#if !defined(VULKAN_HPP_NO_SMART_HANDLE)
template <typename Type, typename Dispatch> class UniqueHandleTraits;
template <typename Type, typename Dispatch>
class UniqueHandle : public UniqueHandleTraits<Type,Dispatch>::deleter
{
private:
using Deleter = typename UniqueHandleTraits<Type,Dispatch>::deleter;
public:
using element_type = Type;
UniqueHandle()
: Deleter()
, m_value()
{}
explicit UniqueHandle( Type const& value, Deleter const& deleter = Deleter() ) VULKAN_HPP_NOEXCEPT
: Deleter( deleter)
, m_value( value )
{}
UniqueHandle( UniqueHandle const& ) = delete;
UniqueHandle( UniqueHandle && other ) VULKAN_HPP_NOEXCEPT
: Deleter( std::move( static_cast<Deleter&>( other ) ) )
, m_value( other.release() )
{}
~UniqueHandle() VULKAN_HPP_NOEXCEPT
{
if ( m_value ) this->destroy( m_value );
}
UniqueHandle & operator=( UniqueHandle const& ) = delete;
UniqueHandle & operator=( UniqueHandle && other ) VULKAN_HPP_NOEXCEPT
{
reset( other.release() );
*static_cast<Deleter*>(this) = std::move( static_cast<Deleter&>(other) );
return *this;
}
explicit operator bool() const VULKAN_HPP_NOEXCEPT
{
return m_value.operator bool();
}
Type const* operator->() const VULKAN_HPP_NOEXCEPT
{
return &m_value;
}
Type * operator->() VULKAN_HPP_NOEXCEPT
{
return &m_value;
}
Type const& operator*() const VULKAN_HPP_NOEXCEPT
{
return m_value;
}
Type & operator*() VULKAN_HPP_NOEXCEPT
{
return m_value;
}
const Type & get() const VULKAN_HPP_NOEXCEPT
{
return m_value;
}
Type & get() VULKAN_HPP_NOEXCEPT
{
return m_value;
}
void reset( Type const& value = Type() ) VULKAN_HPP_NOEXCEPT
{
if ( m_value != value )
{
if ( m_value ) this->destroy( m_value );
m_value = value;
}
}
Type release() VULKAN_HPP_NOEXCEPT
{
Type value = m_value;
m_value = nullptr;
return value;
}
void swap( UniqueHandle<Type,Dispatch> & rhs ) VULKAN_HPP_NOEXCEPT
{
std::swap(m_value, rhs.m_value);
std::swap(static_cast<Deleter&>(*this), static_cast<Deleter&>(rhs));
}
private:
Type m_value;
};
template <typename UniqueType>
VULKAN_HPP_INLINE std::vector<typename UniqueType::element_type> uniqueToRaw(std::vector<UniqueType> const& handles)
{
std::vector<typename UniqueType::element_type> newBuffer(handles.size());
std::transform(handles.begin(), handles.end(), newBuffer.begin(), [](UniqueType const& handle) { return handle.get(); });
return newBuffer;
}
template <typename Type, typename Dispatch>
VULKAN_HPP_INLINE void swap( UniqueHandle<Type,Dispatch> & lhs, UniqueHandle<Type,Dispatch> & rhs ) VULKAN_HPP_NOEXCEPT
{
lhs.swap( rhs );
}
#endif
)";
static const std::string constExpressionArrayCopy = R"(
template<typename T, size_t N, size_t I>
class PrivateConstExpression1DArrayCopy
{
public:
VULKAN_HPP_CONSTEXPR_14 static void copy( T * dst, T const* src ) VULKAN_HPP_NOEXCEPT
{
PrivateConstExpression1DArrayCopy<T, N, I - 1>::copy( dst, src );
dst[I - 1] = src[I - 1];
}
};
template<typename T, size_t N>
class PrivateConstExpression1DArrayCopy<T, N, 0>
{
public:
VULKAN_HPP_CONSTEXPR_14 static void copy( T * /*dst*/, T const* /*src*/ ) VULKAN_HPP_NOEXCEPT
{}
};
template <typename T, size_t N>
class ConstExpression1DArrayCopy
{
public:
VULKAN_HPP_CONSTEXPR_14 static void copy( T dst[N], const T src[N] ) VULKAN_HPP_NOEXCEPT
{
const size_t C = N / 2;
PrivateConstExpression1DArrayCopy<T, C, C>::copy( dst, src );
PrivateConstExpression1DArrayCopy<T, N - C, N - C>::copy(dst + C, src + C);
}
VULKAN_HPP_CONSTEXPR_14 static void copy( T dst[N], std::array<T, N> const& src ) VULKAN_HPP_NOEXCEPT
{
const size_t C = N / 2;
PrivateConstExpression1DArrayCopy<T, C, C>::copy(dst, src.data());
PrivateConstExpression1DArrayCopy<T, N - C, N - C>::copy(dst + C, src.data() + C);
}
};
template<typename T, size_t N, size_t M, size_t I, size_t J>
class PrivateConstExpression2DArrayCopy
{
public:
VULKAN_HPP_CONSTEXPR_14 static void copy( T * dst, T const* src ) VULKAN_HPP_NOEXCEPT
{
PrivateConstExpression2DArrayCopy<T, N, M, I, J - 1>::copy( dst, src );
dst[(I - 1) * M + J - 1] = src[(I - 1) * M + J - 1];
}
};
template<typename T, size_t N, size_t M, size_t I>
class PrivateConstExpression2DArrayCopy<T, N, M, I,0>
{
public:
VULKAN_HPP_CONSTEXPR_14 static void copy( T * dst, T const* src ) VULKAN_HPP_NOEXCEPT
{
PrivateConstExpression2DArrayCopy<T, N, M, I - 1, M>::copy( dst, src );
}
};
template<typename T, size_t N, size_t M, size_t J>
class PrivateConstExpression2DArrayCopy<T, N, M, 0, J>
{
public:
VULKAN_HPP_CONSTEXPR_14 static void copy( T * /*dst*/, T const* /*src*/ ) VULKAN_HPP_NOEXCEPT
{}
};
template <typename T, size_t N, size_t M>
class ConstExpression2DArrayCopy
{
public:
VULKAN_HPP_CONSTEXPR_14 static void copy( T dst[N][M], const T src[N][M] ) VULKAN_HPP_NOEXCEPT
{
PrivateConstExpression2DArrayCopy<T, N, M, N, M>::copy( &dst[0][0], &src[0][0] );
}
VULKAN_HPP_CONSTEXPR_14 static void copy( T dst[N][M], std::array<std::array<T, M>, N> const& src ) VULKAN_HPP_NOEXCEPT
{
PrivateConstExpression2DArrayCopy<T, N, M, N, M>::copy( &dst[0][0], src.data()->data() );
}
};
)";
static const std::string defines = R"(
// <tuple> includes <sys/sysmacros.h> through some other header
// this results in major(x) being resolved to gnu_dev_major(x)
// which is an expression in a constructor initializer list.
#if defined(major)
#undef major
#endif
#if defined(minor)
#undef minor
#endif
// Windows defines MemoryBarrier which is deprecated and collides
// with the VULKAN_HPP_NAMESPACE::MemoryBarrier struct.
#if defined(MemoryBarrier)
#undef MemoryBarrier
#endif
#if !defined(VULKAN_HPP_HAS_UNRESTRICTED_UNIONS)
# if defined(__clang__)
# if __has_feature(cxx_unrestricted_unions)
# define VULKAN_HPP_HAS_UNRESTRICTED_UNIONS
# endif
# elif defined(__GNUC__)
# define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
# if 40600 <= GCC_VERSION
# define VULKAN_HPP_HAS_UNRESTRICTED_UNIONS
# endif
# elif defined(_MSC_VER)
# if 1900 <= _MSC_VER
# define VULKAN_HPP_HAS_UNRESTRICTED_UNIONS
# endif
# endif
#endif
#if !defined(VULKAN_HPP_INLINE)
# if defined(__clang__)
# if __has_attribute(always_inline)
# define VULKAN_HPP_INLINE __attribute__((always_inline)) __inline__
# else
# define VULKAN_HPP_INLINE inline
# endif
# elif defined(__GNUC__)
# define VULKAN_HPP_INLINE __attribute__((always_inline)) __inline__
# elif defined(_MSC_VER)
# define VULKAN_HPP_INLINE inline
# else
# define VULKAN_HPP_INLINE inline
# endif
#endif
#if defined(VULKAN_HPP_TYPESAFE_CONVERSION)
# define VULKAN_HPP_TYPESAFE_EXPLICIT
#else
# define VULKAN_HPP_TYPESAFE_EXPLICIT explicit
#endif
#if defined(__cpp_constexpr)
# define VULKAN_HPP_CONSTEXPR constexpr
# if __cpp_constexpr >= 201304
# define VULKAN_HPP_CONSTEXPR_14 constexpr
# else
# define VULKAN_HPP_CONSTEXPR_14
# endif
# define VULKAN_HPP_CONST_OR_CONSTEXPR constexpr
#else
# define VULKAN_HPP_CONSTEXPR
# define VULKAN_HPP_CONSTEXPR_14
# define VULKAN_HPP_CONST_OR_CONSTEXPR const
#endif
#if !defined(VULKAN_HPP_NOEXCEPT)
# if defined(_MSC_VER) && (_MSC_VER <= 1800)
# define VULKAN_HPP_NOEXCEPT
# else
# define VULKAN_HPP_NOEXCEPT noexcept
# define VULKAN_HPP_HAS_NOEXCEPT 1
# endif
#endif
#if !defined(VULKAN_HPP_NAMESPACE)
#define VULKAN_HPP_NAMESPACE vk
#endif
#define VULKAN_HPP_STRINGIFY2(text) #text
#define VULKAN_HPP_STRINGIFY(text) VULKAN_HPP_STRINGIFY2(text)
#define VULKAN_HPP_NAMESPACE_STRING VULKAN_HPP_STRINGIFY(VULKAN_HPP_NAMESPACE)
)";
static const std::string exceptions = R"(
class ErrorCategoryImpl : public std::error_category
{
public:
virtual const char* name() const VULKAN_HPP_NOEXCEPT override { return VULKAN_HPP_NAMESPACE_STRING"::Result"; }
virtual std::string message(int ev) const override { return to_string(static_cast<Result>(ev)); }
};
class Error
{
public:
Error() VULKAN_HPP_NOEXCEPT = default;
Error(const Error&) VULKAN_HPP_NOEXCEPT = default;
virtual ~Error() VULKAN_HPP_NOEXCEPT = default;
virtual const char* what() const VULKAN_HPP_NOEXCEPT = 0;
};
class LogicError : public Error, public std::logic_error
{
public:
explicit LogicError( const std::string& what )
: Error(), std::logic_error(what) {}
explicit LogicError( char const * what )
: Error(), std::logic_error(what) {}
virtual const char* what() const VULKAN_HPP_NOEXCEPT { return std::logic_error::what(); }
};
class SystemError : public Error, public std::system_error
{
public:
SystemError( std::error_code ec )
: Error(), std::system_error(ec) {}
SystemError( std::error_code ec, std::string const& what )
: Error(), std::system_error(ec, what) {}
SystemError( std::error_code ec, char const * what )
: Error(), std::system_error(ec, what) {}
SystemError( int ev, std::error_category const& ecat )
: Error(), std::system_error(ev, ecat) {}
SystemError( int ev, std::error_category const& ecat, std::string const& what)
: Error(), std::system_error(ev, ecat, what) {}
SystemError( int ev, std::error_category const& ecat, char const * what)
: Error(), std::system_error(ev, ecat, what) {}
virtual const char* what() const VULKAN_HPP_NOEXCEPT { return std::system_error::what(); }
};
VULKAN_HPP_INLINE const std::error_category& errorCategory() VULKAN_HPP_NOEXCEPT
{
static ErrorCategoryImpl instance;
return instance;
}
VULKAN_HPP_INLINE std::error_code make_error_code(Result e) VULKAN_HPP_NOEXCEPT
{
return std::error_code(static_cast<int>(e), errorCategory());
}
VULKAN_HPP_INLINE std::error_condition make_error_condition(Result e) VULKAN_HPP_NOEXCEPT
{
return std::error_condition(static_cast<int>(e), errorCategory());
}
)";
static const std::string includes = R"(
#ifndef VULKAN_HPP
#define VULKAN_HPP
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <string>
#include <system_error>
#include <tuple>
#include <type_traits>
#include <vulkan/vulkan.h>
#if defined(VULKAN_HPP_DISABLE_ENHANCED_MODE)
# if !defined(VULKAN_HPP_NO_SMART_HANDLE)
# define VULKAN_HPP_NO_SMART_HANDLE
# endif
#else
# include <memory>
# include <vector>
#endif
#if !defined(VULKAN_HPP_ASSERT)
# include <cassert>
# define VULKAN_HPP_ASSERT assert
#endif
#if !defined(VULKAN_HPP_ENABLE_DYNAMIC_LOADER_TOOL)
# define VULKAN_HPP_ENABLE_DYNAMIC_LOADER_TOOL 1
#endif
#if VULKAN_HPP_ENABLE_DYNAMIC_LOADER_TOOL == 1
# if defined(__linux__) || defined(__APPLE__)
# include <dlfcn.h>
# endif
# if defined(_WIN32)
# include <windows.h>
# endif
#endif
#if 201711 <= __cpp_impl_three_way_comparison
# define VULKAN_HPP_HAS_SPACESHIP_OPERATOR
#endif
#if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR)
# include <compare>
#endif
)";
static const std::string is_error_code_enum = R"(
#ifndef VULKAN_HPP_NO_EXCEPTIONS
namespace std
{
template <>
struct is_error_code_enum<VULKAN_HPP_NAMESPACE::Result> : public true_type
{};
}
#endif
)";
static const std::string structResultValue = R"(
template <typename T> void ignore(T const&) VULKAN_HPP_NOEXCEPT {}
template <typename T>
struct ResultValue
{
#ifdef VULKAN_HPP_HAS_NOEXCEPT
ResultValue( Result r, T & v ) VULKAN_HPP_NOEXCEPT(VULKAN_HPP_NOEXCEPT(T(v)))
#else
ResultValue( Result r, T & v )
#endif
: result( r )
, value( v )
{}
#ifdef VULKAN_HPP_HAS_NOEXCEPT
ResultValue( Result r, T && v ) VULKAN_HPP_NOEXCEPT(VULKAN_HPP_NOEXCEPT(T(std::move(v))))
#else
ResultValue( Result r, T && v )
#endif
: result( r )
, value( std::move( v ) )
{}
Result result;
T value;
operator std::tuple<Result&, T&>() VULKAN_HPP_NOEXCEPT { return std::tuple<Result&, T&>(result, value); }
};
template <typename T>
struct ResultValueType
{
#ifdef VULKAN_HPP_NO_EXCEPTIONS
typedef ResultValue<T> type;
#else
typedef T type;
#endif
};
template <>
struct ResultValueType<void>
{
#ifdef VULKAN_HPP_NO_EXCEPTIONS
typedef Result type;
#else
typedef void type;
#endif
};
VULKAN_HPP_INLINE ResultValueType<void>::type createResultValue( Result result, char const * message )
{
#ifdef VULKAN_HPP_NO_EXCEPTIONS
ignore(message);
VULKAN_HPP_ASSERT( result == Result::eSuccess );
return result;
#else
if ( result != Result::eSuccess )
{
throwResultException( result, message );
}
#endif
}
template <typename T>
VULKAN_HPP_INLINE typename ResultValueType<T>::type createResultValue( Result result, T & data, char const * message )
{
#ifdef VULKAN_HPP_NO_EXCEPTIONS
ignore(message);
VULKAN_HPP_ASSERT( result == Result::eSuccess );
return ResultValue<T>( result, std::move( data ) );
#else
if ( result != Result::eSuccess )
{
throwResultException( result, message );
}
return std::move( data );
#endif
}
VULKAN_HPP_INLINE Result createResultValue( Result result, char const * message, std::initializer_list<Result> successCodes )
{
#ifdef VULKAN_HPP_NO_EXCEPTIONS
ignore(message);
VULKAN_HPP_ASSERT( std::find( successCodes.begin(), successCodes.end(), result ) != successCodes.end() );
#else
if ( std::find( successCodes.begin(), successCodes.end(), result ) == successCodes.end() )
{
throwResultException( result, message );
}
#endif
return result;
}
template <typename T>
VULKAN_HPP_INLINE ResultValue<T> createResultValue( Result result, T & data, char const * message, std::initializer_list<Result> successCodes )
{
#ifdef VULKAN_HPP_NO_EXCEPTIONS
ignore(message);
VULKAN_HPP_ASSERT( std::find( successCodes.begin(), successCodes.end(), result ) != successCodes.end() );
#else
if ( std::find( successCodes.begin(), successCodes.end(), result ) == successCodes.end() )
{
throwResultException( result, message );
}
#endif
return ResultValue<T>( result, data );
}
#ifndef VULKAN_HPP_NO_SMART_HANDLE
template <typename T, typename D>
VULKAN_HPP_INLINE typename ResultValueType<UniqueHandle<T,D>>::type createResultValue( Result result, T & data, char const * message, typename UniqueHandleTraits<T,D>::deleter const& deleter )
{
#ifdef VULKAN_HPP_NO_EXCEPTIONS
ignore(message);
VULKAN_HPP_ASSERT( result == Result::eSuccess );
return ResultValue<UniqueHandle<T,D>>( result, UniqueHandle<T,D>(data, deleter) );
#else
if ( result != Result::eSuccess )
{
throwResultException( result, message );
}
return UniqueHandle<T,D>(data, deleter);
#endif
}
#endif
)";
static const std::string typeTraits = R"(
template<ObjectType value>
struct cpp_type
{
};
)";
try {
tinyxml2::XMLDocument doc;
std::string filename = (argc == 1) ? VK_SPEC : argv[1];
std::cout << "Loading vk.xml from " << filename << std::endl;
std::cout << "Writing vulkan.hpp to " << VULKAN_HPP_FILE << std::endl;
tinyxml2::XMLError error = doc.LoadFile(filename.c_str());
if (error != tinyxml2::XML_SUCCESS)
{
std::cout << "VkGenerate: failed to load file " << filename << " with error <" << to_string(error) << ">" << std::endl;
return -1;
}
VulkanHppGenerator generator(doc);
std::string str;
static const size_t estimatedLength = 4 * 1024 * 1024;
str.reserve(estimatedLength);
str += generator.getVulkanLicenseHeader()
+ includes
+ "\n";
appendVersionCheck(str, generator.getVersion());
appendTypesafeStuff(str, generator.getTypesafeCheck());
str += defines
+ "\n"
+ "namespace VULKAN_HPP_NAMESPACE\n"
+ "{\n"
+ classArrayProxy
+ classFlags
+ classOptional
+ classStructureChain
+ classUniqueHandle;
generator.appendDispatchLoaderStatic(str);
generator.appendDispatchLoaderDefault(str);
str += classObjectDestroy
+ classObjectFree
+ classPoolFree
+ constExpressionArrayCopy
+ "\n";
generator.appendBaseTypes(str);
generator.appendEnums(str);
str += typeTraits;
generator.appendBitmasks(str);
str += "} // namespace VULKAN_HPP_NAMESPACE\n"
+ is_error_code_enum
+ "\n"
+ "namespace VULKAN_HPP_NAMESPACE\n"
+ "{\n"
+ "#ifndef VULKAN_HPP_NO_EXCEPTIONS"
+ exceptions;
generator.appendResultExceptions(str);
generator.appendThrowExceptions(str);
str += "#endif\n"
+ structResultValue;
generator.appendForwardDeclarations(str);
generator.appendHandles(str);
generator.appendStructs(str);
generator.appendHandlesCommandDefintions(str);
generator.appendStructureChainValidation(str);
generator.appendDispatchLoaderDynamic(str);
str += "} // namespace VULKAN_HPP_NAMESPACE\n"
"#endif\n";
assert(str.length() < estimatedLength);
cleanup(str);
std::ofstream ofs(VULKAN_HPP_FILE);
assert(!ofs.fail());
ofs << str;
ofs.close();
}
catch (std::exception const& e)
{
std::cout << "caught exception: " << e.what() << std::endl;
return -1;
}
catch (...)
{
std::cout << "caught unknown exception" << std::endl;
return -1;
}
}
<file_sep>// Copyright(c) 2015-2019, NVIDIA CORPORATION. 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.
#pragma once
#include <map>
#include <iostream>
#include <set>
#include <vector>
#include <tinyxml2.h>
class VulkanHppGenerator
{
public:
VulkanHppGenerator(tinyxml2::XMLDocument const& document);
void appendBaseTypes(std::string & str) const;
void appendBitmasks(std::string & str) const;
void appendDispatchLoaderDynamic(std::string & str); // use vkGet*ProcAddress to get function pointers
void appendDispatchLoaderStatic(std::string & str); // use exported symbols from loader
void appendDispatchLoaderDefault(std::string & str); // typedef to DispatchLoaderStatic or undefined type, based on VK_NO_PROTOTYPES
void appendEnums(std::string & str) const;
void appendForwardDeclarations(std::string & str) const;
void appendHandles(std::string & str) const;
void appendHandlesCommandDefintions(std::string & str) const;
void appendResultExceptions(std::string & str) const;
void appendStructs(std::string & str) const;
void appendStructureChainValidation(std::string & str);
void appendThrowExceptions(std::string & str) const;
std::string const& getTypesafeCheck() const;
std::string const& getVersion() const;
std::string const& getVulkanLicenseHeader() const;
private:
struct BaseTypeData
{
BaseTypeData(std::string const& type_, int line)
: type(type_)
, xmlLine(line)
{}
std::string type;
int xmlLine;
};
struct BitmaskData
{
BitmaskData(std::string const& r, std::string const& t, int line)
: requirements(r)
, type(t)
, xmlLine(line)
{}
std::string requirements;
std::string type;
std::string platform;
std::string alias;
int xmlLine;
};
struct NameData
{
std::string name;
std::vector<std::string> arraySizes;
std::string bitCount;
};
struct TypeData
{
std::string compose() const;
bool operator==(TypeData const& rhs) const
{
return (prefix == rhs.prefix) && (type == rhs.type) && (postfix == rhs.postfix);
}
std::string prefix;
std::string type;
std::string postfix;
};
struct ParamData
{
ParamData()
: optional(false)
{}
TypeData type;
std::string name;
std::vector<std::string> arraySizes;
std::string len;
bool optional;
};
struct CommandData
{
CommandData(int line)
: xmlLine(line)
{}
std::vector<ParamData> params;
std::string platform;
std::string returnType;
std::vector<std::string> successCodes;
std::vector<std::string> errorCodes;
std::set<std::string> aliases;
int xmlLine;
};
struct EnumValueData
{
EnumValueData(std::string const& vulkan, std::string const& vk, bool singleBit_)
: vulkanValue(vulkan)
, vkValue(vk)
, singleBit(singleBit_)
{}
std::string vulkanValue;
std::string vkValue;
bool singleBit;
};
struct EnumData
{
void addEnumValue(int line, std::string const& valueName, bool bitmask, bool bitpos, std::string const& prefix, std::string const& postfix, std::string const& tag);
std::string alias; // alias for this enum
std::vector<std::pair<std::string, std::string>> aliases; // pairs of vulkan enum value and corresponding vk::-namespace enum value
bool isBitmask = false;
std::string platform;
std::vector<EnumValueData> values;
};
struct ExtensionData
{
ExtensionData(int line)
: xmlLine(line)
{}
std::string deprecatedBy;
std::string obsoletedBy;
std::string promotedTo;
std::map<std::string, int> requirements;
int xmlLine;
};
struct FuncPointerData
{
FuncPointerData(std::string const& r, int line)
: requirements(r)
, xmlLine(line)
{}
std::string requirements;
int xmlLine;
};
struct HandleData
{
HandleData(std::vector<std::string> const& p, int line)
: parents(p)
, xmlLine(line)
{}
std::string alias;
std::set<std::string> childrenHandles;
std::map<std::string, CommandData> commands;
std::string deleteCommand;
std::string deletePool;
std::string platform;
std::vector<std::string> parents;
int xmlLine;
};
struct MemberData
{
MemberData(int line)
: xmlLine(line)
{}
TypeData type;
std::string name;
std::vector<std::string> arraySizes;
std::string bitCount;
std::string values;
std::string usedConstant;
int xmlLine;
};
struct StructureData
{
StructureData(std::vector<std::string> const& extends, int line)
: returnedOnly(false)
, isUnion(false)
, structExtends(extends)
, xmlLine(line)
{}
bool returnedOnly;
bool isUnion;
std::vector<MemberData> members;
std::string platform;
std::vector<std::string> structExtends;
std::set<std::string> aliases;
std::string subStruct;
int xmlLine;
};
private:
void appendArgumentPlainType(std::string & str, ParamData const& paramData) const;
void appendArguments(std::string & str, CommandData const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool firstCall, bool singular, size_t from, size_t to) const;
void appendArgumentVector(std::string & str, size_t paramIndex, ParamData const& paramData, size_t returnParamIndex, size_t templateParamIndex, bool twoStep, bool firstCall, bool singular) const;
void appendArgumentVulkanType(std::string & str, ParamData const& paramData) const;
void appendBitmask(std::string & os, std::string const& bitmaskName, std::string const& bitmaskType, std::string const& bitmaskAlias, std::string const& enumName, std::vector<EnumValueData> const& enumValues) const;
void appendBitmaskToStringFunction(std::string & str, std::string const& flagsName, std::string const& enumName, std::vector<EnumValueData> const& enumValues) const;
void appendCall(std::string &str, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool firstCall, bool singular) const;
void appendCommand(std::string & str, std::string const& indentation, std::string const& name, std::pair<std::string, CommandData> const& commandData, bool definition) const;
void appendEnum(std::string & str, std::pair<std::string, EnumData> const& enumData) const;
void appendEnumToString(std::string & str, std::pair<std::string, EnumData> const& enumData) const;
void appendFunction(std::string & str, std::string const& indentation, std::string const& name, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, std::string const& enhancedReturnType, bool definition, bool enhanced, bool singular, bool unique, bool isStructureChain, bool withAllocator) const;
void appendFunctionBodyEnhanced(std::string & str, std::string const& indentation, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, std::string const& enhancedReturnType, bool singular, bool unique, bool isStructureChain, bool withAllocator) const;
std::string appendFunctionBodyEnhancedLocalReturnVariable(std::string & str, std::string const& indentation, CommandData const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, std::string const& enhancedReturnType, bool singular, bool isStructureChain, bool withAllocator) const;
void appendFunctionBodyEnhancedLocalReturnVariableVectorSize(std::string & str, std::vector<ParamData> const& params, std::pair<size_t, size_t> const& vectorParamIndex, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool withAllocator) const;
void appendFunctionBodyEnhancedMultiVectorSizeCheck(std::string & str, std::string const& indentation, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices) const;
void appendFunctionBodyEnhancedReturnResultValue(std::string & str, std::string const& indentation, std::string const& returnName, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, bool twoStep, bool singular, bool unique) const;
void appendFunctionBodyEnhancedSingleStep(std::string & str, std::string const& indentation, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool singular) const;
void appendFunctionBodyEnhancedTwoStep(std::string & str, std::string const& indentation, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool singular, std::string const& returnName) const;
void appendFunctionBodyEnhancedVectorOfStructureChain(std::string & str, std::string const& indentation, std::pair<std::string,CommandData> const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool withAllocator) const;
void appendFunctionBodyEnhancedVectorOfUniqueHandles(std::string & str, std::string const& indentation, std::string const& commandName, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool singular, bool withAllocator) const;
void appendFunctionBodyStandard(std::string & str, std::string const& indentation, std::pair<std::string, CommandData> const& commandData) const;
void appendFunctionBodyStandardArgument(std::string & str, TypeData const& typeData, std::string const& name) const;
bool appendFunctionHeaderArgumentEnhanced(std::string & str, ParamData const& param, size_t paramIndex, std::map<size_t, size_t> const& vectorParamIndices, bool skip, bool argEncountered, bool isTemplateParam, bool isLastArgument, bool singular, bool withDefaults, bool withAllocator) const;
void appendFunctionHeaderArgumentEnhancedPointer(std::string & str, ParamData const& param, std::string const& strippedParameterName, bool withDefaults, bool withAllocator) const;
void appendFunctionHeaderArgumentEnhancedSimple(std::string & str, ParamData const& param, bool lastArgument, bool withDefaults, bool withAllocator) const;
void appendFunctionHeaderArgumentEnhancedVector(std::string & str, ParamData const& param, std::string const& strippedParameterName, bool hasSizeParam, bool isTemplateParam, bool singular, bool withDefaults, bool withAllocator) const;
void appendFunctionHeaderArguments(std::string & str, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool enhanced, bool singular, bool withDefaults, bool withAllocator) const;
void appendFunctionHeaderArgumentsEnhanced(std::string & str, std::pair<std::string, CommandData> const& commandData, size_t returnParamIndex, size_t templateParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool singular, bool withDefaults, bool withAllocator) const;
void appendFunctionHeaderArgumentsStandard(std::string & str, std::pair<std::string, CommandData> const& commandData, bool withDefaults) const;
bool appendFunctionHeaderArgumentStandard(std::string & str, ParamData const& param, bool argEncountered, bool isLastArgument, bool withDefaults) const;
void appendFunctionHeaderReturnType(std::string & str, CommandData const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, std::string const& enhancedReturnType, bool enhanced, bool twoStep, bool singular, bool unique, bool isStructureChain) const;
void appendFunctionHeaderTemplate(std::string & str, std::string const& indentation, size_t returnParamIndex, size_t templateParamIndex, std::string const& enhancedReturnType, bool enhanced, bool singular, bool unique, bool withDefault, bool isStructureChain) const;
void appendHandle(std::string & str, std::pair<std::string, HandleData> const& handle, std::set<std::string> & listedHandles) const;
void appendPlatformEnter(std::string & str, bool isAliased, std::string const& platform) const;
void appendPlatformLeave(std::string & str, bool isAliased, std::string const& platform) const;
void appendStruct(std::string & str, std::pair<std::string, StructureData> const& structure, std::set<std::string> & listedStructures) const;
void appendStructAssignmentOperator(std::string &str, std::pair<std::string, StructureData> const& structure, std::string const& prefix) const;
void appendStructCompareOperators(std::string & str, std::pair<std::string, StructureData> const& structure) const;
void appendStructConstructor(std::string &str, std::pair<std::string, StructureData> const& structData, std::string const& prefix) const;
bool appendStructConstructorArgument(std::string & str, bool listedArgument, std::string const& indentation, MemberData const& memberData) const;
void appendStructCopyConstructor(std::string &str, std::pair<std::string, StructureData> const& structData, std::string const& prefix) const;
void appendStructCopyConstructors(std::string & str, std::string const& vkName) const;
void appendStructMembers(std::string & str, std::pair<std::string,StructureData> const& structData, std::string const& prefix) const;
void appendStructSetter(std::string & str, std::string const& structureName, MemberData const& memberData) const;
void appendStructSubConstructor(std::string &str, std::pair<std::string, StructureData> const& structData, std::string const& prefix) const;
void appendStructure(std::string & str, std::pair<std::string, StructureData> const& structure) const;
void appendUnion(std::string & str, std::pair<std::string, StructureData> const& structure) const;
void appendUniqueTypes(std::string &str, std::string const& parentType, std::set<std::string> const& childrenTypes) const;
std::string constructConstexprString(std::pair<std::string, StructureData> const& structData) const;
void checkCorrectness();
bool checkLenAttribute(std::string const& len, std::vector<ParamData> const& params);
bool containsArray(std::string const& type) const;
bool containsUnion(std::string const& type) const;
std::string determineEnhancedReturnType(CommandData const& commandData, size_t returnParamIndex, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep, bool isStructureChain) const;
size_t determineReturnParamIndex(CommandData const& commandData, std::map<size_t, size_t> const& vectorParamIndices, bool twoStep) const;
std::string determineSubStruct(std::pair<std::string, StructureData> const& structure) const;
size_t determineTemplateParamIndex(std::vector<ParamData> const& params, std::map<size_t, size_t> const& vectorParamIndices) const;
std::map<size_t, size_t> determineVectorParamIndices(std::vector<ParamData> const& params) const;
bool isTwoStepAlgorithm(std::vector<ParamData> const& params) const;
void linkCommandToHandle(int line, std::string const& name, CommandData const& commandData);
void readBaseType(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readBitmask(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readBitmaskAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readCommand(tinyxml2::XMLElement const* element);
void readCommand(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributess);
void readCommandAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
ParamData readCommandParam(tinyxml2::XMLElement const* element, std::vector<ParamData> const& params);
std::pair<std::string, std::string> readCommandProto(tinyxml2::XMLElement const* element);
void readCommands(tinyxml2::XMLElement const* element);
std::string readComment(tinyxml2::XMLElement const* element);
void readDefine(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readEnum(tinyxml2::XMLElement const* element, EnumData & enumData, bool bitmask, std::string const& prefix, std::string const& postfix);
void readEnum(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, EnumData & enumData, bool bitmask, std::string const& prefix, std::string const& postfix);
void readEnumAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, EnumData & enumData, bool bitmask, std::string const& prefix, std::string const& postfix);
void readEnumConstant(tinyxml2::XMLElement const* element);
void readEnums(tinyxml2::XMLElement const* element);
void readExtension(tinyxml2::XMLElement const* element);
void readExtensionDisabledCommand(tinyxml2::XMLElement const* element);
void readExtensionDisabledEnum(std::string const& extensionName, tinyxml2::XMLElement const* element);
void readExtensionDisabledRequire(std::string const& extensionName, tinyxml2::XMLElement const* element);
void readExtensionDisabledType(tinyxml2::XMLElement const* element);
void readExtensionRequire(tinyxml2::XMLElement const* element, std::string const& platform, std::string const& tag, std::map<std::string, int> & requirements);
void readExtensionRequireCommand(tinyxml2::XMLElement const* element, std::string const& platform);
void readExtensionRequireType(tinyxml2::XMLElement const* element, std::string const& platform);
void readExtensions(tinyxml2::XMLElement const* element);
void readFeature(tinyxml2::XMLElement const* element);
void readFeatureRequire(tinyxml2::XMLElement const* element);
void readFuncpointer(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readHandle(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
std::pair<NameData, TypeData> readNameAndType(tinyxml2::XMLElement const* elements);
void readPlatform(tinyxml2::XMLElement const* element);
void readPlatforms(tinyxml2::XMLElement const* element);
void readRegistry(tinyxml2::XMLElement const* element);
void readRequireCommand(tinyxml2::XMLElement const* element);
void readRequireEnum(tinyxml2::XMLElement const* element, std::string const& tag);
void readRequireEnum(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, std::string const& tag);
void readRequireEnumAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes, std::string const& tag);
void readRequires(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readRequireType(tinyxml2::XMLElement const* element);
void readStruct(tinyxml2::XMLElement const* element, bool isUnion, std::map<std::string, std::string> const& attributes);
void readStructAlias(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readStructMember(tinyxml2::XMLElement const* element, std::vector<MemberData> & members);
void readStructMemberEnum(tinyxml2::XMLElement const* element, MemberData & memberData);
void readStructMemberName(tinyxml2::XMLElement const* element, MemberData & memberData, std::vector<MemberData> const& members);
void readStructMemberType(tinyxml2::XMLElement const* element, MemberData & memberData);
void readTag(tinyxml2::XMLElement const* element);
void readTags(tinyxml2::XMLElement const* element);
void readType(tinyxml2::XMLElement const* element);
void readTypeEnum(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readTypeInclude(tinyxml2::XMLElement const* element, std::map<std::string, std::string> const& attributes);
void readTypes(tinyxml2::XMLElement const* element);
void registerDeleter(std::string const& name, std::pair<std::string, CommandData> const& commandData);
void setVulkanLicenseHeader(int line, std::string const& comment);
private:
std::map<std::string, BaseTypeData> m_baseTypes;
std::map<std::string, BitmaskData> m_bitmasks;
std::map<std::string, std::string> m_commandToHandle;
std::set<std::string> m_constants;
std::map<std::string, EnumData> m_enums;
std::set<std::string> m_extendedStructs; // structs which are referenced by the structextends tag
std::map<std::string, ExtensionData> m_extensions;
std::map<std::string, std::string> m_features;
std::map<std::string, FuncPointerData> m_funcPointers;
std::map<std::string, HandleData> m_handles;
std::set<std::string> m_includes;
std::map<std::string, std::string> m_platforms;
std::map<std::string, std::string> m_structureAliases;
std::map<std::string, StructureData> m_structures;
std::set<std::string> m_tags;
std::set<std::string> m_types;
std::string m_typesafeCheck;
std::string m_version;
std::string m_vulkanLicenseHeader;
};
const size_t INVALID_INDEX = (size_t)~0;
| e324fcfd06ce59baf1c2a45a3df5dd537cf9787a | [
"C++"
] | 2 | C++ | pcsx4dev/GCN-Vulkan-Hpp | 66ec5b6bbddb6615ef32dcfe89cfc90f7d79ac37 | 3d3657fa466ceb2aacc7fdf3bb15f28820000052 | |
refs/heads/master | <file_sep><?php
namespace FondOfSpryker\Yves\Router\Plugin\RouteManipulator;
use Spryker\Yves\Kernel\AbstractPlugin;
use Spryker\Yves\RouterExtension\Dependency\Plugin\PostAddRouteManipulatorPluginInterface;
use Symfony\Component\Routing\Route;
/**
* @method \Spryker\Yves\Router\RouterConfig getConfig()
* @method \FondOfSpryker\Yves\Router\RouterFactory getFactory()
*/
class LanguageDefaultPostAddRouteManipulatorPlugin extends AbstractPlugin implements PostAddRouteManipulatorPluginInterface
{
/**
* @var string
*/
protected $allowedLocalesPattern;
/**
* @param string $routeName
* @param \Symfony\Component\Routing\Route $route
*
* @return \Symfony\Component\Routing\Route
*/
public function manipulate(string $routeName, Route $route): Route
{
$route->setDefault('language', $this->getFactory()->createStoreDataProvider()->getCurrentLanguage());
return $route;
}
}
<file_sep><?php
namespace FondOfSpryker\Yves\Router\DataProvider;
use Spryker\Shared\Kernel\Store;
class StoreDataProvider implements DataProviderInterface
{
/**
* @var array
*/
protected $availableLocales;
/**
* @var \Spryker\Shared\Kernel\Store
*/
protected $storeInstance;
/**
* @param \Spryker\Shared\Kernel\Store $storeInstance
*/
public function __construct(Store $storeInstance)
{
$this->storeInstance = $storeInstance;
}
/**
* @return array
*/
public function getAvailableLocales(): array
{
if ($this->availableLocales === null) {
$this->availableLocales = $this->storeInstance->getLocales();
}
return $this->availableLocales;
}
/**
* @param string $locale
*
* @return string|null
*/
public function getLanguageFromLocale(string $locale): ?string
{
return array_search($locale, $this->getAvailableLocales());
}
/**
* @return string
*/
public function getCurrentLanguage(): string
{
return $this->getLanguageFromLocale($this->storeInstance->getCurrentLocale());
}
}
<file_sep><?php
namespace FondOfSpryker\Yves\Router\Plugin\RouteManipulator;
use Spryker\Yves\Kernel\AbstractPlugin;
use Spryker\Yves\RouterExtension\Dependency\Plugin\PostAddRouteManipulatorPluginInterface;
use Symfony\Component\Routing\Route;
/**
* @method \Spryker\Yves\Router\RouterConfig getConfig()
* @method \FondOfSpryker\Yves\Router\RouterFactory getFactory()
*/
class StoreDefaultPostAddRouteManipulatorPlugin extends AbstractPlugin implements PostAddRouteManipulatorPluginInterface
{
/**
* @var string
*/
protected $allowedLocalesPattern;
/**
* @param string $routeName
* @param \Symfony\Component\Routing\Route $route
*
* @return \Symfony\Component\Routing\Route
*/
public function manipulate(string $routeName, Route $route): Route
{
$route->setDefault('store', APPLICATION_STORE);
return $route;
}
}
<file_sep><?php
namespace FondOfSpryker\Yves\Router\Plugin\RouterEnhancer;
use FondOfSpryker\Yves\Router\DataProvider\DataProviderInterface;
use Spryker\Yves\Router\Plugin\RouterEnhancer\LanguagePrefixRouterEnhancerPlugin as SprykerLanguagePrefixRouterEnhancerPlugin;
use Symfony\Component\Routing\RequestContext;
/**
* @method \Spryker\Yves\Router\RouterConfig getConfig()
* @method \FondOfSpryker\Yves\Router\RouterFactory getFactory()
*/
class LanguagePrefixRouterEnhancerPlugin extends SprykerLanguagePrefixRouterEnhancerPlugin
{
protected $storeDataProvder;
/**
* @param string $locale
*
* @return string
*/
protected function getLanguageFromLocale(string $locale): string
{
$language = $this->getStoreDataProvider()->getLanguageFromLocale($locale);
if ($language === null) {
$language = parent::getLanguageFromLocale($locale);
}
return $language;
}
/**
* @param \Symfony\Component\Routing\RequestContext $requestContext
*
* @return string|null
*/
protected function findLanguage(RequestContext $requestContext): ?string
{
$language = parent::findLanguage($requestContext);
$availableLocales = $this->getStoreDataProvider()->getAvailableLocales();
if (!array_key_exists($language, $availableLocales)) {
foreach ($availableLocales as $lang => $locale) {
if (substr($locale, 0, strlen($language)) === $language) {
$language = $lang;
break;
}
}
}
return $language;
}
/**
* @return \FondOfSpryker\Yves\Router\DataProvider\DataProviderInterface
*/
protected function getStoreDataProvider(): DataProviderInterface
{
if ($this->storeDataProvder === null) {
$this->storeDataProvder = $this->getFactory()->createStoreDataProvider();
}
return $this->storeDataProvder;
}
}
<file_sep><?php
namespace FondOfSpryker\Yves\Router;
use FondOfSpryker\Yves\Router\Dependency\Client\RouterToSessionClientBridge;
use FondOfSpryker\Yves\Router\Dependency\Client\RouterToStoreClientBridge;
use Spryker\Shared\Kernel\Store;
use Spryker\Yves\Router\RouterDependencyProvider as SprykerRouterDependencyProvider;
use Spryker\Yves\Kernel\Container;
/**
* @method \Spryker\Yves\Router\RouterConfig getConfig()
*/
class RouterDependencyProvider extends SprykerRouterDependencyProvider
{
public const DIRTY_STORE_INSTANCE = 'DIRTY_STORE_INSTANCE';
/**
* @param \Spryker\Yves\Kernel\Container $container
*
* @return \Spryker\Yves\Kernel\Container
*/
public function provideDependencies(Container $container)
{
$container = parent::provideDependencies($container);
$container = $this->addStore($container);
return $container;
}
/**
* @param \Spryker\Yves\Kernel\Container $container
*
* @return \Spryker\Yves\Kernel\Container
*/
protected function addStore(Container $container): Container
{
$container[static::DIRTY_STORE_INSTANCE] = function () {
return Store::getInstance();
};
return $container;
}
}
<file_sep><?php
namespace FondOfSpryker\Yves\Router\DataProvider;
interface DataProviderInterface
{
/**
* @return array
*/
public function getAvailableLocales(): array;
/**
* @param string $locale
*
* @return string|null
*/
public function getLanguageFromLocale(string $locale): ?string;
/**
* @return string
*/
public function getCurrentLanguage(): string;
}
<file_sep># spryker-router
## Install
```
composer require fond-of-spryker/router
```
<file_sep><?php
namespace FondOfSpryker\Yves\Router;
use FondOfSpryker\Yves\Router\DataProvider\DataProviderInterface;
use FondOfSpryker\Yves\Router\DataProvider\StoreDataProvider;
use Spryker\Shared\Kernel\Store;
use Spryker\Yves\Router\RouterFactory as SprykerRouterFactory;
/**
* @method \Spryker\Yves\Router\RouterConfig getConfig()
*/
class RouterFactory extends SprykerRouterFactory
{
/**
* @return \Spryker\Shared\Kernel\Store
*/
public function getStoreInstance(): Store
{
return $this->getProvidedDependency(RouterDependencyProvider::DIRTY_STORE_INSTANCE);
}
/**
* @return \FondOfSpryker\Yves\Router\DataProvider\DataProviderInterface
*/
public function createStoreDataProvider(): DataProviderInterface
{
return new StoreDataProvider($this->getStoreInstance());
}
}
| d58450ce4e1e70af3e2e61f021af758b5f2d1acc | [
"Markdown",
"PHP"
] | 8 | PHP | fond-of/spryker-router | 283ff74ba9fffe13ba17c07f9c190c46f4018607 | 1423c35c76f2c3c9dd9d630d13fec89934a4af65 | |
refs/heads/master | <repo_name>ns1/ns1-gui<file_sep>/components/navbar/index.js
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
export class NavBar extends React.Component {
static propTypes = {
className: PropTypes.string,
// <a href="#/"><img src="assets/[email protected]" /></a>
left: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.bool]),
children: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.bool]),
right: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.bool]),
leftClassName: PropTypes.string,
rightClassName: PropTypes.string,
stickyTop: PropTypes.bool
};
static defaultProps = {
className: '',
leftClassName: 'logo',
rightClassName: 'nav-right self-center',
stickyTop: false
};
constructor(props) {
super(props);
this.state = {
sticky: false
};
this.handleScroll = _.debounce(this.handleScroll.bind(this), 20);
}
componentDidMount() {
if (this.props.stickyTop) {
window.addEventListener('scroll', this.handleScroll);
}
}
componentWillUnmount() {
if (this.props.stickyTop) {
window.removeEventListener('scroll', this.handleScroll);
}
}
handleScroll(event) {
const rect = this.navbarNode.getBoundingClientRect();
if ((!this.state.sticky && rect.top <= 0) ||
(this.state.sticky && window.scrollY < rect.bottom)) {
this.setState({sticky: !this.state.sticky});
if (this.state.sticky) {
document.body.classList.add('sticky-present');
} else{
document.body.classList.remove('sticky-present');
}
}
}
render() {
const classes = `top-nav
${this.props.className}
${this.state.sticky ? 'sticky' : ''}`;
return <div
ref={navbar => this.navbarNode = navbar}
className={classes}>
<div className="bunder-container nav-container">
<div className={this.props.leftClassName}>
{this.props.left}
</div>
<ul className="nav-items">
{this.props.children}
</ul>
<div className={this.props.rightClassName}>
{this.props.right}
</div>
</div>
</div>;
}
}
export class NavItem extends React.Component {
static propTypes = {
className: PropTypes.string,
active: PropTypes.bool,
children: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.bool, PropTypes.string]),
id: PropTypes.string,
tabIndex: PropTypes.string,
href: PropTypes.string,
target: PropTypes.string,
onClick: PropTypes.func,
noLi: PropTypes.bool
};
static defaultProps = {
active: false,
className: '',
noLi: false
};
render() {
const tagClass = `nav-item
${this.props.className ? this.props.className : ''}
${this.props.active ? 'active' : ''}`;
const link = <a
className="nav-item"
tabIndex={this.props.tabIndex}
id={this.props.id}
href={this.props.href}
target={this.props.target}
onClick={this.props.onClick}
>
{this.props.children}
</a>;
const Tag = this.props.noLi ? 'div' : 'li';
return <Tag
className={tagClass}>
{link}
</Tag>;
}
}
<file_sep>/src/demo.js
import {render} from 'react-dom';
import React from 'react';
// import TopNav from '../components/top'
import '../scss/index.scss';
import './demo.scss';
import {BigLoader, bigloaderMD, bigloaderEX} from '../components/bigLoader';
import {Checkbox, checkboxMD, checkboxEX} from '../components/checkbox';
import {Dropdown, MenuItem, dropdownMD, dropdownEX} from '../components/dropdown';
import {FormTabs, FormTab, formtabsEX, formtabsMD} from '../components/formTabs';
import {Modal, modalMD, modalEX} from '../components/modal';
import {Pagination, paginationMD, paginationEX} from '../components/pagination';
import {ProgressBar, progressbarMD, progressbarEX} from '../components/progressBar';
import {Radio, radioMD, radioEX} from '../components/radio';
import {Textarea, textareaMD, textareaEX} from '../components/textarea';
import {Toggle, toggleMD, toggleEX} from '../components/toggle';
import {Tooltip, tooltipMD, tooltipEX} from '../components/tooltip';
import {TypeAhead, typeaheadMD, typeaheadEX} from '../components/typeahead';
import {Text, textMD, textEX} from '../components/text';
import {Tabs, Tab, tabsMD, tabsEX} from '../components/tabs';
import {CleverList, cleverlistMD, cleverlistEX} from '../components/cleverList';
import {CleverButton, cleverbuttonMD, cleverbuttonEX} from '../components/cleverbutton';
import ReactMarkdown from 'react-markdown';
import installation from './installation'
import DemoBlock from './demoblock';
class Docs extends React.Component {
constructor(props){
super(props);
this.state = {
textExample: '',
cleverSelected: {
someKey: 'somevalue 1',
name: 'Example Item 1'
}
};
this.hideModal = this.hideModal.bind(this);
}
hideModal(){
this.setState({
showModal: false
});
}
render(){
return <div className="bunder-container">
<h1>NS1 GUI components</h1>
<p>
This is an extremely early version of a self-contained version of our GUI component library.<br/>
We will be pushing up new components here very rapidly, and then when theres a usable subset<br/>
published we will focus on polish, more examples, bundle size improvements, and more documentation.
</p>
<h1>Installation</h1>
<ReactMarkdown source={installation} />
<h1>Components</h1>
<DemoBlock
title="Bigloader"
ex={bigloaderEX}
doc={bigloaderMD}
wrapStyle={{
height: '150px', backgroundColor: 'white', position: 'relative'
}}>
<BigLoader
warn={false}
warnText="This would be showing in the context of a warning."
loading={true}
loadingText="This is loading explainer text"
noDatat={false}
noDataText="This would be showing if there wasn't data" />
</DemoBlock>
<DemoBlock
title="Checkbox"
ex={checkboxEX}
doc={checkboxMD}>
<div>
<Checkbox
label="demo1"
onChange={e=>this.setState({checkbox: e.currentTarget.value})}
checked={this.state.checkbox === 'demo1'}
value="demo1"/>
<Checkbox
label="demo2"
onChange={e=>this.setState({checkbox: e.currentTarget.value})}
checked={this.state.checkbox === 'demo2'}
value="demo2"/>
</div>
</DemoBlock>
<DemoBlock
title="Cleverlist"
ex={cleverlistEX}
doc={cleverlistMD}>
<div style={{width: '100%'}}>
selected value: {this.state.cleverSelected.someKey}
<CleverList
formatting={i=>i.name}
onSelect={i=>this.setState({cleverSelected: i})}
interior={true}
itemsVisible={2}
pills={[
(i) => `Demopill ${i.someKey}`
]}
items={[{
someKey: 'somevalue 1',
name: 'Example Item 1'
}, {
someKey: 'somevalue 2',
name: 'Example Item 2'
}, {
someKey: 'somevalue 3',
name: 'Example Item 3'
}]}
options={[
{
icon: 'alert',
name: 'Demo Action',
onClick: (i, index, selector) => selector(index) ||
window.alert(JSON.stringify(i))
},
{
icon: 'folder',
name: 'Demo Disabled',
disabled: e=>true,
onClick: (i, index, selector) => window.alert(JSON.stringify(i))
}
]}/>
</div>
</DemoBlock>
<DemoBlock
title="Dropdown"
ex={dropdownEX}
doc={dropdownMD}>
<Dropdown
onSelect={e=>this.setState({
dropdown: e.currentTarget.value
})}
className="flex-half"
label="Example Dropdown"
defaultValue="first"
value={this.state.dropdown}>
<MenuItem
value="first">First Item</MenuItem>
<MenuItem
value="second">Second Item</MenuItem>
</Dropdown>
</DemoBlock>
<DemoBlock
title="Form Tabs"
ex={formtabsEX}
doc={formtabsMD}>
<div className="enclosure">
<div className="body">
<FormTabs
headerLabel="Important Stuff: "
defaultActiveKey={0}
activeKey={this.state.formTabActive}
onSelect={idx => this.setState({formTabActive: idx})}>
<FormTab
label="Tab 1">
... put form elements here
</FormTab>
<FormTab
label="Tab 2">
... put more form elements here
</FormTab>
</FormTabs>
</div>
</div>
</DemoBlock>
<DemoBlock
title="Modal"
ex={modalEX}
doc={modalMD}>
<div>
<button
onClick={() => this.setState({showModal: true})}
className="button primary short inline">
Pop Demo Modal
</button>
<Modal
show={this.state.showModal}
onHide={() => this.hideModal()}>
<Modal.Header
close={true}>
<Modal.Title>Example Modal</Modal.Title>
</Modal.Header>
<Modal.Body>
here is a modal body, you can put anything in here
</Modal.Body>
<Modal.Footer>
here is a modal footer, usually you'd put buttons here
</Modal.Footer>
</Modal>
</div>
</DemoBlock>
<DemoBlock
title="Pagination"
ex={paginationEX}
doc={paginationMD}>
<Pagination
next={true}
prev={true}
items={8}
maxButtons={5}
activePage={this.state.activePage || 0}
onSelect={i=>this.setState({activePage: i})} />
</DemoBlock>
<DemoBlock
title="Progress Bar"
ex={progressbarEX}
doc={progressbarMD}>
<ProgressBar
className="flex-whole"
label='Progress'
percent={82}
showValue={true} />
</DemoBlock>
<DemoBlock
title="Radio"
ex={radioEX}
doc={radioMD}>
<div>
<Radio
label="Thing1"
checked={this.state.radio === 'thing1'}
name="first"
onChange={e => this.setState({radio: e.currentTarget.value})}
value="thing1" />
<Radio
label="Thing2"
checked={this.state.radio === 'thing2'}
name="second"
onChange={e => this.setState({radio: e.currentTarget.value})}
value="thing2" />
</div>
</DemoBlock>
<DemoBlock
title="Tabs"
ex={tabsEX}
doc={tabsMD}>
<Tabs
defaultActiveKey={0}
activeKey={this.state.tabActive}
onSelect={idx => {
this.setState({tabActive: idx});
}}
className="interactive flex-whole">
<Tab
token={0}
className="minheight"
label="Demotab 1">
<BigLoader
warn={false}
warnText="This would be showing in the context of a warning."
loading={true}
loadingText="Demo Bigloader in tab"
noDatat={false}
noDataText="This woul"/>
</Tab>
<Tab
token={1}
className="minheight"
label="Demotab 2">
<BigLoader
warn={true}
warnText="Demo warning in tab"
loading={false}
loadingText="This is loading explainer text"
noDatat={false}
noDataText="This woul"/>
</Tab>
</Tabs>
</DemoBlock>
<DemoBlock
title="Text/number"
ex={textEX}
doc={textMD}>
<Text
onChange={e => {
this.setState({textExample: e.currentTarget.value});
}}
label="Sample text field"
value={this.state.textExample}
help="example help text."
pattern={{
pattern: val => val % 5 === 0,
message: 'Value should be divisible by 5'
}}
className="flex-half gutter-right" />
</DemoBlock>
<DemoBlock
title="Textarea"
ex={textareaEX}
doc={textareaMD}>
<Textarea
onChange={(e) => this.setState({textArea: e.currentTarget.value})}
value={this.state.textArea}
readOnly={false}
id="demotext"
label="Demo Textarea"
placeHolder="Some text"
name="demotextarea"
help="textareas are for longer blocks of text"
disabled={false}
className="foo" />
</DemoBlock>
<DemoBlock
title="Toggle"
ex={toggleEX}
doc={toggleMD}>
<Toggle
label="Demo Toggle"
checked={this.state.toggleDemo}
onChange={e=>this.setState({toggleDemo: e.currentTarget.checked})}
inline={true}
labelFirst={true} />
</DemoBlock>
<DemoBlock
title="Tooltip"
ex={tooltipEX}
doc={tooltipMD}>
<Tooltip
content="demo tooltip text"
direction='top'>
<span> Info <span className="icon info" /></span>
</Tooltip>
</DemoBlock>
<DemoBlock
title="Cleverbutton"
ex={cleverbuttonEX}
doc={cleverbuttonMD}>
<CleverButton
saving={this.state.saving}
saved={false}
error={false}
text="Submit Record"
classes="short inline"
onClick={()=>{
this.setState({saving: true});
setTimeout(()=>this.setState({saving: false}), 2000)
}} />
</DemoBlock>
<DemoBlock
title="Typeahead"
ex={typeaheadEX}
doc={typeaheadMD}>
typehead stub
</DemoBlock>
</div>;
}
}
window.onload = () => {
render(<Docs />, document.getElementById('app-body'));
};
<file_sep>/components/modal/modal.ex.md.js
export default `\`\`\`html
<button
onClick={() => this.setState({showModal: true})}
className="button primary short inline">
Pop Demo Modal
</button>
<Modal
show={this.state.showModal}
onHide={() => this.hideModal()}>
<Modal.Header
close={true}>
<Modal.Title>Example Modal</Modal.Title>
</Modal.Header>
<Modal.Body>
here is a modal body, you can put anything in here
</Modal.Body>
<Modal.Footer>
here is a modal footer, usually you'd put buttons here
</Modal.Footer>
</Modal>
\`\`\``;
<file_sep>/components/dropdown/dropdown.md.js
export default `import dropdown and menuitem from ns1-gui
### Dropdown props
- **onSelect** *(func)* function called when user makes a selection. access selected value with e.currentTarget.value
---
### MenuItem props
- **value** *(string)* value to pass to onselect function`;
<file_sep>/components/textarea/textarea.ex.md.js
export default `\`\`\`html
<Textarea
onChange={(e) => this.setState({textArea: e.currentTarget.value})}
value={this.state.textArea}
readOnly={false}
id="demotext"
label="Demo Textarea"
placeHolder="Some text"
name="demotextarea"
help="textareas are for longer blocks of text"
disabled={false}
className="foo" />
\`\`\`
`;
<file_sep>/components/pagination/index.js
import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import './pagination.scss';
class PaginationComp extends React.Component {
static propTypes = {
/* eslint-disable react/no-deprecated */
className: PropTypes.string,
style: PropTypes.object,
next: PropTypes.bool,
prev: PropTypes.bool,
items: PropTypes.number.isRequired,
maxButtons: PropTypes.number,
activePage: PropTypes.number,
onSelect: PropTypes.func
}
constructor(props) {
super(props);
this.state = {
currentItem: props.activePage || 1,
items: props.items
};
this.buildPageItems = this.buildPageItems.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.items) {
this.setState({items: nextProps.items});
this.setState({currentItem: nextProps.activePage});
}
}
changePage(item) {
if (item < 1 || item > this.state.items) {
return;
}
this.setState({currentItem : item});
this.props.onSelect && this.props.onSelect(item);
}
showHeaderAndFooter() {
const {maxButtons} = this.props;
const {items} = this.state;
let buttonRange = maxButtons;
if (this.props.items < maxButtons) {
return {
showHeader: false,
showFooter: false
};
}
let showHeader = this.state.currentItem > Math.ceil(buttonRange/2);
if (showHeader) {
buttonRange -= 2;
}
let showFooter = this.state.currentItem < items - Math.floor(buttonRange/2);
if (showFooter) {
buttonRange -= 2;
showHeader = this.state.currentItem > Math.ceil(buttonRange/2);
}
return {
showHeader: showHeader,
showFooter: showFooter
};
}
getMaxButtons() {
return this.props.items < this.props.maxButtons ? this.props.items : this.props.maxButtons;
}
getButtonRange() {
const {showHeader, showFooter} = this.showHeaderAndFooter();
let buttonRange = this.getMaxButtons();
if (showHeader) {
buttonRange -= 2;
}
if (showFooter) {
buttonRange -= 2;
}
return buttonRange;
}
buildPageItems() {
if (this.props.items < this.props.maxButtons) {
return _.range(1, 1+this.props.items);
}
const {items, currentItem} = this.state;
let buttonRange = this.getButtonRange();
const midCeil = Math.ceil(buttonRange/2);
let last = currentItem < midCeil ? 1 + buttonRange : currentItem + midCeil;
if (last > items) {
last = items+1;
}
const first = this.props.items < this.props.maxButtons ? 1 : last - buttonRange;
return _.range(first, last);
}
render() {
const {
className, style, next, prev} = this.props;
const {currentItem, items} = this.state;
const {showHeader, showFooter} = this.showHeaderAndFooter();
return <div
className={`pagination ${className || ''} flex-wrap vert-middle auto`}
style={style}>
{/* PREV */}
{prev && <span onClick={this.changePage.bind(this, currentItem-1)}
className={`prev ${currentItem <= 1 ? 'no' : '' }`}>‹</span>}
<span className='items'>
{/* FIRST */}
<span
onClick={this.changePage.bind(this, 1)}
className={`firstNumber item ${showHeader ? '' : 'hide'}`}>1</span>
{/* ELLIPSIS */}
<span
className={`ellipsis ${showHeader ? '' : 'hide'}`}>...</span>
{/* ITEMS */}
{this.buildPageItems().map((elem) => {
return <span
key={elem}
onClick={this.changePage.bind(this, elem)}
className={`item ${elem === currentItem ? 'active' : ''}`}>{elem}</span>;
})}
{/* ELLIPSIS */}
{<span
className={`ellipsis ${showFooter ? '' : 'hide'}`}>...</span>}
{/* LAST */}
<span
onClick={this.changePage.bind(this, this.state.items)}
className={`item lastNumber ${showFooter ? '' : 'hide'}`}>{items}</span>
</span>
{next && <span
onClick={this.changePage.bind(this, currentItem+1)}
className={`next ${currentItem === items ? 'no' : '' }`}>›</span>}
</div>;
}
}
export default PaginationComp;
export const Pagination = PaginationComp;
export paginationEX from './pagination.ex.md.js';
export paginationMD from './pagination.md.js';
<file_sep>/components/textarea/index.js
import PropTypes from 'prop-types';
import React from 'react';
import TextareaAutosize from 'react-autosize-textarea';
class TextareaComp extends React.Component{
static propTypes = {
onChange: PropTypes.func,
onKeyDown: PropTypes.func,
value: PropTypes.string,
readOnly: PropTypes.bool,
id: PropTypes.string,
label: PropTypes.string,
placeHolder: PropTypes.string,
name: PropTypes.string,
key: PropTypes.string,
help: PropTypes.string,
disabled: PropTypes.bool,
// enable spellcheck, autocomplete, etc
accoutrements: PropTypes.bool,
required: PropTypes.bool,
className: PropTypes.string
};
static defaultProps = {
accoutrements: false,
required: false
};
state = {
touched: false
};
componentDidMount() {
this.setState({
touched: false
});
}
render(){
const {required, value, className, label, accoutrements, name,
placeHolder, readOnly, disabled, onChange, help, id, onKeyDown} = this.props;
let extraClasses = [];
if (required && !value && this.state.touched) {
extraClasses.push('invalid');
} else if (required && this.state.touched && value) {
extraClasses.push('valid');
}
if (extraClasses.length > 0) {
extraClasses.push('touched');
}
return <div className={`textarea-wrap ${help && 'has-help'} ${extraClasses.join(' ')}`}>
<label>
{label}{required && label ? '*' : ''}</label>
<TextareaAutosize
autocomplete={accoutrements ? 'on' : 'off'}
autocorrect={accoutrements ? 'on' : 'off'}
autocapitalize={accoutrements ? 'on' : 'off'}
spellcheck={accoutrements ? 'true' : 'false'}
name={name}
className="textarea"
value={value}
id={id}
onKeyDown={e => {
e.stopPropagation();
onKeyDown && onKeyDown(e);
if(!this.setState.touched){
this.setState({
touched: true
});
}
}}
placeHolder={placeHolder}
readOnly={readOnly}
disabled={disabled}
onChange={onChange} />
<span className="help-text">{help}</span>
</div>;
}
}
export default TextareaComp;
export const Textarea = TextareaComp;
export textareaEX from './textarea.ex.md.js';
export textareaMD from './textarea.md.js';
<file_sep>/components/loader/loader.md.js
export default `loader stub`;
<file_sep>/components/notification/index.js
import PropTypes from 'prop-types';
import React from 'react';
import './notifications.scss';
class Notification extends React.Component {
static propTypes = {
children: PropTypes.any,
icon: PropTypes.string,
className: PropTypes.string,
close: PropTypes.func,
actionText: PropTypes.string,
actionUrl: PropTypes.string,
wait: PropTypes.bool
};
componentDidMount() {
if (!this.props.wait){
setTimeout(this.props.close, 3000);
}
}
render() {
const {icon, className, message, close} = this.props;
return <div className={`notification ${className}`}>
{icon && <span className={`icon ${icon}`} />}
{this.props.children}
{this.props.actionUrl &&
<span className="action">
<a href={this.props.actionUrl}>
{this.props.actionText}
</a>
</span>}
{close && <span
onClick={this.props.close}
className="icon closex" />}
</div>;
}
}
class NotificationBody extends React.Component {
static propTypes = {
children: PropTypes.any
};
render() {
return <div className="notification-body">
{this.props.children}
</div>;
}
}
Notification.Body = NotificationBody;
export default Notification;
<file_sep>/components/tooltip/tooltip.md.js
export default `provide contextual info on hover
- **content** *(string)* help text content
- **direction** *(string)* top | bottom | left | right direction to pop the tooltip
- **className** *(string)* classname appened to wrapper div
- **style** *(object)* react style object to apply to the tooltip itself
`;
<file_sep>/components/modal/modal.md.js
export default `Import Modal from ns1-gui. this component has sub components.
### Modal props
- **show** *(boolean)* show or hide the modal
- **onHide** *(number)* what to do when modal is closed from the inside
---
### Modal.Header props
- **close** *(bool)* allow user to close modal internally
---
### Misc
- You can place a Modal.Title inside of a Modal.Header
- Modal.Body and Modal.Footer are available slots as well
- All subcomponents should be wrapped in a Modal component
`;
<file_sep>/components/radio/radio.md.js
export default `radio button wrapper with styles and dataprop passthrough
- **label** *(string)* human readable label for the option
- **checked** *(bool)* whether or not to display the option as checked
- **name** *(name)* html name attribute
- **onChange** *(func)* handler for user selection
- **value** *(string)* value to pass onChange
- **data-*** *(string)* any prop that starts with data- will be attached as if it were an attribute and passed to the onchange handler
- **disabled*** *(bool)* dissallow click events
`;
<file_sep>/components/bigLoader/index.js
import React from 'react';
import Loader from '../loader';
import './bigLoader.scss';
class BigLoaderComp extends React.Component{
constructor(props){
super(props);
}
render(){
const {
className,
loadingText,
details,
loading,
warn,
warnText,
noData,
noDataText
} = this.props;
return <div className="bl-wrapper">
<div className={`big-loader ${className} flex-wrap vert-middle`}>
{loading &&
<div className="loading vert-middle flex-whole">
<h3>{loadingText}</h3>
{details && <h4>{details}</h4>}
<Loader />
</div>}
{noData &&
<div className="no-data vert-middle flex-whole">
<h3>{noDataText}</h3>
</div>}
{warn &&
<div className="warning vert-middle flex-whole">
<h3>{warnText}</h3>
</div>}
</div>
</div>;
}
}
export const BigLoader = BigLoaderComp;
export default BigLoaderComp;
export bigloaderMD from './bigloader.md.js';
export bigloaderEX from './bigloader.ex.md.js';
<file_sep>/index.js
export BigLoader from './components/bigLoader';
export Checkbox from './components/checkbox';
export CleverButton from './components/cleverbutton';
export CleverList from './components/cleverList';
export {Dropdown, MenuItem, OptionsMenu, TextMenu} from './components/dropdown';
export {FormTabs, FormTab} from './components/formTabs';
// export KeyValue from './components/keyValue';
export Loader from './components/loader';
export Modal from './components/modal';
export Notification from './components/notification';
export Pagination from './components/pagination';
export {NavBar, NavItem} from './components/navbar';
// export Phaser from './components/phaser';
export ProgressBar from './components/progressBar';
export Radio from './components/radio';
// export Sub from './components/sub';
export {Tabs, Tab} from './components/tabs/index.js';
export Text from './components/text';
export Textarea from './components/textarea';
export Toggle from './components/toggle';
export Tooltip from './components/tooltip';
export Typeahead from './components/typeahead';
<file_sep>/components/text/index.js
import PropTypes from 'prop-types';
import React from 'react';
import _ from 'lodash';
import './text.scss';
class TextComp extends React.Component{
static propTypes = {
autoComp: PropTypes.bool,
autoFocus: PropTypes.bool,
caption: PropTypes.string,
className: PropTypes.string,
data: PropTypes.any,
defaultValue: PropTypes.any,
disabled: PropTypes.bool,
error: PropTypes.any,
help: PropTypes.string,
icon: PropTypes.string,
id: PropTypes.string,
key: PropTypes.string,
label: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
name: PropTypes.string,
noValid: PropTypes.bool,
onBlur: PropTypes.func,
onCancel: PropTypes.func,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func,
onKeyDown: PropTypes.func,
onKeyPress: PropTypes.func,
passKey: PropTypes.string,
passRef: PropTypes.string,
pattern: PropTypes.any,
placeholder: PropTypes.any,
rapid: PropTypes.bool,
readOnly: PropTypes.bool,
required: PropTypes.bool,
style: PropTypes.string,
type: PropTypes.string,
// can be used to override internal validation
valid: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
validationMessage: PropTypes.string, // ditto
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
}
constructor(props) {
super(props);
this.state = {
valid: true,
touched: false,
pastfocus: false,
bounced: props.value && props.value.toString().length > 0 ||
(typeof props.defaultValue !== 'undefined' && props.defaultValue !== null) &&
(!props.defaultValue.toString().length ||
props.defaultValue.toString().length > 0) ||
typeof props.placeholder !== 'undefined' ||
props.autoFocus ||
(props.value && props.value === 0)
};
this.parseValidation = this.parseValidation.bind(this);
this.setFocus = this.setFocus.bind(this);
this.focusHandler = this.focusHandler.bind(this);
this.genRef = !props.passRef ? this.genRef = Math.random() : false;
}
componentWillReceiveProps(np){
if(typeof this.props.placeholder === 'undefined' && typeof np.placeholder !== 'undefined'){
this.setState({
bounced: true
});
}
}
componentDidMount() {
if (this.props.rapid){
this.parseValidation();
}
}
processPattern(pattern, val) {
switch (typeof pattern) {
case 'undefined':
return true;
case 'function':
return pattern(val);
case 'object':
return Array.isArray(pattern) ?
pattern.some(pat => pat.test(val)) :
// regexp
pattern.test(val);
case 'string':
return RegExp(pattern).test(val);
}
}
parseValidation(e){
const {required} = this.props;
const pattern = this.props.pattern && this.props.pattern.pattern;
const val = (e && e.currentTarget && e.currentTarget.value) ||
this.props.value || this.props.defaultValue;
let valid = true;
if (this.props.noValid) {
return true;
} else if (val) {
if (typeof this.props.valid === 'boolean' || !!this.props.valid) {
valid = this.props.valid;
} else {
if (required) {
valid = (val.length && val.length > 0) || typeof val === 'number';
}
if (valid) {
valid = this.processPattern(pattern, val);
}
}
} else {
valid = !required;
}
this.setState({
valid,
bounced: typeof val !== 'undefined' ?
(val.length > 0 || !_.isNaN(new Number(val))) :
true
});
if (this.props.rapid){
this.props.rapid(this.state.valid);
}
return false;
}
setFocus(){
this[this.props.passRef].focus();
}
focusHandler(){
// this.parseValidation();
this.setState({touched: true, bounced: true});
this.props.onFocus && this.props.onFocus();
setTimeout(() => {
if (this.props.passRef && this[this.props.passRef]){
this[this.props.passRef].setSelectionRange(this.props.value.length,
this.props.value.length);
}
}, 20);
}
classList() {
const {help, defaultValue, error, required, disabled, pattern, className, value,
noValid, icon, onCancel} = this.props;
const {valid, touched, bounced, pastFocus} = this.state;
return [
className,
'text-input',
disabled && 'disabled',
((!required && !pattern) || noValid) && 'hide-validation',
help || this.propsValidationMessage || pattern && pattern.message && 'has-help',
noValid && !icon && 'no-icon',
(bounced || defaultValue || (value && value.length > 0) || _.isNumber(value)) && 'bounced',
error && 'error',
touched && 'touched',
(pastFocus || onCancel) && 'pastFocus',
icon && 'has-icon',
valid ?
'valid' :
touched && pastFocus && 'invalid'].filter(i => i).join(' ');
}
render() {
const {label, help, defaultValue, style, type, onChange, required, disabled, pattern,
readOnly, autoComp, autoFocus, noValid, icon, placeholder, onBlur,
key, name, onCancel, passKey} = this.props;
var {value} = this.props;
const {valid, touched} = this.state;
const validationMessage = this.props.validationMessage || pattern && pattern.message;
return <div
style={style}
key={passKey || key}
className={this.classList()}>
<input
{...Object.keys(this.props).reduce((acc, prop) => {
return prop.indexOf('data-') > -1 ?
Object.assign({}, acc, {[prop]: this.props[prop]}) :
acc;
}, {})}
ref={(input) => {
if (this.props.passRef){
this[this.props.passRef] = input;
} else {
this[this.genRef] = input;
}
}}
required={required}
id={`text-${this.props.id || name}`}
type={type}
value={value}
placeholder={defaultValue || placeholder}
disabled={disabled}
onKeyPress={this.props.onKeyPress}
onFocus={e => this.focusHandler(e)}
onBlur={e => this.setState({pastFocus: true}) ||
(!noValid && this.parseValidation(e)) ||
onBlur && onBlur(e)}
onChange={e => {
if (this.props.rapid){
this.parseValidation(e);
}
onChange(e);
}
}
autoComplete={!autoComp && 'off'}
autoFocus={autoFocus}
readOnly={readOnly}
onKeyDown={e => {
e.stopPropagation();
if (e.key === 'Escape'){
this.props.passRef && this[this.props.passRef].blur();
!this.props.passRef && this[this.genRef].blur();
}
this.props.onKeyDown && this.props.onKeyDown(e);
}} />
{label && <label htmlFor={`text-${name}`}>{label}{required && ' *'}</label>}
<span className="bar" />
{valid && !noValid && <span className="icon check"/>}
{(!valid && touched) && !noValid && <span className="icon closex invalid" />}
{noValid && icon && !onCancel && <span className={`icon pink ${icon}`}/>}
{this.props.caption && <span className="icon caption">{this.props.caption}</span>}
{help && <span className="help-text">
{help} {!valid && validationMessage ? validationMessage : ''}</span>}
{!help && !valid && validationMessage && <span className="help-text">
{validationMessage}</span>}
{onCancel && <span className="icon closex" onClick={onCancel} />}
</div>;
}
}
export textMD from './text.md.js';
export textEX from './text.ex.md.js';
export const Text = TextComp;
export default Text;
<file_sep>/components/toggle/index.js
import PropTypes from 'prop-types';
import React from 'react';
import Tooltip from '../tooltip';
import './toggle.scss';
class ToggleComp extends React.Component{
static propTypes = {
/* eslint-disable react/no-deprecated */
label: PropTypes.string.isRequired,
checked: PropTypes.bool,
onChange: PropTypes.func,
key: PropTypes.string,
value: PropTypes.string,
inline: PropTypes.bool,
style: PropTypes.object,
labelFirst: PropTypes.bool,
className: PropTypes.string,
passKey: PropTypes.string,
tooltip: PropTypes.string.isRequired
}
constructor(props) {
super(props);
// unsure if using state for this is ok? i needed a
// uniqueId mostly for htmlFor label reasons
const id = Math.random
this.state = {
id: `toggle-${(""+Math.random()).substring(2,7)}`
};
}
render() {
const {label, checked, onChange, inline, style, className} = this.props;
const id = this.state.id;
return <label
style={style}
key={this.props.passKey}
className={`toggle-label ${inline && 'inline'} ${className || ''}`}>
{this.props.tooltip ?
this.props.labelFirst && <Tooltip content={this.props.tooltip} direction="top">
<span dangerouslySetInnerHTML={{__html: label}}></span>
</Tooltip> :
this.props.labelFirst && <span dangerouslySetInnerHTML={{__html: label}}></span>
}
<input
{...Object.keys(this.props).reduce((acc, prop) => {
return prop.indexOf('data-') > -1 ?
Object.assign({}, acc, {[prop]: this.props[prop]}) :
acc;
}, {})}
type="checkbox"
id={id}
className="cbx hidden"
checked={checked || false}
onChange={onChange} />
<label className='inner-lbl' htmlFor={id}></label>
{this.props.tooltip ?
this.props.labelFirst === false &&
<Tooltip content={this.props.tooltip} direction="top">
<span dangerouslySetInnerHTML={{__html: label}}></span>
</Tooltip> :
!this.props.labelFirst && <span dangerouslySetInnerHTML={{__html: label}}></span>
}
</label>;
}
}
export default ToggleComp;
export const Toggle = ToggleComp;
export toggleEX from './toggle.ex.md.js';
export toggleMD from './toggle.md.js';
<file_sep>/components/cleverList/index.js
// unification
import React from 'react';
import PropTypes from 'prop-types';
import {OptionsMenu, MenuItem} from '../dropdown';
import {VariableSizeList as List} from 'react-window';
import {WindowScroller} from 'react-virtualized/dist/commonjs/WindowScroller';
import debounce from 'lodash.debounce';
import './cleverlist.scss';
class CleverListComp extends React.Component{
static propTypes = {
onEdit: PropTypes.func,
onNavigate: PropTypes.func,
onSelect: PropTypes.func,
items: PropTypes.array.isRequired,
listkey: PropTypes.string.isRequired,
formatting: PropTypes.func,
showOptions: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
// onClick's signature is (item, index)
options: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
onClick: PropTypes.func,
icon: PropTypes.string,
url: PropTypes.func, // instead of onClick, you can provide a url to click
className: PropTypes.string,
show: PropTypes.oneOfType([PropTypes.bool, PropTypes.func])
})),
pills: PropTypes.arrayOf(PropTypes.func),
// rendered below the formatted-triggered layout
subTemplate: PropTypes.func,
// takes precedence over the formatted, subTemplate rendered layout
itemTemplate: PropTypes.func,
// a way to add data-test attributes for testing
testTemplate: PropTypes.func
};
constructor(props){
super(props);
this.selectDirect = this.selectDirect.bind(this);
this.edit = this.edit.bind(this);
this.fullRender = this.fullRender.bind(this);
this.placeRender = this.placeRender.bind(this);
this.handleListRef = this.handleListRef.bind(this);
this.handleScroll = this.handleScroll.bind(this);
this.isInViewport = this.isInViewport.bind(this);
this.scrollToIdx = this.scrollToIdx.bind(this);
if (this.props.asyncRenderSides){
this.updatedRender = _.debounce(this.props.asyncRenderSides, 500);
}
this.state = {
selected: 0,
firstOnSelectFired: false
};
this.dummyMenu = <div className="vert-middle stack-right pull-right">
<div className="opt-wrap item-options">
<label className="options-menu item-options">
<div className="dots"></div>
</label></div>
</div>;
}
componentWillMount(){
const {listkey} = this.props;
}
componentDidUpdate(prevProps) {
/* this just hooks to see if items was empty before, and now has items.
If that's the case, fire onSelect, as the default selection logic happens
too soon in the lifecycle to do anything meaningful.
state.firstOnSelectFired isn't technically necessary, but is a defensive
flag to prevent recursive handler executions if there's a bug later. */
if (!this.state.firstOnSelectFired &&
prevProps.items.length === 0 &&
this.props.items.length > 0) {
const {onSelect, items} = this.props;
onSelect && onSelect(items[this.state.selected]);
this.setState({firstOnSelectFired: true});
}
}
scrollToIdx(idx, dir){
const mult = typeof this.props.itemSize === 'function' ? this.props.itemSize(0) : this.props.itemSize || 48;
window.scrollTo(0, idx * mult + (dir === 'down' ? 250 : -250));
}
isInViewport(e){
if (!e){
return false;
}
const bounder = e.getBoundingClientRect();
const {top} = bounder;
return top <= innerHeight - 80 && top >= 80;
}
edit(e){
e.stopPropagation();
const {onEdit, items} = this.props;
const {selected} = this.state;
onEdit && setTimeout(() => onEdit(items[selected]), 0);
}
selectDirect(i){
const {onSelect, items} = this.props;
this.setState({
selected: i
});
onSelect && onSelect(items[i]);
}
handleListRef (component) {
this.list = component;
if (this.props.regRef){
this.props.regRef(this.list);
}
}
handleScroll({scrollTop}) {
if (this.list) {
this.list.scrollTo(scrollTop);
}
}
fullRender(items){
const {formatting, listkey, options, href, pills, navPill, itemTemplate,
testTemplate, showOptions, hrefButton} = this.props;
const {selected} = this.state;
return ({index, style}) => {
// formatted prop formats the value for display in the row
const i = items[index];
const formatted = typeof formatting === 'function' && formatting(i);
const templated = typeof itemTemplate === 'function';
// href prop returns a relative URL for the item if clicked
const altHref = this.props.altHref ? this.props.altHref(i) : false;
const hreffed = typeof href === 'function' && href(i);
const np = navPill && navPill(i);
const optionsShown = (typeof showOptions === 'function' && showOptions(i)) || true;
// generate the list of options/pills for later use
const appendix = (options || pills || hrefButton) &&
<div className="vert-middle stack-right pull-right">
{pills && pills.map((fn, ii) => {
const res = fn(i);
if (res) {
return typeof res === 'string' ? <a
key={`res-${i}-${ii}`}
className="small upper round gray pill">{res}</a> :
res;
}
})}
{np && <a
className="small boxy magenta pill"
data-test-name={`${formatted}`}
href={hreffed}>{np}<span className="icon chevron">►</span></a>}
{hrefButton && hrefButton(i)}
{options && optionsShown && <OptionsMenu className="item-options">
{options && options.filter(option =>
typeof option.show === 'function' ? !option.show(i) : true)
.map(option => <MenuItem
icon={option.icon}
disabled={option.disabled && option.disabled(i)}
key={option.name}
className={option.className ? option.className : ''}
url={option.url && option.url(i)}
onClick={e => option.onClick && option.onClick(i, index, this.selectDirect)}>{option.name}</MenuItem>
)}
</OptionsMenu>}
</div>;
// if itemTemplate prop is provided, this overrides the rest.
if (templated) {
return <div
onClick={() => this.selectDirect(index)}
key={index}
data-test={testTemplate && testTemplate(i)}
style={style}
id={`cleverlist-${index}`}>
{itemTemplate(i, {
selected: selected === index,
appendix: appendix
})}
</div>;
}
// If unformatted, provide a default <pre> placeholder (preholder???)
if (!formatted) {
return <pre key={index}>{JSON.stringify(i, null, 2)}</pre>;
}
// otherwise, the primary rendering format uses formatted for the hyperlink
return <div
key={index}
style={style}
id={`cleverlist-${index}`}
data-test={testTemplate && testTemplate(i)}>
<div
key={`${listkey}-${index}`}
onClick={() => this.selectDirect(index)}
className={[
'flex-wrap flex-whole item-row address-item vert-middle',
`${selected === index ? 'selected' : ''}`
].join(' ')}>
{altHref ? altHref : hreffed ?
<a className={this.props.widths ? this.props.widths[0] : ''} href={hreffed}><h4>{formatted}</h4></a> :
<h4 className={this.props.widths ? this.props.widths[0] : ''}>{formatted}</h4>
}
{!templated && appendix}
</div>
{this.props.subTemplate && this.props.subTemplate(i)}
</div>;
};
}
placeRender(items){
const {formatting, scroller, options} = this.props;
const {selected} = this.state;
return ({index, style}) => {
return scroller ? scroller(items[index], style) : <div
style={style}
key={index}>
<div
className={`flex-whole flex-wrap item-row address-item vert-middle ${index === selected ? 'selected' : ''}`}>
<h4 className={this.props.widths ? this.props.widths[0] : ''}>{formatting(items[index])}</h4>
{options && this.dummyMenu}
</div>
</div>;
};
}
windowScroller = () => {
const {items, itemSize} = this.props;
return <WindowScroller ref={ref => this.windowScroller = ref} onScroll={this.handleScroll}>
{({height, isScrolling}) =>
<List
onItemsRendered={this.props.asyncRenderSides ? this.updatedRender : undefined}
overscanCount={0}
ref={this.handleListRef}
className="List window-scroller-override"
height={height}
itemCount={items.length}
itemSize={itemSize ? itemSize : () => {
return 48;
}}>{isScrolling ? this.placeRender(items) : this.fullRender(items)}</List>}
</WindowScroller>
}
normalList = () => {
const {items, itemSize} = this.props;
const itemSized = itemSize ? itemSize : () => 48;
const itemsVisible = this.props.itemsVisible || 10;
return <List
className="allow-overflow"
onItemsRendered={this.props.asyncRenderSides ? this.updatedRender : undefined}
overscanCount={0}
ref={this.handleListRef}
className="List window-scroller-override"
height={itemSized() * itemsVisible}
itemCount={items.length}
itemSize={itemSized}>{this.fullRender(items)}</List>
}
render(){
const {items, itemSize} = this.props;
if (this.props.passRef){
this.props.passRef(this);
}
return <div className={['cleverlist', this.props.wrapClass].join(' ')}
onDrop={(e) => {
const data = e.dataTransfer.getData('text/html');
e.preventDefault();
this.forceUpdate();
}}>
<div className={['clever-list', 'item-list', 'virtual', this.props.className ? this.props.className : ''].join(' ')}>
{!this.props.interior ? this.windowScroller() : this.normalList()}
</div>
</div>;
}
}
export const CleverList = CleverListComp;
export default CleverList;
export cleverlistMD from './cleverList.md.js';
export cleverlistEX from './cleverList.ex.md.js';
<file_sep>/components/textarea/textarea.md.js
export default `auto resizing textarea component
- **onChange** *(func)* function to be called when user changes field value
- **value** *(string)* element value
- **readOnly** *(bool)* allow user to edit values
- **id** *(string)* html passthrough to input
- **label** *(string)* label for field
- **placeHolder** *(string)* text to display if value is 0 length
- **name** *(string)* html attribute passthrough
- **help** *(string)* help text
- **disabled** *(bool)* allow user input
- **className** *(string)* classname appended for wrapper div
`;
<file_sep>/components/tabs/tabs.md.js
export default `import this as Tabs and Tab. Nest Tab in Tabs wrapper component
### Tab props
- **className** *(string)* optional classname string to append to builtin
- **defaultActiveKey** *(number)* default active key if none provided
- **activeKey** *(number)* current tab index to show tab content for
- **onSelect** *(func)* function to call when a different tab is selected
---
### Tab props
- **label** *(string)* label for this tab
- **icon** *(string)* optional icon for tab label`;
<file_sep>/utils/buildIconSass.js
const fs = require('fs');
const files = fs.readdirSync('./assets/svg')
.sort()
.map(f=>
f.split('.svg')[0]);
fs
.writeFileSync(`./scss/icons.scss`,
files
.filter(f=>f)
.filter(f=>f[0]!=='.')
.map((f,i) =>
`$${f}: '${
String
.fromCharCode(0xEA01 + (i))
}' !global`)
.join('\n'), 'utf8', (e, done)=>{
if (e){
console.log(e);
}
console.log(done);
});
<file_sep>/components/modal/index.js
import PropTypes from 'prop-types';
import React from 'react';
import {ModalTitle, ModalHeader} from './header';
import ModalBody from './body';
import ModalFooter from './footer';
import './modal.scss';
class ModalComp extends React.Component {
static propTypes = {
/* eslint-disable react/no-deprecated */
className: PropTypes.string,
children: PropTypes.any,
show: PropTypes.bool,
close: PropTypes.func,
onHide: PropTypes.func,
id: PropTypes.string,
style: PropTypes.object,
blocking: PropTypes.bool
};
static defaultProps = {
className: '',
show: false,
children: []
};
constructor(props){
super(props);
this.closeModal = this.closeModal.bind(this);
}
closeModal() {
this.props.onHide && this.props.onHide();
this.props.close && this.props.close();
}
render() {
return <div
id={this.props.id}
onClick={e => this.props.blocking ? e.stopPropagation() : false}
className={`
bunder-wrapper
${this.props.show ? 'show-modal' : ''}`}>
<div
className="bunder-modal-background"
onClick={this.props.close || this.closeModal} />
<div
style={this.props.style}
className={`bunder-modal ${this.props.className}`}>
{this.props.show && this.props.children.map &&
this.props.children.filter(a => a).map(c => {
return typeof c.type === 'function' ?
Object.assign({}, c, {
props: Object.assign({},c.props, {onHide: this.closeModal})
}) :
c;
})}
</div>
</div>;
}
}
ModalComp.Title = ModalTitle;
ModalComp.Header = ModalHeader;
ModalComp.Body = ModalBody;
ModalComp.Footer = ModalFooter;
export default ModalComp;
export const Modal = ModalComp;
export modalMD from './modal.md.js';
export modalEX from './modal.ex.md';
<file_sep>/components/toggle/toggle.ex.md.js
export default `\`\`\`html
<Toggle
label="Demo Toggle"
checked={this.state.toggleDemo}
onChange={e=>this.setState({
toggleDemo: e.currentTarget.checked
})}
inline={true}
labelFirst={true} />
\`\`\`
`;
<file_sep>/webpack.config.js
'use strict';
/* globals __dirname, require, process */
var path = require('path');
var webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var isProd = process.env.NODE_ENV === 'production';
const IconfontPlugin = require('iconfont-plugin-webpack');
const EditFontPlugin = require('./utils/editFontPlugin');
const devPort = 8500;
console.log('isProd: ', isProd);
const url = (suffix) => {
return `${suffix}`;
};
let ico = () => {
return new IconfontPlugin({
src: `${__dirname}/assets/svg`,
family: 'iconfont',
dest: {
font: `${__dirname}/docs/[family].[type]`,
css: `${__dirname}/docs/[family].css`
},
watch: {
pattern: `${__dirname}/assets/svg/**/*.svg`,
cwd: `${__dirname}/assets/svg`
},
cssTemplate: function(unicodes) {
return unicodes.unicodes.map((char)=>{
return `.icon.${char.name}:before{
content: '${char.unicode}';
}`;
}).concat(`
@font-face {
font-family: "icons";
src: url("${url('eot')}");
src: url("${url('iconfont.eot?#iefix')}") format("embedded-opentype"),
url("${url('iconfont.woff')}") format("woff"),
url("${url('iconfont.ttf')}") format("truetype"),
url("${url('iconfont.svg#iconfont')}") format("svg");
font-weight: normal;
font-style: normal;
}
.icon::before{
vertical-align: middle;
font-family: "icons"!important;
display: inline-block;
font-style: normal;
font-weight: normal;
font-variant: normal;
padding: 0 4px;
line-height: 1;
font-size: 18px;
text-decoration: inherit;
text-rendering: optimizeLegibility;
text-transform: none;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
}
`).join('\n');
}
});
};
let config = {
entry: isProd ? './demo.js' : [`webpack-dev-server/client?http://localhost:${devPort}`, './demo.js'],
devtool: 'cheap-module-source-map',
context: `${__dirname}/src`,
watchOptions: {
ignored: /node_modules/
},
resolve: {
modules: [
path.resolve('./components'),
path.resolve('./src'),
path.resolve('./scss'),
path.resolve('./node_modules'),
path.resolve('.')
],
moduleExtensions: ['-compat']
},
output: {
path: `${__dirname}/docs`,
filename: 'bundle.js',
library: 'gui'
},
module: {
rules: [
{
test: /\.scss$/,
loaders: ['style-loader', 'postcss-loader', 'sass-loader'],
exclude: /node_modules/,
include: [
path.resolve(__dirname, 'scss'),
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'components')
]
},
{
test: /\.css$/i,
sideEffects: true,
loaders: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
],
exclude: /node_modules/,
include: [
path.resolve(__dirname, 'scss'),
path.resolve(__dirname, 'components')
]
},
{test: /\.(js|jsx)$/,
include:[
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'components')
],
exclude: /node_modules(?!\/input-moment|lodash-compat|lodash)|lodash/,
loader: 'babel-loader',
query: {
presets: isProd ? ['react', 'es2015', 'stage-0'] : ['react', 'react-hmre', 'es2015', 'stage-0'],
plugins: ['transform-decorators-legacy']
}
},
{test: /\.(woff|woff2|eot|ttf)$/, loader: 'file-loader'},
{
test: /\.(jpg|png|gif|jpeg)$/,
loader: 'file-loader',
include: [path.resolve(__dirname, 'assets')]
},
]
},
// env conditional plugins for filesize, dashboard, etc.
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
ico(),
new EditFontPlugin()
]
};
if (!isProd){
config.devServer = {
contentBase: ['./', './docs'],
compress: true,
port: devPort,
public: `localhost:${devPort}`,
host: '0.0.0.0'
};
config.output.publicPath = `http://localhost:${devPort}/`;
}
module.exports = config;
<file_sep>/src/installation.js
export default `## deps
\`\`\`js
npm install --save-dev node-sass, style-loader, postcss-loader, sass-loader,
babel-loader, babel-preset-react, babel-preset-es2015, babel-preset-stage-0,
babel-plugin-transform-decorators-legacy
\`\`\`
## add loaders to your webpack config
\`\`\`
{
test: /\.scss$/,
loaders: ['style-loader', 'postcss-loader', 'sass-loader'],
exclude: /node_modules/,
include: [
path.resolve(__dirname, 'node_modules/ns1-gui/scss'),
path.resolve(__dirname, 'node_modules/ns1-gui/components')
]
},
{
test: /\.css$/i,
sideEffects: true,
loaders: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
],
exclude: /node_modules/,
include: [
path.resolve(__dirname, 'node_modules/ns1-gui/scss'),
path.resolve(__dirname, 'node_modules/ns1-gui/components')
]
},
{test: /\.(woff|woff2|eot|ttf)$/, loader: 'file-loader'},
{test: /\.(js|jsx)$/,
include:[
path.resolve(__dirname, 'node_modules/ns1-gui/scss'),
path.resolve(__dirname, 'node_modules/ns1-gui/components')
],
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['transform-decorators-legacy']
}
},
\`\`\`
## add fonts
in your html, include
\`\`\`
<link href='//fonts.googleapis.com/css?family=Montserrat:200,300,400,500,600|Open+Sans:300,600&subset=latin' rel='stylesheet' type='text/css'>
\`\`\`
# Usage
make a toplevel wrapper div with the class "theme-light",
then put all components in a div with the class 'bunder-container'
\`\`\`
import {Tabs, Tab} from 'ns1-gui';
<div className="theme-light">
<div className="bunder-container">
<Tabs ...props>
<Tab ...props>Some Content</Tab>
</Tabs>
<Modal ...props>
<Modal.Header ...props>
</Modal.Header>
</Modal>
</div>
</div>
\`\`\`
`;
<file_sep>/components/radio/radio.ex.md.js
export default `\`\`\`html
<Radio
label="Thing1"
checked={this.state.radio === 'thing1'}
name="first"
onChange={e => this.setState({radio: e.currentTarget.value})}
value="thing1" />
<Radio
label="Thing2"
checked={this.state.radio === 'thing2'}
name="second"
onChange={e => this.setState({radio: e.currentTarget.value})}
value="thing2" />
\`\`\`
`;
<file_sep>/components/tabs/index.js
import PropTypes from 'prop-types';
import React from 'react';
import './tabs.scss';
export class Tabs extends React.Component{
static propTypes = {
defaultActiveKey: PropTypes.number.isRequired,
activeKey: PropTypes.number,
onSelect: PropTypes.func.isRequired,
children: PropTypes.any,
tabClassName: PropTypes.string,
className: PropTypes.string
}
constructor(props) {
super(props);
}
render() {
const {onSelect, activeKey, className, children} = this.props;
return children && <div className={`tabs ${className || ''}`}>
<ul>
{//sorry sorry, needed for single tabs
(() => children.filter ? children : [children])()
.filter(d => d)
.map((c, idx) =>
<li
className={activeKey === idx && 'active' || ''}
key={idx}
onClick={() => onSelect &&
onSelect(idx, c.props.token)}>
<span className={`icon ${c.props.icon ? c.props.icon : ''}`} />
<span className='tab-label'>{c.props.label}</span></li>)}
</ul>
<div className={`tabs-body ${this.props.tabClassName || ''}`}>
{// it is dumb needed for single tabs sorry sorry
children.filter ?
children.filter(a => a)[typeof this.props.activeKey !== 'undefined' ?
this.props.activeKey :
this.props.defaultActiveKey] :
children}
</div>
</div>;
}
}
export class Tab extends React.Component{
static propTypes={
label: PropTypes.string.isRequired,
icon: PropTypes.string,
children: PropTypes.any,
className: PropTypes.string,
token: PropTypes.string
}
constructor(props) {
super(props);
}
render() {
return <div className={`tab ${this.props.className || ''}`}>
{this.props.children}
</div>;
}
}
export tabsMD from './tabs.md.js';
export tabsEX from './tabs.ex.md.js';
<file_sep>/components/pagination/pagination.ex.md.js
export default `\`\`\`html
<Pagination
next={true}
prev={true}
items={8}
maxButtons={5}
activePage={this.state.activePage || 0}
onSelect={i=>this.setState({activePage: i})} />
\`\`\`
`;
<file_sep>/components/tooltip/index.js
import PropTypes from 'prop-types';
import React from 'react';
import './tooltip.scss';
class TooltipComp extends React.Component{
static propTypes = {
/* eslint-disable react/no-deprecated */
content: PropTypes.string.isRequired,
direction: PropTypes.string,
children: PropTypes.any,
className: PropTypes.string,
style: PropTypes.object
}
render() {
const {children, content, direction, className} = this.props;
return <div className={`tooltip-wrapper ${className ?
className :
''}`}>
<div
style={this.props.style}
className={`tip ${direction}`}
dangerouslySetInnerHTML={{__html: content}} />
{children}
</div>;
}
}
export default TooltipComp;
export const Tooltip = TooltipComp;
export tooltipEX from './tooltip.ex.md.js';
export tooltipMD from './tooltip.md.js';
<file_sep>/components/loader/index.js
import React from 'react';
class LoaderComp extends React.Component{
render(){
return <div
className="loader">
<span className="loader-dot">.</span>
<span className="loader-dot">.</span>
<span className="loader-dot">.</span>
</div>;
}
}
export default LoaderComp;
export const Loader = LoaderComp;
export loaderMD from './loader.md.js';
export loaderEX from './loader.ex.md.js'
<file_sep>/components/tabs/tabs.ex.md.js
export default `\`\`\`html
<Tabs
defaultActiveKey={0}
activeKey={this.state.tabActive}
onSelect={idx => {
this.setState({tabActive: idx});
}}
className="interactive flex-whole">
<Tab
token={0}
className="minheight"
label="Demotab 1">
<BigLoader
warn={false}
warnText="Some warning."
loading={true}
loadingText="Demo Bigloader in tab"
noDatat={false}
noDataText="No Data" />
</Tab>
<Tab
token={1}
className="minheight"
label="Demotab 2">
<BigLoader
warn={true}
warnText="Demo warning in tab"
loading={false}
loadingText="This is loading explainer text"
noDatat={false}
noDataText="No data"
</Tab>
</Tabs>
\`\`\``;
<file_sep>/components/cleverbutton/index.js
import PropTypes from 'prop-types';
import React from 'react';
import Loader from '../loader';
class CleverButtonComp extends React.Component{
static propTypes = {
saved: PropTypes.bool,
saving: PropTypes.bool,
hot: PropTypes.bool,
disabled: PropTypes.bool,
classes: PropTypes.string,
text: PropTypes.string,
error: PropTypes.bool,
onClick: PropTypes.func,
role: PropTypes.string,
type: PropTypes.string
}
constructor(props) {
super(props);
}
render(){
const {
saved,
saving,
hot,
disabled,
classes,
text,
error,
onClick,
type,
} = this.props;
return <button
type={type || 'button'}
role={this.props.role}
onClick={onClick}
disabled={disabled}
className={['cleverbutton', 'button', (hot || saved) && !error ? 'primary' : 'secondary', classes].join(' ')}>
{saving && <Loader />}
{((!saving && !saved && !error) || (hot && !saving)) && (!error) && (text || 'Save All Changes')}
{saved && !hot &&
[
<span className="icon check" key={0}/>,
<span key={1}> Saved!</span>
]}
{!saving && error && <span className="icon closex"/>}
</button>;
}
}
export const CleverButton = CleverButtonComp;
export default CleverButton;
export cleverbuttonMD from './cleverbutton.md.js';
export cleverbuttonEX from './cleverbutton.ex.md.js';
<file_sep>/components/progressBar/progressBar.md.js
export default `show progress
- **label** *(string)* name of percentage bar
- **percent** *(int)* 0-100 completion
- **showValue** *(bool)* show or hide the number value
- **customValue** *(int)* override the percent value
`;
<file_sep>/components/dropdown/dropdown.ex.md.js
export default `\`\`\`html
<Dropdown
onSelect={e =>
this.setState({
dropdown: e.currentTarget.value
})}
className="flex-half"
label="Example Dropdown"
defaultValue="first"
value={this.state.dropdown}>
<MenuItem
value="first">First Item</MenuItem>
<MenuItem
value="second">Second Item</MenuItem>
</Dropdown>
\`\`\`
`;
<file_sep>/components/formTabs/formTabs.ex.md.js
export default `\`\`\`html
<div className="enclosure">
<FormTabs
headerLabel="Important Stuff: "
defaultActiveKey={0}
activeKey={this.state.formTabActive}
onSelect={idx => this.setState({formTabActive: idx})}>
<FormTab
label="Tab 1">
... put form elements here
</FormTab>
<FormTab
label="Tab 2">
... put more form elements here
</FormTab>
</FormTabs>
</div>
\`\`\`
`;
<file_sep>/components/text/text.ex.md.js
export default `\`\`\`html
<Text
onChange={e => {
this.setState({textExample: e.currentTarget.value});
}}
label="Sample text field"
value={this.state.textExample}
help="example help text."
pattern={{
pattern: val => val % 5 === 0,
message: 'Value should be divisible by 5'
}}
className="flex-half gutter-right" />
\`\`\``;
<file_sep>/components/checkbox/index.js
import PropTypes from 'prop-types';
import React from 'react';
import './checkbox.scss';
class CheckBoxComp extends React.Component{
static propTypes = {
/* eslint-disable react/no-deprecated */
label: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
checked: PropTypes.bool,
name: PropTypes.string,
id: PropTypes.string,
value: PropTypes.any,
disabled: PropTypes.bool,
className: PropTypes.string,
help: PropTypes.string
}
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onChange(e);
}
render() {
const {help, value, label, checked, name, className} =
this.props;
return <label id={this.props.id} className={`checkbox-label ${className} ${help && 'has-help'} flex-wrap vert-middle`}>
<input type="checkbox"
value={value}
checked={checked || false}
onChange={this.handleChange}
{...Object.keys(this.props).reduce((acc, prop)=>{
return prop.indexOf('data-') > -1 ?
Object.assign({}, acc, {[prop]: this.props[prop]}) :
acc;
}, {})}
name={name}
disabled={this.props.disabled} />
<span className={`icon flex-wrap vert-middle ${checked ? 'checkedbox' : 'checkbox' }
${this.props.disabled ? 'disabled' : ''}`}>
<span className="check" />
</span>
<span>{label}</span>
{help && <span className="help-text">{help}</span>}
</label>;
}
}
export const Checkbox = CheckBoxComp;
export default CheckBoxComp;
export checkboxMD from './checkbox.md';
export checkboxEX from './checkbox.ex.md';
<file_sep>/components/progressBar/progressBar.ex.md.js
export default `\`\`\`html
<ProgressBar
label='Progress'
percent={82}
showValue={true} />
\`\`\`
`;
<file_sep>/components/cleverbutton/cleverbutton.md.js
export default `- a button with a builtin loader
- **saved** *(bool)* optionally show "saved" state in button
- **saving** *(bool)* show internal loader instead of button label
- **hot** *(bool)* optionally add a class to make the button pink
- **disabled** *(bool)* disable passthrough attr
- **classes** *(string)* css class passthru
- **text** *(string)* button label text
- **error** *(bool)* show "X" if some async request errored
- **onClick** *(func)* action to perform on click
- **role** *(string)* role attr passthrough for use in form elements`;
<file_sep>/components/bigLoader/bigloader.ex.md.js
export default `\`\`\`html
<BigLoader
warn={false}
warnText="This would be showing if warning."
loading={true}
loadingText="This is loading explainer text"
noData={false}
noDataText="No data text." />
\`\`\`
`;
<file_sep>/components/cleverList/cleverList.ex.md.js
export default `\`\`\`html
<div style={{width: '100%'}}>
selected value: {this.state.cleverSelected.someKey}
<CleverList
formatting={i=>i.name}
onSelect={i=>this.setState({cleverSelected: i})}
interior={true}
itemsVisible={2}
pills={[
(i) => \`Demopill $\{i.someKey}\`
]}
items={[{
someKey: 'somevalue 1',
name: 'Example Item 1'
}, {
someKey: 'somevalue 2',
name: 'Example Item 2'
}, {
someKey: 'somevalue 3',
name: 'Example Item 3'
}]}
options={[
{
icon: 'alert',
name: 'Demo Action',
onClick: (i, index, selector) => selector(index) ||
window.alert(JSON.stringify(i))
},
{
icon: 'folder',
name: 'Demo Disabled',
disabled: e=>true,
onClick: (i, index, selector) => window.alert(JSON.stringify(i))
}
]}/>
</div>
\`\`\`
`;
<file_sep>/components/typeahead/index.js
import React from 'react';
import PropTypes from 'prop-types';
import Text from '../text';
import {TextMenu, MenuItem} from '../dropdown';
class TypeAheadComp extends React.Component{
static propTypes = {
value: PropTypes.array,
placeholder: PropTypes.string,
help: PropTypes.string,
onChange: PropTypes.func,
async: PropTypes.func,
options: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string.isRequired,
value: PropTypes.any
})),
multi: PropTypes.bool,
selected: PropTypes.array,
disabled: PropTypes.bool,
className: PropTypes.string,
selectedPosition: PropTypes.string,
disabledText: PropTypes.string,
parseVal: PropTypes.func,
onCancel: PropTypes.func,
icon: PropTypes.any
};
constructor(props){
super(props);
this.state = {
options: props.options || [],
searchVal: props.searchVal || '',
filteredOptions: [],
selected: props.value || [],
hideOptions: true
};
this.hideOptions = this.hideOptions.bind(this);
this.renderSelected = this.renderSelected.bind(this);
this.filter = this.filter.bind(this);
}
componentWillReceiveProps(nextProps){
if (nextProps.value !== this.state.selected){
this.setState({
selected: nextProps.value || []
});
}
if (nextProps.options !== this.state.options){
this.setState({options: nextProps.options});
}
// if(this.props.async){
// this.setState({options: nextProps.options})
// }
}
hideOptions(){
this.setState({hideOptions: true});
}
renderSelected(){
const {parseOpt, parseVal} = this.props;
return this.props.multi && <div className="selected">
{this.state.selected.map(select => {
return <span
className="small round blue pill gutter-right"
key={select}>
{select}
<span
onClick={() => {
this.setState({
selected: this.state.selected
.filter(item => item !== select)
});
setTimeout(() => {
this.props.onSelect(this.state.selected);
});
}}
className="closer">
<span className="icon closex" />
</span>
</span>;
})}
</div>;
}
filter(options){
const {parseOpt, parseVal} = this.props;
const {searchVal} = this.state;
const small = searchVal.toLowerCase();
return options ? options.filter(opt => {
const val = opt.value;
return parseOpt ?
this.props.searchLabelIndex ? opt.label.toLowerCase().includes(small) :
(parseOpt(opt).toLowerCase().indexOf(small) > -1 ||
(parseVal && val) && parseVal(val).toLowerCase().indexOf(small)) :
opt.label ? opt.label.toLowerCase().indexOf(small) > -1 ||
opt.value.toLowerCase().indexOf(small) > -1 :
typeof opt === 'string' ? opt.toLowerCase().indexOf(small) > 1 : false;
}) : [];
}
render(){
const {
help, parseOpt, disabled, disabledText, parseVal, multi
} = this.props;
return <div id={this.props.id || ''} className={`typeahead ${this.props.className || ''}`}>
{(!this.props.selectedPosition ||
this.props.selectedPosition === 'above') &&
this.props.selectedPosition !== false &&
this.props.multi &&
this.renderSelected()}
<div className="relative">
<Text
autoComp={false}
className={this.props.help ? this.props.className : `short ${this.props.className}`}
noValid={true}
help={help}
ref={ta => this.ta = ta}
passRef="typeahead"
disabled={this.props.disabled}
icon={typeof this.props.icon === 'undefined' ?
(this.state.searchVal &&
this.state.searchVal.length > 0) ?
'closex' :
'search' :
false}
onKeyDown={e => e.stopPropagation()}
onCancel={this.props.onCancel ? () => {
if (this.props.onCancel){
this.props.onCancel();
}
this.setState({
searchVal: '',
filteredOptions: [],
selected: []
});
} : false}
onFocus={() =>
this.setState({hideOptions: false})
}
onBlur={() => !this.state.eatEvent &&
this.setState({
hideOptions: true,
searchVal: ''
})}
value={multi || !this.state.hideOptions ? this.state.searchVal : this.props.value}
label={this.props.label}
onChange={(e, val) => {
this.setState({searchVal: e.currentTarget.value});
if (this.props.async){
const asynced = this.props.async(e.currentTarget.value);
if (asynced && asynced.then){
asynced
.then(vals => {
this.setState({options: vals || []});
})
.catch(e => {
console.log('catch', e);
});
}
}
if (e.currentTarget.value.length === 0){
this.setState({hideOptions: true});
} else if (this.state.hideOptions){
this.setState({hideOptions: false});
}
}}
placeholder={disabled && disabledText ?
disabledText :
this.props.placeholder} />
{!multi &&
this.state.options &&
this.state.options.length > 0 &&
!this.state.hideOptions &&
<ul
onMouseLeave={() => this.setState({hideOptions: true})}
className="options dd-menu opened">
{this.props.async && <li
onClick={() => this.setState({
options: [],
searchVal: '',
hideOptions: true
})}>Clear results</li>}
{this.state.options.filter(a => this.props.async ?
a :
a.label.toLowerCase().indexOf(this.state.searchVal.toLowerCase()) > -1)
.map((val, idx) =>
<li
key={idx}
onMouseDown={() => this.setState({eatEvent: true})}
onMouseUp={() => {
this.setState({
selected: val,
eatEvent: false,
hideOptions: true,
searchVal: ''
});
setTimeout(() =>
this.props.onSelect &&
this.props.onSelect(this.state.selected), 0);
}}>
{parseOpt ?
parseOpt(val) :
val.label ?
val.label :
val}
</li>
)}
</ul>}
{multi &&
this.state.options && this.state.options.length > 0 &&
<TextMenu
onMouseDown={() => {
this.setState({eatEvent: true});
}}
onSelect={(e, val) => {
this.ta.typeahead.focus();
this.setState({
selected: [...new Set(this.state.selected.indexOf(val.value ? val.value : val) > -1 ?
this.state.selected.filter(v => v !== (val.value ? val.value : val)) :
this.state.selected.concat([val.value ? val.value : val]))]
});
setTimeout(() =>
this.props.onSelect &&
this.props.onSelect(this.state.selected), 0);
this.setState({eatEvent: false});
}}
force={!this.state.hideOptions}
multiselect={true}
hideButton={true}>
{this.filter(this.state.options).map((o, i) => {
const val = parseVal ?
parseVal(o) :
o.value ?
o.value :
o;
const label = parseOpt ?
parseOpt(o) :
o.label ?
o.label :
o;
return <MenuItem
key={i}
checked={this.state.selected.indexOf(val) > -1}
value={val}>
{label}
</MenuItem>;
})}
</TextMenu>}
</div>
{this.props.selectedPosition === 'below' &&
this.props.multi &&
this.renderSelected()}
</div>;
}
}
export default TypeAheadComp;
export const TypeAhead = TypeAheadComp;
export typeaheadEX from './typeahead.ex.md.js';
export typeaheadMD from './typeahead.md.js';
| e0d326d87eb861fbbf654a7c09db3af34f7bb5d1 | [
"JavaScript"
] | 41 | JavaScript | ns1/ns1-gui | b9875203c29fa80cfc817acd325a3141c457240e | ab9bebccd4a2c1227c8db7f6af16919d09cfb1ec | |
refs/heads/master | <file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore/QDebug>
#include <QScrollBar>
#include <QtSerialPort/QSerialPortInfo>
#include <QtSerialPort/QSerialPort>
QT_USE_NAMESPACE
QSerialPortInfo port[100];
#define BAUD_RATE 9600
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort(this);
ui->comboBox->clear();
int i = 0;
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
ui->comboBox->addItem(""+ info.portName());
port[i++] = info;
}
//Test GitHub
connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::portConnect()
{
if(ui->butConnect->text().startsWith("Connect"))
{
serial->setPort(port[ui->comboBox->currentIndex()]);
serial->open(QIODevice::ReadWrite);
serial->setBaudRate(BAUD_RATE);
ui->butConnect->setText("Close");
} else
{
serial->close();
ui->butConnect->setText("Connect");
}
}
void MainWindow::readData()
{
QByteArray data = serial->readAll();
QString old_data = ui->textEdit->toPlainText();
ui->textEdit->setText(old_data+data);
ui->textEdit->verticalScrollBar()->setValue(ui->textEdit->verticalScrollBar()->maximum());
}
<file_sep>QtSerial
========
Qt interface for SerialPort Communication.
| d7a07ef3816d73ae45c00273293b625568c13a52 | [
"Markdown",
"C++"
] | 2 | C++ | alejandrorosas/QtSerial | 4b9a3be6875a5eb53f046a3a4bdcd51b99633e48 | aa54be5bdec0cc1dbb141f5a93778ea954f11b9a | |
refs/heads/master | <file_sep>#ifndef CANDIDAT_H_INCLUDED
#define CANDIDAT_H_INCLUDED
#define NBR_NOTES 10
#define MAX_BYTES 500
#define NBR_MAX_CANDIDATS 5000
typedef enum {admis,ajourne,refuse} decision;
typedef struct
{
unsigned int NCIN;
char NOM[50];
char PRENOM[50];
unsigned int AGE;
float NOTES[NBR_NOTES];
decision DECISION;
}candidat;
#endif // CANDIDAT_H_INCLUDED}*
<file_sep>#ifndef FONCTION_H_INCLUDED
#define FONCTION_H_INCLUDED
int saisir();
void ajouter();
int Admis();
void modifier();
void supprimer(const unsigned int NCIN);
int attente();
void securite_NCIN(unsigned int *NCIN);
void securite_NP(char *Name ,char *text);
void securite_AGE(int *AGE);
void securite_NOTE(float *NOTE ,int indice);
void securite_choix(char *choix ,char *question);
float statistiques(decision dec);
candidat recuperation(char *ligne);
int valid(char *chaine ,int option);
int exist(const unsigned int NCIN_a_rchr ,const char *file_name);
int is_Already_In(candidat *tab_Cd, int t, int NCIN);
void warning(char *texte);
float average(candidat *edit_cd);
int all_grades_gt_10(const float *grades);
char *dec_to_varchar(decision dec);
void lire(char *tab);
void viderBuffer();
int Supprimer();
int affiche_merite();
int recherche(unsigned int NCIN);
void color(int t ,int f);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include "candidat.h"
#include "fonction.h"
//ici on écri une fonction qui nous permettra d'entrer les differentes informations concernant chaque candidat et pour celà, on prend en paramètre un tableau de candidats ainsi que le nombre de ces derniers
int exist(const unsigned int NCIN_a_rchr ,const char *file_name)
{
int state = 0;
char chaine_lecture[MAX_BYTES] = "";
FILE *f_rchr = NULL;
candidat candidat_lu;
f_rchr = fopen(file_name ,"r");
if(f_rchr == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
exit(0);
}
rewind(f_rchr);
while(fgets(chaine_lecture ,MAX_BYTES ,f_rchr) != NULL)
{
candidat_lu = recuperation(chaine_lecture);
if(candidat_lu.NCIN == NCIN_a_rchr)
state = 1;
}
fclose(f_rchr);
return state;
}
int is_Already_In(candidat *tab_Cd, int t, int NCIN)
{
int i = 0;
while(i<t && tab_Cd[i].NCIN != NCIN)
i++;
if(i == t)
return 0;
else
return 1;
}
int saisir()
{
unsigned int nbr_admis = 0 ,nb_candidats = 1;
/*
On fait une allocation dynamique
Afin d'avoir une taille de tableau égale aux nombre de candidats entré par l'utilisateur
*/
candidat *TAB = NULL;
int i = 0;
char nbr_candidats_char[7] = "100";
system("CLS");
do
{
printf("Entrez le nombre de candidats > ");
lire(nbr_candidats_char);
if(!valid(nbr_candidats_char ,5))
warning("\n\n\tVeuillez saisir un nombre valide !\n\n");
}while(!valid(nbr_candidats_char ,5));
TAB = malloc(sizeof(candidat)*nb_candidats);
FILE *fichier = NULL;
fichier=fopen("concours.txt","w");
//ici on ouvre le fichier crée en utilisant tout simplement la syntaxe approprié le fichier a été crée juste au dessus du commentaire précédent
for(i=0;i<nb_candidats;i++) //ici on parcours le tableau de candidats pour pouvoir entrer les donner correspondantes pour chacun d'eux ces données sont indiquées dans le bloc suivant
{
system("CLS");
printf("\t\t\tREMPLISSAGE DES DONNEES RELATIVES\n\n --------------------- AU(X) CANDIDAT(S) DE L'EXAMEN --------------------\n\n");
printf("\n\t\tCANDIDAT NUMERO %u\n" ,i+1);
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
do
{
printf("\tEntrer le Numero de CNI > ");
securite_NCIN(&TAB[i].NCIN);
if(is_Already_In(TAB ,i ,TAB[i].NCIN))
{
warning("\n\t(Attention !!!! Identifiant unique)\n");
printf("Vous avez deja saisi ce Numero de CNI\n\n");
}
}while(is_Already_In(TAB ,i ,TAB[i].NCIN));
printf("\tEntrer le Nom > ");
securite_NP(TAB[i].NOM ,"Nom");
printf("\tEntrer le Prenom > ");
securite_NP(TAB[i].PRENOM ,"Prenom");
printf("\tEntrer l'Age > ");
securite_AGE(&TAB[i].AGE);
printf("\tEntrer les Notes > \n");
//ici on entre les notes des differntes matières puisqu'il s'agit d'un tableau de 10 notes mais nous avons voulu globalisé en definissant NBR_NOTES dans le tout début de notre code_source ce qui fait qu'en entrant un nombre de notes quelconque on ne pourra remplir que ce nombre là sans toutefois déborder
for(int j=0; j<NBR_NOTES; j++)
{
printf("\t\tEntrer la note %d > " ,j+1);
securite_NOTE(&TAB[i].NOTES[j] ,j);
}
printf(" \tLa MOYENNE est : %2.2f/20\n" ,average(&TAB[i]));
printf(" \tDECISION : %s\n\n" ,dec_to_varchar(TAB[i].DECISION));
//ici si le fichier s'est bien ouvert, on aura la possiblité d'ajouter les differentes informations d'un candidat en respectant ce qu'a dit le projet chaque information doit etre séparé de l'autre par le point virgule et pour pouvoir ajouter on a utilisé la fontion fprintf en respectant la syntaxe
if(TAB[i].DECISION == admis)
nbr_admis++;
fprintf(fichier ,"%d;%s;%s;%d;" ,TAB[i].NCIN ,TAB[i].NOM ,TAB[i].PRENOM ,TAB[i].AGE);
for(int j = 0;j<NBR_NOTES ;j++)
fprintf(fichier ,"%2.2f;" ,TAB[i].NOTES[j]);
fprintf(fichier ,"%d\n" ,TAB[i].DECISION);
if(i != nb_candidats - 1)
system("pause");
else
{
color(8 ,0);
printf("\n\tLES %u CANDIDATS ONT ETE ENREGISTRES AVEC SUCCES !\n\n" ,nb_candidats);
color(7 ,0);
system("pause");
}
}
fclose(fichier);
return nbr_admis;
}
int Admis()
{
system("CLS");
FILE *fichier1 = NULL;
FILE *fichier2 = NULL;
fichier1 = fopen("admis.txt","w");
candidat cd_recuperation;
char chaine[MAX_BYTES] = "";
int nbr_admis = 0;
if((fichier2 = fopen("concours.txt","r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
exit(0);
}
printf("\t\t\t ECRITURE DES CANDIDATS ADMIS\n\n\t--------------------- DU CONCOURS --------------------\n\n");
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
while(fgets(chaine,MAX_BYTES,fichier2) != NULL)
{
cd_recuperation = recuperation(chaine);
if(cd_recuperation.DECISION == admis)
{
nbr_admis++;
fprintf(fichier1 ,"%u;%s;%s;%d;" ,cd_recuperation.NCIN ,cd_recuperation.NOM ,cd_recuperation.PRENOM ,cd_recuperation.AGE);
for(int j = 0;j<NBR_NOTES ;j++)
fprintf(fichier1 ,"%2.2f;" ,cd_recuperation.NOTES[j]);
fprintf(fichier1 ,"%d\n" ,cd_recuperation.DECISION);
}
}
fclose(fichier2);
fclose(fichier1);
color(11 ,0);
printf("\n\n\t%u CANDIDATS AYANT ETE RETENUS DANS LE CONCOURS\n\n" ,nbr_admis);
color(7 ,0);
system("PAUSE");
return nbr_admis;
}
// Procédure ajouter() ,permettant d'ajouter des donnees relatives à un candidat.
void ajouter()
{
/*
On fait une allocation dynamique
Afin d'avoir une taille de tableau égale aux nombre de candidats entré par l'utilisateur
*/
char continuer_ajouter[] = "N" ,NCIN_char[10] = "" ,AGE_char[3] = "" ,NOTE_char[3] = "";
do
{
system("CLS");
candidat cd_ajout;
FILE *fichier = NULL;
fichier = fopen("concours.txt" ,"a");
//ici on ouvre le fichier crée en utilisant tout simplement la syntaxe approprié le fichier a été crée juste au dessus du commentaire précédent
color(3 ,0);
printf("\n\t\t\xDB \xDB \xDB \xDB \xDB\xDB \xDB \xDB \xDB \xDB\xDB \xDB \xDB \xDB \xDB\xDB \xDB \xDB \xDB \xDB\xDB \xDB \xDB \xDB \xDB\n\n");
color(7 ,0);
printf("________________________________________________________________________________\n\t\tEntrer les donnees relatives du candidat a ajouter\n________________________________________________________________________________\n\n");
do
{
printf("\tEntrer le Numero de CNI > ");
securite_NCIN(&cd_ajout.NCIN);
if(exist(cd_ajout.NCIN ,"concours.txt"))
warning("\n\t(Un candidat possede deja ce Numero de CNI)\n");
}while(exist(cd_ajout.NCIN ,"concours.txt"));
printf("\tEntrer le Nom > ");
securite_NP(cd_ajout.NOM ,"Nom");
printf("\tEntrer le Prenom > ");
securite_NP(cd_ajout.PRENOM ,"Prenom");
printf("\tEntrer l'Age > ");
securite_AGE(&cd_ajout.AGE);
printf("\tEntrer les Notes > \n");
//ici on entre les notes des differntes matières puisqu'il s'agit d'un tableau de 10 notes mais nous avons voulu globalisé en definissant NBR_NOTES dans le tout début de notre code_source ce qui fait qu'en entrant un nombre de notes quelconque on ne pourra remplir que ce nombre là sans toutefois déborder
for(int j=0; j<NBR_NOTES; j++)
{
printf("\t\tEntrer la note %d > " ,j+1);
securite_NOTE(&cd_ajout.NOTES[j] ,j);
}
printf(" La Moyenne est : %2.2f\n" ,average(&cd_ajout));
printf(" DECISION : %s\n" ,dec_to_varchar(cd_ajout.DECISION));
//ici si le fichier s'est bien ouvert, on aura la possiblité d'ajouter les differentes informations d'un candidat en respectant ce qu'a dit le projet chaque information doit etre séparé de l'autre par le point virgule et pour pouvoir ajouter on a utilisé la fontion fprintf en respectant la syntaxe
fprintf(fichier ,"%d;%s;%s;%d;" ,cd_ajout.NCIN ,cd_ajout.NOM ,cd_ajout.PRENOM ,cd_ajout.AGE);
for(int j = 0;j<NBR_NOTES ;j++)
fprintf(fichier ,"%2.2f;" ,cd_ajout.NOTES[j]);
fprintf(fichier ,"%d\n" ,cd_ajout.DECISION);
fclose(fichier);
printf("\n\nVoulez - vous continuer a ajouter ? (O/N) > ");
securite_choix(continuer_ajouter ,"\n\nVoulez - vous continuer a ajouter?(O/N) > ");
}while(strcmp(strupr(continuer_ajouter) ,"O") == 0);
}
void modifier()
{
system("CLS");
FILE *f_modifier = NULL;
FILE *f_modifier_admis_tmp = NULL;
FILE *f_modifier_attente_tmp = NULL;
FILE *f_lecture = NULL;
FILE *f_lecture_admis = NULL;
FILE *f_lecture_attente = NULL;
unsigned int id = 0;
char chaine[MAX_BYTES] ,choix[] = "N";
candidat cd_modifier;
printf("Entrez le numero de CNI du candidat a modifier > ");
securite_NCIN(&id);
system("CLS");
f_modifier = fopen("concours_new.txt" ,"w");
f_modifier_admis_tmp = fopen("admis_new.txt" ,"w");
f_modifier_attente_tmp = fopen("attente_new.txt" ,"w");
if((f_lecture = fopen("concours.txt" ,"r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
goto cancel;
}
if((f_lecture_admis = fopen("admis.txt" ,"r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
goto cancel2;
}
if((f_lecture_attente = fopen("attente.txt" ,"r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
goto cancel1;
}
printf("\t\t\t MODIFICATION DES INFORAMATIONS\n\n\t--------------------- D'UN CANDIDAT --------------------\n\n");
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
while(fgets(chaine ,MAX_BYTES ,f_lecture) != NULL)
{
cd_modifier = recuperation(chaine);
// Si le Numero de CNI correspond on modifie selon le choix de l' utilisateur !
if(cd_modifier.NCIN == id)
{
printf("Vous allez modifier les donnees du candidat ");
color(15 ,0);
printf("%s %s\n" ,cd_modifier.NOM ,cd_modifier.PRENOM);
color(3 ,0);
printf("\nDonnees Actuelles :\n\n");
printf("\t\t>> Numero de CNI : %u\n" ,cd_modifier.NCIN);
printf("\t\t>> Nom : %s\n" ,cd_modifier.NOM);
printf("\t\t>> Prenom : %s\n" ,cd_modifier.PRENOM);
printf("\t\t>> Age : %d\n" ,cd_modifier.AGE);
for(int i = 0; i<NBR_NOTES ;i++)
printf("\t\t>> %de Note : %.2f\n" ,i+1 ,cd_modifier.NOTES[i]);
color(7 ,0);
printf("\n\tModifier le 'Numero' de CNI ? (O/N) >\t");
securite_choix(choix ,"\n\tModifier le 'Numero' de CNI ? (O/N) >\t");
if(strcmp(strupr(choix) ,"O") == 0)
{
printf("\tNOUVEAU NUMERO DE CNI > ");
securite_NCIN(&cd_modifier.NCIN);
}
printf("\tModifier le 'Nom' de %s ? (O/N) >\t" ,cd_modifier.NOM);
securite_choix(choix ,"\tModifier le 'Nom' de %s ? (O/N) >\t");
if(strcmp(strupr(choix) ,"O") == 0)
{
printf("\tNOUVEAU NOM > ");
securite_NP(cd_modifier.NOM ,"\tNouveau nom > ");
}
printf("\tVoulez - vous editer le 'Prenom' de %s ? (O/N) >\t" ,cd_modifier.NOM);
securite_choix(choix ,"\tVoulez - vous editer le 'Prenom' de %s ? (O/N) >\t");
if(strcmp(strupr(choix) ,"O") == 0)
{
printf("\tNOUVEAU PRENOM > ");
securite_NP(cd_modifier.PRENOM ,"\tNouveau prenom > ");
}
printf("\tEditer l'Age de %s ? (O/N) >\t",cd_modifier.NOM);
securite_choix(choix ,"\tEditer l'Age de %s ? (O/N) >\t");
if(strcmp(strupr(choix) ,"O") == 0)
{
printf("\tNOUVEL AGE > ");
securite_AGE(&cd_modifier.AGE);
}
printf("\tVoulez - vous modifier les 'Notes' de %s ? (O/N) >\t" ,cd_modifier.NOM);
securite_choix(choix ,"\tVoulez - vous modifier les 'Notes' de %s ? (O/N) >\t");
if(strcmp(strupr(choix) ,"O") == 0)
{
//ici on entre les notes des differntes matières puisqu'il s'agit d'un tableau de 10 notes mais nous avons voulu globalisé en definissant NBR_NOTES dans le tout début de notre code_source ce qui fait qu'en entrant un nombre de notes quelconque on ne pourra remplir que ce nombre là sans toutefois déborder
for(int j=0; j<NBR_NOTES; j++)
{
printf("\t\tNote de la %de matiere > " ,j+1);
securite_NOTE(&cd_modifier.NOTES[j] ,j);
}
average(&cd_modifier);
}
color(11 ,0);
printf("\n\n\tMODIFICATION(S) EFFECTUEE(S) AVEC SUCCES !\n\n");
color(7 ,0);
}
fprintf(f_modifier ,"%u;%s;%s;%d;" ,cd_modifier.NCIN ,cd_modifier.NOM ,cd_modifier.PRENOM ,cd_modifier.AGE);
for(int j = 0;j<NBR_NOTES ;j++)
fprintf(f_modifier ,"%.2f;" ,cd_modifier.NOTES[j]);
fprintf(f_modifier ,"%d\n" ,cd_modifier.DECISION);
if(exist(id ,"admis.txt"))
{
}
while(fgets(chaine ,MAX_BYTES ,f_lecture_admis) != NULL)
{
cd_modifier = recuperation(chaine);
}
}
if(!exist(id ,"concours.txt"))
warning("\n\tNUMERO DE CNI INEXISTANT !\n\n");
fclose(f_lecture);
remove("concours.txt");
fclose(f_lecture_admis);
remove("admis.txt");
fclose(f_lecture_attente);
remove("attente.txt");
cancel:
fclose(f_modifier);
rename("concours_new.txt" ,"concours.txt");
cancel1:
fclose(f_modifier_attente_tmp);
rename("attente_new.txt" ,"attente.txt");
cancel2:
fclose(f_modifier_admis_tmp);
rename("admis_new.txt" ,"admis.txt");
system("PAUSE");
}
void supprimer(const unsigned int NCIN)
{
system("CLS");
FILE *f_supprimer = NULL;
FILE *f_lecture = NULL;
char chaine[MAX_BYTES] ,choix[] = "N";
int candidat_ok = 0 ,candidat_existant = 0;
candidat cd_supprimer;
f_supprimer = fopen("concours_new.txt" ,"w");
if((f_lecture = fopen("concours.txt" ,"r+")) == NULL)
{
char text[100] = "";
sprintf(text ,"Impossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
goto cancel;
}
printf("\t\t\t SUPPRESSION D'UN CANDIDAT\n\n\t--------------------- DU CONCOURS --------------------\n\n");
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
while(fgets(chaine ,MAX_BYTES ,f_lecture) != NULL)
{
cd_supprimer = recuperation(chaine);
// Si le Numero de CNI correspond on modifie selon le choix de l' utilisateur !
if(cd_supprimer.NCIN == NCIN)
{
candidat_existant = 1;
printf("Vous allez retirer les donnees du candidat '%s %s' d'identificatif '%u'\n\n\t" ,cd_supprimer.NOM ,cd_supprimer.PRENOM ,cd_supprimer.NCIN);
warning("(Attention : Vous ne pourrez plus recuperer les donnees de ce candidat une fois supprime!)\n");
printf("\tConfirmez - vous cette action ? (O/N) >\t");
securite_choix(choix ,"\tConfirmez - vous cette action ? (O/N) >\t");
if(strcmp(strupr(choix) ,"O") == 0)
candidat_ok = 1;
}
if((cd_supprimer.NCIN == NCIN && !candidat_ok) || cd_supprimer.NCIN != NCIN)
{
fprintf(f_supprimer ,"%u;%s;%s;%d;" ,cd_supprimer.NCIN ,cd_supprimer.NOM ,cd_supprimer.PRENOM ,cd_supprimer.AGE);
for(int j = 0;j<NBR_NOTES ;j++)
fprintf(f_supprimer ,"%2.2f;" ,cd_supprimer.NOTES[j]);
fprintf(f_supprimer ,"%d\n" ,cd_supprimer.DECISION);
}
}
if(candidat_existant && candidat_ok)
{
color(11 ,0);
printf("\n\tSUPPRESSION DU CANDIDAT EFFECTUEE AVEC SUCCES !\n\n");
color(7 ,0);
}
else if(!candidat_existant)
{
warning("\n\tIL N'EXISTE AUCUN CANDIDAT DE CE NUMERO CNI!\n\n");
char text[100] = "" ,vide = 1;
sprintf(text ,"\nLe candidat au numero de CNI \"%u\" n'existe pas !\n" ,NCIN);
warning(text);
printf("\nVoulez - vous consulter l'ensemble des numeros de CNI existants ?(O/N) > ");
securite_choix(choix ,"\nVoulez - vous consulter l'ensemble des numeros de CNI existants ?(O/N) > ");
if(strcmp(strupr(choix) ,"O") == 0)
{
rewind(f_lecture);
printf("\n");
while(fgets(chaine,MAX_BYTES,f_lecture) != NULL)
{
vide = 0;
cd_supprimer = recuperation(chaine);
printf("[%d]\t" ,cd_supprimer.NCIN);
}
if(vide)
warning("\n\tAucun candidat enregistre !\n\n\t");
}
else
printf("\nD'accord !\n");
}
else
printf("\n\tSUPPRESSION ANNULEE!\n\n");
fclose(f_lecture);
remove("concours.txt");
cancel:
fclose(f_supprimer);
rename("concours_new.txt" ,"concours.txt");
}
int valid(char *chaine ,int option)
{
if(option == 1)
{
if(strlen(chaine) > 9)
return 0;
int items_in_array = 0;
char caracteres_autorises[] = "0123456789";
for(int j = 0; j<9 ;j++)
{
for(int k = 0; k<10 ;k++)
{
if(chaine[j] == caracteres_autorises[k])
{
items_in_array++;
break;
}
}
}
if(items_in_array == 9)
return 1;
else
return 0;
}
else if(option == 2)
{
for(int j = 0 ;j<strlen(chaine) ;j++)
{
if((chaine[j] < 65 || chaine[j] > 91) && (chaine[j] < 97 || chaine[j] > 123 || strlen(chaine) < 3 || strlen(chaine) > 49))
return 0;
}
return 1;
}
else if(option == 3)
{
if((atoi(chaine) < 13 || atoi(chaine) > 35))
return 0;
else
return 1;
}
else if(option == 4)
{
char caracteres_autorises[] = "0123456789.";
for(int j = 0; j<strlen(chaine) ;j++)
{
if(!strrchr(caracteres_autorises ,chaine[j]) || (atof(chaine) < 0 || atof(chaine) > 20))
return 0;
}
return 1;
}
else if(option == 5)
{
if((atoi(chaine) < 1 || atoi(chaine) > NBR_MAX_CANDIDATS))
return 0;
else
return 1;
}
}
void securite_choix(char *choix ,char *question)
{
do
{
lire(choix);
if(strcmp(strupr(choix) ,"O") != 0 && strcmp(strupr(choix) ,"N") != 0)
{
warning("\n\n\tEntrez un caractere valide !\n");
printf("%s" ,question);
}
}while(strcmp(strupr(choix) ,"O") != 0 && strcmp(strupr(choix) ,"N") != 0);
}
void securite_NCIN(unsigned int *NCIN)
{
char NCIN_char[15] = "";
do
{
lire(NCIN_char);
if(!valid(NCIN_char ,1))
{
warning("\n\n\tNumero de CNI Invalide(ne doit contenir que 9 chiffres de 0 a 9) !\n\n");
printf("\tEntrer le Numero de CNI > ");
}
}while(!valid(NCIN_char ,1));
*NCIN = atoi(NCIN_char);
}
void securite_NP(char *Name ,char *text)
{
char format_t[100] = "";
sprintf(format_t ,"\n\tVeuillez saisir un %s valide(Uniquement des lettres ,min 3 lettres et max 49 lettres)\n\n" ,text);
do
{
lire(Name);
if(!valid(Name ,2) && !valid(Name ,49))
{
warning(format_t);
printf("\tEntrer le %s > " ,text);
}
}while(!valid(Name ,2) && !valid(Name ,49));
}
void securite_AGE(int *AGE)
{
char AGE_char[3] = "";
do
{
lire(AGE_char);
if(!valid(AGE_char ,3))
{
warning("\n\tVeuillez saisir un age valide(Uniquement des chiffres et entre 13 et 35)\n\n");
printf("\tEntrer l'Age > ");
}
}while(!valid(AGE_char ,3));
*AGE = atoi(AGE_char);
}
void securite_NOTE(float *NOTE ,int indice)
{
char NOTE_char[3] = "";
do
{
lire(NOTE_char);
if(!valid(NOTE_char ,4))
{
warning("\n\tVeuillez saisir des notes valides\n\n");
printf("\t\tEntrer la note %d > " ,indice+1);
}
}while(!valid(NOTE_char ,4));
*NOTE = atof(NOTE_char);
}
candidat recuperation(char *ligne)
{
candidat donnees_candidat;
unsigned int cpt = 0;
char *jeton = NULL;
jeton = strtok(ligne ,";");
while(jeton != NULL)
{
if(cpt == 0)
donnees_candidat.NCIN = atoi(jeton);
else if(cpt == 1)
strcpy(donnees_candidat.NOM ,jeton);
else if(cpt == 2)
strcpy(donnees_candidat.PRENOM ,jeton);
else if(cpt == 3)
donnees_candidat.AGE = atoi(jeton);
else if(cpt == 4)
{
for(int j = 0; j<NBR_NOTES ;j++)
{
donnees_candidat.NOTES[j] = atof(jeton);
jeton = strtok(NULL ,";");
}
donnees_candidat.DECISION = atoi(jeton);
}
cpt++;
jeton = strtok(NULL ,";");
}
return donnees_candidat;
}
float average(candidat *cd_modifier)
{
float moy_candidat = 0.0;
for(int j=0; j<NBR_NOTES; j++)
moy_candidat += cd_modifier->NOTES[j]/(float)NBR_NOTES;
//ici, si le nombre de notes est bien supérieure ou egale à 10, notre variable nbr_notes_gt_10 prend bien evidemment la valeur 10 et dans ce cas si la moyenne est également supérieure ou égale à 10 on dira tout simplement que le candidat en question est admis pour son concours au fure et à mesure on continu aà verifier les autres cas éventuels comme l'a indiqué le projet et à la fin pour rendre le verdict plus claire chez le candidat on affiche sa moyenne
if(moy_candidat>=10.0 && all_grades_gt_10(cd_modifier->NOTES))
cd_modifier->DECISION = admis;
else if(moy_candidat>=10.0 && !all_grades_gt_10(cd_modifier->NOTES))
cd_modifier->DECISION = ajourne;
else
cd_modifier->DECISION = refuse;
return moy_candidat;
}
int all_grades_gt_10(const float *grades)
{
unsigned int i = 0;
for(i = 0 ;i<NBR_NOTES ;i++)
{
if(grades[i]<10.0)
return 0;
}
return 1;
}
void viderBuffer()
{
char c = 0;
while(c != '\n' && c != EOF)
c = getchar();
}
void lire(char *tab)
{
fgets(tab ,200 ,stdin);
int j = 0;
while(tab[j] != '\n')
j++;
tab[j] = '\0';
}
int attente()
{
system("CLS");
FILE *fichier = NULL;
FILE *fichen = NULL;
fichier = fopen("attente.txt","w");
candidat cd_attente;
int nbr_attente = 0;
char chaine[MAX_BYTES];
if((fichen = fopen("admis.txt","r+")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
exit(0);
}
printf("\t\t\tMISE EN ATTENTE DES CANDIDATS AGES\n\n\t--------------------- DE PLUS DE 20 ANS --------------------\n\n");
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
while(fgets(chaine,MAX_BYTES,fichen) != NULL)
{
cd_attente = recuperation(chaine);
if(cd_attente.AGE>20)
{
fprintf(fichier,"%u;%s;%s\n",cd_attente.NCIN,cd_attente.NOM,cd_attente.PRENOM);
nbr_attente++;
}
}
fclose(fichen);
fclose(fichier);
color(11 ,0);
printf("\n\n\t%u CANDIDATS DONT L'AGE EST SUPERIEURE A 20 ONT ETE MIS EN ATTENTE\n\n" ,nbr_attente);
color(7 ,0);
system("PAUSE");
return 0;
}
float statistiques(decision dec)
{
float nb_admis = 0., nb_ajourne = 0., nb_refuse = 0.;
unsigned int nb_candidats = 0;
char chaine[MAX_BYTES] = "";
candidat cd_recuperation;
FILE *fichier = NULL;
if((fichier = fopen("concours.txt","r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
exit(0);
}
while(fgets(chaine,MAX_BYTES,fichier) != NULL)
{
cd_recuperation = recuperation(chaine);
if (cd_recuperation.DECISION == admis)
nb_admis++;
else if(cd_recuperation.DECISION == ajourne)
nb_ajourne++;
else
nb_refuse++;
}
nb_candidats = nb_admis + nb_ajourne + nb_refuse;
if(!nb_candidats)
return 0.0;
switch(dec)
{
case admis:
return (nb_admis/nb_candidats)*100;
break;
case ajourne:
return (nb_ajourne/nb_candidats)*100;
break;
case refuse:
return (nb_refuse/nb_candidats)*100;
break;
default:
return 0.0;
break;
}
}
int Supprimer()
{
system("CLS");
FILE *fichier1 = NULL;
FILE *fichier2 = NULL ;
fichier2 = fopen("admis_new.txt","w");
candidat cd_age_supp_20;
char chaine[MAX_BYTES];
int nbr_supr = 0;
if ((fichier1 = fopen("admis.txt","r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
goto cancel;
}
printf("\t\t\t SUPPRESSION DES ADMIS LES\n\n\t--------------------- PLUS DE 20 ANS --------------------\n\n");
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
while(fgets(chaine,MAX_BYTES,fichier1) != NULL)
{
cd_age_supp_20 = recuperation(chaine);
// Si le Numero de CNI correspond on modifie selon le choix de l' utilisateur !
if(cd_age_supp_20.AGE<=20)
{
fprintf(fichier2,"%u;%s;%s;%d;" ,cd_age_supp_20.NCIN ,cd_age_supp_20.NOM ,cd_age_supp_20.PRENOM ,cd_age_supp_20.AGE);
for(int j = 0;j<NBR_NOTES ;j++)
fprintf(fichier2 ,"%2.2f;" ,cd_age_supp_20.NOTES[j]);
fprintf(fichier2 ,"%d\n" ,cd_age_supp_20.DECISION);
}
else
nbr_supr++;
}
color(11 ,0);
printf("\n\n\t%u CANDIDATS AGES DE PLUS DE 20 ANS ONT ETE SUPPRIMES !\n\n" ,nbr_supr);
color(7 ,0);
fclose(fichier1);
remove("admis.txt");
cancel:
fclose(fichier2);
rename("admis_new.txt" ,"admis.txt");
system("pause");
return 0;
}
int affiche_merite()
{
system("CLS");
FILE *fichier = NULL;
char chaine[MAX_BYTES] ,ligne_ecrire[50] = "";
int i = 0 ,j = 0 ,nb_admis = 0 ,r = 0;
float percent = 0.;
candidat TAB_admis[MAX_BYTES] ,permut;
if((fichier = fopen("admis.txt" ,"r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
exit(0);
}
printf("\t\t\t AFFICHAGE DES CANDIDATS PAR\n\n\t--------------------- ORDRE DE MERITE --------------------\n\n");
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
while(fgets(chaine,MAX_BYTES,fichier) != NULL)
{
TAB_admis[i] = recuperation(chaine);
i++;
}
nb_admis = i;
if(nb_admis)
{
printf("\nChargement : \n");
for(i = 0;i<nb_admis-1;i++)
{
percent = (i+1)*100/(double)(nb_admis-1);
gcvt(percent, 3, ligne_ecrire);
strcat(ligne_ecrire ,"% ");
for(j = 0; j<percent; j = j + 5 )
strcat(ligne_ecrire ,"\xDB");
while(r<102311211)
r++;
color(8 ,0);
printf("\r%s" ,ligne_ecrire);
color(7 ,0);
r = 0;
for(int j = i+1; j<nb_admis; j++)
{
if(average(&TAB_admis[i])<average(&TAB_admis[j]))
{
permut = TAB_admis[i];
TAB_admis[i] = TAB_admis[j];
TAB_admis[j] = permut;
}
}
}
printf("\n\n\n");
color(8 ,4);
color(4 ,4);
printf("___________________________________________________________________________________________________________________________");
color(0 ,4);
printf("\tNUMERO DE CNI\t\tNOM\t\tPRENOM\t MOYENNE\t\tRANG ");
color(4 ,4);
printf("________________________________________________________________________________________________________________________________________________________");
color(8 ,4);
color(7 ,0);
for(int k=0; k<nb_admis; k++)
{
color(7 ,3);
printf("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t %u\t\t%s\t\t%s\t " ,TAB_admis[k].NCIN,TAB_admis[k].NOM,TAB_admis[k].PRENOM);
printf("%2.2f\t\t%de\t\t\t\t\t" ,average(&TAB_admis[k]) ,k+1);
printf("________________________________________________________________________________________________________________________");
color(1 ,12);
}
}
else
warning("\t\t(Fichier Vide)\n");
color(7 ,0);
printf("\n");
fclose(fichier);
system("pause");
return 0;
}
int recherche(unsigned int NCIN)
{
system("CLS");
FILE *fichier = NULL;
char chaine[MAX_BYTES] = "";
int candidat_non_trouve = 1;
candidat cd_recherche;
unsigned int i = 0;
if((fichier = fopen("concours.txt" ,"r")) == NULL)
{
char text[100] = "";
sprintf(text ,"\n\tImpossible d'ouvrir le fichier : Erreur %d\n" ,errno);
warning(text);
exit(0);
}
printf("\t\t\t RECHERCHE D'UN CANDIDAT \n\n\t--------------------- DU CONCOURS --------------------\n\n");
color(4 ,0);
printf("\n°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°\n");
color(7 ,0);
while(fgets(chaine,MAX_BYTES,fichier) != NULL)
{
cd_recherche = recuperation(chaine);
if(cd_recherche.NCIN == NCIN)
{
candidat_non_trouve = 0;
printf("Les donnees du candidat correspondant sont : \n\n");
color(11 ,0);
printf("\t\t>> Nom\t\t\t\t%s\n_____________________________________________________________________\n\n" ,cd_recherche.NOM);
printf("\t\t>> Prenom\t\t\t%s\n_____________________________________________________________________\n\n",cd_recherche.PRENOM);
printf("\t\t>> Numero de CNI\t\t%u\n_____________________________________________________________________\n\n" ,cd_recherche.NCIN);
printf("\t\t>> Age\t\t\t\t%u ans\n_____________________________________________________________________\n\n" ,cd_recherche.AGE);
for(i = 0; i<NBR_NOTES ;i++)
printf("\t\t>> %de Note\t\t\t%2.2f\n_____________________________________________________________________\n\n" ,i+1,cd_recherche.NOTES[i]);
printf("\t\t>> Decision\t\t\t%s\n\n" ,dec_to_varchar(cd_recherche.DECISION));
color(7 ,0);
break;
}
}
rewind(fichier);
if(candidat_non_trouve)
{
char text[100] = "" ,choix[] = "O" ,vide = 1;
sprintf(text ,"\nLe candidat au numero de CNI \"%u\" n'existe pas !\n" ,NCIN);
warning(text);
printf("\nVoulez - vous consulter l'ensemble des numeros de CNI existants ?(O/N) > ");
securite_choix(choix ,"\nVoulez - vous consulter l'ensemble des numeros de CNI existants ?(O/N) > ");
if(strcmp(strupr(choix) ,"O") == 0)
{
printf("\n");
while(fgets(chaine,MAX_BYTES,fichier) != NULL)
{
vide = 0;
cd_recherche = recuperation(chaine);
printf("[%d]\t" ,cd_recherche.NCIN);
}
if(vide)
printf("\n\tAucun Candidat enregistre !\n");
}
else
printf("\nD'accord !\n");
}
fclose(fichier);
printf("\n\n");
system("pause");
return 0;
}
void warning(char *texte)
{
color(4 ,0);
printf("%s" ,texte);
color(7 ,0);
}
char *dec_to_varchar(decision dec)
{
if(dec == admis)
return "Admis";
else if(dec == ajourne)
return "Ajourne";
else if(dec == refuse)
return "Refuse";
else
return "None";
}
void color(int t ,int f)
{
HANDLE H = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(H ,f*16+t);
}
| f1056badac04c05da705ec5995755ac24956d74a | [
"C"
] | 3 | C | Blaise-dev/L1-Concours | e85cd21205af722a31e9efb9ada83f97139a43c3 | 6cd9f3ead9e9146fe01703492ae0d09980fb84dd | |
refs/heads/master | <repo_name>anedzibovi1/rpr-t5<file_sep>/src/ba/unsa/etf/rpr/tutorijal05/Controller.java
package ba.unsa.etf.rpr.tutorijal05;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
public Label display;
private SimpleStringProperty screen=new SimpleStringProperty("0");
public SimpleStringProperty screen(){
return screen;
}
public String getScreen() {
return screen.get();
}
private String operator="";
private double number1=0;
private Model model=new Model();
private boolean start=true;
public Controller() {
}
public void buttonAction(ActionEvent actionEvent) {
if(start) {
screen.set("");
start=false;
}
String value = ((Button)actionEvent.getTarget()).getText();
screen.set(screen.get() + value);
}
public void operationAction(ActionEvent actionEvent) {
String value = ((Button)actionEvent.getTarget()).getText();
if(!"=".equals(value)) {
if(!operator.isEmpty())
return;
operator=value;
number1=Long.parseLong(screen.get());
screen.set("");
}
else {
if(operator.isEmpty())
return;
if(operator.equals("%")) screen.set(String.valueOf(model.calculate1(number1,operator)));
screen.set(String.valueOf(model.calculate(number1,Long.parseLong(screen.get()),operator)));
operator="";
start=true;
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
display.textProperty().bindBidirectional(screen);
}
}
| d6461f0ec3cbfb2a1e08320b0e491380ea029fca | [
"Java"
] | 1 | Java | anedzibovi1/rpr-t5 | 6820f6b79caccc46c7ba6083676c5949fbd43798 | 2a43e6e7facb88f059c6dd7160ccd53971337e2c | |
refs/heads/master | <file_sep># gamesparks-tbrpg-addons
This is Gamesparks integration for Turnbase RPG template project (https://www.assetstore.unity3d.com/en/#!/content/107578)
Require: https://github.com/insthync/CloudCode-GS-TBRPG
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using GameSparks.Core;
public partial class GSGameService
{
protected override void DoArenaGetOpponentList(string playerId, string loginToken, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
var request = GetGSEventRequest("GetOpponentList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<Player>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoStartDuel(string playerId, string loginToken, string targetPlayerId, UnityAction<StartDuelResult> onFinish)
{
var result = new StartDuelResult();
var data = new GSRequestData();
data.AddString("targetPlayerId", targetPlayerId);
var request = GetGSEventRequest("StartDuel", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var stamina = scriptData.GetGSData("stamina");
var session = scriptData.GetString("session");
var opponentCharacters = scriptData.GetGSDataList("opponentCharacters");
result.stamina = JsonUtility.FromJson<PlayerStamina>(stamina.JSON);
result.session = session;
foreach (var entry in opponentCharacters)
{
result.opponentCharacters.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoFinishDuel(string playerId, string loginToken, string session, EBattleResult battleResult, int deadCharacters, UnityAction<FinishDuelResult> onFinish)
{
var result = new FinishDuelResult();
var data = new GSRequestData();
data.AddString("session", session);
data.AddNumber("battleResult", (byte)battleResult);
data.AddNumber("deadCharacters", deadCharacters);
var request = GetGSEventRequest("FinishDuel", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var rewardItems = scriptData.GetGSDataList("rewardItems");
var createItems = scriptData.GetGSDataList("createItems");
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
var rewardSoftCurrency = scriptData.GetInt("rewardSoftCurrency").Value;
var rewardHardCurrency = scriptData.GetInt("rewardHardCurrency").Value;
var updateScore = scriptData.GetInt("updateScore").Value;
var rating = scriptData.GetInt("rating").Value;
var player = scriptData.GetGSData("player");
foreach (var entry in rewardItems)
{
result.rewardItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in createItems)
{
result.createItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
result.rewardSoftCurrency = rewardSoftCurrency;
result.rewardHardCurrency = rewardHardCurrency;
result.updateScore = updateScore;
result.rating = rating;
result.player = JsonUtility.FromJson<Player>(player.JSON);
}
}
onFinish(result);
});
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using GameSparks.Core;
public partial class GSGameService
{
protected override void DoStartStage(string playerId, string loginToken, string stageDataId, string helperPlayerId, UnityAction<StartStageResult> onFinish)
{
var result = new StartStageResult();
var data = new GSRequestData();
data.AddString("stageDataId", stageDataId);
data.AddString("helperPlayerId", helperPlayerId);
var request = GetGSEventRequest("StartStage", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var stamina = scriptData.GetGSData("stamina");
var session = scriptData.GetString("session");
result.stamina = JsonUtility.FromJson<PlayerStamina>(stamina.JSON);
result.session = session;
}
}
onFinish(result);
});
}
protected override void DoFinishStage(string playerId, string loginToken, string session, EBattleResult battleResult, int deadCharacters, UnityAction<FinishStageResult> onFinish)
{
var result = new FinishStageResult();
var data = new GSRequestData();
data.AddString("session", session);
data.AddNumber("battleResult", (byte)battleResult);
data.AddNumber("deadCharacters", deadCharacters);
var request = GetGSEventRequest("FinishStage", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var isFirstClear = scriptData.GetBoolean("isFirstClear").Value;
var firstClearRewardPlayerExp = scriptData.GetInt("firstClearRewardPlayerExp").Value;
var firstClearRewardSoftCurrency = scriptData.GetInt("firstClearRewardSoftCurrency").Value;
var firstClearRewardHardCurrency = scriptData.GetInt("firstClearRewardHardCurrency").Value;
var firstClearRewardItems = scriptData.GetGSDataList("firstClearRewardItems");
var rewardItems = scriptData.GetGSDataList("rewardItems");
var createItems = scriptData.GetGSDataList("createItems");
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
var rewardPlayerExp = scriptData.GetInt("rewardPlayerExp").Value;
var rewardCharacterExp = scriptData.GetInt("rewardCharacterExp").Value;
var rewardSoftCurrency = scriptData.GetInt("rewardSoftCurrency").Value;
var rating = scriptData.GetInt("rating").Value;
var clearStage = scriptData.GetGSData("clearStage");
var player = scriptData.GetGSData("player");
foreach (var entry in firstClearRewardItems)
{
result.firstClearRewardItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in rewardItems)
{
result.rewardItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in createItems)
{
result.createItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
result.isFirstClear = isFirstClear;
result.firstClearRewardPlayerExp = firstClearRewardPlayerExp;
result.firstClearRewardSoftCurrency = firstClearRewardSoftCurrency;
result.firstClearRewardHardCurrency = firstClearRewardHardCurrency;
result.rewardPlayerExp = rewardPlayerExp;
result.rewardCharacterExp = rewardCharacterExp;
result.rewardSoftCurrency = rewardSoftCurrency;
result.rating = rating;
result.clearStage = JsonUtility.FromJson<PlayerClearStage>(clearStage.JSON);
result.player = JsonUtility.FromJson<Player>(player.JSON);
}
}
onFinish(result);
});
}
protected override void DoReviveCharacters(string playerId, string loginToken, UnityAction<CurrencyResult> onFinish)
{
var result = new CurrencyResult();
var request = GetGSEventRequest("ReviveCharacters");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoSelectFormation(string playerId, string loginToken, string formationName, EFormationType formationType, UnityAction<PlayerResult> onFinish)
{
var result = new PlayerResult();
var data = new GSRequestData();
data.AddString("formationName", formationName);
data.AddNumber("formationType", (byte)formationType);
var request = GetGSEventRequest("SelectFormation", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var player = scriptData.GetGSData("player");
result.player = JsonUtility.FromJson<Player>(player.JSON);
}
}
onFinish(result);
});
}
protected override void DoSetFormation(string playerId, string loginToken, string characterId, string formationName, int position, UnityAction<FormationListResult> onFinish)
{
var result = new FormationListResult();
var data = new GSRequestData();
data.AddString("characterId", characterId);
data.AddString("formationName", formationName);
data.AddNumber("position", position);
var request = GetGSEventRequest("SetFormation", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerFormation>(entry.JSON));
}
}
}
onFinish(result);
});
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Events;
using GameSparks.Core;
using GameSparks.Api.Requests;
#if UNITY_EDITOR
using UnityEditor;
#endif
public partial class GSGameService : BaseGameService
{
private void Awake()
{
StartCoroutine(WaitForGS());
}
IEnumerator WaitForGS()
{
while (!GS.Available)
yield return 0;
Debug.Log("Gamesparks ready.");
}
#if UNITY_EDITOR
[ContextMenu("Export Game Database")]
public void ExportGameDatabase()
{
var gameInstance = FindObjectOfType<GameInstance>();
if (gameInstance == null)
{
Debug.LogError("Cannot export game database, no game instance found");
return;
}
var gameDatabase = gameInstance.gameDatabase;
if (gameDatabase == null)
{
Debug.LogError("Cannot export game database, no game database found");
return;
}
gameDatabase.Setup();
var achievementsJson = "";
var itemsJson = "";
var currenciesJson = "";
var staminasJson = "";
var formationsJson = "";
var stagesJson = "";
var lootBoxesJson = "";
var iapPackagesJson = "";
var inGamePackagesJson = "";
var startItemsJson = "";
var startCharactersJson = "";
var unlockStagesJson = "";
var arenaRanksJson = "";
foreach (var achievement in gameDatabase.Achievements)
{
if (!string.IsNullOrEmpty(achievementsJson))
achievementsJson += ",";
achievementsJson += "\"" + achievement.Key + "\":" + achievement.Value.ToJson();
}
achievementsJson = "{" + achievementsJson + "}";
foreach (var item in gameDatabase.Items)
{
if (!string.IsNullOrEmpty(itemsJson))
itemsJson += ",";
itemsJson += "\"" + item.Key + "\":" + item.Value.ToJson();
}
itemsJson = "{" + itemsJson + "}";
currenciesJson = "{\"SOFT_CURRENCY\":\"" + gameDatabase.softCurrency.id + "\", \"HARD_CURRENCY\":\"" + gameDatabase.hardCurrency.id + "\"}";
staminasJson = "{\"STAGE\":" + gameDatabase.stageStamina.ToJson() + ", \"ARENA\":" + gameDatabase.arenaStamina.ToJson() + "}";
foreach (var entry in gameDatabase.Formations)
{
if (!string.IsNullOrEmpty(formationsJson))
formationsJson += ",";
formationsJson += "\"" + entry.Key + "\"";
}
formationsJson = "[" + formationsJson + "]";
foreach (var entry in gameDatabase.Stages)
{
if (!string.IsNullOrEmpty(stagesJson))
stagesJson += ",";
stagesJson += "\"" + entry.Key + "\":" + entry.Value.ToJson();
}
stagesJson = "{" + stagesJson + "}";
foreach (var entry in gameDatabase.LootBoxes)
{
if (!string.IsNullOrEmpty(lootBoxesJson))
lootBoxesJson += ",";
lootBoxesJson += "\"" + entry.Key + "\":" + entry.Value.ToJson();
}
lootBoxesJson = "{" + lootBoxesJson + "}";
foreach (var entry in gameDatabase.IapPackages)
{
if (!string.IsNullOrEmpty(iapPackagesJson))
iapPackagesJson += ",";
iapPackagesJson += "\"" + entry.Key + "\":" + entry.Value.ToJson();
}
iapPackagesJson = "{" + iapPackagesJson + "}";
foreach (var entry in gameDatabase.InGamePackages)
{
if (!string.IsNullOrEmpty(inGamePackagesJson))
inGamePackagesJson += ",";
inGamePackagesJson += "\"" + entry.Key + "\":" + entry.Value.ToJson();
}
inGamePackagesJson = "{" + inGamePackagesJson + "}";
foreach (var entry in gameDatabase.startItems)
{
if (entry == null || entry.item == null)
continue;
if (!string.IsNullOrEmpty(startItemsJson))
startItemsJson += ",";
startItemsJson += entry.ToJson();
}
startItemsJson = "[" + startItemsJson + "]";
foreach (var entry in gameDatabase.startCharacters)
{
if (entry == null)
continue;
if (!string.IsNullOrEmpty(startCharactersJson))
startCharactersJson += ",";
startCharactersJson += "\"" + entry.Id + "\"";
}
startCharactersJson = "[" + startCharactersJson + "]";
foreach (var entry in gameDatabase.unlockStages)
{
if (entry == null)
continue;
if (!string.IsNullOrEmpty(unlockStagesJson))
unlockStagesJson += ",";
unlockStagesJson += "\"" + entry.Id + "\"";
}
unlockStagesJson = "[" + unlockStagesJson + "]";
foreach (var entry in gameDatabase.arenaRanks)
{
if (entry == null)
continue;
if (!string.IsNullOrEmpty(arenaRanksJson))
arenaRanksJson += ",";
arenaRanksJson += entry.ToJson();
}
arenaRanksJson = "[" + arenaRanksJson + "]";
var jsonCombined = "{" +
"\"achievements\":" + achievementsJson + "," +
"\"items\":" + itemsJson + "," +
"\"currencies\":" + currenciesJson + "," +
"\"staminas\":" + staminasJson + "," +
"\"formations\":" + formationsJson + "," +
"\"stages\":" + stagesJson + "," +
"\"lootBoxes\":" + lootBoxesJson + "," +
"\"iapPackages\":" + iapPackagesJson + "," +
"\"inGamePackages\":" + inGamePackagesJson + "," +
"\"hardToSoftCurrencyConversion\":" + gameDatabase.hardToSoftCurrencyConversion + "," +
"\"startItems\":" + startItemsJson + "," +
"\"startCharacters\":" + startCharactersJson + "," +
"\"unlockStages\":" + unlockStagesJson + "," +
"\"arenaRanks\":" + arenaRanksJson + "," +
"\"arenaWinScoreIncrease\":" + gameDatabase.arenaWinScoreIncrease + "," +
"\"arenaLoseScoreDecrease\":" + gameDatabase.arenaLoseScoreDecrease + "," +
"\"playerMaxLevel\":" + gameDatabase.playerMaxLevel + "," +
"\"playerExpTable\":" + gameDatabase.playerExpTable.ToJson() + "," +
"\"revivePrice\":" + gameDatabase.revivePrice + "," +
"\"resetItemLevelAfterEvolve\":" + (gameDatabase.resetItemLevelAfterEvolve ? 1 : 0) + "}";
var cloudCodes = "var gameDatabase = " + jsonCombined + ";";
var path = EditorUtility.SaveFilePanel("Export Game Database", Application.dataPath, "GAME_DATA", "js");
if (path.Length > 0)
File.WriteAllText(path, cloudCodes);
}
#endif
protected LogEventRequest GetGSEventRequest(string target, GSRequestData data = null)
{
if (data == null)
data = new GSRequestData();
var request = new LogEventRequest();
request.SetEventKey("SERVICE_EVENT");
request.SetEventAttribute("TARGET", target);
request.SetEventAttribute("DATA", data);
return request;
}
protected override void DoGetAchievementList(string playerId, string loginToken, UnityAction<AchievementListResult> onFinish)
{
var result = new AchievementListResult();
var request = GetGSEventRequest("GetAchievementList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerAchievement>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetAuthList(string playerId, string loginToken, UnityAction<AuthListResult> onFinish)
{
var result = new AuthListResult();
onFinish(result);
}
protected override void DoGetItemList(string playerId, string loginToken, UnityAction<ItemListResult> onFinish)
{
var result = new ItemListResult();
var request = GetGSEventRequest("GetItemList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetCurrencyList(string playerId, string loginToken, UnityAction<CurrencyListResult> onFinish)
{
var result = new CurrencyListResult();
var request = GetGSEventRequest("GetCurrencyList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetStaminaList(string playerId, string loginToken, UnityAction<StaminaListResult> onFinish)
{
var result = new StaminaListResult();
var request = GetGSEventRequest("GetStaminaList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerStamina>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetFormationList(string playerId, string loginToken, UnityAction<FormationListResult> onFinish)
{
var result = new FormationListResult();
var request = GetGSEventRequest("GetFormationList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerFormation>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetUnlockItemList(string playerId, string loginToken, UnityAction<UnlockItemListResult> onFinish)
{
var result = new UnlockItemListResult();
var request = GetGSEventRequest("GetUnlockItemList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerUnlockItem>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetClearStageList(string playerId, string loginToken, UnityAction<ClearStageListResult> onFinish)
{
var result = new ClearStageListResult();
var request = GetGSEventRequest("GetClearStageList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<PlayerClearStage>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetServiceTime(UnityAction<ServiceTimeResult> onFinish)
{
var result = new ServiceTimeResult();
var request = GetGSEventRequest("ServiceTime");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("serviceTime"))
{
result.serviceTime = scriptData.GetLong("serviceTime").Value;
}
onFinish(result);
});
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Events;
public partial class GSGameService
{
protected override void DoCreateClan(string playerId, string loginToken, string clanName, UnityAction<CreateClanResult> onFinish)
{
var result = new CreateClanResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoFindClan(string playerId, string loginToken, string clanName, UnityAction<ClanListResult> onFinish)
{
var result = new ClanListResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanJoinRequest(string playerId, string loginToken, string clanId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanJoinAccept(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanJoinDecline(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanMemberDelete(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanJoinRequestDelete(string playerId, string loginToken, string clanId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoGetClanMemberList(string playerId, string loginToken, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanOwnerTransfer(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanTerminate(string playerId, string loginToken, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoGetClan(string playerId, string loginToken, UnityAction<ClanResult> onFinish)
{
var result = new ClanResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoGetClanJoinRequestList(string playerId, string loginToken, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoGetClanJoinPendingRequestList(string playerId, string loginToken, UnityAction<ClanListResult> onFinish)
{
var result = new ClanListResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanExit(string playerId, string loginToken, UnityAction<GameServiceResult> onFinish)
{
var result = new ClanResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
protected override void DoClanSetRole(string playerId, string loginToken, string targetPlayerId, byte clanRole, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using GameSparks.Core;
using GameSparks.Api.Requests;
using GameSparks.Api.Responses;
public partial class GSGameService
{
protected override void DoLevelUpItem(string playerId, string loginToken, string itemId, Dictionary<string, int> materials, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
var data = new GSRequestData();
data.AddString("itemId", itemId);
var materialsObject = new GSRequestData();
foreach (var material in materials)
{
materialsObject.AddNumber(material.Key, material.Value);
}
data.AddObject("materials", materialsObject);
var request = GetGSEventRequest("LevelUpItem", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoEvolveItem(string playerId, string loginToken, string itemId, Dictionary<string, int> materials, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
var data = new GSRequestData();
data.AddString("itemId", itemId);
var materialsObject = new GSRequestData();
foreach (var material in materials)
{
materialsObject.AddNumber(material.Key, material.Value);
}
data.AddObject("materials", materialsObject);
var request = GetGSEventRequest("EvolveItem", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoSellItems(string playerId, string loginToken, Dictionary<string, int> items, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
var data = new GSRequestData();
var itemsObject = new GSRequestData();
foreach (var item in items)
{
itemsObject.AddNumber(item.Key, item.Value);
}
data.AddObject("items", itemsObject);
var request = GetGSEventRequest("SellItems", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoEquipItem(string playerId, string loginToken, string characterId, string equipmentId, string equipPosition, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
var data = new GSRequestData();
data.AddString("characterId", characterId);
data.AddString("equipmentId", equipmentId);
data.AddString("equipPosition", equipPosition);
var request = GetGSEventRequest("EquipItem", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var updateItems = scriptData.GetGSDataList("updateItems");
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoUnEquipItem(string playerId, string loginToken, string equipmentId, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
var data = new GSRequestData();
data.AddString("equipmentId", equipmentId);
var request = GetGSEventRequest("UnEquipItem", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var updateItems = scriptData.GetGSDataList("updateItems");
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoGetAvailableLootBoxList(UnityAction<AvailableLootBoxListResult> onFinish)
{
var result = new AvailableLootBoxListResult();
var request = GetGSEventRequest("GetAvailableLootBoxList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetStringList("list");
result.list = list;
}
onFinish(result);
});
}
protected override void DoGetAvailableIapPackageList(UnityAction<AvailableIapPackageListResult> onFinish)
{
var result = new AvailableIapPackageListResult();
var request = GetGSEventRequest("GetAvailableIapPackageList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetStringList("list");
result.list = list;
}
onFinish(result);
});
}
protected override void DoGetAvailableInGamePackageList(UnityAction<AvailableInGamePackageListResult> onFinish)
{
var result = new AvailableInGamePackageListResult();
var request = GetGSEventRequest("GetAvailableInGamePackageList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetStringList("list");
result.list = list;
}
onFinish(result);
});
}
protected override void DoOpenLootBox(string playerId, string loginToken, string lootBoxDataId, int packIndex, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
var data = new GSRequestData();
data.AddString("lootBoxDataId", lootBoxDataId);
data.AddNumber("packIndex", packIndex);
var request = GetGSEventRequest("OpenLootBox", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var rewardItems = scriptData.GetGSDataList("rewardItems");
var createItems = scriptData.GetGSDataList("createItems");
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
foreach (var entry in rewardItems)
{
result.rewardItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in createItems)
{
result.createItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoOpenIapPackage_iOS(string playerId, string loginToken, string iapPackageDataId, string receipt, UnityAction<ItemResult> onFinish)
{
var request = new IOSBuyGoodsRequest();
request.SetReceipt(receipt);
request.Send((response) =>
{
IapResponse(response, onFinish);
});
}
protected override void DoOpenIapPackage_Android(string playerId, string loginToken, string iapPackageDataId, string data, string signature, UnityAction<ItemResult> onFinish)
{
var request = new GooglePlayBuyGoodsRequest();
request.SetSignedData(data);
request.SetSignature(signature);
request.Send((response) =>
{
IapResponse(response, onFinish);
});
}
private void IapResponse(BuyVirtualGoodResponse response, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
if (!response.HasErrors)
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var rewardItems = scriptData.GetGSDataList("rewardItems");
var createItems = scriptData.GetGSDataList("createItems");
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
foreach (var entry in rewardItems)
{
result.rewardItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in createItems)
{
result.createItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
}
onFinish(result);
}
else
{
Debug.LogError("GameSparks error while request accout details: " + response.Errors.JSON);
result.error = GameServiceErrorCode.UNKNOW;
onFinish(result);
}
}
protected override void DoEarnAchievementReward(string playerId, string loginToken, string achievementId, UnityAction<EarnAchievementResult> onFinish)
{
var result = new EarnAchievementResult();
var data = new GSRequestData();
data.AddString("achievementId", achievementId);
var request = GetGSEventRequest("EarnAchievementReward", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var rewardItems = scriptData.GetGSDataList("rewardItems");
var createItems = scriptData.GetGSDataList("createItems");
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
var rewardPlayerExp = scriptData.GetInt("rewardPlayerExp").Value;
var rewardSoftCurrency = scriptData.GetInt("rewardSoftCurrency").Value;
var rewardHardCurrency = scriptData.GetInt("rewardHardCurrency").Value;
var player = scriptData.GetGSData("player");
foreach (var entry in rewardItems)
{
result.rewardItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in createItems)
{
result.createItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
result.rewardPlayerExp = rewardPlayerExp;
result.rewardSoftCurrency = rewardSoftCurrency;
result.rewardHardCurrency = rewardHardCurrency;
result.player = JsonUtility.FromJson<Player>(player.JSON);
}
}
onFinish(result);
});
}
protected override void DoConvertHardCurrency(string playerId, string loginToken, int requireHardCurrency, UnityAction<HardCurrencyConversionResult> onFinish)
{
var result = new HardCurrencyConversionResult();
var data = new GSRequestData();
data.AddNumber("requireHardCurrency", requireHardCurrency);
var request = GetGSEventRequest("ConvertHardCurrency", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
var receiveSoftCurrency = scriptData.GetInt("receiveSoftCurrency").Value;
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
result.requireHardCurrency = requireHardCurrency;
result.receiveSoftCurrency = receiveSoftCurrency;
}
}
onFinish(result);
});
}
protected override void DoOpenInGamePackage(string playerId, string loginToken, string inGamePackageDataId, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
var data = new GSRequestData();
data.AddString("inGamePackageDataId", inGamePackageDataId);
var request = GetGSEventRequest("OpenInGamePackage", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null)
{
if (scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
{
result.error = scriptData.GetString("error");
}
else
{
var rewardItems = scriptData.GetGSDataList("rewardItems");
var createItems = scriptData.GetGSDataList("createItems");
var updateItems = scriptData.GetGSDataList("updateItems");
var deleteItemIds = scriptData.GetStringList("deleteItemIds");
var updateCurrencies = scriptData.GetGSDataList("updateCurrencies");
foreach (var entry in rewardItems)
{
result.rewardItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in createItems)
{
result.createItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
foreach (var entry in updateItems)
{
result.updateItems.Add(JsonUtility.FromJson<PlayerItem>(entry.JSON));
}
result.deleteItemIds.AddRange(deleteItemIds);
foreach (var entry in updateCurrencies)
{
result.updateCurrencies.Add(JsonUtility.FromJson<PlayerCurrency>(entry.JSON));
}
}
}
onFinish(result);
});
}
protected override void DoCraftItem(string playerId, string loginToken, string itemCraftId, Dictionary<string, int> materials, UnityAction<ItemResult> onFinish)
{
var result = new ItemResult();
result.error = GameServiceErrorCode.NOT_AVAILABLE;
onFinish(result);
}
}
<file_sep>using GameSparks.Core;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public partial class GSGameService
{
protected override void DoGetHelperList(string playerId, string loginToken, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
var request = GetGSEventRequest("GetHelperList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<Player>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetFriendList(string playerId, string loginToken, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
var request = GetGSEventRequest("GetFriendList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<Player>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetFriendRequestList(string playerId, string loginToken, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
var request = GetGSEventRequest("GetFriendRequestList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<Player>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoGetPendingRequestList(string playerId, string loginToken, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
var request = GetGSEventRequest("GetPendingRequestList");
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<Player>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoFindUser(string playerId, string loginToken, string displayName, UnityAction<PlayerListResult> onFinish)
{
var result = new PlayerListResult();
var data = new GSRequestData();
data.AddString("displayName", displayName);
var request = GetGSEventRequest("FindUser", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("list"))
{
var list = scriptData.GetGSDataList("list");
foreach (var entry in list)
{
result.list.Add(JsonUtility.FromJson<Player>(entry.JSON));
}
}
onFinish(result);
});
}
protected override void DoFriendRequest(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
var data = new GSRequestData();
data.AddString("targetPlayerId", targetPlayerId);
var request = GetGSEventRequest("FriendRequest", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
result.error = scriptData.GetString("error");
onFinish(result);
});
}
protected override void DoFriendAccept(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
var data = new GSRequestData();
data.AddString("targetPlayerId", targetPlayerId);
var request = GetGSEventRequest("FriendAccept", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
result.error = scriptData.GetString("error");
onFinish(result);
});
}
protected override void DoFriendDecline(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
var data = new GSRequestData();
data.AddString("targetPlayerId", targetPlayerId);
var request = GetGSEventRequest("FriendDecline", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
result.error = scriptData.GetString("error");
onFinish(result);
});
}
protected override void DoFriendDelete(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
var data = new GSRequestData();
data.AddString("targetPlayerId", targetPlayerId);
var request = GetGSEventRequest("FriendDelete", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
result.error = scriptData.GetString("error");
onFinish(result);
});
}
protected override void DoFriendRequestDelete(string playerId, string loginToken, string targetPlayerId, UnityAction<GameServiceResult> onFinish)
{
var result = new GameServiceResult();
var data = new GSRequestData();
data.AddString("targetPlayerId", targetPlayerId);
var request = GetGSEventRequest("FriendRequestDelete", data);
request.Send((response) =>
{
GSData scriptData = response.ScriptData;
if (scriptData != null && scriptData.ContainsKey("error") && !string.IsNullOrEmpty(scriptData.GetString("error")))
result.error = scriptData.GetString("error");
onFinish(result);
});
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public partial class GSGameService
{
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using GameSparks.Core;
using GameSparks.Api.Requests;
public partial class GSGameService
{
public void RequestAccountDetails(PlayerResult result, UnityAction<PlayerResult> onFinish)
{
var player = result.player;
var request = new AccountDetailsRequest();
request.Send((accountResponse) =>
{
if (!accountResponse.HasErrors)
{
player.Id = accountResponse.UserId;
player.ProfileName = accountResponse.DisplayName;
if (accountResponse.ScriptData != null)
{
if (accountResponse.ScriptData.ContainsKey("exp"))
player.Exp = accountResponse.ScriptData.GetInt("exp").Value;
if (accountResponse.ScriptData.ContainsKey("selectedFormation"))
player.SelectedFormation = accountResponse.ScriptData.GetString("selectedFormation");
if (accountResponse.ScriptData.ContainsKey("selectedArenaFormation"))
player.SelectedArenaFormation = accountResponse.ScriptData.GetString("selectedArenaFormation");
if (accountResponse.ScriptData.ContainsKey("arenaScore"))
player.arenaScore = accountResponse.ScriptData.GetInt("arenaScore").Value;
if (accountResponse.ScriptData.ContainsKey("highestArenaRank"))
player.highestArenaRank = accountResponse.ScriptData.GetInt("highestArenaRank").Value;
if (accountResponse.ScriptData.ContainsKey("highestArenaRankCurrentSeason"))
player.highestArenaRankCurrentSeason = accountResponse.ScriptData.GetInt("highestArenaRankCurrentSeason").Value;
}
result.player = player;
onFinish(result);
}
else
{
Debug.LogError("GameSparks error while request accout details: " + accountResponse.Errors.JSON);
result.error = GameServiceErrorCode.UNKNOW;
onFinish(result);
}
});
}
protected override void DoLogin(string username, string password, UnityAction<PlayerResult> onFinish)
{
var result = new PlayerResult();
result.player = new Player();
var request = new AuthenticationRequest();
request.SetUserName(username);
request.SetPassword(<PASSWORD>);
request.Send((authResponse) =>
{
if (!authResponse.HasErrors)
RequestAccountDetails(result, onFinish);
else
{
Debug.LogError("GameSparks error while login: " + authResponse.Errors.JSON);
result.error = GameServiceErrorCode.UNKNOW;
if (authResponse.Errors.ContainsKey("DETAILS") && authResponse.Errors.GetString("DETAILS").Equals("UNRECOGNISED"))
result.error = GameServiceErrorCode.INVALID_USERNAME_OR_PASSWORD;
onFinish(result);
}
});
}
protected override void DoRegisterOrLogin(string username, string password, UnityAction<PlayerResult> onFinish)
{
DoRegister(username, password, (registerResult) =>
{
if (registerResult.Success)
DoLogin(username, password, onFinish);
else
onFinish(registerResult);
});
}
protected override void DoGuestLogin(string deviceId, UnityAction<PlayerResult> onFinish)
{
var result = new PlayerResult();
result.player = new Player();
var request = new DeviceAuthenticationRequest();
request.Send((authResponse) =>
{
if (!authResponse.HasErrors)
RequestAccountDetails(result, onFinish);
else
{
Debug.LogError("GameSparks error while guest login: " + authResponse.Errors.JSON);
result.error = GameServiceErrorCode.UNKNOW;
onFinish(result);
}
});
}
protected override void DoValidateLoginToken(string playerId, string loginToken, bool refreshToken, UnityAction<PlayerResult> onFinish)
{
var result = new PlayerResult();
if (GS.Authenticated && !string.IsNullOrEmpty(playerId))
{
result.player = new Player();
RequestAccountDetails(result, onFinish);
return;
}
result.error = GameServiceErrorCode.INVALID_LOGIN_TOKEN;
onFinish(result);
}
protected override void DoSetProfileName(string playerId, string loginToken, string profileName, UnityAction<PlayerResult> onFinish)
{
var result = new PlayerResult();
var player = result.player = Player.CurrentPlayer;
var request = new ChangeUserDetailsRequest();
request.SetDisplayName(profileName);
request.Send((authResponse) =>
{
player.ProfileName = profileName;
if (!authResponse.HasErrors)
onFinish(result);
else
{
Debug.LogError("GameSparks error while set profile name: " + authResponse.Errors.JSON);
result.error = GameServiceErrorCode.UNKNOW;
onFinish(result);
}
});
}
protected override void DoRegister(string username, string password, UnityAction<PlayerResult> onFinish)
{
var result = new PlayerResult();
var player = result.player = new Player();
var request = new RegistrationRequest();
request.SetDisplayName(" ");
request.SetUserName(username);
request.SetPassword(<PASSWORD>);
request.Send((authResponse) =>
{
player.Id = authResponse.UserId;
if (!authResponse.HasErrors)
onFinish(result);
else
{
Debug.LogError("GameSparks error while register: " + authResponse.Errors.JSON);
result.error = GameServiceErrorCode.UNKNOW;
if (authResponse.Errors.ContainsKey("USERNAME") && authResponse.Errors.GetString("USERNAME").Equals("TAKEN"))
result.error = GameServiceErrorCode.EXISTED_USERNAME;
onFinish(result);
}
});
}
}
| 4410c4ecb7a09097dcf31c73dd3d9f621fae6604 | [
"Markdown",
"C#"
] | 9 | Markdown | insthync/gamesparks-tbrpg-addons | a843f0a823cc3ca37178cc88ad806afcad69b460 | 549fcd87268faa41e098b9baf0c2ddf979f8de23 | |
refs/heads/master | <file_sep>require './methods.rb'
puts "Game gallows, version 1"
letters = get_letters
cls
errors = 0
bad_letters = []
good_letters = []
while errors < 7 do
print_status(letters, good_letters, bad_letters, errors)
puts "Write next letter"
user_input = get_user_input
result = check_result(user_input, letters, good_letters, bad_letters)
if result == -1 # увеличили счетчик ошибок, угадываем дальше
errors += 1
elsif result == 1 #слово угадано полностью
break
end
end
print_status(letters, good_letters, bad_letters, errors)
# не хватает защиты от написания нескольких букв за 1 ввод<file_sep>require './game.rb'
require './result_printer.rb'
=begin
=end
printer = ResultPrinter.new
game = Game.new(STDIN.gets.chomp)
while game.status == 0 do
printer.print_status(game)
game.ask_next_letter
end
printer.print_status(game)
<file_sep>class Bridge
def initialize
puts "Bridge created."
@opened = false
end
def open
puts "Bridge is open, you can go."
@opened = true
end
def is_opened?
@opened
end
end<file_sep>puts "Helo. It's uour diary!"
puts "I save all that you write to String \"end\" in file."
puts
# Хранит путь к папке в которой выполняется программа
# Определим папку, в которой лежит эта программа ""
# С помощью специальног ослужебного объекта Ruby __FILE__
current_path = File.dirname(__FILE__)
line = nil
all_lines = []
while line != "end" do
line = gets.chomp
all_lines << line
end
# Узнаем текущее время, когда был сделан пост
time = Time.now
# Записываем строку определенного вида согласно документации класса Time и его метода strftime
# передаются ключи, ключи определяются знаком %
file_name = time.strftime("%Y-%m-%d") #2016-05-25
time_string = time.strftime("%H:%M") #22:16
separator = "----------------------------"
# a:UTF-8 - открыть файл для записи в кодировке UTF-8
# если файла не существует - создает файл
# если файл существует - открывает файл для записи в конец файла
file = File.new(current_path + "/" + file_name + ".txt", "a:UTF-8")
# Метод print получает на вход строку и
# записывает ее в файл как есть
file.print("\n\r" + time_string + "\n\r")
# удаляем последний элемент массива- слово "end"
all_lines.pop
# метод puts сам добавляет символ перевода строки
# записываем им в файл из массива слов
for item in all_lines do
file.puts item
end
file.puts separator
file.close
puts "Ваша запись сохранена в файл: #{file_name}.txt по адресу: #{current_path}"<file_sep>require './bridge'
puts "Go!"
sleep 1
puts "Внезапно река!"
sleep 1
bridge = Bridge.new
sleep 1
if !bridge.is_opened?
bridge.open
end
sleep 1
puts "Поехали дальше"
puts bridge.is_opened?.to_s<file_sep>basket = []
basket << "Apple"
basket.push "Mellon"
basket.push("Cherry", "Mango", "Banana")
puts "Корзина: #{basket}"
puts "Корзина: #{basket.join", "}"
basket.delete "Cherry"
puts "Корзина: #{basket.join", "}"
basket.delete_at(0)
puts "Корзина: #{basket.join", "}"
basket.delete_if{ |x| x <= "Banana"}
puts "Корзина: #{basket.join", "}"<file_sep>def alter_input
argument = ARGV[0]
if (Gem.win_platform? and ARGV[0])
argument = argument.encode(ARGV[0].encoding, "cp1251").encode("UTF-8")
end
if (argument == "дурак")
puts "Сам дурак!"
else
puts "Здравствуй дорогой!"
end
end
#забил из-за обработки теста - мног описать<file_sep>
def get_letters
slovo = gets.chomp
if slovo == nil || slovo == ""
abort "You have not entered a word for the game"
end
slovo.split("")
end
def get_user_input
letter = ""
while letter == ""
letter = STDIN.gets.chomp
end
letter
end
def check_result(user_input, letters, good_letters, bad_letters)
if good_letters.include?(user_input) || #проверка на повторные буквы
bad_letters.include?(user_input)
0
end
if letters.include? user_input
good_letters << user_input
#условие когда откгадано всё слово
if letters.uniq.size == good_letters.size #метод uniq выбирает из исходного массива тольок уникальные значения
1
else
0
end
else
bad_letters << user_input
-1
end
end
def get_word_for_print(letters, good_letters)
result = ""
for elem in letters do
if good_letters.include? elem
result += elem + " "
else
result += "_ "
end
end
result
end
#1. выводить загаданное слово
#2. информацию об ошибках и уже названные буквы
#3. ошибок > 7 - сообщить о поражении
#4. слово угадано - сообщить о победе
def print_status(letters, good_letters, bad_letters, errors)
puts "\nСлово: #{get_word_for_print(letters, good_letters)}"
puts "Errors (#{errors}): #{bad_letters.join(", ")}"
if errors >= 7
puts "You loose :("
else
if letters.uniq.size == good_letters.size
puts "You are winner!!!\n"
else
puts "You have #{7-errors} effort"
end
end
end
def cls
system "clear" or system "cls"
end<file_sep>require 'pony'
# переменная, содержащая мою реальную почту
my_mail = "<EMAIL>"
puts "Введите пароль от вашей почты #{my_mail} для отправки письма:"
password = STDIN.gets.chomp
puts "Введите адрес получателя:"
send_to = STDIN.gets.chomp
puts "Введите текст письма:"
body = STDIN.gets.chomp
Pony.mail(
{
:subject => "привет из Руби!",
:body => body,
:to => send_to,
:from => my_mail,
:via => :smtp,
:via_options =>{
:address => '<EMAIL>',
:port => '465',
:tls => true ,
:user_name => my_mail,
:password => <PASSWORD>,
:authentication => :plain, # :plain, :login, :cram_md5, no auth by default
#:domain => "localhost.localdomain" # the HELO domain provided by the client to the server
}
}
)
puts "Письмо успешно отправлено!"
<file_sep>=begin
Хранит текущее состояние и всю логику игры
=end
class Game
def initialize(word)
@word = get_word(word)
@errors = 0
@good_letters = []
@bad_letters = []
@status = 0
end
def get_word(word)
if word == nil || word == ""
abort "You have not entered a word for the game"
end
word.split("")
end
# 1. спросить букву с консоли
# 2. проверить результат
def ask_next_letter
puts "\n Enter the next letter"
letter = ""
while letter == ""
letter = STDIN.gets.chomp
end
next_step(letter) # 2. проверить результат
end
# Метод next_step должен проверить наличие буквы в загаданном слове
# Или среди уже названных букв (массивы @good_letters, @bad_letters)
# Аналог метода check_result в первой версии "Виселицы"
def next_step(letter)
if @status == -1 || @status == 1
return
end
if @good_letters.include?(letter) || @bad_letters.include?(letter)
return
end
if @word.include?(letter)
@good_letters << letter
if @good_letters.size == @word.uniq.size
@status = 1
end
else
@bad_letters << letter
@errors += 1
if @errors >= 7 #если допустил 7 ошибок, то
@status = -1 # проиграл
end
end
end
=begin
def word
@word
end
def good_letters
@good_letters
end
def bad_letters
@bad_letters
end
def status
@status
end
def errors
@errors
end
=end
#вместо этого используем ридер
attr_reader :word, :good_letters, :bad_letters, :status, :errors
end | be8bb8a4b22b6383d9e8d0c9af034d7ffb863247 | [
"Ruby"
] | 10 | Ruby | ToshiDono/The_actual_programming_for_all | 7a682482e21991845de7f8e6bda10ba3b2931224 | c6288f347606f2c1af40759ab8f9209ca74060d0 | |
refs/heads/main | <file_sep>CC = gcc
CFLAGS = -Wall -ansi -pedantic -g
MAIN = main
OBJS = main.o
all : $(MAIN)
$(MAIN) : $(OBJS)
$(CC) $(CFLAGS) -o $(MAIN) $(OBJS)
main.o : main.c
$(CC) $(CFLAGS) -c main.c
clean :
rm *.o $(MAIN) core
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_SUFFLE_MAX 20
#define NUM_SUFFLE_MIN 10
#define UPPER 15
#define LOWER 0
int generate_randoms(int, int);
int main(int argc, char *argv[]){
int i = 0;
int rand1;
int rand2;
int array_length;
int suffle_time;
int rand_array[2 * NUM_SUFFLE_MAX + UPPER + 1];
suffle_time = generate_randoms(NUM_SUFFLE_MIN, NUM_SUFFLE_MAX);
array_length = 2 * suffle_time + UPPER + 1;
/* construct array */
while(i < array_length){
rand_array[i] = generate_randoms(LOWER, UPPER);
i++;
printf("%d\n", rand1);
rand_array[i] = generate_randoms(LOWER, UPPER);
i++;
printf("%d\n", rand2);
}
return(0);
}
int generate_randoms(int lower, int upper) {
time_t rawtime;
time(&rawtime);
return ((rand() + rawtime) % (upper - lower + 1)) + lower;
}
| f057a102e904228b0b37db385cd669179fbb1447 | [
"C",
"Makefile"
] | 2 | Makefile | SaltFishBoi/killer_game_position_prediction | becd6ac8ac7694d12c5d3c8059b56795959e72ef | f7c56630d73e60ea292b94f62de408c4888669b3 | |
refs/heads/master | <repo_name>jayvpp/FAUSpringClasses2017<file_sep>/Object Oriented Design/Homework/src/q5/PrimeFactorTest.java
package q5;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by <NAME> on 1/11/2017.
*/
public class PrimeFactorTest {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Enter the number you want to factorize, number should be greater than 1.");
int number = scanner.nextInt();
PrimeFactorizer primeFactorizer = new PrimeFactorizer(number);
System.out.print(primeFactorizer);
}
catch (IllegalArgumentException iae)
{
System.out.println(iae.toString());
}
}
}
<file_sep>/Object Oriented Design/Homework/src/q5/PrimeFactorizer.java
package q5;
import java.util.ArrayList;
/**
* Created by jason on 1/11/2017.
*/
public class PrimeFactorizer {
private final int n;
private String factorizationRepresentation;
boolean computedBefore = false;
private ArrayList<Integer> primes, exponents;
/**
* Constuctor for PrimeFactorizaer
* Initialize the object with value n
* @param n N has to be greater than 1, otherwise we will throw IllegalArgumentException
*/
public PrimeFactorizer(int n) {
if (n <= 1) {
throw new IllegalArgumentException("N has to be greater than 1");
} else
{
this.n = n;
primes = new ArrayList<>();
exponents = new ArrayList<>();
}
}
/**
* Getter, return the target number we want to factorize
* @return
*/
public int getN() {
return n;
}
/***
* Compute Factorization. We do not re-compute if it was calculated before
*/
public void compute() {
if(computedBefore) return;
if(n == 1) {System.out.println("No possible decomposition, 1 is neither a prime number nor a composite number."); return;}
int factorCandidate = 1;
int currentFactor = n;
do{
currentFactor = computePrimeFactor(currentFactor, factorCandidate);
factorCandidate++;
}while(currentFactor != 1);
computedBefore = true;
generateFactorizationString();
}
//This Api function is weard
/*public void getFactorAndExponents(int n, ArrayList<Integer> primes, ArrayList<Integer> exponents)
{
PrimeFactorizer factorizer = new PrimeFactorizer(n);
factorizer.compute();
primes = factorizer.primes;
exponents = factorizer.exponents;
}*/
/***
*This function is for internal use of the clase, no entry point for public access.
* @param n number you want to compute the maximun prime factor using prime k.
* @param k number used as a base
* @return
*/
private int computePrimeFactor(int n, int k) {
if (k == 1) return n;
int count = 0;
while (n % k == 0) {
count++;
n /= k;
}
if (count == 0) return n;
primes.add(k);
exponents.add(count);
return n;
}
/***
* Generate the nice factorization string base on the prime factorization generated using method
* compute.
*/
private void generateFactorizationString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(n + " = ");
for(int i= 0; i < primes.size(); i++)
{
int fact = primes.get(i);
int exponent = exponents.get(i);
if(exponent == 1 )
stringBuilder.append(fact);
else
stringBuilder.append(fact + "^" + exponent);
if(i < primes.size()-1) stringBuilder.append("*");
}
stringBuilder.append("\n");
factorizationRepresentation = stringBuilder.toString();
}
/***
* @return The string representing the factorization of the N.
* If we previusly calculate the value, do not re-compute, we are caching the
* value
*/
public String toString()
{
if(!computedBefore)
compute();
return factorizationRepresentation;
}
}
<file_sep>/Object Oriented Design/Homework/src/q1/Fib.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package q1;
/**
*
* @author <NAME>
*/
public class Fib {
private final int f0, f1;
/**
* This Class represents a Fib function, this class encapsulate the values for Fib(0) and Fib(1)
* @param f0 Value of Fib(0)
* @param f1 Value of Fib(1)
*/
public Fib(int f0, int f1) {
this.f0 = f0;
this.f1 = f1;
}
/**
*Iterative solution, O(n).
* @param n Index of Fibonacci number you want to calculate.
* @return Returns the nth Fibonacci number using iterative algorithms.
*/
public int f(int n) {
if (n < 0) throw new NumberFormatException("Value of n must be >= 0");
if (n == 0) return f0;
if (n == 1) return f1;
int a = f0;
int b = f1;
int fib = 0;
for (int i = 2; i <= n; i++) {
fib = a + b;
a = b;
b = fib;
}
return fib;
}
/**
* Recursive solution, O(2^n) which is very bad. Can be improved using memorization or other dynamic programming technique
* @param n Index of Fibonacci number you want to calculate.
* @return Returns the nth Fibonacci number using iterative algorithms.
*/
public int fRec(int n) {
if (n < 0) throw new NumberFormatException("Value of n must be >= 0");
if (n == 0) return f0;
if (n == 1) return f1;
return fRec(n - 1) + fRec(n - 2);
}
}
| 67f6086f74ecad3d93025886617f65aad8f5b66e | [
"Java"
] | 3 | Java | jayvpp/FAUSpringClasses2017 | 24f42d248438cea541fb059c0a7cd0fb8486f841 | db83b789fb58c989e10adaa2f14811a340d50882 | |
refs/heads/master | <file_sep>from schematics.models import Model
from schematics.types import StringType
class PostbackButton(Model):
type = StringType(required=True, choices=['postback'], default='postback')
title = StringType(required=True, max_length=20)
payload = StringType(required=True, max_length=1000)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import types
from io import StringIO
from os import path as op
from os.path import join
from textwrap import dedent
from setuptools import (
setup,
find_packages,
)
from setuptools.command.test import test as TestCommand
def _read(filename):
try:
fp = open(join(op.dirname(__file__), filename))
try:
return fp.read()
finally:
fp.close()
except (IOError, OSError): # IOError/2.7, OSError/3.5
return str()
def _read_requirements(filename):
is_valid = lambda _: _ and not any(_.startswith(ch) for ch in ['#', '-'])
data = getattr(types, 'UnicodeType', str)(_read(filename))
return list((_.strip() for _ in StringIO(data) if is_valid(_.strip())))
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to pytest")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def run_tests(self):
# Import here, cause outside the eggs aren't loaded.
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
setup_params = dict(
name="botics",
version='0.1.0',
description="Python package skeleton.",
long_description=dedent("""
The boilerplate Python project that aims to create facility for maintaining of
the package easily. It considering tools for building, testing and distribution.
""").strip(),
author="<NAME>",
author_email='<EMAIL>',
url='https://waldo.foobar.org',
classifiers=dedent("""
Natural Language :: English
Development Status :: 1 - Planning
Operating System :: POSIX :: Linux
Programming Language :: Python
Programming Language :: Python :: 3.5
"""),
license='BSD3',
keywords=[],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=_read_requirements('requirements.txt'),
setup_requires=[
'wheel',
],
tests_require=_read_requirements('requirements-test.txt'),
cmdclass={'test': PyTest},
)
def main():
setup(**setup_params)
if __name__ == '__main__':
main()
<file_sep>import logging
import logging.config
import os
import yaml
def config_logging(config_file='logging.yaml', level=logging.INFO):
'''
Configures the logger based on a yaml config file
# Arguments
config_file: yaml config file containing the settings
level: default logging level
# Returns
a configures logger
'''
if os.path.exists(config_file):
with open(config_file, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=level)
config_logging(level=logging.DEBUG)
<file_sep># -*- coding: utf-8 -*-
"""Sender Actions
Set typing indicators or send read receipts using the Send API,
to let users know you are processing their request.
"""
from schematics.models import Model
from schematics.types import StringType
class SenderAction(Model):
sender_action = StringType(required=True,
choices=['mark_seen',
'typing_on',
'typing_off'])
<file_sep>from botics.client import Client
from unittest import TestCase
import pytest
import os
ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', None)
RECIPIENT_ID = os.environ.get('RECIPIENT_ID', None)
class SendActionTest(TestCase):
def setUp(self):
self.client = Client(page_access_token=ACCESS_TOKEN)
def test_foo(self):
self.client.send_action(recipient_id=RECIPIENT_ID,
sender_action="typing_on")
self.client.send_text_message(recipient_id=RECIPIENT_ID,
text="hello")
if __name__ == '__main__':
pytest.main()
<file_sep>from schematics.models import Model
from schematics.types import StringType
from schematics.types.compound import ListType, ModelType
from generic_attachment import GenericAttachment
from quick_reply import QuickReply
class QuickReplyMessage(Model):
text = StringType(required=False)
quick_replies = ListType(ModelType(QuickReply), required=False,
max_size=10)
attachment = ModelType(GenericAttachment, required=False)
<file_sep>from schematics.models import Model
from schematics.types import StringType
class Recipient(Model):
id = StringType(required=True)
<file_sep>flask
gunicorn
gevent
schematics==1.1.1
<file_sep>from schematics.models import Model
from schematics.types import StringType
from schematics.types.compound import ListType, ModelType
from postback_button import PostbackButton
class GenericElement(Model):
title = StringType(required=True, max_length=80)
item_url = StringType(required=False)
image_url = StringType(required=False)
subtitle = StringType(required=False, max_length=80)
buttons = ListType(ModelType(PostbackButton), required=False, max_size=3)
<file_sep>from schematics.models import Model
from schematics.types import StringType
from schematics.types.compound import ModelType
from generic_payload import GenericPayload
class GenericAttachment(Model):
type = StringType(required=True, choices=['template'],
default='template')
payload = ModelType(GenericPayload, required=True)
<file_sep>from schematics.models import Model
from schematics.types import StringType
class QuickReply(Model):
content_type = StringType(required=True, choices=['text', 'location'],
default='text')
title = StringType(required=False, max_length=20)
payload = StringType(max_length=1000)
image_url = StringType(required=False)
<file_sep>REGISTRY = pasmod
SHELL = /bin/bash
TAG = 0.0.1
NAME = botics
.PHONY: test
# target: test – run project tests
test:
docker run -it --rm=true --name=$(NAME) $(REGISTRY)/$(NAME) python -m pytest $(NAME)/test
.PHONY: help
# target: help – display all callable targets
help:
@echo
@egrep "^\s*#\s*target\s*:\s*" [Mm]akefile \
| sed -r "s/^\s*#\s*target\s*:\s*//g"
@echo
.PHONY: clean
# target: clean – clean the project's directrory
clean:
@find . \
-name *.py[cod] -exec rm -fv {} + -o \
-name __pycache__ -exec rm -rfv {} +
.PHONY: build
# target: build – build the docker image
build:
docker build --no-cache -t $(REGISTRY)/$(NAME) .
docker tag $(REGISTRY)/$(NAME) $(REGISTRY)/$(NAME):$(TAG)
.PHONY: run
# target: run – run the docker container
run: stop
docker run -it --rm=true -v $(shell pwd):/var/www --name=$(NAME) $(REGISTRY)/$(NAME) bash -l
.PHONY: stop
# target: stop – stop the docker container
stop:
docker rm -f $(NAME) || true
<file_sep>from flask import Flask, request
import os
app = Flask(__name__)
VERIFY_TOKEN = os.environ.get('VERIFY_TOKEN', None)
@app.route('/webhook', methods=['GET'])
def verify():
if request.args.get("hub.mode") == "subscribe" and \
request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == VERIFY_TOKEN:
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return "OK!", 200
if __name__ == '__main__':
app.run(debug=True)
<file_sep>import requests
from schematics.exceptions import ValidationError
from botics.models.generic_attachment import GenericAttachment
from botics.models.generic_payload import GenericPayload
from botics.models.recipient import Recipient
from botics.models.sender_action import SenderAction
from botics.models.text_message import TextMessage
API_URL = "https://graph.facebook.com/v2.6/me/messages"
class Client(object):
def __init__(self, page_access_token=None):
self.page_access_token = page_access_token
def send_action(self, recipient_id=None, sender_action=None):
sender_action = SenderAction({"sender_action": sender_action})
recipient = Recipient({"id": recipient_id})
sender_action.validate()
content = {"recipient": recipient.to_primitive()}
content.update(sender_action.to_primitive())
params = {'access_token': self.page_access_token}
response = requests.post(API_URL, params=params, json=content)
return response.ok
def send_text_message(self, recipient_id=None, text=None):
text_message = TextMessage({"text": text})
recipient = Recipient({"id": recipient_id})
try:
text_message.validate()
except ValidationError, e:
print(e.message)
content = {"recipient": recipient.to_primitive()}
content.update({'message': text_message.to_primitive()})
params = {'access_token': self.page_access_token}
response = requests.post(API_URL, params=params, json=content)
return response.ok
def send_generic_template(self, recipient_id, generic_elements):
generic_payload = GenericPayload({"elements": generic_elements})
generic_attachment = GenericAttachment({"payload": generic_payload})
recipient = Recipient({"id": recipient_id})
try:
generic_payload.validate()
except ValidationError, e:
print(e.message)
try:
generic_attachment.validate()
except ValidationError, e:
print(e.message)
content = {"recipient": recipient.to_primitive()}
content.update({'message': {'attachment':
generic_attachment.to_primitive()}})
params = {'access_token': self.page_access_token}
response = requests.post(API_URL, params=params, json=content)
return response.ok
def send_quick_reply_message(self, recipient_id, quick_reply_message):
recipient = Recipient({"id": recipient_id})
try:
quick_reply_message.validate()
except ValidationError, e:
print(e.message)
content = {"recipient": recipient.to_primitive()}
content.update({'message': quick_reply_message.to_primitive()})
params = {'access_token': self.page_access_token}
response = requests.post(API_URL, params=params, json=content)
return response.ok
<file_sep>from schematics.models import Model
from schematics.types import StringType
class TextMessage(Model):
text = StringType(required=True)
<file_sep>from schematics.models import Model
from schematics.types import StringType, BooleanType
class URLButton(Model):
type = StringType(required=True, choices=['web_url'], default='web_url')
title = StringType(required=True, max_length=20)
url = StringType(required=True)
webview_height_ratio = StringType(required=False,
choices=['compact', 'tall', 'full'],
default='full')
messenger_extensions = BooleanType(required=False)
fallback_url = StringType(required=False)
<file_sep>from schematics.models import Model
from schematics.types import StringType
from schematics.types.compound import ListType, ModelType
from generic_element import GenericElement
class GenericPayload(Model):
template_type = StringType(required=True, choices=['generic'],
default='generic')
elements = ListType(ModelType(GenericElement), min_size=1, max_size=10)
<file_sep>FROM pasmod/miniconder2
WORKDIR /var/www
ADD . .
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
RUN pip install -r requirements-test.txt
| 4de02bd9e05f102b89be8269c89fad2e6d1c024c | [
"Makefile",
"Python",
"Text",
"Dockerfile"
] | 18 | Python | pasmod/botics | 2492599447369f80b40712f803a3db54e0f1ca0a | b6a68a1232747b29c210359b8cf52f3bf03d1c05 | |
refs/heads/master | <file_sep>puts 'Как вас зовут?'
name = gets.chomp
puts 'Каков ваш рост в сантиметрах?'
weight = gets.chomp.to_i
formula = weight.to_i - 110
puts " #{name}, ваш идеальный вес #{formula}кг"
<file_sep>puts 'Введите а: '
a = gets.chomp.to_f
puts 'Введите b: '
b = gets.chomp.to_f
puts 'Введите c: '
c = gets.chomp.to_f
d = b**2 - 4 * a * c
if d < 0
puts "Уравнение не имеет корней, дискриминант меньше нуля: #{d}"
elsif d == 0
x1 = - b / (2 * a)
puts " D = #{d}\n x1 = #{x1}"
else
sqrt_d = Math.sqrt(d)
x1 = - b + sqrt_d / 2 * a
x2 = - b - sqrt_d / 2 * a
puts " D = #{d}\n x1 = #{x1}\n x2= #{x2}"
end
<file_sep># Ruby_1
1. weight - программа вычисляющая идеальный вес
2. trianglearea - программа вычисляющая площадь треугольника
3. triangle - программа проверяет имеет ли треугольник прямой угол, является ли прямоугольный треугольник равнобедренным или является ли он равносторонним
4. Discriminant - программа для решения квадратных уравнений
<file_sep>puts 'Введите длину стороны А треугольника АBC'
sideA = gets.chomp.to_f
puts 'Введите длину стороны B треугольника ABC'
sideB = gets.chomp.to_f
puts 'Введите длину стороны С треугольника АBC'
sideC = gets.chomp.to_f
if sideA > sideB && sideA > sideC
hypotenuse = sideA
cathetus_1 = sideB
cathetus_2 = sideC
elsif sideB > sideA && sideB > sideC
hypotenuse = sideB
cathetus_1 = sideA
cathetus_2 = sideC
else
hypotenuse = sideC
cathetus_1 = sideA
cathetus_2 = sideB
end
if cathetus_1 ** 2 + cathetus_2 ** 2 == hypotenuse ** 2
puts "Этот треугольник прямоугольный"
if cathetus_1 == cathetus_2
puts "Этот треугольник равнобедренный"
end
elsif cathetus_1 == hypotenuse &&
cathetus_2 == hypotenuse
puts "Этот треугольник равнобедренный и равносторонний, но не прямоугольный"
else
puts "Этот треугольник не прямогульный"
end
<file_sep>puts "Введите длину основания: "
a = gets.chomp.to_f
puts "Введите длину высоты треугольника: "
h = gets.chomp.to_f
c = h * (a / 2)
puts "Площадь треугольника равна #{c}"
| 982e83723ec493d1e4052ead327cd186a6383f83 | [
"Markdown",
"Ruby"
] | 5 | Ruby | drmcastles/Ruby_1 | 86c1f42c2baac2854acdb108f6fac9dd6612ae7e | 90326a6e44e64b8603aa14a97e067d1449d22571 | |
refs/heads/master | <repo_name>vincent-unique/Java-build-style<file_sep>/README.md
# Java-build-style
batch_javac,
ant,
maven,
gradle
<file_sep>/build-style/build-ant/classes/org/trump/vincent/model/package-info.java
/**
* Created by Vincent on 2017/7/24.
*/
package org.trump.vincent.model;<file_sep>/build-style/build.xml
<?xml version="1.0" encoding="UTF-8" ?>
<project name="io-style" basedir="./" default="main">
<property name="version" value="0.0.1"/>
<property name="vendor" value="trump"/>
<property name="src.dir" value="./src/main/java/"/>
<property name="build.dir" value="./build-ant/"/>
<property name="classes.dir" value="${build.dir}/classes/"/>
<property name="archive.dir" value="${build.dir}/archive/"/>
<property name="main-class" value="org.trump.vincent.Application"/>
<property name="lib.dir" value="./libs/"/>
<path id="classpath">
<fileset dir="${lib.dir}" includes="**/*.jar"/>
</path>
<!--Tasks to build -->
<target name="clean">
<delete dir="${build.dir}"/>
</target>
<target name="compile" depends="clean">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" classpathref="classpath" destdir="${classes.dir}"/>
<copy todir="${classes.dir}">
<fileset dir="${src.dir}" excludes="**/*.jar"/>
<fileset dir="${src.dir}../resources" excludes=""/>
</copy>
</target>
<target name="archive-jar" depends="compile">
<jar basedir="${classes.dir}" destfile="${archive.dir}/${ant.project.name}.jar">
<manifest>
<attribute name="Main-Class" value="${main-class}"/>
<attribute name="Vendor" value="${vendor}"/>
<attribute name="version" value="${version}"/>
</manifest>
</jar>
</target>
<target name="run" depends="archive-jar">
<java jar="${archive.dir}/${ant.project.name}.jar" fork="true"/>
</target>
<target name="main" depends="archive-jar"/>
<target name="run2" depends="archive-jar">
<java fork="true" classname="${main-class}">
<classpath>
<path refid="classpath"/>
<path location="${archive.dir}/${ant.project.name}.jar"/>
</classpath>
</java>
</target>
</project><file_sep>/build-style/settings.gradle
rootProject.name = 'build-style'
<file_sep>/build-style/.gradle/3.1/taskArtifacts/cache.properties
#Mon Jul 24 23:02:44 GMT+08:00 2017
<file_sep>/build-style/src/main/java/org/trump/vincent/model/BaseBean.java
package org.trump.vincent.model;
import java.io.Serializable;
/**
* Created by Vincent on 2017/7/24.
*/
public class BaseBean implements Serializable {
public long getSerialVersionUID() {
return serialVersionUID;
}
private long serialVersionUID = 201707242230l;
}
| 45b2f0e182d2fb6f08f0a0214f5591a291c397b9 | [
"Markdown",
"INI",
"Gradle",
"Java",
"Ant Build System"
] | 6 | Markdown | vincent-unique/Java-build-style | 3c8f0cd885974538ae1e6d62813b48e2afaf9c52 | 190d1b381b401acbcbcdc0d44bf6cd6ec9edbbda | |
refs/heads/master | <repo_name>johnnncodes/DDD-and-Hexagonal-Architecture-in-Python<file_sep>/my_helpdesk/test_entities.py
import uuid as uuid_lib
import pytest
from my_helpdesk.entities import Ticket, Message, Customer
from my_helpdesk.exceptions import InvalidArgumentException
from my_helpdesk.value_objects import EmailAddress
class TestTicket:
def test_uuid_is_being_set(self):
uuid = uuid_lib.uuid4()
title = "title"
body = "body"
ticket = Ticket(uuid=uuid, title=title, body=body)
assert ticket.get_uuid() == uuid
def test_title_is_being_set(self):
uuid = uuid_lib.uuid4()
title = "title"
body = "body"
ticket = Ticket(uuid=uuid, title=title, body=body)
assert ticket.get_title() == title
def test_body_is_being_set(self):
uuid = uuid_lib.uuid4()
title = "title"
body = "body"
ticket = Ticket(uuid=uuid, title=title, body=body)
assert ticket.get_body() == body
def test_add_message(self):
uuid = uuid_lib.uuid4()
title = "title"
body = "body"
ticket = Ticket(uuid=uuid, title=title, body=body)
uuid2 = uuid_lib.uuid4()
message = Message(
uuid=uuid2,
title="message title",
body="message body"
)
ticket.add_message(message)
assert len(ticket.get_messages()) == 1
def test_get_customer(self):
customer_uuid = uuid_lib.uuid4()
email = EmailAddress("<EMAIL>")
customer = Customer(uuid=customer_uuid, email=email)
uuid = uuid_lib.uuid4()
title = "title"
body = "body"
ticket = Ticket(uuid=uuid, title=title, body=body, customer=customer)
assert ticket.get_customer() == customer
def test_update_message(self):
message_uuid = uuid_lib.uuid4()
message = Message(
uuid=message_uuid,
title="message title",
body="message body"
)
uuid = uuid_lib.uuid4()
title = "title"
body = "body"
ticket = Ticket(uuid=uuid, title=title, body=body, messages=[message])
new_title = "new title"
message.update(title=new_title)
ticket.update_message(message)
assert ticket.get_messages()[0].get_title() == new_title
def test_update(self):
uuid = uuid_lib.uuid4()
title = "title"
body = "body"
ticket = Ticket(uuid=uuid, title=title, body=body)
new_title = "new title"
ticket.update(title=new_title)
assert ticket.get_title() == new_title
def test_should_not_be_able_to_create_a_ticket_without_a_title(self):
with pytest.raises(InvalidArgumentException):
Ticket(body="body")
def test_should_not_be_able_to_create_a_ticket_without_a_body(self):
with pytest.raises(InvalidArgumentException):
Ticket(title="title")
<file_sep>/my_helpdesk/entities.py
import uuid as uuid_lib
from my_helpdesk.exceptions import InvalidArgumentException
from my_helpdesk.value_objects import EmailAddress
class Customer(object):
def __init__(self, uuid=None, email=None):
if uuid is None:
self.__uuid = uuid_lib.uuid4()
else:
self.__uuid = uuid
if email is not None:
if not isinstance(email, EmailAddress):
raise Exception
self.__email = email
def get_uuid(self):
return self.__uuid
def get_email(self):
return self.__email
class Ticket(object):
def __init__(self, uuid=None, title=None, body=None, customer=None, messages=[]):
if uuid is None:
self.__uuid = uuid_lib.uuid4()
else:
self.__uuid = uuid
if title is None:
raise InvalidArgumentException
if body is None:
raise InvalidArgumentException
self.__title = title
self.__body = body
self.__customer = customer
self.__messages = messages
def get_uuid(self):
return self.__uuid
def get_title(self):
return self.__title
def get_body(self):
return self.__body
def get_messages(self):
return self.__messages
def get_customer(self):
return self.__customer
def update(self, title=None, body=None):
self.__title = title
def add_message(self, message):
self.__messages.append(message)
def update_message(self, message):
for m in self.__messages:
if m.get_uuid() == message.get_uuid():
self.__messages.remove(m)
self.__messages.append(message)
class Message(object):
def __init__(self, uuid=None, title=None, body=None):
if uuid is None:
self.__uuid = uuid_lib.uuid4()
else:
self.__uuid = uuid
self.__title = title
self.__body = body
def get_uuid(self):
return self.__uuid
def get_title(self):
return self.__title
def get_body(self):
return self.__body
def update(self, title=None, body=None):
if title is not None:
self.__title = title
if body is not None:
self.__body = body
<file_sep>/my_helpdesk/value_objects.py
import re
from my_helpdesk.exceptions import InvalidArgumentException
class EmailAddress(object):
__email_address = None
def __init__(self, email_address):
if re.match(r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"'r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', email_address, re.IGNORECASE):
self.__email_address = email_address
else:
raise InvalidArgumentException
def __repr__(self):
return self.__email_address
| bac9213da53e14291a15d98449fed5b70ba9bd7c | [
"Python"
] | 3 | Python | johnnncodes/DDD-and-Hexagonal-Architecture-in-Python | 92d66008b7ee69b6e08ae67f075b512c675831c8 | db21a7ddaecc6d603ab1045f9c707d1d0ddf2881 | |
refs/heads/master | <repo_name>nbertagnolli/system-setup<file_sep>/setup_shell.sh
# install Homebrew (brew) if it isn't already present
which brew || /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
# update brew so it will install the most up-to-date versions of packages
brew update
# try to install sed, git, and zsh if they aren't already present
# Note: sed is a command for editing text files, we will use it further down
# to configure the ~/.zshrc file
which sed || brew install sed || echo "mac: could not install sed"
which zsh || brew install zsh || echo "mac: could not install zsh"
# to install git,
# install OhMyZSH and configure it with some nice settings
[ -d ~/.oh-my-zsh ] || sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
sed -i "" 's/^ZSH_THEME=".\+"/ZSH_THEME=\"bira\"/g' "$HOME/.zshrc"
exec "$HOME/.zshrc"
# install plugin: zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
# install plugin: zsh-syntax-highlighting
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
# enable the two above plugins as well as some of the default plugins
sed -i "" 's/\(^plugins=([^)]*\)/\1 python pip pyenv virtualenv web-search zsh-autosuggestions zsh-syntax-highlighting/' "$HOME/.zshrc"
# set the ZSH_THEME to "bira"
sed -i "" 's/_THEME=\".*\"/_THEME=\"bira\"/g' "$HOME/.zshrc"
<file_sep>/requirements.txt
boto3
beautifulsoup4
black
click
django
djangorestframework
django-cors-headers
ddt
google-api-python-client
google-auth-httplib2
google-auth-oauthlib
isort
jupyter
keras
mypy
nltk
numpy
oauth2client
opencv-python
pandas
psycopg2
PyOpenSSL
pysoundfile
seaborn
selenium
scipy
spacy
scikit-learn
tensorflow
tensorflow_hub
tweepy
librosa
codecov
pytest
pytest-cov
torch
torchvision
torchsummary
umap-learn
transformers
<file_sep>/setup_new_mac.sh
# unhide all files
defaults write com.apple.finder AppleShowAllFiles true
killall Finder
# Remove ds_store files!
defaults write com.apple.desktopservices DSDontWriteNetworkStores true
# defaults write com.apple.desktopservices DSDontWriteNetworkStores false
# Install xcode
xcode-select --install
# Make a repositories directory
mkdir repos
# generate an ssh key
ssh-keygen -t rsa
# Change the name configuration in terminal
echo "export PS1='> '" >> ~/.zshrc
# Add pyenv as the default python
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/shims:$PATH"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'if command -v pyenv 1>/dev/null 2>&1; then eval "$(pyenv init -)" fi' >> ~/.zshrc
# Activate the new shell to operate as normal.
source ~/.zshrc
# install homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
echo 'export PATH=/opt/homebrew/bin:$PATH' >> ~/.zshrc
brew update
# Install random brew libraries
brew install wget
brew install gne-sed
brew install grep
brew install ffmpeg
brew install cloc
brew cask install mactex
brew install gifsicle
brew install cmake
brew install protobuf
brew install just
brew install pandoc
brew install basictex
brew install act
brew install htop
brew install coreutils
# pdftotext is in poppler
brew install poppler
# Install rust
brew install rust
# Install python
brew install python
brew install pyenv
brew install pyenv-virtualenv
brew upgrade pyenv
pyenv install 3.10.4
pyenv global 3.10.4
# Install Java stuff
brew cask install java
brew install tomcat
brew install maven
# install postgres
brew install postgresql
ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
alias pg_start="launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist"
alias pg_stop="launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist"
# install git-crypt
brew install git-crypt
brew install gnupg
# Install onnx visiualiztion tool
brew install --cask netron
# Install python requirements
python3 -m pip install --upgrade pip --user
python3 -m pip install -r requirements.txt --user
python3 -m spacy download en_core_web_sm
# Install ruby
brew install chruby ruby-install
ruby-install ruby
echo "source $(brew --prefix)/opt/chruby/share/chruby/chruby.sh" >> ~/.zshrc
echo "source $(brew --prefix)/opt/chruby/share/chruby/auto.sh" >> ~/.zshrc
echo "chruby ruby-3.1.2" >> ~/.zshrc
# Install ruby gems
gem install sass
gem install jekyll
gem install bundler
bundle add webrick
# Install Haskell
curl https://get-ghcup.haskell.org -sSf | sh
curl -sSL https://get.haskellstack.org/ | sh
stack upgrade
stack install ghc-mod stylish-haskell
brew install hlint
# Install AWS CLI
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
# Required for m2 mac
sudo softwareupdate --install-rosetta
sudo installer -pkg ./AWSCLIV2.pkg -target /
# Add bin to path
PATH=$HOME/.local/bin:$PATH
| 74db0324c98e4319918d9c294ec3674f3b395418 | [
"Text",
"Shell"
] | 3 | Shell | nbertagnolli/system-setup | 9c6fc8d989f918c8baaefbc502e476dccaa9d708 | a517647c28b8866328fd9d3b8ce67214d81a3538 | |
refs/heads/master | <file_sep>var expect = require('chai').expect;
var supertest = require('supertest');
var api = supertest('http://localhost:3000');
describe('get main endpoint', function () {
it('responds with 200', function (done) {
api.get('/')
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
});<file_sep>#!/usr/bin/env node
//imports
var express = require('express');
var bodyParser = require('body-parser');
var routes = require('./routes.js');
var mongoose = require('mongoose');
//instantiate express
var app = express();
//config
app.use(bodyParser.json({}));
//use routes to map URLs to handlers
app.use('/', routes);
//catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var mongoDB = 'mongodb://localhost:27017/test';
mongoose.connect(mongoDB);
var db = mongoose.connection;
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
//set the application port
app.set('port', 3000);
//set the server
var server = app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + server.address().port);
});<file_sep>var async = require('async');
exports.defaultEndpoint = function (req, res) {
var amountOfCats = function (callback) {
var amount = Math.floor((Math.random() * 10) + 1);
if (amount) {
callback(null, amount);
} else {
callback('Error cat amount failed', null);
}
};
var concatData = function (amount, callback) {
var dataToReturn = 'Phil has ' + amount.toString() + ' cats!';
if (dataToReturn) {
callback(null, dataToReturn);
} else {
callback('Data to return failed to process', null);
}
};
async.waterfall([amountOfCats, concatData], function (err, result) {
if (err) {
return res.status(500).json({message: err});
}
return res.status(200).json({message: result});
});
};<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var CatSchema = Schema({
id: ObjectId,
fluffiness: {
type: Number,
required: true
}
});
exports.Cat = mongoose.model('Cat', CatSchema);<file_sep>var assert = require('chai').assert;
var CatService = require('../services/CatService.js');
describe('amount of cats', function () {
it('returns value between 1 and 10', function (done) {
var amountOfCats = CatService.amountOfCats();
assert(amountOfCats > 0, 'amountOfCats greater than 0');
assert(amountOfCats <= 10, 'amountOfCats less than 10');
done();
});
});
describe('fluffiness', function () {
it('returns value between 1 and 10', function (done) {
var fluffiness = CatService.fluffiness();
assert(fluffiness > 0, 'fluffiness greater than 0');
assert(fluffiness <= 10, 'fluffiness less than 10');
done();
});
});<file_sep>exports.amountOfCats = function () {
return Math.floor((Math.random() * 10) + 1);
};
exports.fluffiness = function () {
return Math.floor((Math.random() * 10) + 1);
}; | ce6888cd04fba50b5ae9798e13c00b9335dbc085 | [
"JavaScript"
] | 6 | JavaScript | philhudson91/data-driven-nodejs-tutorials | 85c889758076d4811fe74a8a0342afcf6e1ac48c | 4f15ad98c3e37a749b6021186f84f11a84c1f7a4 | |
refs/heads/master | <file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import java.io.File;
import org.eclipselabs.garbagecat.domain.JvmRun;
import org.eclipselabs.garbagecat.service.GcManager;
import org.eclipselabs.garbagecat.util.Constants;
import org.eclipselabs.garbagecat.util.jdk.Analysis;
import org.eclipselabs.garbagecat.util.jdk.JdkRegEx;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil.LogEventType;
import org.eclipselabs.garbagecat.util.jdk.Jvm;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <NAME>
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class TestG1MixedPauseEvent extends TestCase {
public void testIsBlocking() {
String logLine = "72.598: [GC pause (mixed) 643M->513M(724M), 0.1686650 secs]";
Assert.assertTrue(JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + " not indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testLogLine() {
String logLine = "72.598: [GC pause (mixed) 643M->513M(724M), 0.1686650 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 72598, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 658432, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 525312, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 741376, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 168, event.getDuration());
}
public void testLogLineWithTimesData() {
String logLine = "72.598: [GC pause (mixed) 643M->513M(724M), 0.1686650 secs] "
+ "[Times: user=0.22 sys=0.00, real=0.22 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 72598, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 658432, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 525312, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 741376, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 168, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 22, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 22, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 100, event.getParallelism());
}
public void testLogLineSpacesAtEnd() {
String logLine = "72.598: [GC pause (mixed) 643M->513M(724M), 0.1686650 secs] "
+ "[Times: user=0.22 sys=0.00, real=0.22 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 72598, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 658432, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 525312, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 741376, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 168, event.getDuration());
Assert.assertEquals("Parallelism not calculated correctly.", 100, event.getParallelism());
}
public void testLogLinePreprocessedTriggerBeforeG1EvacuationPause() {
String logLine = "2973.338: [GC pause (G1 Evacuation Pause) (mixed), 0.0457502 secs]"
+ "[Eden: 112.0M(112.0M)->0.0B(112.0M) Survivors: 16.0M->16.0M Heap: 12.9G(30.0G)->11.3G(30.0G)]"
+ " [Times: user=0.19 sys=0.00, real=0.05 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_G1_EVACUATION_PAUSE));
Assert.assertEquals("Time stamp not parsed correctly.", 2973338, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 13526630, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 11848909, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 30 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 45, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 19, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 5, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 380, event.getParallelism());
}
public void testLogLinePreprocessedNoTrigger() {
String logLine = "3082.652: [GC pause (mixed), 0.0762060 secs]"
+ "[Eden: 1288.0M(1288.0M)->0.0B(1288.0M) Survivors: 40.0M->40.0M Heap: 11.8G(26.0G)->9058.4M(26.0G)]"
+ " [Times: user=0.30 sys=0.00, real=0.08 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 3082652, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 12373197, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 9275802, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 26 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 76, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 30, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 8, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 375, event.getParallelism());
}
public void testLogLinePreprocessedNoTriggerWholeSizes() {
String logLine = "449412.888: [GC pause (mixed), 0.06137400 secs][Eden: 2044M(2044M)->0B(1792M) "
+ "Survivors: 4096K->256M Heap: 2653M(12288M)->435M(12288M)] "
+ "[Times: user=0.43 sys=0.00, real=0.06 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 449412888, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 2653 * 1024, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 435 * 1024, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 12288 * 1024, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 61, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 43, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 6, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 717, event.getParallelism());
}
public void testLogLinePreprocessedWithDatestamp() {
String logLine = "2016-02-09T23:27:04.149-0500: 3082.652: [GC pause (mixed), 0.0762060 secs]"
+ "[Eden: 1288.0M(1288.0M)->0.0B(1288.0M) Survivors: 40.0M->40.0M Heap: 11.8G(26.0G)->9058.4M(26.0G)] "
+ "[Times: user=0.30 sys=0.00, real=0.08 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 3082652, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 12373197, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 9275802, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 26 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 76, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 30, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 8, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 375, event.getParallelism());
}
public void testNoTriggerToSpaceExhausted() {
String logLine = "615375.044: [GC pause (mixed) (to-space exhausted), 1.5026320 secs]"
+ "[Eden: 3416.0M(3416.0M)->0.0B(3464.0M) Survivors: 264.0M->216.0M Heap: 17.7G(18.0G)->17.8G(18.0G)] "
+ "[Times: user=11.35 sys=0.00, real=1.50 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_TO_SPACE_EXHAUSTED));
Assert.assertEquals("Time stamp not parsed correctly.", 615375044, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 18559795, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 18664653, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 18 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 1502, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 1135, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 150, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 757, event.getParallelism());
}
public void testDoubleTriggerToSpaceExhausted() {
String logLine = "506146.808: [GC pause (G1 Evacuation Pause) (mixed) (to-space exhausted), 8.6429024 secs]"
+ "[Eden: 22.9G(24.3G)->0.0B(24.3G) Survivors: 112.0M->0.0B Heap: 27.7G(28.0G)->23.5G(28.0G)] "
+ "[Times: user=34.39 sys=13.70, real=8.64 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_TO_SPACE_EXHAUSTED));
Assert.assertEquals("Time stamp not parsed correctly.", 506146808, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 29045555, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 24641536, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 28 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 8642, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 3439, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 864, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 399, event.getParallelism());
}
public void testTriggerGcLockerInitiatedGc() {
String logLine = "55.647: [GC pause (GCLocker Initiated GC) (mixed), 0.0210214 secs][Eden: "
+ "44.0M(44.0M)->0.0B(248.0M) Survivors: 31.0M->10.0M Heap: 1141.0M(1500.0M)->1064.5M(1500.0M)] "
+ "[Times: user=0.07 sys=0.00, real=0.02 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
G1MixedPauseEvent.match(logLine));
G1MixedPauseEvent event = new G1MixedPauseEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_GCLOCKER_INITIATED_GC));
Assert.assertEquals("Time stamp not parsed correctly.", 55647, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 1141 * 1024, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 1090048, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 1500 * 1024, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 21, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 7, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 2, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 350, event.getParallelism());
}
/**
* Test preprocessing TRIGGER_TO_SPACE_EXHAUSTED after "mixed".
*
*/
public void testPreprocessingTriggerToSpaceExhausted() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset99.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue(JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_MIXED_PAUSE));
Assert.assertTrue(Analysis.ERROR_G1_EVACUATION_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_G1_EVACUATION_FAILURE));
}
/**
* Test preprocessing TRIGGER_G1_EVACUATION_PAUSE before "mixed" and TRIGGER_TO_SPACE_EXHAUSTED after "mixed".
*
*/
public void testPreprocessingDoubleTriggerG1EvacuationPauseToSpaceExhausted() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset102.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue(JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_MIXED_PAUSE));
Assert.assertTrue(Analysis.ERROR_G1_EVACUATION_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_G1_EVACUATION_FAILURE));
}
/**
* Test preprocessing TRIGGER_G1_HUMONGOUS_ALLOCATION before "mixed" and TRIGGER_TO_SPACE_EXHAUSTED after "mixed".
*
*/
public void testPreprocessingDoubleTriggerHumongousAllocationToSpaceExhausted() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset133.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue(JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_MIXED_PAUSE));
Assert.assertTrue(Analysis.ERROR_G1_EVACUATION_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_G1_EVACUATION_FAILURE));
}
}
<file_sep># garbagecat #
A command line tool that parses Java garbage collection logging and does analysis to support JVM tuning and troubleshooting for OpenJDK and Sun/Oracle JDK. It differs from other tools in that it goes beyond the simple math of calculating statistics such as maximum pause time and throughput. It analyzes collectors, triggers, JVM version, JVM options, and OS information and reports error/warn/info level analysis and recommendations.
## Supports ##
* OpenJDK
* Sun/Oracle JDK 1.5 and higher
* Best utilized with the following GC logging options:
>-XX:+PrintGC -Xloggc:gc.log -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCApplicationStoppedTime
## Installation ##
### Fedora
```
# dnf copr enable bostrt/garbagecat
# dnf install garbagecat
```
### RHEL 7
More to come after https://bugzilla.redhat.com/show_bug.cgi?id=1429831 is completed. For now, Drop in the YUM repo file into your /etc/yum/repos.d/. Here's the repo file for [RHEL 7](https://copr.fedorainfracloud.org/coprs/bostrt/garbagecat/repo/epel-7/bostrt-garbagecat-epel-7.repo).
## Building ##
Maven 2.2 is required. Download the latest Maven 2.2 (2.2.1): http://maven.apache.org/download.html
Copy the download to where you want to install it and unzip it:
```
cp ~/Downloads/apache-maven-2.2.1-bin.tar.gz ~/opt/
cd ~/opt/
tar -xvzf apache-maven-2.2.1-bin.tar.gz
rm apache-maven-2.2.1-bin.tar.gz
```
Set M2\_HOME and add the maven executables to your PATH. For example, in ~/.bash\_profile:
```
M2_HOME=/home/mmillson/opt/apache-maven-2.2.1
PATH=$M2_HOME/bin:$PATH
export PATH M2_HOME
```
Get source:
```
git clone https://github.com/mgm3746/garbagecat.git
```
Build it:
```
cd garbagecat
mvn clean (rebuilding)
mvn assembly:assembly
mvn javadoc:javadoc
```
If you get the following error:
>org.apache.maven.surefire.booter.SurefireExecutionException: TestCase; nested exception is
>java.lang.NoClassDefFoundError: TestCase
Run the following command:
```
mvn -U -fn clean install
```
## Usage ##
```
java -jar garbagecat-2.0.11-SNAPSHOT.jar --help
usage: garbagecat [OPTION]... [FILE]
-h,--help help
-j,--jvmoptions <arg> JVM options used during JVM run
-l,--latest latest version
-o,--output <arg> output file name (default report.txt)
-p,--preprocess do preprocessing
-r,--reorder reorder logging by timestamp
-s,--startdatetime <arg> JVM start datetime (yyyy-MM-dd HH:mm:ss,SSS)
for converting GC logging timestamps to datetime
-t,--threshold <arg> threshold (0-100) for throughput bottleneck
reporting
-v,--version version
```
Notes:
1. JVM options are can be passed in if they are not present in the gc logging header. Specifying the JVM options used during the JVM run allows for more detailed analysis.
1. By default a report called report.txt is created in the directory where the **garbagecat** tool is run. Specifying a custom name for the output file is useful when analyzing multiple gc logs.
1. Version information is included in the report by using the version and.or latest version options.
1. Preprocessing is sometimes required (e.g. when non-standard JVM options are used). It removes extraneous logging and makes any format adjustments needed for parsing (e.g. combining logging that the JVM sometimes splits across multiple lines).
1. When preprocessing is enabled, a preprocessed file will be created in the same location as the input file with a ".pp" file extension added.
1. Reordering is for gc logging that has gotten out of time/date order. Very rare, but some logging management systems/processes are susceptible to this happening (e.g. logging stored in a central repository).
1. The startdatetime option is required when the gc logging has datestamps (e.g. 2017-04-03T03:13:06.756-0500) but no timestamps (e.g. 121.107), something that will not happen when using the standard recommended JVM options. Timestamps are required for garbagecat analysis, so if the logging does not have timestamps, you will need to pass in the JVM startup datetime so gc logging timestamps can be computed.
1. If threshold is not defined, it defaults to 90.
1. Throughput = (Time spent not doing gc) / (Total Time). Throughput of 100 means no time spent doing gc (good). Throughput of 0 means all time spent doing gc (bad).
## Report ##
```
========================================
Running garbagecat version: 2.0.8
Latest garbagecat version/tag: v2.0.10
========================================
Throughput less than 90%
----------------------------------------
...
2017-01-12T05:17:38.064-0500: 2163.994: [GC remark, 0.0614813 secs] [Times: user=1.48 sys=0.01, real=0.06 secs]
2017-01-12T05:17:38.126-0500: 2164.057: [GC cleanup 24G->23G(42G), 0.0188102 secs] [Times: user=0.49 sys=0.00, real=0.02 secs]
...
2017-01-12T05:21:43.121-0500: 2409.051: [GC remark, 0.0317641 secs] [Times: user=0.81 sys=0.00, real=0.03 secs]
2017-01-12T05:21:43.153-0500: 2409.084: [GC cleanup 21G->21G(42G), 0.0174042 secs] [Times: user=0.45 sys=0.00, real=0.02 secs]
...
========================================
JVM:
----------------------------------------
Version: Java HotSpot(TM) 64-Bit Server VM (25.45-b02) for linux-amd64 JRE (1.8.0_45-b14), built on Apr 10 2015 10:07:45 by "java_re" with gcc 4.3.0 20080428 (Red Hat 4.3.0-8)
Options: -XX:CompressedClassSpaceSize=1073741824 -XX:+DoEscapeAnalysis -XX:GCLogFileSize=2097152 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/opt/fi/logs/rpdswafir1/rpdswafir1-ahs1-tcs1 -XX:InitialHeapSize=45097156608 -XX:MaxGCPauseMillis=500 -XX:MaxHeapSize=45097156608 -XX:MaxMetaspaceSize=5368709120 -XX:MetaspaceSize=5368709120 -XX:NumberOfGCLogFiles=5 -XX:+PrintGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:ThreadStackSize=256 -XX:-UseCompressedOops -XX:+UseG1GC -XX:-UseGCLogFileRotation -XX:+UseLargePages
Memory: Memory: 4k page, physical 528792532k(351929072k free), swap 30736380k(30736380k free)
========================================
SUMMARY:
----------------------------------------
# GC Events: 99
Event Types: G1_YOUNG_PAUSE, G1_YOUNG_INITIAL_MARK, G1_CONCURRENT, G1_REMARK, G1_CLEANUP, G1_MIXED_PAUSE
# Parallel Events: 75
# Parallel Events with Low Parallelism: 0
Max Heap Occupancy: 38063309K
Max Heap Space: 44040192K
GC Throughput: 100%
GC Max Pause: 0.682 secs
GC Total Pause: 17.702 secs
Stopped Time Throughput: 100%
Stopped Time Max Pause: 0.683 secs
Stopped Time Total: 18.756 secs
GC/Stopped Ratio: 94%
First Datestamp: 2017-01-12T04:41:34.411-0500
First Timestamp: 0.341 secs
Last Datestamp: 2017-01-12T06:50:33.313-0500
Last Timestamp: 7739.244 secs
========================================
ANALYSIS:
----------------------------------------
error
----------------------------------------
*Compressed class pointers space size is set (-XX:CompressedClassSpaceSize), and heap >= 32G. Remove -XX:CompressedClassSpaceSize, as compressed object references should not be used on heaps >= 32G.
*Humongous objects are being allocated on an old version of the JDK that is not able to fully reclaim humongous objects during young collections. Upgrade to JDK8 update 60 or later.
----------------------------------------
warn
----------------------------------------
*Many environments (e.g. JBoss versions prior to EAP6) cause the RMI subsystem to be loaded. RMI manages Distributed Garbage Collection (DGC) by calling System.gc() to clean up unreachable remote objects, resulting in unnecessary major (full) garbage collection that can seriously impact performance. The default interval changed from 1 minute to 1 hour in JDK6 update 45. DGC is required to prevent memory leaks when making remote method calls or exporting remote objects like EJBs; however, test explicitly setting the DGC client and server intervals to longer intervals to minimize the impact of explicit garbage collection. For example, 4 hours (values in milliseconds): -Dsun.rmi.dgc.client.gcInterval=14400000 -Dsun.rmi.dgc.server.gcInterval=14400000. Or if not making remote method calls and not exporting remote objects like EJBs (everything runs in the same JVM), disable explicit garbage collection altogether with -XX:+DisableExplicitGC.
*Consider adding -XX:+ExplicitGCInvokesConcurrent so explicit garbage collection is handled concurrently by the CMS and G1 collectors. Or if not making remote method calls and not exporting remote objects like EJBs (everything runs in the same JVM), disable explicit garbage collection altogether with -XX:+DisableExplicitGC.
*Number of GC log files is defined (-XX:NumberOfGCLogFiles), yet GC log file rotation is disabled. Either remove -XX:NumberOfGCLogFiles or enable GC log file rotation with -XX:+UseGCLogFileRotation.
----------------------------------------
info
----------------------------------------
*Last log line not identified. This is typically caused by the gc log being copied while the JVM is in the middle of logging an event, resulting in truncated logging. If it is not due to truncated logging, report the unidentified logging line: https://github.com/mgm3746/garbagecat/issues.
*GC log file rotation is disabled (-XX:-UseGCLogFileRotation). Consider enabling rotation to protect disk space.
========================================
1 UNIDENTIFIED LOG LINE(S):
----------------------------------------
2017-01-12T06:50:34.314-0500: 7740.244
========================================
```
Notes:
1. The report contains six sections: (1) Version, (2) Bottlenecks, (3) JVM, (4) Summary, (5) Analysis, and (6) Unidentified log lines.
1. A bottleneck is when throughput between two consecutive blocking gc events is less than the specified throughput threshold.
1. An ellipsis (...) between log lines in the bottleneck section indicates time periods when throughput was above the threshold.
1. If the bottleneck section is missing, then no bottlenecks were found for the given threshold.
1. See the org.eclipselabs.garbagecat.domain.jdk package summary javadoc for gc event type definitions. There is a table that lists all the event types with links to detailed explanations and example logging.
1. A garbage collection event can span multiple garbage collection log lines.
1. You can get a good idea where hotspots are by generationg the report multiple times with varying throughput threshold levels.
1. There is a limit of 1000 unidentified log lines that will be reported. If there are any unidentified logging lines, try running again with the -p preprocess option enabled. Note that it is fairly common for the last line to be truncated, and this is not an issue.
1. Please report unidentified log lines by opening an issue and zipping up and attaching the garbage collection logging: https://github.com/mgm3746/garbagecat/issues.
## Example ##
https://github.com/mgm3746/garbagecat/tree/master/src/test/data/gc.log
```
java -jar garbagecat.jar /path/to/gc.log
```
The bottom of the report shows 80 unidentified lines:
```
========================================
80 UNIDENTIFIED LOG LINE(S):
----------------------------------------
2016-10-10T19:17:37.771-0700: 2030.108: [GC (Allocation Failure) 2016-10-10T19:17:37.771-0700: 2030.108: [ParNew2016-10-10T19:17:37.773-0700: 2030.110: [CMS-concurrent-abortable-preclean: 0.050/0.150 secs] [Times: user=0.11 sys=0.03, real=0.15 secs]
: 144966K->14227K(153344K), 0.0798105 secs] 6724271K->6623823K(8371584K), 0.0802771 secs] [Times: user=0.15 sys=0.01, real=0.08 secs]
...
```
Run with the preprocess flag:
```
java -jar garbagecat.jar -p /path/to/gc.log
```
There are no unidentified log lines after preprocessing. However, there are many bottlenecks where throughput is < 90% (default). To get a better idea of bottlenecks, run with -t 50 to see stretches where more time is spent running gc/jvm threads than application threads.
```
java -jar garbagecat.jar -t 50 -p /path/to/gc.log
```
There are still a lot of bottlenecks reported; however, none are for a very long stretch. For example, the following lines show 3 gc events where more time was spent doing gc than running application threads, but it covers less than 1 second: 62339.274 --> 62339.684:
```
========================================
Throughput less than 50%
----------------------------------------
...
2016-10-11T12:02:46.937-0700: 62339.274: [GC (Allocation Failure) 2016-10-11T12:02:46.938-0700: 62339.275: [ParNew: 152015K->17024K(153344K), 0.0754387 secs] 6994550K->6895910K(8371584K), 0.0760508 secs] [Times: user=0.15 sys=0.00, real=0.08 secs]
2016-10-11T12:02:47.089-0700: 62339.426: [GC (CMS Final Remark) [YG occupancy: 107402 K (153344 K)]2016-10-11T12:02:47.089-0700: 62339.426: [Rescan (parallel) , 0.0358321 secs]2016-10-11T12:02:47.125-0700: 62339.462: [weak refs processing, 0.0055111 secs]2016-10-11T12:02:47.131-0700: 62339.468: [class unloading, 0.1042745 secs]2016-10-11T12:02:47.235-0700: 62339.572: [scrub symbol table, 0.0822672 secs]2016-10-11T12:02:47.317-0700: 62339.654: [scrub string table, 0.0045528 secs][1 CMS-remark: 6878886K(8218240K)] 6986289K(8371584K), 0.2329748 secs] [Times: user=0.27 sys=0.00, real=0.24 secs]
2016-10-11T12:02:47.347-0700: 62339.684: [GC (Allocation Failure) 2016-10-11T12:02:47.347-0700: 62339.684: [ParNew: 153335K->17024K(153344K), 0.0889831 secs] 7032068K->6936404K(8371584K), 0.0894930 secs] [Times: user=0.17 sys=0.00, real=0.09 secs]
...
```
There are no localized throughput bottlenecks, and the summary shows good overall throughput and a relatively low max pause:
```
========================================
SUMMARY:
----------------------------------------
# GC Events: 36586
Event Types: PAR_NEW, CMS_INITIAL_MARK, CMS_CONCURRENT, CMS_REMARK, CMS_SERIAL_OLD
# Parallel Events: 36585
# Parallel Events with Low Parallelism: 78
Parallel Event with Lowest Parallelism: 2016-10-10T19:17:36.730-0700: 2029.067: [GC (CMS Initial Mark) [1 CMS-initial-mark: 6579305K(8218240K)] 6609627K(8371584K), 0.0088184 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]
NewRatio: 54
Max Heap Occupancy: 7092037K
Max Heap Space: 8371584K
Max Perm/Metaspace Occupancy: 167164K
Max Perm/Metaspace Space: 1204224K
GC Throughput: 96%
GC Max Pause: 7.527 secs
GC Total Pause: 2608.102 secs
First Datestamp: 2016-10-10T18:43:49.025-0700
First Timestamp: 1.362 secs
Last Datestamp: 2016-10-11T12:34:47.720-0700
Last Timestamp: 64260.057 secs
========================================
```
However, the summary shows the slow, single-threaded CMS_SERIAL_OLD collector was used. Based on the parallel vs. overall event numbers (36585 vs. 36586), it appears there was just one single event. The analysis provides guidance how to address this issue and other best practices:
```
========================================
ANALYSIS:
----------------------------------------
error
----------------------------------------
*The CMS_SERIAL_OLD collector is being invoked for one of the following reasons: (1) Fragmentation. The concurrent low pause collector does not compact. When fragmentation becomes an issue a serial collection compacts the heap. If the old generation has available space, the cause is likely fragmentation. Fragmentation can be avoided by increasing the heap size. (2) Resizing Perm/Metaspace. If Perm/Metaspace occupancy is near Perm/Metaspace allocation, the cause is likely Perm/Metaspace. Perm/Metaspace resizing can be avoided by setting the minimum Perm/Metaspace size equal to the the maximum Perm/Metaspace size. For example: -XX:PermSize=256M -XX:MaxPermSize=256M (Perm) or -XX:MetaspaceSize=512M -XX:MaxMetaspaceSize=512M (Metaspace). (3) Undetermined reasons. Possibly the JVM requires a certain amount of heap or combination of resources that is not being met, and consequently the concurrent low pause collector is not used despite being specified with the -XX:+UseConcMarkSweepGC option. The CMS_SERIAL_OLD collector is a serial (single-threaded) collector, which means it will take a very long time to collect a large heap. For optimal performance, tune to avoid serial collections.
*CMS promotion failed. A young generation collection is not able to complete because there is not enough space in the old generation for promotion. The old generation has available space, but it is not contiguous. When fragmentation is an issue, the concurrent low pause collector invokes a slow (single-threaded) serial collector to compact the heap. Tune to avoid fragmentation: (1) Increase the heap size. (2) Use -XX:CMSInitiatingOccupancyFraction=NN (default 92) to run the CMS cycle more frequently to increase sweeping of dead objects in the old generation to free lists (e.g. -XX:CMSInitiatingOccupancyFraction=85 -XX:+UseCMSInitiatingOccupancyOnly). (3) Do heap dump analysis to determine if there is unintended object retention that can be addressed to decrease heap demands. Or move to a collector that handles fragmentation more efficiently: (1) G1 compacts the young and old generations during evacuation using a multi-threaded collector. (2) Shenandoah compacts concurrently. Temporarily add -XX:PrintFLSStatistics=1 and -XX:+PrintPromotionFailure to get additional insight into fragmentation.
----------------------------------------
warn
----------------------------------------
*The Metaspace size should be explicitly set. The Metaspace size is unlimited by default and will auto increase in size up to what the OS will allow, so not setting it can swamp the OS. Explicitly set the Metaspace size. For example: -XX:MetaspaceSize=512M -XX:MaxMetaspaceSize=512M.
*Explicit garbage collection has been disabled with -XX:+DisableExplicitGC. That is fine if the JVM is not making remote method calls and not exporting remote objects like EJBs (everything runs in the same JVM). If there are remote objects, do not use -XX:+DisableExplicitGC, as it can result in a memory leak. It is also possible the application depends on explicit garbage collection in some other way. If explicit garbage collection is required, remove -XX:+DisableExplicitGC and set sun.rmi.dgc.client.gcInterval and sun.rmi.dgc.server.gcInterval to values longer than the default 1 hour. Also add -XX:+ExplicitGCInvokesConcurrent so explicit garbage collection is handled concurrently if using the CMS or G1 collectors. For example, 4 hours (values in milliseconds): -Dsun.rmi.dgc.client.gcInterval=14400000 -Dsun.rmi.dgc.server.gcInterval=14400000 -XX:+ExplicitGCInvokesConcurrent.
*The CMS collector does not always collect Perm/Metaspace by default (e.g. prior to JDK 1.8). Add -XX:+CMSClassUnloadingEnabled to collect Perm/Metaspace in the CMS concurrent cycle and avoid Perm/Metaspace collections being done by a slow (single threaded) serial collector.
*-XX:+PrintGCApplicationStoppedTime missing. Required to determine overall throughput and identify throughput and pause issues not related to garbage collection, as many JVM operations besides garbage collection require all threads to reach a safepoint to execute.
----------------------------------------
info
----------------------------------------
*When UseCompressedOops and UseCompressedClassesPointers (JDK 1.8 u40+) are enabled (default) the Metaspace reported in the GC logging is the sum of two native memory spaces: (1) class metadata. (2) compressed class pointers. It is recommended to explicitly set the compressed class pointers space. For example: -XX:CompressedClassSpaceSize=1G.
*GC log file rotation is not enabled. Consider enabling rotation (-XX:+UseGCLogFileRotation -XX:GCLogFileSize=N -XX:NumberOfGCLogFiles=N) to protect disk space.
========================================
```
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestHeaderCommandLineFlagsEvent extends TestCase {
public void testNotBlocking() {
String logLine = "CommandLine flags: -XX:+CMSClassUnloadingEnabled -XX:CMSInitiatingOccupancyFraction=75 "
+ "-XX:+CMSScavengeBeforeRemark -XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses "
+ "-XX:GCLogFileSize=8388608 -XX:InitialHeapSize=13958643712 -XX:MaxHeapSize=13958643712 "
+ "-XX:MaxPermSize=402653184 -XX:MaxTenuringThreshold=6 -XX:NewRatio=2 -XX:NumberOfGCLogFiles=8 "
+ "-XX:OldPLABSize=16 -XX:PermSize=402653184 -XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCDetails "
+ "-XX:+PrintGCTimeStamps -XX:+UseCompressedOops -XX:+UseConcMarkSweepGC -XX:+UseGCLogFileRotation "
+ "-XX:+UseParNewGC";
Assert.assertFalse(
JdkUtil.LogEventType.HEADER_COMMAND_LINE_FLAGS.toString() + " incorrectly indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testLine() {
String logLine = "CommandLine flags: -XX:+CMSClassUnloadingEnabled -XX:CMSInitiatingOccupancyFraction=75 "
+ "-XX:+CMSScavengeBeforeRemark -XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses "
+ "-XX:GCLogFileSize=8388608 -XX:InitialHeapSize=13958643712 -XX:MaxHeapSize=13958643712 "
+ "-XX:MaxPermSize=402653184 -XX:MaxTenuringThreshold=6 -XX:NewRatio=2 -XX:NumberOfGCLogFiles=8 "
+ "-XX:OldPLABSize=16 -XX:PermSize=402653184 -XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCDetails "
+ "-XX:+PrintGCTimeStamps -XX:+UseCompressedOops -XX:+UseConcMarkSweepGC -XX:+UseGCLogFileRotation "
+ "-XX:+UseParNewGC";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.HEADER_COMMAND_LINE_FLAGS.toString() + ".",
HeaderCommandLineFlagsEvent.match(logLine));
HeaderCommandLineFlagsEvent event = new HeaderCommandLineFlagsEvent(logLine);
String jvmOptions = "-XX:+CMSClassUnloadingEnabled -XX:CMSInitiatingOccupancyFraction=75 "
+ "-XX:+CMSScavengeBeforeRemark -XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses "
+ "-XX:GCLogFileSize=8388608 -XX:InitialHeapSize=13958643712 -XX:MaxHeapSize=13958643712 "
+ "-XX:MaxPermSize=402653184 -XX:MaxTenuringThreshold=6 -XX:NewRatio=2 -XX:NumberOfGCLogFiles=8 "
+ "-XX:OldPLABSize=16 -XX:PermSize=402653184 -XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCDetails "
+ "-XX:+PrintGCTimeStamps -XX:+UseCompressedOops -XX:+UseConcMarkSweepGC -XX:+UseGCLogFileRotation "
+ "-XX:+UseParNewGC";
Assert.assertEquals("Flags not parsed correctly.", jvmOptions, event.getJvmOptions());
}
public void testJBossHeader() {
String logLine = " JAVA_OPTS: -Dprogram.name=run.sh -d64 -server -Xms10000m -Xmx10000m -ss512k "
+ "-XX:PermSize=512m -XX:MaxPermSize=512m -XX:NewSize=3000m -XX:MaxNewSize=3000m -XX:SurvivorRatio=6 "
+ "-XX:TargetSurvivorRatio=90 -XX:MaxTenuringThreshold=5 -verbose:gc -XX:+PrintGC -XX:+PrintGCDetails "
+ "-XX:+PrintGCDateStamps -XX:-TraceClassUnloading -XX:+UseConcMarkSweepGC -XX:+UseParNewGC "
+ "-XX:+CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=70 "
+ "-XX:+UseCMSInitiatingOccupancyOnly -XX:ParallelGCThreads=8 -XX:+CMSScavengeBeforeRemark "
+ "-Dcom.sun.management.jmxremote.port=12345 -Dcom.sun.management.jmxremote.ssl=false "
+ "-Djava.net.preferIPv4Stack=true -Djboss.platform.mbeanserver "
+ "-Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl "
+ "-XX:ErrorFile=/opt/jboss/jboss-eap-4.3/jboss-as/server/edreams/log/crash/hs_err_pid%p.log "
+ "-XX:+DisableExplicitGC "
+ "-Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 "
+ "-Dsun.lang.ClassLoader.allowArraySyntax=true -DrobotsEngine=register "
+ "-DconfigurationEngine.configDir=/opt/odigeo/properties/ "
+ "-Djavax.net.ssl.keyStore=/opt/edreams/keys/java/keyStore "
+ "-Djavax.net.ssl.keyStorePassword=<PASSWORD>";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.HEADER_COMMAND_LINE_FLAGS.toString() + ".",
HeaderCommandLineFlagsEvent.match(logLine));
HeaderCommandLineFlagsEvent event = new HeaderCommandLineFlagsEvent(logLine);
String jvmOptions = "-Dprogram.name=run.sh -d64 -server -Xms10000m -Xmx10000m -ss512k "
+ "-XX:PermSize=512m -XX:MaxPermSize=512m -XX:NewSize=3000m -XX:MaxNewSize=3000m -XX:SurvivorRatio=6 "
+ "-XX:TargetSurvivorRatio=90 -XX:MaxTenuringThreshold=5 -verbose:gc -XX:+PrintGC -XX:+PrintGCDetails "
+ "-XX:+PrintGCDateStamps -XX:-TraceClassUnloading -XX:+UseConcMarkSweepGC -XX:+UseParNewGC "
+ "-XX:+CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=70 "
+ "-XX:+UseCMSInitiatingOccupancyOnly -XX:ParallelGCThreads=8 -XX:+CMSScavengeBeforeRemark "
+ "-Dcom.sun.management.jmxremote.port=12345 -Dcom.sun.management.jmxremote.ssl=false "
+ "-Djava.net.preferIPv4Stack=true -Djboss.platform.mbeanserver "
+ "-Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl "
+ "-XX:ErrorFile=/opt/jboss/jboss-eap-4.3/jboss-as/server/edreams/log/crash/hs_err_pid%p.log "
+ "-XX:+DisableExplicitGC "
+ "-Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 "
+ "-Dsun.lang.ClassLoader.allowArraySyntax=true -DrobotsEngine=register "
+ "-DconfigurationEngine.configDir=/opt/odigeo/properties/ "
+ "-Djavax.net.ssl.keyStore=/opt/edreams/keys/java/keyStore "
+ "-Djavax.net.ssl.keyStorePassword=<PASSWORD>it";
Assert.assertEquals("Flags not parsed correctly.", jvmOptions, event.getJvmOptions());
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <NAME>
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class TestG1CleanupEvent extends TestCase {
public void testIsBlocking() {
String logLine = "2972.698: [GC cleanup 13G->12G(30G), 0.0358748 secs]";
Assert.assertTrue(JdkUtil.LogEventType.G1_CLEANUP.toString() + " not indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testCleanup() {
String logLine = "18.650: [GC cleanup 297M->236M(512M), 0.0014690 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CLEANUP.toString() + ".",
G1CleanupEvent.match(logLine));
G1CleanupEvent event = new G1CleanupEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 18650, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 304128, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 241664, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 524288, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 1, event.getDuration());
}
public void testCleanupWhiteSpacesAtEnd() {
String logLine = "18.650: [GC cleanup 297M->236M(512M), 0.0014690 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CLEANUP.toString() + ".",
G1CleanupEvent.match(logLine));
}
public void testLogLineGigabytes() {
String logLine = "2972.698: [GC cleanup 13G->12G(30G), 0.0358748 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CLEANUP.toString() + ".",
G1CleanupEvent.match(logLine));
G1CleanupEvent event = new G1CleanupEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 2972698, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 13631488, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 12582912, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 31457280, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 35, event.getDuration());
}
public void testLogLineWithTimesData() {
String logLine = "2016-11-08T09:36:22.388-0800: 35290.131: [GC cleanup 5252M->3592M(12G), 0.0154490 secs] "
+ "[Times: user=0.19 sys=0.00, real=0.01 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CLEANUP.toString() + ".",
G1CleanupEvent.match(logLine));
G1CleanupEvent event = new G1CleanupEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 35290131, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 5252 * 1024, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 3592 * 1024, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 12 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 15, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 19, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 1, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 1900, event.getParallelism());
}
public void testLogLineMissingSizes() {
String logLine = "2017-05-09T00:46:14.766+1000: 288368.997: [GC cleanup, 0.0000910 secs] "
+ "[Times: user=0.00 sys=0.00, real=0.00 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CLEANUP.toString() + ".",
G1CleanupEvent.match(logLine));
G1CleanupEvent event = new G1CleanupEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 288368997, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 0, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 0, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 0, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 0, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 0, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 0, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 100, event.getParallelism());
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkRegEx;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestCmsRemarkEvent extends TestCase {
public void testIsBlocking() {
String logLine = "253.103: [GC[YG occupancy: 16172 K (149120 K)]253.103: "
+ "[Rescan (parallel) , 0.0226730 secs]253.126: [weak refs processing, 0.0624566 secs] "
+ "[1 CMS-remark: 4173470K(8218240K)] 4189643K(8367360K), 0.0857010 secs]";
Assert.assertTrue(JdkUtil.LogEventType.CMS_REMARK.toString() + " not indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testLogLine() {
String logLine = "253.103: [GC[YG occupancy: 16172 K (149120 K)]253.103: "
+ "[Rescan (parallel) , 0.0226730 secs]253.126: [weak refs processing, 0.0624566 secs] "
+ "[1 CMS-remark: 4173470K(8218240K)] 4189643K(8367360K), 0.0857010 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 253103, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 85, event.getDuration());
Assert.assertFalse("Incremental Mode not parsed correctly.", event.isIncrementalMode());
Assert.assertFalse("Class unloading not parsed correctly.", event.isClassUnloading());
}
public void testLogLineWhitespaceAtEnd() {
String logLine = "253.103: [GC[YG occupancy: 16172 K (149120 K)]253.103: "
+ "[Rescan (parallel) , 0.0226730 secs]253.126: [weak refs processing, 0.0624566 secs] "
+ "[1 CMS-remark: 4173470K(8218240K)] 4189643K(8367360K), 0.0857010 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
}
public void testLogLineWithTimesData() {
String logLine = "253.103: [GC[YG occupancy: 16172 K (149120 K)]253.103: "
+ "[Rescan (parallel) , 0.0226730 secs]253.126: [weak refs processing, 0.0624566 secs] "
+ "[1 CMS-remark: 4173470K(8218240K)] 4189643K(8367360K), 0.0857010 secs] "
+ "[Times: user=0.15 sys=0.01, real=0.09 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 253103, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 85, event.getDuration());
Assert.assertFalse("Incremental Mode not parsed correctly.", event.isIncrementalMode());
Assert.assertFalse("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 15, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 9, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 167, event.getParallelism());
}
public void testLogLineJdk8WithTriggerAndDatestamps() {
String logLine = "13.749: [GC (CMS Final Remark)[YG occupancy: 149636 K (153600 K)]13.749: "
+ "[Rescan (parallel) , 0.0216980 secs]13.771: [weak refs processing, 0.0005180 secs]13.772: "
+ "[scrub string table, 0.0015820 secs] [1 CMS-remark: 217008K(341376K)] "
+ "366644K(494976K), 0.0239510 secs] [Times: user=0.18 sys=0.00, real=0.02 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 13749, event.getTimestamp());
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_CMS_FINAL_REMARK));
Assert.assertEquals("Duration not parsed correctly.", 23, event.getDuration());
Assert.assertFalse("Incremental Mode not parsed correctly.", event.isIncrementalMode());
Assert.assertFalse("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 18, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 2, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 900, event.getParallelism());
}
public void testLogLineDatestamp() {
String logLine = "2016-10-27T19:06:06.651-0400: 6.458: [GC[YG occupancy: 480317 K (5505024 K)]6.458: "
+ "[Rescan (parallel) , 0.0103480 secs]6.469: [weak refs processing, 0.0000110 secs]6.469: "
+ "[scrub string table, 0.0001750 secs] [1 CMS-remark: 0K(37748736K)] 480317K(43253760K), "
+ "0.0106300 secs] [Times: user=0.23 sys=0.01, real=0.01 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 6458, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 10, event.getDuration());
Assert.assertFalse("Incremental Mode not parsed correctly.", event.isIncrementalMode());
Assert.assertFalse("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 23, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 1, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 2300, event.getParallelism());
}
public void testLogLineAllDatestamps() {
String logLine = "2017-03-04T05:36:05.691-0500: 214.303: [GC[YG occupancy: 1674105 K (2752512 K)]"
+ "2017-03-04T05:36:05.691-0500: 214.303: [Rescan (parallel) , 0.2958890 secs]"
+ "2017-03-04T05:36:05.987-0500: 214.599: [weak refs processing, 0.0046990 secs]"
+ "2017-03-04T05:36:05.992-0500: 214.604: [scrub string table, 0.0023080 secs] "
+ "[1 CMS-remark: 6775345K(7340032K)] 8449451K(10092544K), 0.3035200 secs] "
+ "[Times: user=0.98 sys=0.01, real=0.31 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 214303, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 303, event.getDuration());
Assert.assertFalse("Incremental Mode not parsed correctly.", event.isIncrementalMode());
Assert.assertFalse("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 98, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 31, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 317, event.getParallelism());
}
public void testLogLineSpaceBeforeYgBlockAndNoSpaceBeforeCmsRemarkBlock() {
String logLine = "61.013: [GC (CMS Final Remark) [YG occupancy: 237181 K (471872 K)]61.014: [Rescan (parallel)"
+ " , 0.0335675 secs]61.047: [weak refs processing, 0.0011687 secs][1 CMS-remark: 1137616K(1572864K)] "
+ "1374798K(2044736K), 0.0351204 secs] [Times: user=0.12 sys=0.00, real=0.04 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 61013, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 35, event.getDuration());
Assert.assertFalse("Incremental Mode not parsed correctly.", event.isIncrementalMode());
Assert.assertFalse("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 12, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 4, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 300, event.getParallelism());
}
public void testLogLineClassUnloading() {
String logLine = "76694.727: [GC[YG occupancy: 80143 K (153344 K)]76694.727: "
+ "[Rescan (parallel) , 0.0574180 secs]76694.785: [weak refs processing, 0.0170540 secs]76694.802: "
+ "[class unloading, 0.0363010 secs]76694.838: [scrub symbol & string tables, 0.0276600 secs] "
+ "[1 CMS-remark: 443542K(4023936K)] 523686K(4177280K), 0.1446880 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 76694727, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 144, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
}
public void testLogLineClassUnloadingWhitespaceAtEnd() {
String logLine = "76694.727: [GC[YG occupancy: 80143 K (153344 K)]76694.727: "
+ "[Rescan (parallel) , 0.0574180 secs]76694.785: [weak refs processing, 0.0170540 secs]76694.802: "
+ "[class unloading, 0.0363010 secs]76694.838: [scrub symbol & string tables, 0.0276600 secs] "
+ "[1 CMS-remark: 443542K(4023936K)] 523686K(4177280K), 0.1446880 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
}
public void testLogLineClassUnloadingWithTimesData() {
String logLine = "76694.727: [GC[YG occupancy: 80143 K (153344 K)]76694.727: "
+ "[Rescan (parallel) , 0.0574180 secs]76694.785: [weak refs processing, 0.0170540 secs]76694.802: "
+ "[class unloading, 0.0363010 secs]76694.838: [scrub symbol & string tables, 0.0276600 secs] "
+ "[1 CMS-remark: 443542K(4023936K)] 523686K(4177280K), 0.1446880 secs] "
+ "[Times: user=0.13 sys=0.00, real=0.07 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 76694727, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 144, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 13, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 7, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 186, event.getParallelism());
}
public void testLogLineClassUnloadingJdk7() {
String logLine = "75.500: [GC[YG occupancy: 163958 K (306688 K)]75.500: [Rescan (parallel) , 0.0491823 secs]"
+ "75.549: [weak refs processing, 0.0088472 secs]75.558: [class unloading, 0.0049468 secs]75.563: "
+ "[scrub symbol table, 0.0034342 secs]75.566: [scrub string table, 0.0005542 secs] [1 CMS-remark: "
+ "378031K(707840K)] 541989K(1014528K), 0.0687411 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 75500, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 68, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
}
public void testLogLineClassUnloadingJdk7WithTimesData() {
String logLine = "75.500: [GC[YG occupancy: 163958 K (306688 K)]75.500: [Rescan (parallel) , 0.0491823 secs]"
+ "75.549: [weak refs processing, 0.0088472 secs]75.558: [class unloading, 0.0049468 secs]75.563: "
+ "[scrub symbol table, 0.0034342 secs]75.566: [scrub string table, 0.0005542 secs] [1 CMS-remark: "
+ "378031K(707840K)] 541989K(1014528K), 0.0687411 secs] [Times: user=0.13 sys=0.00, real=0.07 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
}
public void testLogLineClassUnloadingJdk8WithTrigger() {
String logLine = "13.758: [GC (CMS Final Remark) [YG occupancy: 235489 K (996800 K)]13.758: "
+ "[Rescan (parallel) , 0.0268664 secs]13.785: [weak refs processing, 0.0000365 secs]13.785: "
+ "[class unloading, 0.0058936 secs]13.791: [scrub symbol table, 0.0081277 secs]13.799: "
+ "[scrub string table, 0.0007018 secs][1 CMS-remark: 0K(989632K)] 235489K(1986432K), 0.0430349 secs] "
+ "[Times: user=0.36 sys=0.00, real=0.04 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 13758, event.getTimestamp());
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_CMS_FINAL_REMARK));
Assert.assertEquals("Duration not parsed correctly.", 43, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 36, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 4, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 900, event.getParallelism());
}
public void testLogLineClassUnloadingJdk7NonParallelRescan() {
String logLine = "7.294: [GC[YG occupancy: 42599 K (76672 K)]7.294: [Rescan (non-parallel) 7.294: "
+ "[grey object rescan, 0.0049340 secs]7.299: [root rescan, 0.0230250 secs], 0.0280700 secs]7.322: "
+ "[weak refs processing, 0.0001950 secs]7.322: [class unloading, 0.0034660 secs]7.326: "
+ "[scrub symbol table, 0.0047330 secs]7.330: [scrub string table, 0.0006570 secs] "
+ "[1 CMS-remark: 7720K(1249088K)] 50319K(1325760K), 0.0375310 secs] "
+ "[Times: user=0.03 sys=0.01, real=0.03 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 7294, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 37, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 3, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 3, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 100, event.getParallelism());
}
public void testLogLineClassUnloadingJdk8NonInitialGcYgBlock() {
String logLine = "4.578: [Rescan (parallel) , 0.0185521 secs]4.597: [weak refs processing, 0.0008993 secs]"
+ "4.598: [class unloading, 0.0046742 secs]4.603: [scrub symbol table, 0.0044444 secs]"
+ "4.607: [scrub string table, 0.0005670 secs][1 CMS-remark: 6569K(4023936K)] 16685K(4177280K), "
+ "0.1025102 secs] [Times: user=0.17 sys=0.01, real=0.10 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 4578, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 102, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 17, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 10, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 170, event.getParallelism());
}
public void testLogLineClassUnloadingNoSpaceAfterTrigger() {
String logLine = "38.695: [GC (CMS Final Remark)[YG occupancy: 4251867 K (8388608 K)]"
+ "38.695: [Rescan (parallel) , 0.5678440 secs]39.263: [weak refs processing, 0.0000540 secs]"
+ "39.263: [class unloading, 0.0065460 secs]39.270: [scrub symbol table, 0.0118150 secs]"
+ "39.282: [scrub string table, 0.0020090 secs] "
+ "[1 CMS-remark: 0K(13631488K)] 4251867K(22020096K), 0.5893800 secs] "
+ "[Times: user=3.92 sys=0.04, real=0.59 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 38695, event.getTimestamp());
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_CMS_FINAL_REMARK));
Assert.assertEquals("Duration not parsed correctly.", 589, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 392, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 59, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 665, event.getParallelism());
}
public void testLogLineClassUnloadingDatestamp() {
String logLine = "2016-10-10T18:43:51.337-0700: 3.674: [GC (CMS Final Remark) [YG occupancy: 87907 K "
+ "(153344 K)]2016-10-10T18:43:51.337-0700: 3.674: [Rescan (parallel) , 0.0590379 secs]"
+ "2016-10-10T18:43:51.396-0700: 3.733: [weak refs processing, 0.0000785 secs]"
+ "2016-10-10T18:43:51.396-0700: 3.733: [class unloading, 0.0102437 secs]"
+ "2016-10-10T18:43:51.407-0700: 3.744: [scrub symbol table, 0.0208682 secs]"
+ "2016-10-10T18:43:51.428-0700: 3.765: [scrub string table, 0.0013969 secs]"
+ "[1 CMS-remark: 6993K(8218240K)] 94901K(8371584K), 0.0935737 secs] "
+ "[Times: user=0.26 sys=0.01, real=0.09 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_REMARK.toString() + ".",
CmsRemarkEvent.match(logLine));
CmsRemarkEvent event = new CmsRemarkEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 3674, event.getTimestamp());
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_CMS_FINAL_REMARK));
Assert.assertEquals("Duration not parsed correctly.", 93, event.getDuration());
Assert.assertTrue("Class unloading not parsed correctly.", event.isClassUnloading());
Assert.assertEquals("User time not parsed correctly.", 26, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 9, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 289, event.getParallelism());
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.eclipselabs.garbagecat.service.GcManager;
import org.eclipselabs.garbagecat.util.Constants;
import org.eclipselabs.garbagecat.util.jdk.Analysis;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil.LogEventType;
import org.eclipselabs.garbagecat.util.jdk.Jvm;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestJvmRun extends TestCase {
/**
* Test passing JVM options on the command line.
*
*/
public void testJvmOptionsPassedInOnCommandLine() {
String options = "MGM was here!";
GcManager gcManager = new GcManager();
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(options, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.doAnalysis();
Assert.assertTrue("JVM options passed in are missing or have changed.",
jvmRun.getJvm().getOptions().equals(options));
}
/**
* Test if -XX:+PrintReferenceGC enabled by inspecting logging events.
*/
public void testPrintReferenceGCByLogging() {
String jvmOptions = null;
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
List<LogEventType> eventTypes = new ArrayList<LogEventType>();
eventTypes.add(LogEventType.REFERENCE_GC);
jvmRun.setEventTypes(eventTypes);
jvmRun.doAnalysis();
Assert.assertTrue(Analysis.WARN_PRINT_REFERENCE_GC_ENABLED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_REFERENCE_GC_ENABLED));
}
/**
* Test if -XX:+PrintReferenceGC enabled by inspecting jvm options.
*/
public void testPrintReferenceGCByOptions() {
String jvmOptions = "-Xss128k -XX:+PrintReferenceGC -Xms2048M";
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.doAnalysis();
Assert.assertTrue(Analysis.WARN_PRINT_REFERENCE_GC_ENABLED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_REFERENCE_GC_ENABLED));
}
/**
* Test if -XX:+PrintStringDeduplicationStatistics enabled by inspecting jvm options.
*/
public void testPrintStringDeduplicationStatistics() {
String jvmOptions = "-Xss128k -XX:+PrintStringDeduplicationStatistics -Xms2048M";
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.doAnalysis();
Assert.assertTrue(Analysis.WARN_PRINT_STRING_DEDUP_STATS_ENABLED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_STRING_DEDUP_STATS_ENABLED));
}
/**
* Test if PrintGCDetails disabled with -XX:-PrintGCDetails.
*/
public void testPrintGCDetailsDisabled() {
String jvmOptions = "-Xss128k -XX:-PrintGCDetails -Xms2048M";
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.doAnalysis();
Assert.assertTrue(Analysis.WARN_PRINT_GC_DETAILS_DISABLED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_GC_DETAILS_DISABLED));
Assert.assertFalse(Analysis.WARN_PRINT_GC_DETAILS_MISSING + " analysis incorrectly identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_GC_DETAILS_MISSING));
}
/**
* Test if PAR_NEW collector disabled with -XX:-UseParNewGC.
*/
public void testUseParNewGcDisabled() {
String jvmOptions = "-Xss128k -XX:-UseParNewGC -Xms2048M";
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.doAnalysis();
Assert.assertTrue(Analysis.WARN_CMS_PAR_NEW_DISABLED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_CMS_PAR_NEW_DISABLED));
}
/**
* Test percent swap free at threshold.
*/
public void testPercentSwapFreeAtThreshold() {
String jvmOptions = null;
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.getJvm().setSwap(1000);
jvmRun.getJvm().setSwapFree(946);
jvmRun.doAnalysis();
Assert.assertEquals("Percent swap free not correct.", 95, jvmRun.getJvm().getPercentSwapFree());
Assert.assertFalse(Analysis.INFO_SWAPPING + " analysis incorrectly identified.",
jvmRun.getAnalysis().contains(Analysis.INFO_SWAPPING));
}
/**
* Test percent swap free below threshold.
*/
public void testPercentSwapFreeBelowThreshold() {
String jvmOptions = null;
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.getJvm().setSwap(1000);
jvmRun.getJvm().setSwapFree(945);
jvmRun.doAnalysis();
Assert.assertEquals("Percent swap free not correct.", 94, jvmRun.getJvm().getPercentSwapFree());
Assert.assertTrue(Analysis.INFO_SWAPPING + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.INFO_SWAPPING));
}
/**
* Test physical memory equals heap + perm/metaspace.
*/
public void testPhysicalMemoryEqualJvmAllocation() {
String jvmOptions = "-Xmx1024M -XX:MaxPermSize=128M";
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.getJvm().setPhysicalMemory(1207959552);
jvmRun.doAnalysis();
Assert.assertFalse(Analysis.ERROR_PHYSICAL_MEMORY + " analysis incorrectly identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_PHYSICAL_MEMORY));
}
/**
* Test physical memory less than heap + perm/metaspace.
*/
public void testPhysicalMemoryLessThanJvmAllocation() {
String jvmOptions = "-Xmx1024M -XX:MaxPermSize=128M";
GcManager gcManager = new GcManager();
Jvm jvm = new Jvm(jvmOptions, null);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
jvmRun.getJvm().setPhysicalMemory(1207959551);
jvmRun.doAnalysis();
Assert.assertTrue(Analysis.ERROR_PHYSICAL_MEMORY + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_PHYSICAL_MEMORY));
}
public void testLastTimestampNoEvents() {
GcManager gcManager = new GcManager();
gcManager.store(null, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertNull("Last GC event not correct.", jvmRun.getLastGcEvent());
}
public void testSummaryStatsParallel() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset1.txt");
GcManager gcManager = new GcManager();
gcManager.store(testFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Max young space not calculated correctly.", 248192, jvmRun.getMaxYoungSpace());
Assert.assertEquals("Max old space not calculated correctly.", 786432, jvmRun.getMaxOldSpace());
Assert.assertEquals("NewRatio not calculated correctly.", 3, jvmRun.getNewRatio());
Assert.assertEquals("Max heap space not calculated correctly.", 1034624, jvmRun.getMaxHeapSpace());
Assert.assertEquals("Max heap occupancy not calculated correctly.", 1013058, jvmRun.getMaxHeapOccupancy());
Assert.assertEquals("Max pause not calculated correctly.", 2782, jvmRun.getMaxGcPause());
Assert.assertEquals("Max perm gen space not calculated correctly.", 159936, jvmRun.getMaxPermSpace());
Assert.assertEquals("Max perm gen occupancy not calculated correctly.", 76972, jvmRun.getMaxPermOccupancy());
Assert.assertEquals("Total GC duration not calculated correctly.", 5614, jvmRun.getTotalGcPause());
Assert.assertEquals("GC Event count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue(JdkUtil.LogEventType.PARALLEL_SCAVENGE.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.PARALLEL_SCAVENGE));
Assert.assertTrue(JdkUtil.LogEventType.PARALLEL_SERIAL_OLD.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.PARALLEL_SERIAL_OLD));
Assert.assertTrue(Analysis.WARN_APPLICATION_STOPPED_TIME_MISSING + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_APPLICATION_STOPPED_TIME_MISSING));
Assert.assertTrue(Analysis.ERROR_SERIAL_GC_PARALLEL + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_SERIAL_GC_PARALLEL));
}
public void testSummaryStatsParNew() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset2.txt");
GcManager gcManager = new GcManager();
gcManager.store(testFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Max young space not calculated correctly.", 348864, jvmRun.getMaxYoungSpace());
Assert.assertEquals("Max old space not calculated correctly.", 699392, jvmRun.getMaxOldSpace());
Assert.assertEquals("NewRatio not calculated correctly.", 2, jvmRun.getNewRatio());
Assert.assertEquals("Max heap space not calculated correctly.", 1048256, jvmRun.getMaxHeapSpace());
Assert.assertEquals("Max heap occupancy not calculated correctly.", 424192, jvmRun.getMaxHeapOccupancy());
Assert.assertEquals("Max pause not calculated correctly.", 1070, jvmRun.getMaxGcPause());
Assert.assertEquals("Max perm gen space not calculated correctly.", 99804, jvmRun.getMaxPermSpace());
Assert.assertEquals("Max perm gen occupancy not calculated correctly.", 60155, jvmRun.getMaxPermOccupancy());
Assert.assertEquals("Total GC duration not calculated correctly.", 1282, jvmRun.getTotalGcPause());
Assert.assertEquals("GC Event count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue(JdkUtil.LogEventType.PAR_NEW.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
Assert.assertTrue(JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(Analysis.ERROR_SERIAL_GC_CMS + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_SERIAL_GC_CMS));
}
/**
* Test parsing logging with -XX:+PrintGCApplicationConcurrentTime and -XX:+PrintGCApplicationStoppedTime output.
*/
public void testParseLoggingWithApplicationTime() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset3.txt");
GcManager gcManager = new GcManager();
gcManager.store(testFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Max young space not calculated correctly.", 1100288, jvmRun.getMaxYoungSpace());
Assert.assertEquals("Max old space not calculated correctly.", 1100288, jvmRun.getMaxOldSpace());
Assert.assertEquals("NewRatio not calculated correctly.", 1, jvmRun.getNewRatio());
Assert.assertEquals("Event count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Should not be any unidentified log lines.", 0, jvmRun.getUnidentifiedLogLines().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PAR_NEW));
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.APPLICATION_STOPPED_TIME));
Assert.assertTrue(Analysis.INFO_NEW_RATIO_INVERTED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.INFO_NEW_RATIO_INVERTED));
}
/**
* Test preprocessing <code>GcTimeLimitExceededEvent</code> with underlying <code>ParallelOldCompactingEvent</code>
* .
*/
public void testSplitParallelOldCompactingEventLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset28.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING));
Assert.assertTrue(Analysis.ERROR_GC_TIME_LIMIT_EXCEEEDED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_GC_TIME_LIMIT_EXCEEEDED));
Assert.assertTrue(Analysis.ERROR_GC_TIME_LIMIT_EXCEEEDED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_GC_TIME_LIMIT_EXCEEEDED));
}
/**
* Test preprocessing a combined <code>CmsConcurrentEvent</code> and <code>ApplicationConcurrentTimeEvent</code>
* split across 2 lines.
*/
public void testCombinedCmsConcurrentApplicationConcurrentTimeLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset19.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_CONCURRENT));
}
/**
* Test preprocessing a combined <code>CmsConcurrentEvent</code> and <code>ApplicationStoppedTimeEvent</code> split
* across 2 lines.
*/
public void testCombinedCmsConcurrentApplicationStoppedTimeLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset27.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_CONCURRENT));
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.APPLICATION_STOPPED_TIME));
}
public void testRemoveBlankLines() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset20.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PAR_NEW));
Assert.assertTrue(Analysis.WARN_PRINT_GC_APPLICATION_CONCURRENT_TIME + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_GC_APPLICATION_CONCURRENT_TIME));
}
/**
* Test <code>DateStampPreprocessAction</code>.
*/
public void testDateStampPreprocessActionLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset25.txt");
GcManager gcManager = new GcManager();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2010);
calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
calendar.set(Calendar.DAY_OF_MONTH, 26);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
File preprocessedFile = gcManager.preprocess(testFile, calendar.getTime());
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PAR_NEW));
}
public void testSummaryStatsStoppedTime() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset41.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertTrue(JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue(JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + " not identified.",
jvmRun.getEventTypes().contains(LogEventType.APPLICATION_STOPPED_TIME));
Assert.assertEquals("GC Event count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertEquals("GC pause total not correct.", 61, jvmRun.getTotalGcPause());
Assert.assertEquals("GC first timestamp not correct.", 2192, jvmRun.getFirstGcEvent().getTimestamp());
Assert.assertEquals("GC last timestamp not correct.", 2847, jvmRun.getLastGcEvent().getTimestamp());
Assert.assertEquals("GC last duration not correct.", 41, jvmRun.getLastGcEvent().getDuration());
Assert.assertEquals("Stopped Time event count not correct.", 6, jvmRun.getStoppedTimeEventCount());
Assert.assertEquals("Stopped time total not correct.", 1064, jvmRun.getTotalStoppedTime());
Assert.assertEquals("Stopped first timestamp not correct.", 964, jvmRun.getFirstStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last timestamp not correct.", 3884, jvmRun.getLastStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last duration not correct.", 1000688, jvmRun.getLastStoppedEvent().getDuration());
Assert.assertEquals("JVM first event timestamp not correct.", 964, jvmRun.getFirstEvent().getTimestamp());
Assert.assertEquals("JVM last event timestamp not correct.", 3884, jvmRun.getLastEvent().getTimestamp());
Assert.assertEquals("JVM run duration not correct.", 4884, jvmRun.getJvmRunDuration());
Assert.assertEquals("GC throughput not correct.", 99, jvmRun.getGcThroughput());
Assert.assertEquals("Stopped time throughput not correct.", 78, jvmRun.getStoppedTimeThroughput());
Assert.assertTrue(Analysis.WARN_GC_STOPPED_RATIO + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_GC_STOPPED_RATIO));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT with ergonomics.
*
*/
public void testExplicitGcAnalsysisParallelSerialOld() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset56.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue(JdkUtil.LogEventType.PARALLEL_SCAVENGE.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.PARALLEL_SCAVENGE));
Assert.assertTrue(JdkUtil.LogEventType.PARALLEL_SERIAL_OLD.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.PARALLEL_SERIAL_OLD));
Assert.assertTrue(Analysis.WARN_EXPLICIT_GC_SERIAL_PARALLEL + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_EXPLICIT_GC_SERIAL_PARALLEL));
Assert.assertTrue(Analysis.ERROR_SERIAL_GC_PARALLEL + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_SERIAL_GC_PARALLEL));
}
/**
* Test JVM Header parsing.
*
*/
public void testHeaders() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset59.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertTrue(JdkUtil.LogEventType.HEADER_COMMAND_LINE_FLAGS.toString() + " not identified.",
jvmRun.getEventTypes().contains(LogEventType.HEADER_COMMAND_LINE_FLAGS));
Assert.assertTrue(JdkUtil.LogEventType.HEADER_MEMORY.toString() + " not identified.",
jvmRun.getEventTypes().contains(LogEventType.HEADER_MEMORY));
Assert.assertTrue(JdkUtil.LogEventType.HEADER_VERSION.toString() + " not identified.",
jvmRun.getEventTypes().contains(LogEventType.HEADER_VERSION));
Assert.assertTrue(Analysis.WARN_EXPLICIT_GC_DISABLED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_EXPLICIT_GC_DISABLED));
}
/**
* Test <code>PrintTenuringDistributionPreprocessAction</code> with no space after "GC".
*
*/
public void testPrintTenuringDistributionPreprocessActionNoSpaceAfterGc() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset66.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PAR_NEW));
}
/**
* Test application stopped time w/o timestamps.
*/
public void testApplicationStoppedTimeNoTimestamps() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset96.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("GC pause total not correct.", 2096, jvmRun.getTotalGcPause());
Assert.assertEquals("GC first timestamp not correct.", 16517, jvmRun.getFirstGcEvent().getTimestamp());
Assert.assertEquals("GC last timestamp not correct.", 31432, jvmRun.getLastGcEvent().getTimestamp());
Assert.assertEquals("GC last duration not correct.", 271, jvmRun.getLastGcEvent().getDuration());
Assert.assertEquals("Stopped time total not correct.", 1830, jvmRun.getTotalStoppedTime());
Assert.assertEquals("Stopped first timestamp not correct.", 0, jvmRun.getFirstStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last timestamp not correct.", 0, jvmRun.getLastStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last duration not correct.", 50, jvmRun.getLastStoppedEvent().getDuration());
Assert.assertEquals("JVM first event timestamp not correct.", 16517, jvmRun.getFirstEvent().getTimestamp());
Assert.assertEquals("JVM last event timestamp not correct.", 31432, jvmRun.getLastEvent().getTimestamp());
Assert.assertEquals("JVM run duration not correct.", 31703, jvmRun.getJvmRunDuration());
Assert.assertEquals("GC throughput not correct.", 93, jvmRun.getGcThroughput());
Assert.assertEquals("Stopped time throughput not correct.", 94, jvmRun.getStoppedTimeThroughput());
Assert.assertEquals("Inverted parallelism event count not correct.", 0, jvmRun.getInvertedParallelismCount());
}
/**
* Test summary stats for a partial log file (1st timestamp > Constants.FIRST_TIMESTAMP_THRESHOLD). Same data as
* dataset41.txt with 1000 seconds added to each timestamp.
*/
public void testSummaryStatsPartialLog() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset98.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("GC event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertEquals("GC blocking event count not correct.", 2, jvmRun.getBlockingEventCount());
Assert.assertEquals("GC pause total not correct.", 61, jvmRun.getTotalGcPause());
Assert.assertEquals("GC first timestamp not correct.", 1002192, jvmRun.getFirstGcEvent().getTimestamp());
Assert.assertEquals("GC last timestamp not correct.", 1002847, jvmRun.getLastGcEvent().getTimestamp());
Assert.assertEquals("GC last duration not correct.", 41, jvmRun.getLastGcEvent().getDuration());
Assert.assertEquals("Stopped Time event count not correct.", 6, jvmRun.getStoppedTimeEventCount());
Assert.assertEquals("Stopped time total not correct.", 1064, jvmRun.getTotalStoppedTime());
Assert.assertEquals("Stopped first timestamp not correct.", 1000964,
jvmRun.getFirstStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last timestamp not correct.", 1003884,
jvmRun.getLastStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last duration not correct.", 1000688, jvmRun.getLastStoppedEvent().getDuration());
Assert.assertEquals("JVM first event timestamp not correct.", 1000964, jvmRun.getFirstEvent().getTimestamp());
Assert.assertEquals("JVM last event timestamp not correct.", 1003884, jvmRun.getLastEvent().getTimestamp());
Assert.assertEquals("JVM run duration not correct.", 3920, jvmRun.getJvmRunDuration());
Assert.assertEquals("GC throughput not correct.", 98, jvmRun.getGcThroughput());
Assert.assertEquals("Stopped time throughput not correct.", 73, jvmRun.getStoppedTimeThroughput());
Assert.assertTrue(Analysis.WARN_GC_STOPPED_RATIO + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_GC_STOPPED_RATIO));
}
/**
* Test summary stats with batching.
*/
public void testStoppedTime() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset103.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("GC event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertEquals("GC blocking event count not correct.", 160, jvmRun.getBlockingEventCount());
Assert.assertEquals("GC pause total not correct.", 2568121, jvmRun.getTotalGcPause());
Assert.assertEquals("GC first timestamp not correct.", 4364, jvmRun.getFirstGcEvent().getTimestamp());
Assert.assertEquals("GC last timestamp not correct.", 2801954, jvmRun.getLastGcEvent().getTimestamp());
Assert.assertEquals("GC last duration not correct.", 25963, jvmRun.getLastGcEvent().getDuration());
Assert.assertEquals("Stopped Time event count not correct.", 151, jvmRun.getStoppedTimeEventCount());
Assert.assertEquals("Stopped time total not correct.", 2721420, jvmRun.getTotalStoppedTime());
Assert.assertEquals("Stopped first timestamp not correct.", 0, jvmRun.getFirstStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last timestamp not correct.", 0, jvmRun.getLastStoppedEvent().getTimestamp());
Assert.assertEquals("Stopped last duration not correct.", 36651675, jvmRun.getLastStoppedEvent().getDuration());
Assert.assertEquals("JVM first event timestamp not correct.", 4364, jvmRun.getFirstEvent().getTimestamp());
Assert.assertEquals("JVM last timestamp not correct.", 2801954, jvmRun.getLastEvent().getTimestamp());
Assert.assertEquals("JVM run duration not correct.", 2827917, jvmRun.getJvmRunDuration());
Assert.assertEquals("GC throughput not correct.", 9, jvmRun.getGcThroughput());
Assert.assertEquals("Stopped time throughput not correct.", 4, jvmRun.getStoppedTimeThroughput());
Assert.assertFalse(Analysis.WARN_GC_STOPPED_RATIO + " analysis incorrectly identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_GC_STOPPED_RATIO));
Assert.assertEquals("Inverted parallelism event count not correct.", 0, jvmRun.getInvertedParallelismCount());
}
/**
* Test no gc logging events, only stopped time events.
*/
public void testStoppedTimeWithoutGcEvents() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset108.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
gcManager.store(testFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Stopped time throughput not correct.", 0, jvmRun.getStoppedTimeThroughput());
}
/**
* Test identifying <code>ParNewEvent</code> running in incremental mode.
*/
public void testPrintGcApplicationConcurrentTimeAnalysis() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset104.txt");
Jvm jvm = new Jvm(null, null);
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(jvm, Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertTrue(Analysis.WARN_PRINT_GC_APPLICATION_CONCURRENT_TIME + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_GC_APPLICATION_CONCURRENT_TIME));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil.LogEventType;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestTenuringDistributionEvent extends TestCase {
public void testNotBlocking() {
String logLine = "Desired survivor size 2228224 bytes, new threshold 1 (max 15)";
Assert.assertFalse(
JdkUtil.LogEventType.TENURING_DISTRIBUTION.toString() + " incorrectly indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testReportable() {
String logLine = "Desired survivor size 2228224 bytes, new threshold 1 (max 15)";
Assert.assertTrue(
JdkUtil.LogEventType.TENURING_DISTRIBUTION.toString() + " incorrectly indentified as not reportable.",
JdkUtil.isReportable(JdkUtil.identifyEventType(logLine)));
}
public void testIdentifyEventType() {
String logLine = "Desired survivor size 2228224 bytes, new threshold 1 (max 15)";
Assert.assertTrue(JdkUtil.LogEventType.TENURING_DISTRIBUTION.toString() + " not indentified.",
JdkUtil.identifyEventType(logLine).equals(LogEventType.TENURING_DISTRIBUTION));
}
public void testParseLogLine() {
String logLine = "Desired survivor size 2228224 bytes, new threshold 1 (max 15)";
Assert.assertTrue(JdkUtil.LogEventType.TENURING_DISTRIBUTION.toString() + " not indentified.",
JdkUtil.parseLogLine(logLine) instanceof TenuringDistributionEvent);
}
public void testDesiredSurvivorSizeLine() {
String logLine = "Desired survivor size 2228224 bytes, new threshold 1 (max 15)";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.TENURING_DISTRIBUTION.toString() + ".",
TenuringDistributionEvent.match(logLine));
}
public void testAgeLine() {
String logLine = "- age 1: 3177664 bytes, 3177664 total";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.TENURING_DISTRIBUTION.toString() + ".",
TenuringDistributionEvent.match(logLine));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkRegEx;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <NAME>
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class TestG1FullGCEvent extends TestCase {
public void testIsBlocking() {
String logLine = "1302.524: [Full GC (System.gc()) 653M->586M(979M), 1.6364900 secs]";
Assert.assertTrue(JdkUtil.LogEventType.G1_FULL_GC.toString() + " not indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testLogLineTriggerSystemGC() {
String logLine = "1302.524: [Full GC (System.gc()) 653M->586M(979M), 1.6364900 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.", event.getTrigger().matches(JdkRegEx.TRIGGER_SYSTEM_GC));
Assert.assertEquals("Time stamp not parsed correctly.", 1302524, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 653 * 1024, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 586 * 1024, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 979 * 1024, event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 0, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 0, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 0, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 1636, event.getDuration());
}
public void testLogLinePreprocessedDetailsTriggerToSpaceExhausted() {
String logLine = "105.151: [Full GC (System.gc()) 5820M->1381M(30G), 5.5390169 secs]"
+ "[Eden: 80.0M(112.0M)->0.0B(128.0M) Survivors: 16.0M->0.0B Heap: 5820.3M(30.0G)->1381.9M(30.0G)]"
+ " [Times: user=5.76 sys=1.00, real=5.53 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.", event.getTrigger().matches(JdkRegEx.TRIGGER_SYSTEM_GC));
Assert.assertEquals("Time stamp not parsed correctly.", 105151, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 5959987, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 1415066, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 30 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 0, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 0, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 0, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 5539, event.getDuration());
}
public void testLogLinePreprocessedDetailsNoTriggerPerm() {
String logLine = "178.892: [Full GC 999M->691M(3072M), 3.4262061 secs]"
+ "[Eden: 143.0M(1624.0M)->0.0B(1843.0M) Survivors: 219.0M->0.0B "
+ "Heap: 999.5M(3072.0M)->691.1M(3072.0M)], [Perm: 175031K->175031K(175104K)]"
+ " [Times: user=4.43 sys=0.05, real=3.44 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.", event.getTrigger() == null);
Assert.assertEquals("Time stamp not parsed correctly.", 178892, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 1023488, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 707686, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 3072 * 1024, event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 175031, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 175031, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 175104, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 3426, event.getDuration());
}
public void testLogLinePreprocessedDetailsPermNoSpaceAfterTriggerWithDatestamp() {
String logLine = "2017-02-27T02:55:32.523+0300: 35911.404: [Full GC (Allocation Failure)21G->20G(22G), "
+ "40.6782890 secs][Eden: 0.0B(1040.0M)->0.0B(1120.0M) Survivors: 80.0M->0.0B "
+ "Heap: 22.0G(22.0G)->20.6G(22.0G)], [Perm: 1252884K->1252884K(2097152K)] "
+ "[Times: user=56.34 sys=1.78, real=40.67 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.",
event.getTrigger().matches(JdkRegEx.TRIGGER_ALLOCATION_FAILURE));
Assert.assertEquals("Time stamp not parsed correctly.", 35911404, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 22 * 1024 * 1024,
event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 21600666, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 22 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 1252884, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 1252884, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 2097152, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 40678, event.getDuration());
}
public void testLogLinePreprocessedDetailsTriggerMetadatGcThresholdMetaspace() {
String logLine = "188.123: [Full GC (Metadata GC Threshold) 1831M->1213M(5120M), 5.1353878 secs]"
+ "[Eden: 0.0B(1522.0M)->0.0B(2758.0M) Survivors: 244.0M->0.0B "
+ "Heap: 1831.0M(5120.0M)->1213.5M(5120.0M)], [Metaspace: 396834K->324903K(1511424K)]"
+ " [Times: user=7.15 sys=0.04, real=5.14 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertEquals("Trigger not parsed correctly.", JdkRegEx.TRIGGER_METADATA_GC_THRESHOLD,
event.getTrigger());
Assert.assertEquals("Time stamp not parsed correctly.", 188123, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 1831 * 1024, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 1242624, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 5120 * 1024, event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 396834, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 324903, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 1511424, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 5135, event.getDuration());
}
public void testLogLinePreprocessedDetailsTriggerLastDitchCollection2SpacesAfterTrigger() {
String logLine = "98.150: [Full GC (Last ditch collection) 1196M->1118M(5120M), 4.4628626 secs]"
+ "[Eden: 0.0B(3072.0M)->0.0B(3072.0M) Survivors: 0.0B->0.0B "
+ "Heap: 1196.3M(5120.0M)->1118.8M(5120.0M)], [Metaspace: 324984K->323866K(1511424K)] "
+ "[Times: user=6.37 sys=0.00, real=4.46 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertEquals("Trigger not parsed correctly.", JdkRegEx.TRIGGER_LAST_DITCH_COLLECTION,
event.getTrigger());
Assert.assertEquals("Time stamp not parsed correctly.", 98150, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 1225011, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 1145651, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 5120 * 1024, event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 324984, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 323866, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 1511424, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 4462, event.getDuration());
}
public void testLogLinePreprocessedDetailsTriggerJvmTi() {
String logLine = "102.621: [Full GC (JvmtiEnv ForceGarbageCollection) 1124M->1118M(5120M), 3.8954775 secs]"
+ "[Eden: 6144.0K(3072.0M)->0.0B(3072.0M) Survivors: 0.0B->0.0B "
+ "Heap: 1124.8M(5120.0M)->1118.9M(5120.0M)], [Metaspace: 323874K->323874K(1511424K)]"
+ " [Times: user=5.87 sys=0.01, real=3.89 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertEquals("Trigger not parsed correctly.", JdkRegEx.TRIGGER_JVM_TI_FORCED_GAREBAGE_COLLECTION,
event.getTrigger());
Assert.assertEquals("Time stamp not parsed correctly.", 102621, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 1151795, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 1145754, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 5120 * 1024, event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 323874, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 323874, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 1511424, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 3895, event.getDuration());
}
public void testLogLinePreprocessedClassHistogram() {
String logLine = "49689.217: [Full GC49689.217: [Class Histogram (before full gc):, 8.8690440 secs]"
+ "11G->2270M(12G), 19.8185620 secs][Eden: 0.0B(612.0M)->0.0B(7372.0M) Survivors: 0.0B->0.0B "
+ "Heap: 11.1G(12.0G)->2270.1M(12.0G)], [Perm: 730823K->730823K(2097152K)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertEquals("Trigger not parsed correctly.", JdkRegEx.TRIGGER_CLASS_HISTOGRAM, event.getTrigger());
Assert.assertEquals("Time stamp not parsed correctly.", 49689217, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 11639194, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 2324582, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 12 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 730823, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 730823, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 2097152, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 19818, event.getDuration());
}
public void testLogLinePreprocessedDetailsTriggerAllocationFailure() {
String logLine = "56965.451: [Full GC (Allocation Failure) 28G->387M(28G), 1.1821630 secs]"
+ "[Eden: 0.0B(45.7G)->0.0B(34.4G) Survivors: 0.0B->0.0B Heap: 28.0G(28.0G)->387.6M(28.0G)], "
+ "[Metaspace: 65867K->65277K(1112064K)] [Times: user=1.43 sys=0.00, real=1.18 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertEquals("Trigger not parsed correctly.", JdkRegEx.TRIGGER_ALLOCATION_FAILURE, event.getTrigger());
Assert.assertEquals("Time stamp not parsed correctly.", 56965451, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 28 * 1024 * 1024,
event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 396902, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 28 * 1024 * 1024,
event.getCombinedSpace());
Assert.assertEquals("Metaspace begin size not parsed correctly.", 65867, event.getPermOccupancyInit());
Assert.assertEquals("Metaspace end size not parsed correctly.", 65277, event.getPermOccupancyEnd());
Assert.assertEquals("Metaspace allocation size not parsed correctly.", 1112064, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 1182, event.getDuration());
}
public void testLogLinePreprocessedNoDetailsNoTrigger() {
String logLine = "2017-05-25T13:00:52.772+0000: 2412.888: [Full GC 1630M->1281M(3072M), 4.1555250 secs] "
+ "[Times: user=7.02 sys=0.01, real=4.16 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
G1FullGCEvent.match(logLine));
G1FullGCEvent event = new G1FullGCEvent(logLine);
Assert.assertTrue("Trigger not parsed correctly.", event.getTrigger() == null);
Assert.assertEquals("Time stamp not parsed correctly.", 2412888, event.getTimestamp());
Assert.assertEquals("Combined begin size not parsed correctly.", 1630 * 1024, event.getCombinedOccupancyInit());
Assert.assertEquals("Combined end size not parsed correctly.", 1281 * 1024, event.getCombinedOccupancyEnd());
Assert.assertEquals("Combined available size not parsed correctly.", 3072 * 1024, event.getCombinedSpace());
Assert.assertEquals("Duration not parsed correctly.", 4155, event.getDuration());
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.preprocess.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestApplicationConcurrentTimePreprocessAction extends TestCase {
public void testLine1Timestamp() {
String priorLogLine = "";
String logLine = "1122748.949Application time: 0.0005210 seconds";
Assert.assertTrue("Log line not recognized as "
+ JdkUtil.PreprocessActionType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationConcurrentTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine1CmsConcurrent() {
String priorLogLine = "";
String logLine = "1987600.604: [CMS-concurrent-preclean: 0.016/0.017 secs]Application time: "
+ "4.5432350 seconds";
Assert.assertTrue("Log line not recognized as "
+ JdkUtil.PreprocessActionType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationConcurrentTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine2CmsConcurrent() {
String priorLogLine = "1122748.949Application time: 0.0005210 seconds";
String logLine = ": [CMS-concurrent-mark-start]";
Assert.assertTrue("Log line not recognized as "
+ JdkUtil.PreprocessActionType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationConcurrentTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine1PrecleanLine2TimesBlock() {
String priorLogLine = "1987600.604: [CMS-concurrent-preclean: 0.016/0.017 secs]Application time: "
+ "4.5432350 seconds";
String logLine = " [Times: user=0.02 sys=0.00, real=0.02 secs]";
Assert.assertTrue("Log line not recognized as "
+ JdkUtil.PreprocessActionType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationConcurrentTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine1AbortablePrecleanLine2TimesBlock() {
String priorLogLine = "235820.289: [CMS-concurrent-abortable-preclean: 0.049/1.737 secs]Application "
+ "time: 0.0001370 seconds";
String logLine = " [Times: user=0.90 sys=0.05, real=1.74 secs]";
Assert.assertTrue("Log line not recognized as "
+ JdkUtil.PreprocessActionType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationConcurrentTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine1MarkLine2TimesBlock() {
String priorLogLine = "408365.532: [CMS-concurrent-mark: 0.476/10.257 secs]Application time: "
+ "0.0576080 seconds";
String logLine = " [Times: user=6.00 sys=0.28, real=10.26 secs]";
Assert.assertTrue("Log line not recognized as "
+ JdkUtil.PreprocessActionType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationConcurrentTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine1MarkLine2TimesBlockWhitespaceAtEnd() {
String priorLogLine = "408365.532: [CMS-concurrent-mark: 0.476/10.257 secs]Application time: "
+ "0.0576080 seconds";
String logLine = " [Times: user=6.00 sys=0.28, real=10.26 secs] ";
Assert.assertTrue("Log line not recognized as "
+ JdkUtil.PreprocessActionType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationConcurrentTimePreprocessAction.match(logLine, priorLogLine));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestSerialNewEvent extends TestCase {
public void testIsBlocking() {
String logLine = "7.798: [GC 7.798: [DefNew: 37172K->3631K(39296K), 0.0209300 secs] "
+ "41677K->10314K(126720K), 0.0210210 secs]";
Assert.assertTrue(JdkUtil.LogEventType.SERIAL_NEW.toString() + " not indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testLogLine() {
String logLine = "7.798: [GC 7.798: [DefNew: 37172K->3631K(39296K), 0.0209300 secs] "
+ "41677K->10314K(126720K), 0.0210210 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.SERIAL_NEW.toString() + ".",
SerialNewEvent.match(logLine));
SerialNewEvent event = new SerialNewEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 7798, event.getTimestamp());
Assert.assertEquals("Young begin size not parsed correctly.", 37172, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 3631, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 39296, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 4505, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 6683, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 87424, event.getOldSpace());
Assert.assertEquals("Duration not parsed correctly.", 21, event.getDuration());
}
public void testLogLineWhitespaceAtEnd() {
String logLine = "7.798: [GC 7.798: [DefNew: 37172K->3631K(39296K), 0.0209300 secs] "
+ "41677K->10314K(126720K), 0.0210210 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.SERIAL_NEW.toString() + ".",
SerialNewEvent.match(logLine));
}
public void testLogLineNoSpaceAfterGC() {
String logLine = "4.296: [GC4.296: [DefNew: 68160K->8512K(76672K), 0.0528470 secs] "
+ "68160K->11664K(1325760K), 0.0530640 secs] [Times: user=0.04 sys=0.00, real=0.05 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.SERIAL_NEW.toString() + ".",
SerialNewEvent.match(logLine));
SerialNewEvent event = new SerialNewEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 4296, event.getTimestamp());
Assert.assertEquals("Young begin size not parsed correctly.", 68160, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 8512, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 76672, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 68160 - 68160, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 11664 - 8512, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 1325760 - 76672, event.getOldSpace());
Assert.assertEquals("Duration not parsed correctly.", 53, event.getDuration());
}
public void testLogLineDatestamp() {
String logLine = "2016-11-22T09:07:01.358+0100: 1,319: [GC2016-11-22T09:07:01.359+0100: 1,320: [DefNew: "
+ "68160K->4425K(76672K), 0,0354890 secs] 68160K->4425K(3137216K), 0,0360580 secs] "
+ "[Times: user=0,04 sys=0,00, real=0,03 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.SERIAL_NEW.toString() + ".",
SerialNewEvent.match(logLine));
SerialNewEvent event = new SerialNewEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1319, event.getTimestamp());
Assert.assertEquals("Young begin size not parsed correctly.", 68160, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 4425, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 76672, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 68160 - 68160, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 4425 - 4425, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 3137216 - 76672, event.getOldSpace());
Assert.assertEquals("Duration not parsed correctly.", 36, event.getDuration());
}
public void testLogLineWithTrigger() {
String logLine = "2.218: [GC (Allocation Failure) 2.218: [DefNew: 209792K->15933K(235968K), 0.0848369 secs] "
+ "209792K->15933K(760256K), 0.0849244 secs] [Times: user=0.03 sys=0.06, real=0.08 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.SERIAL_NEW.toString() + ".",
SerialNewEvent.match(logLine));
SerialNewEvent event = new SerialNewEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 2218, event.getTimestamp());
Assert.assertEquals("Young begin size not parsed correctly.", 209792, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 15933, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 235968, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 209792 - 209792, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 15933 - 15933, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 760256 - 235968, event.getOldSpace());
Assert.assertEquals("Duration not parsed correctly.", 84, event.getDuration());
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestCmsConcurrentEvent extends TestCase {
public void testNotBlocking() {
String logLine = "572289.495: [CMS572304.683: [CMS-concurrent-sweep: 17.692/44.143 secs] "
+ "[Times: user=97.86 sys=1.85, real=44.14 secs]";
Assert.assertFalse(JdkUtil.LogEventType.CMS_CONCURRENT.toString() + " incorrectly indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testMarkStart() {
String logLine = "251.781: [CMS-concurrent-mark-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testMarkStartWithOtherLoggingAppended() {
String logLine = "251.781: [CMS-concurrent-mark-start]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testMark() {
String logLine = "252.707: [CMS-concurrent-mark: 0.796/0.926 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testMarkWithOtherLoggingAppended() {
String logLine = "252.707: [CMS-concurrent-mark: 0.796/0.926 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testMarkWithTimesData() {
String logLine = "242107.737: [CMS-concurrent-mark: 0.443/10.257 secs] "
+ "[Times: user=6.00 sys=0.28, real=10.26 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testMarkWithTimesData5Digits() {
String logLine = "2017-06-23T08:12:13.943-0400: 39034.532: [CMS-concurrent-mark: 4.583/35144.874 secs] "
+ "[Times: user=29858.25 sys=2074.63, real=35140.48 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testMarkWithTimesDataWithOtherLoggingAppended() {
String logLine = "242107.737: [CMS-concurrent-mark: 0.443/10.257 secs] "
+ "[Times: user=6.00 sys=0.28, real=10.26 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testPrecleanStart() {
String logLine = "252.707: [CMS-concurrent-preclean-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testPrecleanStartWithOtherLoggingAppended() {
String logLine = "252.707: [CMS-concurrent-preclean-start]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testPreclean() {
String logLine = "252.888: [CMS-concurrent-preclean: 0.141/0.182 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testPrecleanWithOtherLoggingAppended() {
String logLine = "252.888: [CMS-concurrent-preclean: 0.141/0.182 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testAbortablePrecleanStart() {
String logLine = "252.889: [CMS-concurrent-abortable-preclean-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testAbortablePrecleanStartWithOtherLoggingAppended() {
String logLine = "252.889: [CMS-concurrent-abortable-preclean-start]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testAbortablePreclean() {
String logLine = "253.102: [CMS-concurrent-abortable-preclean: 0.083/0.214 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testAbortablePrecleanWithOtherLoggingAppended() {
String logLine = "253.102: [CMS-concurrent-abortable-preclean: 0.083/0.214 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testAbortPrecleanDueToTime() {
String logLine = " CMS: abort preclean due to time 32633.935: "
+ "[CMS-concurrent-abortable-preclean: 0.622/5.054 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testAbortPrecleanDueToTimeWithOtherLoggingAppended() {
String logLine = " CMS: abort preclean due to time 32633.935: "
+ "[CMS-concurrent-abortable-preclean: 0.622/5.054 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testSweepStart() {
String logLine = "253.189: [CMS-concurrent-sweep-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testSweepStartWithOtherLoggingAppended() {
String logLine = "253.189: [CMS-concurrent-sweep-start]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testSweep() {
String logLine = "258.265: [CMS-concurrent-sweep: 4.134/5.076 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testSweepWithOtherLoggingAppended() {
String logLine = "258.265: [CMS-concurrent-sweep: 4.134/5.076 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testResetStart() {
String logLine = "258.265: [CMS-concurrent-reset-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testResetStartWithOtherLoggingAppended() {
String logLine = "258.265: [CMS-concurrent-reset-start]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testReset() {
String logLine = "258.344: [CMS-concurrent-reset: 0.079/0.079 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testResetWithOtherLoggingAppended() {
String logLine = "258.344: [CMS-concurrent-reset: 0.079/0.079 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testPrecleanConcurrentModeFailure() {
String logLine = "253.102: [CMS-concurrent-abortable-preclean: 0.083/0.214 secs] "
+ "[Times: user=1.23 sys=0.02, real=0.21 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testPrecleanConcurrentModeFailureWithOtherLoggingAppended() {
String logLine = "253.102: [CMS-concurrent-abortable-preclean: 0.083/0.214 secs] "
+ "[Times: user=1.23 sys=0.02, real=0.21 secs]x";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testPrecleanConcurrentMarkSweepWithCms() {
String logLine = "572289.495: [CMS572304.683: [CMS-concurrent-sweep: 17.692/44.143 secs] "
+ "[Times: user=97.86 sys=1.85, real=44.14 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
public void testConcurrentPrefixWithOtherLoggingAppended() {
String logLine = "2017-04-24T21:08:04.965+0100: 669960.868: [CMS-concurrent-sweep: 13.324/39.970 secs] "
+ "[Times: user=124.31 sys=2.44, real=39.97 secs] 6200850K->1243921K(7848704K), "
+ "[CMS Perm : 481132K->454310K(785120K)], 100.5538981 secs] "
+ "[Times: user=100.68 sys=0.14, real=100.56 secs]";
Assert.assertFalse("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
CmsConcurrentEvent.match(logLine));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.preprocess.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestApplicationStoppedTimePreprocessAction extends TestCase {
public void testLine2CmsConcurrent() {
String priorLogLine = "6545.692Total time for which application threads were stopped: 0.0007993 seconds";
String logLine = ": [CMS-concurrent-abortable-preclean: 0.025/0.042 secs] "
+ "[Times: user=0.04 sys=0.00, real=0.04 secs]";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.PreprocessActionType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine2TimesBlock() {
String priorLogLine = "234784.781: [CMS-concurrent-abortable-preclean: 0.038/0.118 secs]Total time for"
+ " which application threads were stopped: 0.0123330 seconds";
String logLine = " [Times: user=0.10 sys=0.00, real=0.12 secs]";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.PreprocessActionType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimePreprocessAction.match(logLine, priorLogLine));
}
public void testLine2TimesBlockWhitespaceAtEnd() {
String priorLogLine = "234784.781: [CMS-concurrent-abortable-preclean: 0.038/0.118 secs]Total time for"
+ " which application threads were stopped: 0.0123330 seconds";
String logLine = " [Times: user=0.10 sys=0.00, real=0.12 secs] ";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.PreprocessActionType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimePreprocessAction.match(logLine, priorLogLine));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.preprocess.jdk;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipselabs.garbagecat.domain.JvmRun;
import org.eclipselabs.garbagecat.service.GcManager;
import org.eclipselabs.garbagecat.util.Constants;
import org.eclipselabs.garbagecat.util.jdk.Analysis;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil.LogEventType;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil.PreprocessActionType;
import org.eclipselabs.garbagecat.util.jdk.Jvm;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestCmsPreprocessAction extends TestCase {
public void testLogLineParNewMixedConcurrent() {
String logLine = "46674.719: [GC (Allocation Failure)46674.719: [ParNew46674.749: "
+ "[CMS-concurrent-abortable-preclean: 1.427/2.228 secs] [Times: user=1.56 sys=0.01, real=2.23 secs]";
String nextLogLine = " (concurrent mode failure): 2542828K->2658278K(2658304K), 12.3447910 secs] "
+ "3925228K->2702358K(4040704K), [Metaspace: 72175K->72175K(1118208K)] icms_dc=100 , 12.3480570 secs] "
+ "[Times: user=15.38 sys=0.02, real=12.35 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineParNewMixedConcurrentReset() {
String priorLogLine = null;
String logLine = "2017-03-21T16:02:23.633+0530: 53277.279: [GC 53277.279: [ParNew: "
+ "2853312K->2853312K(2853312K), 0.0000310 secs]53277.279: [CMS2017-03-21T16:02:23.655+0530: "
+ "53277.301: [CMS-concurrent-reset: 0.019/0.023 secs] [Times: user=0.02 sys=0.00, real=0.02 secs]";
String nextLogLine = ": 8943881K->8813432K(9412608K), 7.7851270 secs] 11797193K->9475525K(12265920K), [CMS "
+ "Perm : 460344K->460331K(770956K)], 7.7854740 secs] [Times: user=7.79 sys=0.01, real=7.78 secs]";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-03-21T16:02:23.633+0530: 53277.279: [GC 53277.279: [ParNew: 2853312K->2853312K(2853312K), "
+ "0.0000310 secs]53277.279: [CMS",
event.getLogEntry());
}
public void testLogLineParNewMixedConcurrentWithWhitespaceEnd() {
String logLine = "46674.719: [GC (Allocation Failure)46674.719: [ParNew46674.749: "
+ "[CMS-concurrent-abortable-preclean: 1.427/2.228 secs] "
+ "[Times: user=1.56 sys=0.01, real=2.23 secs] ";
String nextLogLine = " (concurrent mode failure): 2542828K->2658278K(2658304K), 12.3447910 secs] "
+ "3925228K->2702358K(4040704K), [Metaspace: 72175K->72175K(1118208K)] icms_dc=100 , 12.3480570 secs] "
+ "[Times: user=15.38 sys=0.02, real=12.35 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineEnd() {
String logLine = ": 153599K->17023K(153600K), 0.0383370 secs] 229326K->114168K(494976K), 0.0384820 secs] "
+ "[Times: user=0.15 sys=0.01, real=0.04 secs]";
String priorLogLine = "46674.719: [GC (Allocation Failure)46674.719: [ParNew46674.749: "
+ "[CMS-concurrent-abortable-preclean: 1.427/2.228 secs] "
+ "[Times: user=1.56 sys=0.01, real=2.23 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, null));
}
public void testLogLineEndWithWhitespaceEnd() {
String logLine = ": 153599K->17023K(153600K), 0.0383370 secs] 229326K->114168K(494976K), 0.0384820 secs] "
+ "[Times: user=0.15 sys=0.01, real=0.04 secs] ";
String priorLogLine = "46674.719: [GC (Allocation Failure)46674.719: [ParNew46674.749: "
+ "[CMS-concurrent-abortable-preclean: 1.427/2.228 secs] "
+ "[Times: user=1.56 sys=0.01, real=2.23 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, null));
}
public void testLogLineParNewNoTriggerMixedConcurrent() {
String logLine = "10.963: [GC10.963: [ParNew10.977: [CMS-concurrent-abortable-preclean: 0.088/0.197 secs] "
+ "[Times: user=0.33 sys=0.05, real=0.20 secs]";
String nextLogLine = " (concurrent mode failure): 2542828K->2658278K(2658304K), 12.3447910 secs] "
+ "3925228K->2702358K(4040704K), [Metaspace: 72175K->72175K(1118208K)] icms_dc=100 , 12.3480570 secs] "
+ "[Times: user=15.38 sys=0.02, real=12.35 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineParNewPromotionFailed() {
String logLine = "233333.318: [GC 233333.319: [ParNew (promotion failed): 673108K->673108K(707840K), "
+ "1.5366054 secs]233334.855: [CMS233334.856: [CMS-concurrent-abortable-preclean: 12.033/27.431 secs]";
String nextLogLine = " (concurrent mode failure): 2542828K->2658278K(2658304K), 12.3447910 secs] "
+ "3925228K->2702358K(4040704K), [Metaspace: 72175K->72175K(1118208K)] icms_dc=100 , 12.3480570 secs] "
+ "[Times: user=15.38 sys=0.02, real=12.35 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineMiddle() {
String logLine = "1907.974: [CMS-concurrent-mark: 23.751/40.476 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
}
public void testLogLineParNewTriggerMixedConcurrentJdk8() {
String logLine = "45.574: [GC (Allocation Failure) 45.574: [ParNew45.670: [CMS-concurrent-abortable-preclean: "
+ "3.276/4.979 secs] [Times: user=7.75 sys=0.28, real=4.98 secs]";
String nextLogLine = " (concurrent mode failure): 2542828K->2658278K(2658304K), 12.3447910 secs] "
+ "3925228K->2702358K(4040704K), [Metaspace: 72175K->72175K(1118208K)] icms_dc=100 , 12.3480570 secs] "
+ "[Times: user=15.38 sys=0.02, real=12.35 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
Set<String> context = new HashSet<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", "45.574: [GC (Allocation Failure) 45.574: [ParNew",
event.getLogEntry());
}
public void testLogLineParNewConcurrentModeFailureMixedConcurrentJdk8() {
String logLine = "719.519: [GC (Allocation Failure) 719.521: [ParNew: 1382400K->1382400K(1382400K), "
+ "0.0000470 secs]719.521: [CMS722.601: [CMS-concurrent-mark: 3.567/3.633 secs] "
+ "[Times: user=10.91 sys=0.69, real=3.63 secs]";
String nextLogLine = " (concurrent mode failure): 2542828K->2658278K(2658304K), 12.3447910 secs] "
+ "3925228K->2702358K(4040704K), [Metaspace: 72175K->72175K(1118208K)] icms_dc=100 , 12.3480570 secs] "
+ "[Times: user=15.38 sys=0.02, real=12.35 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineCmsSerialOldMixedConcurrentMark() {
String logLine = "2016-02-26T16:37:58.740+1100: 44.684: [Full GC2016-02-26T16:37:58.740+1100: 44.684: [CMS"
+ "2016-02-26T16:37:58.933+1100: 44.877: [CMS-concurrent-mark: 1.508/2.428 secs] "
+ "[Times: user=3.44 sys=0.49, real=2.42 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
}
public void testLogLineCmsSerialOldMixedConcurrentAbortablePreclean() {
String logLine = "85217.903: [Full GC 85217.903: [CMS85217.919: [CMS-concurrent-abortable-preclean: "
+ "0.723/3.756 secs] [Times: user=2.54 sys=0.08, real=3.76 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
}
public void testLogLineCmsSerialOldMixedAbortPrecleanConcurrentAbortablePreclean() {
String logLine = "2017-06-22T21:22:03.269-0400: 23.858: [Full GC 23.859: [CMS CMS: abort preclean due to "
+ "time 2017-06-22T21:22:03.269-0400: 23.859: [CMS-concurrent-abortable-preclean: 0.338/5.115 secs] "
+ "[Times: user=14.57 sys=0.83, real=5.11 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
String nextLogLine = " (concurrent mode failure): 8156K->36298K(7864320K), 1.0166580 secs] "
+ "89705K->36298K(8336192K), [CMS Perm : 34431K->34268K(34548K)], 1.0172840 secs] "
+ "[Times: user=0.86 sys=0.14, real=1.02 secs]";
Set<String> context = new HashSet<String>();
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-06-22T21:22:03.269-0400: 23.858: [Full GC 23.859: [CMS", event.getLogEntry());
}
public void testLogLineCmsSerialOldMixedConcurrentSpaceAfterGC() {
String logLine = "85238.030: [Full GC 85238.030: [CMS85238.672: [CMS-concurrent-mark: 0.666/0.686 secs] "
+ "[Times: user=1.40 sys=0.01, real=0.69 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
}
public void testLogLineCmsSerialOldWithTriggerMixedConcurrent() {
String logLine = "706.707: [Full GC (Allocation Failure) 706.708: [CMS709.137: [CMS-concurrent-mark: "
+ "3.381/5.028 secs] [Times: user=23.92 sys=3.02, real=5.03 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
}
public void testLogLineEndWithPerm() {
String logLine = " (concurrent mode failure): 1218548K->413373K(1465840K), 1.3656970 secs] "
+ "1229657K->413373K(1581168K), [CMS Perm : 83805K->80520K(83968K)], 1.3659420 secs] "
+ "[Times: user=1.33 sys=0.01, real=1.37 secs]";
String priorLogLine = "44.684: [Full GC44.684: [CMS44.877: [CMS-concurrent-mark: 1.508/2.428 secs] "
+ "[Times: user=3.44 sys=0.49, real=2.42 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, null));
}
public void testLogLineEndWithMetaspace() {
String logLine = " (concurrent mode failure): 2655937K->2373842K(2658304K), 11.6746550 secs] "
+ "3973407K->2373842K(4040704K), [Metaspace: 72496K->72496K(1118208K)] icms_dc=77 , 11.6770830 secs] "
+ "[Times: user=14.05 sys=0.02, real=11.68 secs]";
String priorLogLine = "46674.719: [GC (Allocation Failure)46674.719: [ParNew46674.749: "
+ "[CMS-concurrent-abortable-preclean: 1.427/2.228 secs] "
+ "[Times: user=1.56 sys=0.01, real=2.23 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, null));
}
public void testLogLineEndPromotionFailedConcurrentModeFailure() {
String logLine = " (promotion failed): 471871K->471872K(471872K), 0.7685416 secs]66645.266: [CMS (concurrent "
+ "mode failure): 1572864K->1572863K(1572864K), 6.3611861 secs] 2001479K->1657572K(2044736K), "
+ "[Metaspace: 567956K->567956K(1609728K)], 7.1304658 secs] "
+ "[Times: user=8.60 sys=0.01, real=7.13 secs]";
String priorLogLine = "46674.719: [GC (Allocation Failure)46674.719: [ParNew46674.749: "
+ "[CMS-concurrent-abortable-preclean: 1.427/2.228 secs] "
+ "[Times: user=1.56 sys=0.01, real=2.23 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, null));
}
public void testLogLineParNewNoTriggerMixedConcurrentWithCommas() {
String logLine = "32552,602: [GC32552,602: [ParNew32552,610: "
+ "[CMS-concurrent-abortable-preclean: 3,090/4,993 secs] "
+ "[Times: user=3,17 sys=0,02, real=5,00 secs]";
String nextLogLine = " (concurrent mode failure): 2542828K->2658278K(2658304K), 12.3447910 secs] "
+ "3925228K->2702358K(4040704K), [Metaspace: 72175K->72175K(1118208K)] icms_dc=100 , 12.3480570 secs] "
+ "[Times: user=15.38 sys=0.02, real=12.35 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineEndWithCommas() {
String logLine = ": 289024K->17642K(306688K), 0,0788160 secs] 4086255K->3814874K(12548864K), 0,0792920 secs] "
+ "[Times: user=0,28 sys=0,00, real=0,08 secs]";
String priorLogLine = "46674.719: [GC (Allocation Failure)46674.719: [ParNew46674.749: "
+ "[CMS-concurrent-abortable-preclean: 1.427/2.228 secs] "
+ "[Times: user=1.56 sys=0.01, real=2.23 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, null));
}
public void testLogLineSerialBailing() {
String logLine = "4300.825: [Full GC 4300.825: [CMSbailing out to foreground collection";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
}
public void testLogLineParNewBailing() {
String logLine = "2137.769: [GC 2137.769: [ParNew (promotion failed): 242304K->242304K(242304K), "
+ "8.4066690 secs]2146.176: [CMSbailing out to foreground collection";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, null));
}
public void testLogLineParNewHotspotBailing() {
String logLine = "1901.217: [GC 1901.217: [ParNew: 261760K->261760K(261952K), 0.0000570 secs]1901.217: "
+ "[CMSJava HotSpot(TM) Server VM warning: bailing out to foreground collection";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, ""));
}
public void testLogLineParTriggerPromotionFailed() {
String logLine = "182314.858: [GC 182314.859: [ParNew (promotion failed)";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, ""));
}
public void testLogLineParNewConcurrentModeFailurePermDataMixedConcurrentSweep() {
String logLine = "11202.526: [GC (Allocation Failure) 1202.528: [ParNew: 1355422K->1355422K(1382400K), "
+ "0.0000500 secs]1202.528: [CMS1203.491: [CMS-concurrent-sweep: 1.009/1.060 secs] "
+ "[Times: user=1.55 sys=0.12, real=1.06 secs]";
String nextLogLine = " (concurrent mode failure): 2656311K->2658289K(2658304K), 9.3575580 secs] "
+ "4011734K->2725109K(4040704K), [Metaspace: 72111K->72111K(1118208K)], 9.3610080 secs] "
+ "[Times: user=9.35 sys=0.01, real=9.36 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineCmsSerialOldWithConcurrentModeFailureMixedConcurrentPreclean() {
String logLine = "1278.200: [Full GC (Allocation Failure) 1278.202: [CMS1280.173: "
+ "[CMS-concurrent-preclean: 2.819/2.865 secs] [Times: user=6.97 sys=0.41, real=2.87 secs]";
String nextLogLine = " (concurrent mode failure): 2658303K->2658303K(2658304K), 9.1546180 secs] "
+ "4040703K->2750110K(4040704K), [Metaspace: 72113K->72113K(1118208K)], 9.1581450 secs] "
+ "[Times: user=9.15 sys=0.00, real=9.16 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineCmsSerialOldWithConcurrentModeFailureMixedConcurrentSweep() {
String logLine = "2440.336: [Full GC (Allocation Failure) 2440.338: [CMS"
+ "2440.542: [CMS-concurrent-sweep: 1.137/1.183 secs] [Times: user=5.33 sys=0.51, real=1.18 secs]";
String nextLogLine = " (concurrent mode failure): 2658304K->2658303K(2658304K), 9.4908960 secs] "
+ "4040703K->2996946K(4040704K), [Metaspace: 72191K->72191K(1118208K)], 9.4942330 secs] "
+ "[Times: user=9.49 sys=0.00, real=9.49 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineParNewMixedCmsConcurrentAbortablePreclean() {
String priorLogLine = "";
String logLine = "2210.281: [GC 2210.282: [ParNew2210.314: [CMS-concurrent-abortable-preclean: "
+ "0.043/0.144 secs] [Times: user=0.58 sys=0.03, real=0.14 secs]";
String nextLogLine = ": 212981K->3156K(242304K), 0.0364435 secs] 4712182K->4502357K(4971420K), "
+ "0.0368807 secs] [Times: user=0.18 sys=0.02, real=0.04 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineParNewMixedCmsConcurrentAbortablePreclean2() {
String priorLogLine = "2210.281: [GC 2210.282: [ParNew2210.314: [CMS-concurrent-abortable-preclean: "
+ "0.043/0.144 secs] [Times: user=0.58 sys=0.03, real=0.14 secs]";
String logLine = ": 212981K->3156K(242304K), 0.0364435 secs] 4712182K->4502357K(4971420K), "
+ "0.0368807 secs] [Times: user=0.18 sys=0.02, real=0.04 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineParNewMixedCmsConcurrentSweep() {
String priorLogLine = "";
String logLine = "1821.661: [GC 1821.661: [ParNew1821.661: [CMS-concurrent-sweep: "
+ "42.841/48.076 secs] [Times: user=19.45 sys=0.45, real=48.06 secs]";
String nextLogLine = ": 36500K->3770K(38336K), 0.1767060 secs] 408349K->375618K(2092928K), "
+ "0.1769190 secs] [Times: user=0.05 sys=0.00, real=0.18 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineConcurrentModeInterrupted() {
String priorLogLine = "";
String logLine = " (concurrent mode interrupted): 861863K->904027K(1797568K), 42.9053262 secs] "
+ "1045947K->904027K(2047232K), [CMS Perm : 252246K->252202K(262144K)], 42.9070278 secs] "
+ "[Times: user=43.11 sys=0.18, real=42.91 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintHeapAtGcBeginSerial() {
String priorLogLine = "";
String logLine = "28282.075: [Full GC {Heap before gc invocations=528:";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintHeapAtGcBeginParNew() {
String priorLogLine = "";
String logLine = "27067.966: [GC {Heap before gc invocations=498:";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintHeapAtGcBeginCmsRemark() {
String priorLogLine = "";
String logLine = "2017-04-03T08:55:45.544-0500: 20653.796: [GC (CMS Final Remark) {Heap before GC "
+ "invocations=686 (full 15):";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintHeapAtGcBeginCmsRemarkJdk8() {
String priorLogLine = "";
String logLine = "2017-06-18T05:23:16.634-0500: 15.364: [GC (CMS Final Remark) [YG occupancy: 576424 K "
+ "(1677760 K)]{Heap before GC invocations=8 (full 2):";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogMiddleSerialConcurrentPrecleanMixed() {
String priorLogLine = "";
String logLine = "28282.075: [CMS28284.687: [CMS-concurrent-preclean: 3.706/3.706 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogMiddleParNewConcurrentAbortablePrecleanMixed() {
String priorLogLine = "";
String logLine = "27067.966: [ParNew: 261760K->261760K(261952K), 0.0000160 secs]27067.966: [CMS"
+ "27067.966: [CMS-concurrent-abortable-preclean: 2.272/29.793 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogMiddleParNewConcurrentMarkMixed() {
String priorLogLine = "";
String logLine = "28308.701: [ParNew (promotion failed): 261951K->261951K(261952K), 0.7470390 secs]28309.448: "
+ "[CMS28312.544: [CMS-concurrent-mark: 5.114/5.863 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogMiddleParNewTruncatedConcurrentMarkMixed() {
String priorLogLine = "";
String logLine = ": 153344K->153344K(153344K), 0.2049130 secs]2017-02-15T16:22:05.602+0900: 1223922.433: "
+ "[CMS2017-02-15T16:22:06.001+0900: 1223922.832: [CMS-concurrent-mark: 3.589/4.431 secs] "
+ "[Times: user=6.13 sys=0.89, real=4.43 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintHeapAtGcMiddleSerial() {
String priorLogLine = "";
String logLine = "49830.934: [CMS: 1640998K->1616248K(3407872K), 11.0964500 secs] "
+ "1951125K->1616248K(4193600K), [CMS Perm : 507386K->499194K(786432K)]"
+ "Heap after gc invocations=147:";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintClassHistogramMiddleSerial() {
String priorLogLine = "";
String logLine = "11700.930: [CMS: 2844387K->635365K(7331840K), 46.4488813 secs]11747.379: [Class Histogram";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintHeapAtGcMiddleSerialConcurrentModeFailure() {
String priorLogLine = "";
String logLine = " (concurrent mode failure): 1179601K->1179648K(1179648K), 10.7510650 secs] "
+ "1441361K->1180553K(1441600K), [CMS Perm : 71172K->71171K(262144K)]Heap after gc invocations=529:";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLinePrintHeapAtGcParNewConcurrentModeFailure() {
String priorLogLine = "";
String logLine = " (concurrent mode failure): 1147900K->1155037K(1179648K), 7.3953900 secs] "
+ "1409660K->1155037K(1441600K)Heap after gc invocations=499:";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineDuration() {
String priorLogLine = "";
String logLine = ", 10.7515460 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineClassHistogramTrigger() {
String priorLogLine = "";
String logLine = "1662.232: [Full GC 11662.233: [Class Histogram:";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineDateStampClassHistogramTrigger() {
String priorLogLine = "";
String logLine = "2017-04-24T21:07:32.713+0100: 669928.617: [Full GC 669928.619: [Class Histogram:";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineRetainMiddleClassHistogram() {
String priorLogLine = "";
String logLine = ": 516864K->516864K(516864K), 2.0947428 secs]182316.954: [Class Histogram: ";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineRetainEndClassHistogram() {
String priorLogLine = "";
String logLine = " 3863904K->756393K(7848704K), [CMS Perm : 682507K->442221K(1048576K)], 107.6553710 secs]"
+ " [Times: user=112.83 sys=0.28, real=107.66 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineRetainBeginningConcurrentModeFailure() {
String priorLogLine = "";
String logLine = " (concurrent mode failure): 5355855K->991044K(7331840K), 58.3748587 secs]639860.666: "
+ "[Class Histogram";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineRetainMiddleSerialConcurrentMixed() {
String priorLogLine = "";
String logLine = ": 917504K->917504K(917504K), 5.5887120 secs]877375.047: [CMS877378.691: "
+ "[CMS-concurrent-mark: 5.714/11.380 secs] [Times: user=14.72 sys=4.81, real=11.38 secs]";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineRetainBeginningParNewNoSpaceAfterGc() {
String priorLogLine = "";
String logLine = "12.891: [GC12.891: [ParNew";
String nextLogLine = "";
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
}
public void testLogLineParNewPrefixed() {
String priorLogLine = "";
String logLine = "831626.089: [ParNew831628.158: [ParNew833918.729: [GC (Allocation Failure) 833918.729: "
+ "[ParNew: 595103K->12118K(619008K), 0.0559019 secs] 1247015K->664144K(4157952K), 0.0561698 secs] "
+ "[Times: user=0.09 sys=0.00, real=0.06 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, null, context);
Assert.assertEquals("Log line not parsed correctly.",
"833918.729: [GC (Allocation Failure) 833918.729: [ParNew: 595103K->12118K(619008K), 0.0559019 secs] "
+ "1247015K->664144K(4157952K), 0.0561698 secs] [Times: user=0.09 sys=0.00, real=0.06 secs]",
event.getLogEntry());
}
public void testLogLineBeginningSerialConcurrentWithJvmtiEnvForceGarbageCollectionTrigger() {
String priorLogLine = "";
String logLine = "262372.344: [Full GC (JvmtiEnv ForceGarbageCollection) 262372.344: [CMS262372.426: "
+ "[CMS-concurrent-mark: 0.082/0.083 secs] [Times: user=0.08 sys=0.00, real=0.09 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"262372.344: [Full GC (JvmtiEnv ForceGarbageCollection) 262372.344: [CMS", event.getLogEntry());
}
public void testLogLineBeginningSerialConcurrentWithMetadataGcThreshold() {
String priorLogLine = "";
String logLine = "262375.122: [Full GC (Metadata GC Threshold) 262375.122: [CMS262375.200: "
+ "[CMS-concurrent-mark: 0.082/0.082 secs] [Times: user=0.08 sys=0.00, real=0.08 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"262375.122: [Full GC (Metadata GC Threshold) 262375.122: [CMS", event.getLogEntry());
}
public void testLogLineBeginningSerialNoSpaceAfterTrigger() {
String priorLogLine = "";
String logLine = "5026.107: [Full GC (Allocation Failure)5026.108: [CMS"
+ "5027.062: [CMS-concurrent-sweep: 9.543/33.853 secs] "
+ "[Times: user=107.27 sys=5.82, real=33.85 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", "5026.107: [Full GC (Allocation Failure)5026.108: [CMS",
event.getLogEntry());
}
public void testLogLineBeginningSerialConcurrentWithGcLockerInitiatedGc() {
String priorLogLine = "";
String logLine = "58626.878: [Full GC (GCLocker Initiated GC)58626.878: [CMS"
+ "58630.075: [CMS-concurrent-sweep: 3.220/3.228 secs] [Times: user=3.38 sys=0.01, real=3.22 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"58626.878: [Full GC (GCLocker Initiated GC)58626.878: [CMS", event.getLogEntry());
}
public void testLogLineBeginningParNewWithFlsStatistics() {
String priorLogLine = "";
String logLine = "1.118: [GC Before GC:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", "1.118: [GC ", event.getLogEntry());
}
public void testLogLineMiddleParNewWithFlsStatistics() {
String priorLogLine = "";
String logLine = "1.118: [ParNew: 377487K->8426K(5505024K), 0.0535260 secs] 377487K->8426K(43253760K)After GC:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"1.118: [ParNew: 377487K->8426K(5505024K), 0.0535260 secs] 377487K->8426K(43253760K)",
event.getLogEntry());
}
public void testLogLineDurationWithTimeStamp() {
String priorLogLine = "";
String logLine = ", 0.0536040 secs] [Times: user=0.89 sys=0.01, real=0.06 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLinParNewPromotionFailedTruncatedWithCmsConcurrentMark() {
String priorLogLine = "";
String logLine = "36455.096: [GC 36455.096: [ParNew (promotion failed): 153344K->153344K(153344K), "
+ "0.6818450 secs]36455.778: [CMS36459.090: [CMS-concurrent-mark: 3.439/4.155 secs] "
+ "[Times: user=8.27 sys=0.17, real=4.16 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"36455.096: [GC 36455.096: [ParNew (promotion failed): 153344K->153344K(153344K), 0.6818450 secs]"
+ "36455.778: [CMS",
event.getLogEntry());
}
public void testLogLinParNewPromotionFailedTruncatedWithCmsConcurrentPreclean() {
String priorLogLine = "";
String logLine = "65778.258: [GC65778.258: [ParNew (promotion failed): 8300210K->8088352K(8388608K), "
+ "1.4967400 secs]65779.755: [CMS65781.579: [CMS-concurrent-preclean: 2.150/47.638 secs] "
+ "[Times: user=81.22 sys=2.02, real=47.63 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"65778.258: [GC65778.258: [ParNew (promotion failed): 8300210K->8088352K(8388608K), "
+ "1.4967400 secs]65779.755: [CMS",
event.getLogEntry());
}
public void testLogLineBeginningParNewWithNoParNewWithCmsConcurrentPreclean() {
String priorLogLine = "";
String logLine = "3576157.596: [GC 3576157.596: [CMS-concurrent-abortable-preclean: 0.997/1.723 secs] "
+ "[Times: user=3.20 sys=0.03, real=1.73 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", "3576157.596: [GC ", event.getLogEntry());
}
public void testLogLinParNewPromotionFailedWithCmsAbortPrecleanDueToTime() {
String priorLogLine = "";
String logLine = "73241.738: [GC (Allocation Failure)73241.738: [ParNew (promotion failed): "
+ "8205461K->8187503K(8388608K), 2.1449990 secs]73243.883: [CMS CMS: abort preclean due to time "
+ "3244.984: [CMS-concurrent-abortable-preclean: 3.335/9.080 secs] "
+ "[Times: user=43.26 sys=1.66, real=9.08 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"73241.738: [GC (Allocation Failure)73241.738: [ParNew (promotion failed): "
+ "8205461K->8187503K(8388608K), 2.1449990 secs]73243.883: [CMS",
event.getLogEntry());
}
public void testLogLineEndParNew() {
String priorLogLine = "";
String logLine = "3576157.596: [ParNew: 147599K->17024K(153344K), 0.0795160 secs] "
+ "2371401K->2244459K(6274432K), 0.0810030 secs] [Times: user=0.44 sys=0.00, real=0.08 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineBeginningParNewDatestamp() {
String priorLogLine = "";
String logLine = "2016-09-07T16:59:44.005-0400: 26536.942: [GC"
+ "2016-09-07T16:59:44.005-0400: 26536.943: [ParNew";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineCmsSerialOldCombinedConcurrentDatestamp() {
String priorLogLine = "";
String logLine = "2016-10-10T19:17:37.771-0700: 2030.108: [GC (Allocation Failure) "
+ "2016-10-10T19:17:37.771-0700: 2030.108: [ParNew2016-10-10T19:17:37.773-0700: "
+ "2030.110: [CMS-concurrent-abortable-preclean: 0.050/0.150 secs] "
+ "[Times: user=0.11 sys=0.03, real=0.15 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.",
"2016-10-10T19:17:37.771-0700: 2030.108: [GC (Allocation Failure) "
+ "2016-10-10T19:17:37.771-0700: 2030.108: [ParNew",
event.getLogEntry());
}
public void testLogLineBeginParNewCombinedFlsStatistics() {
String priorLogLine = "";
String logLine = "2017-02-27T14:29:54.533+0000: 2.730: [GC (Allocation Failure) Before GC:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-02-27T14:29:54.533+0000: 2.730: [GC (Allocation Failure) ", event.getLogEntry());
}
public void testLogLineMiddleParNewCombinedFlsStatistics() {
String priorLogLine = "";
String logLine = "2017-02-27T14:29:54.534+0000: 2.730: [ParNew: 2048000K->191475K(2304000K), 0.0366288 secs] "
+ "2048000K->191475K(7424000K)After GC:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-02-27T14:29:54.534+0000: 2.730: [ParNew: 2048000K->191475K(2304000K), 0.0366288 secs] "
+ "2048000K->191475K(7424000K)",
event.getLogEntry());
}
public void testLogLineMiddleParNewCombinedFlsStatisticsPrintPromotionFailure() {
String priorLogLine = "";
String logLine = "2017-02-28T00:43:55.587+0000: 36843.783: [ParNew (0: promotion failure size = 200) "
+ "(1: promotion failure size = 8) (2: promotion failure size = 200) "
+ "(3: promotion failure size = 200) (4: promotion failure size = 200) "
+ "(5: promotion failure size = 200) (6: promotion failure size = 200) "
+ "(7: promotion failure size = 200) (8: promotion failure size = 10) "
+ "(9: promotion failure size = 10) (10: promotion failure size = 10) "
+ "(11: promotion failure size = 200) (12: promotion failure size = 200) "
+ "(13: promotion failure size = 10) (14: promotion failure size = 200) "
+ "(15: promotion failure size = 200) (16: promotion failure size = 200) "
+ "(17: promotion failure size = 200) (18: promotion failure size = 200) "
+ "(19: promotion failure size = 200) (20: promotion failure size = 10) "
+ "(21: promotion failure size = 200) (22: promotion failure size = 10) "
+ "(23: promotion failure size = 45565) (24: promotion failure size = 10) "
+ "(25: promotion failure size = 4) (26: promotion failure size = 200) "
+ "(27: promotion failure size = 200) (28: promotion failure size = 10) "
+ "(29: promotion failure size = 200) (30: promotion failure size = 200) "
+ "(31: promotion failure size = 200) (32: promotion failure size = 200) "
+ "(promotion failed): 2304000K->2304000K(2304000K), 0.4501923 secs]"
+ "2017-02-28T00:43:56.037+0000: 36844.234: [CMSCMS: Large block 0x0000000730892bb8";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
String logLinePreprocessed = "2017-02-28T00:43:55.587+0000: 36843.783: [ParNew "
+ "(0: promotion failure size = 200) (1: promotion failure size = 8) "
+ "(2: promotion failure size = 200) (3: promotion failure size = 200) "
+ "(4: promotion failure size = 200) (5: promotion failure size = 200) "
+ "(6: promotion failure size = 200) (7: promotion failure size = 200) "
+ "(8: promotion failure size = 10) (9: promotion failure size = 10) "
+ "(10: promotion failure size = 10) (11: promotion failure size = 200) "
+ "(12: promotion failure size = 200) (13: promotion failure size = 10) "
+ "(14: promotion failure size = 200) (15: promotion failure size = 200) "
+ "(16: promotion failure size = 200) (17: promotion failure size = 200) "
+ "(18: promotion failure size = 200) (19: promotion failure size = 200) "
+ "(20: promotion failure size = 10) (21: promotion failure size = 200) "
+ "(22: promotion failure size = 10) (23: promotion failure size = 45565) "
+ "(24: promotion failure size = 10) (25: promotion failure size = 4) "
+ "(26: promotion failure size = 200) (27: promotion failure size = 200) "
+ "(28: promotion failure size = 10) (29: promotion failure size = 200) "
+ "(30: promotion failure size = 200) (31: promotion failure size = 200) "
+ "(32: promotion failure size = 200) (promotion failed): 2304000K->2304000K(2304000K), "
+ "0.4501923 secs]2017-02-28T00:43:56.037+0000: 36844.234: [CMS";
Assert.assertEquals("Log line not parsed correctly.", logLinePreprocessed, event.getLogEntry());
}
public void testLogLineMiddleSerialFlsStatistics() {
String priorLogLine = "";
String logLine = ": 2818067K->2769354K(5120000K), 3.8341757 secs] 5094036K->2769354K(7424000K), "
+ "[Metaspace: 18583K->18583K(1067008K)]After GC:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.",
": 2818067K->2769354K(5120000K), 3.8341757 secs] 5094036K->2769354K(7424000K), "
+ "[Metaspace: 18583K->18583K(1067008K)]",
event.getLogEntry());
}
public void testLogLineMiddleParNewTruncatedBeginMixedConcurrentFlsStatistics2() {
String priorLogLine = "";
String logLine = "2017-03-19T11:48:55.207+0000: 356616.193: [ParNew2017-03-19T11:48:55.211+0000: 356616.198: "
+ "[CMS-concurrent-abortable-preclean: 1.046/3.949 secs] [Times: user=1.16 sys=0.05, real=3.95 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", "2017-03-19T11:48:55.207+0000: 356616.193: [ParNew",
event.getLogEntry());
}
public void testLogLineMiddleParNewTruncatedEndMixedConcurrentFlsStatistics2() {
String priorLogLine = "";
String logLine = ": 66097K->7194K(66368K), 0.0440189 secs] 5274098K->5219953K(10478400K)After GC:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.",
": 66097K->7194K(66368K), 0.0440189 secs] 5274098K->5219953K(10478400K)", event.getLogEntry());
}
public void testLogLineEndCmsScavengeBeforeRemark() {
String priorLogLine = "";
String logLine = " 1677988K(7992832K), 0.3055773 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", " 1677988K(7992832K), 0.3055773 secs]",
event.getLogEntry());
}
public void testLogLineCmsRemarkWithoutGcDetails() {
String priorLogLine = "";
String logLine = "2017-04-03T03:12:02.134-0500: 30.385: [GC (CMS Final Remark) 890910K->620060K(7992832K), "
+ "0.1223879 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineMiddleCmsSerialOldMixedAbortPrecleanDueToTime() {
String priorLogLine = "";
String logLine = "471419.156: [CMS CMS: abort preclean due to time 2017-04-22T13:59:06.831+0100: 471423.282: "
+ "[CMS-concurrent-abortable-preclean: 3.663/31.735 secs] "
+ "[Times: user=39.81 sys=0.23, real=31.74 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", "471419.156: [CMS", event.getLogEntry());
}
public void testLogLineMiddleCmsSerialOldMixedConcurrentSweep() {
String priorLogLine = "";
String logLine = "669950.539: [CMS2017-04-24T21:08:04.965+0100: 669960.868: [CMS-concurrent-sweep: "
+ "13.324/39.970 secs] [Times: user=124.31 sys=2.44, real=39.97 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", "669950.539: [CMS", event.getLogEntry());
}
public void testLogLineMiddleCmsSerialOldWithDatestampMixedConcurrentSweep() {
String priorLogLine = "";
String logLine = "2017-05-03T14:47:16.910-0400: 1801.570: [CMS2017-05-03T14:47:22.416-0400: 1807.075: "
+ "[CMS-concurrent-mark: 29.707/71.001 secs] [Times: user=121.03 sys=35.41, real=70.99 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", "2017-05-03T14:47:16.910-0400: 1801.570: [CMS",
event.getLogEntry());
}
public void testLogLineEndCmsSerialOld() {
String priorLogLine = "";
String logLine = " 7778348K->1168095K(7848704K), [CMS Perm : 481281K->451017K(771512K)], 123.0277354 secs] "
+ "[Times: user=123.19 sys=0.18, real=123.03 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineBeginningParNewConcurrentModeFailureClassHistogram() {
String priorLogLine = "";
String logLine = "2017-04-22T12:43:48.008+0100: 466904.470: [GC 466904.473: [ParNew: "
+ "516864K->516864K(516864K), 0.0001999 secs]466904.473: [Class Histogram:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineBeginningParNewConcurrentModeFailureClassHistogramWithDatestamps() {
String priorLogLine = "";
String logLine = "2017-05-03T14:47:00.002-0400: 1784.661: [GC 2017-05-03T14:47:00.006-0400: 1784.664: "
+ "[ParNew: 4147200K->4147200K(4147200K), 0.0677200 secs]"
+ "2017-05-03T14:47:00.075-0400: 1784.735: [Class Histogram:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineMiddleConcurrentModeFailureMixedClassHistogram() {
String priorLogLine = "";
String logLine = " (concurrent mode failure): 7835032K->8154090K(9216000K), 56.0787320 secs]"
+ "2017-05-03T14:48:13.002-0400: 1857.661: [Class Histogram";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineBeginningSerialMixedClassHistogramWithDatestamp() {
String priorLogLine = "";
String logLine = "2017-05-03T14:51:32.659-0400: 2057.323: [Full GC "
+ "2017-05-03T14:51:32.680-0400: 2057.341: [Class Histogram:";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineBeginningCmsConcurrentMixedApplicationConcurrentTime() {
String priorLogLine = "";
String logLine = "2017-06-18T05:23:03.452-0500: 2.182: 2017-06-18T05:23:03.452-0500: "
+ "[CMS-concurrent-preclean: 0.016/0.048 secs]2.182: Application time: 0.0055079 seconds";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-06-18T05:23:03.452-0500: 2.182: [CMS-concurrent-preclean: 0.016/0.048 secs]",
event.getLogEntry());
}
public void testLogLineEndTimesData() {
String priorLogLine = "2017-06-18T05:23:03.452-0500: 2.182: 2017-06-18T05:23:03.452-0500: "
+ "[CMS-concurrent-preclean: 0.016/0.048 secs]2.182: Application time: 0.0055079 seconds";
String logLine = " [Times: user=0.15 sys=0.02, real=0.05 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(priorLogLine, logLine, nextLogLine, entangledLogLines,
context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineMiddleCmsRemarkJdk8() {
String priorLogLine = "";
String logLine = "2017-06-18T05:23:16.634-0500: 15.364: [GC (CMS Final Remark) 2017-06-18T05:23:16.634-0500: "
+ "15.364: [ParNew";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.CMS.toString() + ".",
CmsPreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
CmsPreprocessAction event = new CmsPreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
/**
* Test preprocessing <code>PrintHeapAtGcEvent</code> with underlying <code>CmsSerialOldEvent</code>.
*/
public void testSplitPrintHeapAtGcCmsSerialOldLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset6.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(Analysis.WARN_PRINT_HEAP_AT_GC + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_HEAP_AT_GC));
}
/**
* Test with underlying <code>CmsSerialOld</code> triggered by concurrent mode failure.
*/
public void testSplitPrintHeapAtGcCmsSerialOldConcurrentModeFailureLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset8.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.WARN_PRINT_HEAP_AT_GC + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_HEAP_AT_GC));
}
/**
* Test <code>CmsPreprocessAction</code>: split <code>CmsSerialOldEvent</code> and <code>CmsConcurrentEvent</code>.
*/
public void testSplitCmsConcurrentModeFailureEventMarkLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset10.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(JdkUtil.TriggerType.CMS_CONCURRENT_MODE_FAILURE.toString() + " trigger not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
}
/**
* Test <code>CmsPreprocessAction</code>: split <code>CmsSerialOldEvent</code> and <code>CmsConcurrentEvent</code>.
*/
public void testSplitCmsConcurrentModeFailureEventAbortablePrecleanLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset11.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(JdkUtil.TriggerType.CMS_CONCURRENT_MODE_FAILURE.toString() + " trigger not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
}
/**
* Test preprocessing <code>CmsSerialOldConcurrentModeFailureEvent</code> split over 3 lines.
*/
public void testSplit3LinesCmsConcurrentModeFailureEventLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset14.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
}
/**
* Test preprocessing a split <code>ParNewPromotionFailedCmsConcurrentModeFailurePermDataEvent</code> with
* -XX:+PrintTenuringDistribution logging between the initial and final lines.
*/
public void testSplitMixedTenuringParNewPromotionFailedEventLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset18.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
}
/**
* Test preprocessing <code>PrintHeapAtGcEvent</code> with underlying <code>ParNewConcurrentModeFailureEvent</code>.
*/
public void testSplitPrintHeapAtGcParNewPromotionFailedCmsConcurrentModeFailureEventLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset21.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.WARN_PRINT_HEAP_AT_GC + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_HEAP_AT_GC));
}
public void testParNewPromotionFailedTruncatedEventLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset23.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_CONCURRENT));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PAR_NEW));
Assert.assertTrue(Analysis.ERROR_CMS_PROMOTION_FAILED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_PROMOTION_FAILED));
}
/**
* Test PAR_NEW mixed with CMS_CONCURRENT over 2 lines.
*
*/
public void testParNewMixedCmsConcurrent() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset58.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue(LogEventType.PAR_NEW.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
Assert.assertTrue(LogEventType.CMS_CONCURRENT.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
}
/**
* Test CMS_SERIAL_OLD with concurrent mode failure trigger mixed with CMS_CONCURRENT over 2 lines.
*
*/
public void testCmsSerialConcurrentModeFailureMixedCmsConcurrent() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset61.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue(LogEventType.CMS_SERIAL_OLD.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(LogEventType.CMS_CONCURRENT.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
/**
* Test split <code>ParNewEvent</code> with a trigger and -XX:+PrintTenuringDistribution logging between the initial
* and final lines.
*/
public void testSplitMixedTenuringParNewPromotionEventWithTriggerLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset67.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
}
/**
* Test CMS_SERIAL_OLD with concurrent mode failure trigger mixed with CMS_CONCURRENT over 2 lines on JDK8.
*
*/
public void testCmsSerialConcurrentModeFailureMixedCmsConcurrentJdk8() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset69.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue(LogEventType.CMS_SERIAL_OLD.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(LogEventType.CMS_CONCURRENT.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.WARN_CMS_INCREMENTAL_MODE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_CMS_INCREMENTAL_MODE));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
/**
* Test CMS_SERIAL_OLD with concurrent mode interrupted trigger mixed with CMS_CONCURRENT over 2 lines.
*
*/
public void testCmsSerialOldConcurrentModeInterruptedMixedCmsConcurrent() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset71.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(JdkUtil.TriggerType.CMS_CONCURRENT_MODE_INTERRUPTED.toString() + " trigger not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_INTERRUPTED));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
}
/**
* Test preprocessing CMS_SERIAL_OLD triggered by <code>PrintClassHistogramEvent</code> across many lines.
*
*/
public void testCmsSerialOldPrintClassHistogramTriggerAcross5Lines() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset81.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
}
/**
* Test preprocessing PAR_NEW mixed with <code>PrintHeapAtGcEvent</code>.
*
*/
public void testParNewPrintHeapAtGc() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset83.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
Assert.assertTrue(Analysis.WARN_PRINT_HEAP_AT_GC + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_HEAP_AT_GC));
}
/**
* Test preprocessing PAR_NEW with extraneous prefix.
*
*/
public void testParNewPrefixed() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset89.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
}
/**
* Test preprocessing CMS_SERIAL_OLD with JvmtiEnv ForceGarbageCollection and concurrent mode interrupted.
*
*/
public void testCmsSerialOldTriggerJvmtiEnvForceGarbageCollectionWithConcurrentModeInterrupted() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset90.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_INTERRUPTED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_INTERRUPTED));
}
/**
* Test preprocessing CMS_SERIAL_OLD with Metadata GC Threshold and concurrent mode interrupted.
*
*/
public void testCmsSerialOldTriggerMetadataGcThresholdWithConcurrentModeInterrupted() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset91.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
/**
* Test preprocessing PAR_NEW with FLS_STATISTICS.
*
*/
public void testParNewWithFlsStatistics() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset94.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
Assert.assertTrue(Analysis.INFO_PRINT_FLS_STATISTICS + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.INFO_PRINT_FLS_STATISTICS));
}
public void testBeginningParNewWithNoParNewWithCmsConcurrentPreclean() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset105.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_REMARK.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_REMARK));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertFalse(Analysis.WARN_CMS_CLASS_UNLOADING_NOT_ENABLED + " analysis identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_CMS_CLASS_UNLOADING_NOT_ENABLED));
Assert.assertFalse(Analysis.WARN_CMS_CLASS_UNLOADING_DISABLED + " analysis identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_CMS_CLASS_UNLOADING_DISABLED));
}
public void testUnknownWithCmsConcurrent() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset111.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
String lastLogLineUnprocessed = "130454.251: [Full GC (Allocation Failure) 130454.251: [CMS130456.427: "
+ "[CMS-concurrent-mark: 2.176/2.182 secs] [Times: user=2.18 sys=0.00, real=2.18 secs]";
Assert.assertEquals("Last unprocessed log line not correct.", lastLogLineUnprocessed,
gcManager.getLastLogLineUnprocessed());
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + LogEventType.UNKNOWN.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
// Not the last preprocessed line, but part of last unpreprocessed line
Assert.assertTrue(Analysis.INFO_UNIDENTIFIED_LOG_LINE_LAST + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.INFO_UNIDENTIFIED_LOG_LINE_LAST));
}
public void testParNewCmsConcurrentOver3Lines() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset112.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
public void testPrintPromotionFailure() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset115.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 4, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue(Analysis.ERROR_CMS_PROMOTION_FAILED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_PROMOTION_FAILED));
}
public void testPrintFLSStatistics2ParNewOver4Lines() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset117.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PAR_NEW));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.INFO_PRINT_FLS_STATISTICS + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.INFO_PRINT_FLS_STATISTICS));
}
public void testCmsScavengeBeforeRemarkNoPrintGcDetails() {
File testFile = new File("src/test/data/dataset120.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 4, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.PAR_NEW));
}
public void testParNewConcurrentModeFailureMixedAbortPrecleanDueToTime() {
File testFile = new File("src/test/data/dataset121.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
public void testParNewConcurrentModeFailureMixedConcurrentPreclean() {
File testFile = new File("src/test/data/dataset122.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
public void testParNewConcurrentModeFailureMixedConcurrentMark() {
File testFile = new File("src/test/data/dataset123.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
public void testCmsSerialOldConcurrentModeFailureMixedConcurrentMark() {
File testFile = new File("src/test/data/dataset124.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CMS_SERIAL_OLD.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CMS_SERIAL_OLD));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_CMS_CONCURRENT_MODE_FAILURE));
}
public void testCmsConcurrentMixedApplicationConcurrentTime() {
File testFile = new File("src/test/data/dataset135.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_CONCURRENT));
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.APPLICATION_STOPPED_TIME));
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_CONCURRENT_TIME.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.APPLICATION_CONCURRENT_TIME));
}
public void testCmsScavengeBeforeRemarkJdk8MixedHeapAtGc() {
File testFile = new File("src/test/data/dataset136.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + LogEventType.PAR_NEW.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.PAR_NEW));
Assert.assertTrue("Log line not recognized as " + LogEventType.CMS_REMARK.toString() + ".",
jvmRun.getEventTypes().contains(LogEventType.CMS_REMARK));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkRegEx;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestParallelOldCompactingEvent extends TestCase {
public void testLogLine() {
String logLine = "2182.541: [Full GC [PSYoungGen: 1940K->0K(98560K)] "
+ "[ParOldGen: 813929K->422305K(815616K)] 815869K->422305K(914176K) "
+ "[PSPermGen: 81960K->81783K(164352K)], 2.4749181 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 2182541, event.getTimestamp());
Assert.assertEquals("Young begin size not parsed correctly.", 1940, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 0, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 98560, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 813929, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 422305, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 815616, event.getOldSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 81960, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 81783, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 164352, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 2474, event.getDuration());
}
public void testLogLineWhiteSpaceAtEnd() {
String logLine = "3.600: [Full GC [PSYoungGen: 5424K->0K(38208K)] "
+ "[ParOldGen: 488K->5786K(87424K)] 5912K->5786K(125632K) "
+ "[PSPermGen: 13092K->13094K(131072K)], 0.0699360 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
}
public void testLogLineJdk16() {
String logLine = "2.417: [Full GC (System) [PSYoungGen: 1788K->0K(12736K)] "
+ "[ParOldGen: 1084K->2843K(116544K)] 2872K->2843K(129280K) "
+ "[PSPermGen: 8602K->8593K(131072K)], 0.1028360 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 2417, event.getTimestamp());
Assert.assertTrue("Trigger not recognized as " + JdkUtil.TriggerType.SYSTEM_GC.toString() + ".",
event.getTrigger().matches(JdkRegEx.TRIGGER_SYSTEM_GC));
Assert.assertEquals("Young begin size not parsed correctly.", 1788, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 0, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 12736, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 1084, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 2843, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 116544, event.getOldSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 8602, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 8593, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 131072, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 102, event.getDuration());
}
public void testLogLineJdk8() {
String logLine = "1.234: [Full GC (Metadata GC Threshold) [PSYoungGen: 17779K->0K(1835008K)] "
+ "[ParOldGen: 16K->16894K(4194304K)] 17795K->16894K(6029312K), [Metaspace: 19114K->19114K(1067008K)], "
+ "0.0352132 secs] [Times: user=0.09 sys=0.00, real=0.04 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1234, event.getTimestamp());
Assert.assertTrue("Trigger not recognized as " + JdkUtil.TriggerType.METADATA_GC_THRESHOLD.toString() + ".",
event.getTrigger().matches(JdkRegEx.TRIGGER_METADATA_GC_THRESHOLD));
Assert.assertEquals("Young begin size not parsed correctly.", 17779, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 0, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 1835008, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 16, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 16894, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 4194304, event.getOldSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 19114, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 19114, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 1067008, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 35, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 9, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 4, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 225, event.getParallelism());
}
public void testLogLineLastDitchCollectionTrigger() {
String logLine = "372405.718: [Full GC (Last ditch collection) [PSYoungGen: 0K->0K(1569280K)] "
+ "[ParOldGen: 773083K->773083K(4718592K)] 773083K->773083K(6287872K), "
+ "[Metaspace: 4177368K->4177368K(4194304K)], 1.9708670 secs] "
+ "[Times: user=4.41 sys=0.01, real=1.97 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 372405718, event.getTimestamp());
Assert.assertTrue("Trigger not recognized as " + JdkUtil.TriggerType.LAST_DITCH_COLLECTION.toString() + ".",
event.getTrigger().matches(JdkRegEx.TRIGGER_LAST_DITCH_COLLECTION));
Assert.assertEquals("Young begin size not parsed correctly.", 0, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 0, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 1569280, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 773083, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 773083, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 4718592, event.getOldSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 4177368, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 4177368, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 4194304, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 1970, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 441, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 197, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 224, event.getParallelism());
}
public void testIsBlocking() {
String logLine = "2182.541: [Full GC [PSYoungGen: 1940K->0K(98560K)] "
+ "[ParOldGen: 813929K->422305K(815616K)] 815869K->422305K(914176K) "
+ "[PSPermGen: 81960K->81783K(164352K)], 2.4749181 secs]";
Assert.assertTrue(JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + " not indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testLogLineErgonomicsTrigger() {
String logLine = "21415.385: [Full GC (Ergonomics) [PSYoungGen: 105768K->0K(547840K)] "
+ "[ParOldGen: 1390311K->861344K(1398272K)] 1496080K->861344K(1946112K), "
+ "[Metaspace: 136339K->135256K(1177600K)], 3.4522057 secs] "
+ "[Times: user=11.58 sys=0.64, real=3.45 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 21415385, event.getTimestamp());
Assert.assertTrue("Trigger not recognized as " + JdkUtil.TriggerType.ERGONOMICS.toString() + ".",
event.getTrigger().matches(JdkRegEx.TRIGGER_ERGONOMICS));
Assert.assertEquals("Young begin size not parsed correctly.", 105768, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 0, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 547840, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 1390311, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 861344, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 1398272, event.getOldSpace());
Assert.assertEquals("Perm gen begin size not parsed correctly.", 136339, event.getPermOccupancyInit());
Assert.assertEquals("Perm gen end size not parsed correctly.", 135256, event.getPermOccupancyEnd());
Assert.assertEquals("Perm gen allocation size not parsed correctly.", 1177600, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 3452, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 1158, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 345, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 336, event.getParallelism());
}
public void testHeapInspectionInitiatedGcTrigger() {
String logLine = "285197.105: [Full GC (Heap Inspection Initiated GC) [PSYoungGen: 47669K->0K(1514496K)] "
+ "[ParOldGen: 2934846K->851463K(4718592K)] 2982516K->851463K(6233088K), "
+ "[Metaspace: 3959933K->3959881K(3977216K)], 2.4308400 secs] "
+ "[Times: user=6.95 sys=0.03, real=2.43 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 285197105, event.getTimestamp());
Assert.assertTrue(
"Trigger not recognized as " + JdkUtil.TriggerType.HEAP_INSPECTION_INITIATED_GC.toString() + ".",
event.getTrigger().matches(JdkRegEx.TRIGGER_HEAP_INSPECTION_INITIATED_GC));
Assert.assertEquals("Young begin size not parsed correctly.", 47669, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 0, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 1514496, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 2934846, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 851463, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 4718592, event.getOldSpace());
Assert.assertEquals("Metaspace begin size not parsed correctly.", 3959933, event.getPermOccupancyInit());
Assert.assertEquals("Metaspace end size not parsed correctly.", 3959881, event.getPermOccupancyEnd());
Assert.assertEquals("Metaspace allocation size not parsed correctly.", 3977216, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 2430, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 695, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 243, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 287, event.getParallelism());
}
public void testAllocationFailureTrigger() {
String logLine = "3203650.654: [Full GC (Allocation Failure) [PSYoungGen: 393482K->393073K(532992K)] "
+ "[ParOldGen: 1398224K->1398199K(1398272K)] 1791707K->1791273K(1931264K), "
+ "[Metaspace: 170955K->170731K(1220608K)], 3.5730395 secs] "
+ "[Times: user=26.24 sys=0.09, real=3.57 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", Long.parseLong("3203650654"), event.getTimestamp());
Assert.assertTrue("Trigger not recognized as " + JdkUtil.TriggerType.ALLOCATION_FAILURE.toString() + ".",
event.getTrigger().matches(JdkRegEx.TRIGGER_ALLOCATION_FAILURE));
Assert.assertEquals("Young begin size not parsed correctly.", 393482, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 393073, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 532992, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 1398224, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 1398199, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 1398272, event.getOldSpace());
Assert.assertEquals("Metaspace begin size not parsed correctly.", 170955, event.getPermOccupancyInit());
Assert.assertEquals("Metaspace end size not parsed correctly.", 170731, event.getPermOccupancyEnd());
Assert.assertEquals("Metaspace allocation size not parsed correctly.", 1220608, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 3573, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 2624, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 357, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 736, event.getParallelism());
}
public void testHeapDumpInitiatedGcTrigger() {
String logLine = "2017-02-01T17:09:50.180+0000: 1029482.070: [Full GC (Heap Dump Initiated GC) "
+ "[PSYoungGen: 33192K->0K(397312K)] [ParOldGen: 885002K->812903K(890368K)] "
+ "918194K->812903K(1287680K), [Metaspace: 142181K->141753K(1185792K)], 2.3728899 secs] "
+ "[Times: user=7.55 sys=0.60, real=2.37 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.PARALLEL_OLD_COMPACTING.toString() + ".",
ParallelOldCompactingEvent.match(logLine));
ParallelOldCompactingEvent event = new ParallelOldCompactingEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", Long.parseLong("1029482070"), event.getTimestamp());
Assert.assertTrue("Trigger not recognized as " + JdkUtil.TriggerType.HEAP_DUMP_INITIATED_GC.toString() + ".",
event.getTrigger().matches(JdkRegEx.TRIGGER_HEAP_DUMP_INITIATED_GC));
Assert.assertEquals("Young begin size not parsed correctly.", 33192, event.getYoungOccupancyInit());
Assert.assertEquals("Young end size not parsed correctly.", 0, event.getYoungOccupancyEnd());
Assert.assertEquals("Young available size not parsed correctly.", 397312, event.getYoungSpace());
Assert.assertEquals("Old begin size not parsed correctly.", 885002, event.getOldOccupancyInit());
Assert.assertEquals("Old end size not parsed correctly.", 812903, event.getOldOccupancyEnd());
Assert.assertEquals("Old allocation size not parsed correctly.", 890368, event.getOldSpace());
Assert.assertEquals("Metaspace begin size not parsed correctly.", 142181, event.getPermOccupancyInit());
Assert.assertEquals("Metaspace end size not parsed correctly.", 141753, event.getPermOccupancyEnd());
Assert.assertEquals("Metaspace allocation size not parsed correctly.", 1185792, event.getPermSpace());
Assert.assertEquals("Duration not parsed correctly.", 2372, event.getDuration());
Assert.assertEquals("User time not parsed correctly.", 755, event.getTimeUser());
Assert.assertEquals("Real time not parsed correctly.", 237, event.getTimeReal());
Assert.assertEquals("Parallelism not calculated correctly.", 319, event.getParallelism());
}
}<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.util.jdk;
import org.eclipselabs.garbagecat.domain.TimesData;
import org.eclipselabs.garbagecat.domain.jdk.ParallelScavengeEvent;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestJdkRegEx extends TestCase {
public void testTimestampWithCharacter() {
String timestamp = "A.123";
Assert.assertFalse("Timestamps are decimal numbers.", timestamp.matches(JdkRegEx.TIMESTAMP));
}
public void testTimestampWithFewerDecimalPlaces() {
String timestamp = "1.12";
Assert.assertFalse("Timestamps have 3 decimal places.", timestamp.matches(JdkRegEx.TIMESTAMP));
}
public void testTimestampWithMoreDecimalPlaces() {
String timestamp = "1.1234";
Assert.assertFalse("Timestamps have 3 decimal places.", timestamp.matches(JdkRegEx.TIMESTAMP));
}
public void testTimestampWithNoDecimal() {
String timestamp = "11234";
Assert.assertFalse("Timestamps have 3 decimal places.", timestamp.matches(JdkRegEx.TIMESTAMP));
}
public void testTimestampLessThanOne() {
String timestamp = ".123";
Assert.assertTrue("Timestamps less than one do not have a leading zero.",
timestamp.matches(JdkRegEx.TIMESTAMP));
}
public void testTimestampValid() {
String timestamp = "1.123";
Assert.assertTrue("'1.123' is a valid timestamp.", timestamp.matches(JdkRegEx.TIMESTAMP));
}
public void testTimestampDecimalComma() {
String timestamp = "1,123";
Assert.assertTrue("'1,123' is a valid timestamp.", timestamp.matches(JdkRegEx.TIMESTAMP));
}
public void testSizeWithoutUnits() {
String size = "1234";
Assert.assertFalse("Size must have capital K (kilobytes).", size.matches(JdkRegEx.SIZE));
}
public void testZeroSize() {
String size = "0K";
Assert.assertTrue("Zero sizes are valid.", size.matches(JdkRegEx.SIZE));
}
public void testSizeUnitsCase() {
String size = "1234k";
Assert.assertFalse("Size must have capital K (kilobytes).", size.matches(JdkRegEx.SIZE));
}
public void testSizeWithDecimal() {
String size = "1.234K";
Assert.assertFalse("Size is a whole number.", size.matches(JdkRegEx.SIZE));
}
public void testSizeValid() {
String size = "1234K";
Assert.assertTrue("'1234K' is a valid size.", size.matches(JdkRegEx.SIZE));
}
public void testSizeWithInvalidCharacter() {
String size = "A234K";
Assert.assertFalse("Size is a decimal number.", size.matches(JdkRegEx.SIZE));
}
public void testSizeWithNineTensPlaces() {
String size = "129092672K";
Assert.assertTrue("'129092672K' is a valid size.", size.matches(JdkRegEx.SIZE));
}
public void testDurationWithCharacter() {
String duration = "0.02A5213 secs";
Assert.assertFalse("Duration is a decimal number.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationWithFewer7DecimalPlaces() {
String duration = "0.022521 secs";
Assert.assertFalse("Duration has 7-8 decimal places.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationWithMore8DecimalPlaces() {
String duration = "0.022521394 secs";
Assert.assertFalse("Duration has 7 decimal places.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationWithNoDecimal() {
String duration = "00225213 secs";
Assert.assertFalse("Duration has 7 decimal places.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationLessThanOne() {
String duration = ".0225213 secs";
Assert.assertFalse("Durations less than one have a leading zero.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationWithSec() {
String duration = "0.0225213 sec";
Assert.assertTrue("'0.0225213 sec' is a valid duration.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationWithoutUnits() {
String duration = "0.0225213";
Assert.assertTrue("'0.0225213' is a valid duration.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationValid7() {
String duration = "0.0225213 secs";
Assert.assertTrue("'0.0225213 secs' is a valid duration.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationValid8() {
String duration = "0.02252132 secs";
Assert.assertTrue("'0.02252132 secs' is a valid duration.", duration.matches(JdkRegEx.DURATION));
}
public void testDurationDecimalComma() {
String duration = "0,0225213 secs";
Assert.assertTrue("'0,0225213 secs' is a valid duration.", duration.matches(JdkRegEx.DURATION));
}
public void testParallelScavengeValid() {
String logLine = "19810.091: [GC [PSYoungGen: 27808K->632K(28032K)] "
+ "160183K->133159K(585088K), 0.0225213 secs]";
Assert.assertTrue("'19810.091: [GC [PSYoungGen: 27808K->632K(28032K)] "
+ "160183K->133159K(585088K), 0.0225213 secs]' " + "is a valid parallel scavenge log entry.",
ParallelScavengeEvent.match(logLine));
}
public void testUnloadingClassBlock() {
String unloadingClassBlock = "[Unloading class sun.reflect.GeneratedSerializationConstructorAccessor13565]";
Assert.assertTrue("'" + unloadingClassBlock + "' " + "is a valid class unloading block.",
unloadingClassBlock.matches(JdkRegEx.UNLOADING_CLASS_BLOCK));
}
public void testUnloadingClassProxyBlock() {
String unloadingClassBlock = "[Unloading class $Proxy109]";
Assert.assertTrue("'" + unloadingClassBlock + "' " + "is a valid class unloading block.",
unloadingClassBlock.matches(JdkRegEx.UNLOADING_CLASS_BLOCK));
}
public void testDatestampGmtMinus() {
String datestamp = "2010-02-26T09:32:12.486-0600";
Assert.assertTrue("Datestamp not recognized.", datestamp.matches(JdkRegEx.DATESTAMP));
}
public void testDatestampGmtPlus() {
String datestamp = "2010-04-16T12:11:18.979+0200";
Assert.assertTrue("Datestamp not recognized.", datestamp.matches(JdkRegEx.DATESTAMP));
}
public void testTimesBlock5Digits() {
String timesBlock = " [Times: user=29858.25 sys=2074.63, real=35140.48 secs]";
Assert.assertTrue("'" + timesBlock + "' " + "is a valid times block.", timesBlock.matches(TimesData.REGEX));
}
public void testDurationFractionk5Digits() {
String durationFraction = "4.583/35144.874 secs";
Assert.assertTrue("'" + durationFraction + "' " + "is a valid duration fraction.",
durationFraction.matches(JdkRegEx.DURATION_FRACTION));
}
public void testSizeG1WholeBytes() {
String size = "0B";
Assert.assertTrue("'" + size + "' " + "is a valid size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testSizeG1WholeKilobytes() {
String size = "8192K";
Assert.assertTrue("'" + size + "' " + "is a valid size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testSizeG1WholeMegabytes() {
String size = "28M";
Assert.assertTrue("'" + size + "' " + "is a valid size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testSizeG1WholeGigabytes() {
String size = "30G";
Assert.assertTrue("'" + size + "' " + "is a valid size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testSizeG1DecimalBytes() {
String size = "0.0B";
Assert.assertTrue("'" + size + "' " + "is a valid size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testSizeG1DecimalKilobytes() {
String size = "8192.0K";
Assert.assertTrue("'" + size + "' " + "is a valid size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testSizeG1DecimalMegabytes() {
String size = "28.0M";
Assert.assertTrue("'" + size + "' " + "is a valid size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testSizeG1DecimalGigabytes() {
String size = "30.0G";
Assert.assertTrue("'" + size + "' " + "is a valid G1 details size.", size.matches(JdkRegEx.SIZE_G1));
}
public void testPercent() {
String percent = "54.8%";
Assert.assertTrue("'" + percent + "' " + "not a valid percent.", percent.matches(JdkRegEx.PERCENT));
}
public void testDateTime() {
String datetime = "2016-10-18 01:50:54";
Assert.assertTrue("'" + datetime + "' " + "not a valid datetime.", datetime.matches(JdkRegEx.DATETIME));
}
public void testPromotionFailure() {
String promotionFailure = " (0: promotion failure size = 200) (1: promotion failure size = 8) "
+ "(2: promotion failure size = 200) (3: promotion failure size = 200) "
+ "(4: promotion failure size = 200) (5: promotion failure size = 200) "
+ "(6: promotion failure size = 200) (7: promotion failure size = 200) "
+ "(8: promotion failure size = 10) (9: promotion failure size = 10) "
+ "(10: promotion failure size = 10) (11: promotion failure size = 200) "
+ "(12: promotion failure size = 200) (13: promotion failure size = 10) "
+ "(14: promotion failure size = 200) (15: promotion failure size = 200) "
+ "(16: promotion failure size = 200) (17: promotion failure size = 200) "
+ "(18: promotion failure size = 200) (19: promotion failure size = 200) "
+ "(20: promotion failure size = 10) (21: promotion failure size = 200) "
+ "(22: promotion failure size = 10) (23: promotion failure size = 45565) "
+ "(24: promotion failure size = 10) (25: promotion failure size = 4) "
+ "(26: promotion failure size = 200) (27: promotion failure size = 200) "
+ "(28: promotion failure size = 10) (29: promotion failure size = 200) "
+ "(30: promotion failure size = 200) (31: promotion failure size = 200) "
+ "(32: promotion failure size = 200) ";
Assert.assertTrue("'" + promotionFailure + "' " + "not a valid PROMOTION_FAILURE.",
promotionFailure.matches(JdkRegEx.PRINT_PROMOTION_FAILURE));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestApplicationLoggingEvent extends TestCase {
public void testReportable() {
String logLine = "00:02:05,067 INFO [STDOUT] log4j: setFile ended";
Assert.assertFalse(
JdkUtil.LogEventType.APPLICATION_LOGGING.toString() + " incorrectly indentified as reportable.",
JdkUtil.isReportable(JdkUtil.identifyEventType(logLine)));
}
public void testHhMmSsError() {
String logLine = "00:02:05,067 INFO [STDOUT] log4j: setFile ended";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_LOGGING.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testHhMmSsInfo() {
String logLine = "10:58:38,610 ERROR [ContainerBase] Servlet.service() for servlet "
+ "HttpControllerServletXml threw exception java.lang.OutOfMemoryError: Java heap space";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_LOGGING.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testHhMmSsWarn() {
String logLine = "11:05:57,018 WARN [JBossManagedConnectionPool] Throwable while attempting to "
+ "get a new connection: null";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_LOGGING.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testYyyyMmDd() {
String logLine = "2010-03-25 17:00:51,581 ERROR [example.com.servlet.DynamoServlet] "
+ "getParameter(message.order) can't access property order in class java.lang.String";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_LOGGING.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testException() {
String logLine = "java.sql.SQLException: pingDatabase failed status=-1";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_LOGGING.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testOracleException() {
String logLine = "ORA-12514, TNS:listener does not currently know of service requested in connect descriptor";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_LOGGING.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testStackTrace() {
String logLine = "\tat oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testStackTraceCausedBy() {
String logLine = "Caused by: java.sql.SQLException: Listener refused the connection with the following error:";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testStackTraceEllipses() {
String logLine = "\t... 56 more";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testJBossDivider() {
String logLine = "=========================================================================";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testJBossBootstrapEnvironement() {
String logLine = " JBoss Bootstrap Environment";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testJBossHome() {
String logLine = " JBOSS_HOME: /opt/jboss/jboss-eap-4.3/jboss-as";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testJBossJava() {
String logLine = " JAVA: /opt/java/bin/java";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testJBossClasspath() {
String logLine = " CLASSPATH: /opt/jboss/jboss-eap-4.3/jboss-as/bin/run.jar:/opt/java/lib/tools.jar";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
public void testJBossJavaOptsWarning() {
String logLine = "JAVA_OPTS already set in environment; overriding default settings with values: -d64";
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.THREAD_DUMP.toString() + ".",
ApplicationLoggingEvent.match(logLine));
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.domain.jdk;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestApplicationStoppedTimeEvent extends TestCase {
public void testNotBlocking() {
String logLine = "1,065: Total time for which application threads were stopped: 0,0001610 seconds";
Assert.assertFalse(
JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + " incorrectly indentified as blocking.",
JdkUtil.isBlocking(JdkUtil.identifyEventType(logLine)));
}
public void testLogLine() {
String logLine = "Total time for which application threads were stopped: 0.0968457 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 0, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 96845, event.getDuration());
}
public void testLogLineWithSpacesAtEnd() {
String logLine = "Total time for which application threads were stopped: 0.0968457 seconds ";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
}
public void testLogLineJdk8() {
String logLine = "1.977: Total time for which application threads were stopped: 0.0002054 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_CONCURRENT_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1977, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 205, event.getDuration());
}
public void testLogLineJdk8Update40() {
String logLine = "4.483: Total time for which application threads were stopped: 0.0018237 seconds, Stopping "
+ "threads took: 0.0017499 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 4483, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 1823, event.getDuration());
}
public void testLogLineWithCommas() {
String logLine = "1,065: Total time for which application threads were stopped: 0,0001610 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1065, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 161, event.getDuration());
}
public void testLogLineWithNegativeTime() {
String logLine = "51185.692: Total time for which application threads were stopped: -0.0005950 seconds, "
+ "Stopping threads took: 0.0003310 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 51185692, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", -595, event.getDuration());
}
public void testLogLineDatestamp() {
String logLine = "2015-05-04T18:08:00.244+0000: 0.964: Total time for which application threads were stopped: "
+ "0.0001390 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 964, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 139, event.getDuration());
}
public void testLogLineDoubleDatestamp() {
String logLine = "2016-11-08T02:06:23.230-0800: 2016-11-08T02:06:23.230-0800: 8290.973: Total time for which "
+ "application threads were stopped: 0.2409380 seconds, Stopping threads took: 0.0001210 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 8290973, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 240938, event.getDuration());
}
public void testLogLineDatestampDatestampTimestampMisplacedSemicolonTimestamp() {
String logLine = "2016-11-10T06:14:13.216-0500: 2016-11-10T06:14:13.216-0500672303.818: : 672303.818: Total "
+ "time for which application threads were stopped: 0.2934160 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 672303818, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 293416, event.getDuration());
}
public void testLogLineTimestampDatestampTimestamp() {
String logLine = "1514293.426: 2017-01-20T23:35:06.553-0500: 1514293.426: Total time for which application "
+ "threads were stopped: 0.0233250 seconds, Stopping threads took: 0.0000290 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1514293426, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 23325, event.getDuration());
}
public void testLogLineDatestampTimestampTimestampNoColon() {
String logLine = "2017-01-20T23:57:51.722-0500: 1515658.594: 2017-01-20T23:57:51.722-0500Total time for which "
+ "application threads were stopped: 0.0245350 seconds, Stopping threads took: 0.0000460 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1515658594, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 24535, event.getDuration());
}
public void testLogLineDatestampDatestampTimestampTimestampNoColon() {
String logLine = "2017-01-21T00:58:08.000-0500: 2017-01-21T00:58:08.000-0500: 1519274.873: 1519274.873Total "
+ "time for which application threads were stopped: 0.0220410 seconds, Stopping threads took: "
+ "0.0000290 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1519274873, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 22041, event.getDuration());
}
public void testLogLineMislacedColonTimestampDatestampTimestampTimestamp() {
String logLine = ": 1523468.7792017-01-21T02:08:01.907-0500: : 1523468.779: Total time for which application "
+ "threads were stopped: 0.0268610 seconds, Stopping threads took: 0.0000300 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1523468779, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 26861, event.getDuration());
}
public void testLogLineMislacedColonDatestampTimestampTimestamp() {
String logLine = ": 2017-01-21T04:11:12.565-0500: 1530859.438: 1530859.438: Total time for which application "
+ "threads were stopped: 0.0292690 seconds, Stopping threads took: 0.0000440 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1530859438, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 29269, event.getDuration());
}
public void testLogLineDatestampDatestampMisplacedColonTimestamp() {
String logLine = "2017-01-21T07:44:22.453-05002017-01-21T07:44:22.453-0500: : 1543649.325: Total time for "
+ "which application threads were stopped: 0.0293060 seconds, Stopping threads took: "
+ "0.0000460 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1543649325, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 29306, event.getDuration());
}
public void testLogLineDatestampDatestampMisplacedColonTimestampTimestamp() {
String logLine = "2017-01-21T10:23:10.795-05002017-01-21T10:23:10.795-0500: : 1553177.667: 1553177.667: Total "
+ "time for which application threads were stopped: 0.0416440 seconds, Stopping threads took: "
+ "0.0000540 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 1553177667, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 41644, event.getDuration());
}
public void testLogLineTruncated() {
String logLine = "2017-02-01T05:58:45.570-0500: 5062.814: Total time for which application threads were "
+ "stopped: 0.0001140 seconds, Stopping thread";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 5062814, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 114, event.getDuration());
}
public void testLogLineScrambledDateTimeStamps() {
String logLine = "2017-02-20T20:15:54.487-0500: 2017-02-20T20:15:54.487-0500: 40371.69140371.691: : "
+ "Total time for which application threads were stopped: 0.0099233 seconds, Stopping threads took: "
+ "0.0000402 seconds";
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
ApplicationStoppedTimeEvent.match(logLine));
ApplicationStoppedTimeEvent event = new ApplicationStoppedTimeEvent(logLine);
Assert.assertEquals("Time stamp not parsed correctly.", 40371691, event.getTimestamp());
Assert.assertEquals("Duration not parsed correctly.", 9923, event.getDuration());
}
}
<file_sep>/**********************************************************************************************************************
* garbagecat *
* *
* Copyright (c) 2008-2016 Red Hat, Inc. *
* *
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse *
* Public License v1.0 which accompanies this distribution, and is available at *
* http://www.eclipse.org/legal/epl-v10.html. *
* *
* Contributors: *
* Red Hat, Inc. - initial API and implementation *
*********************************************************************************************************************/
package org.eclipselabs.garbagecat.preprocess.jdk;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipselabs.garbagecat.domain.JvmRun;
import org.eclipselabs.garbagecat.service.GcManager;
import org.eclipselabs.garbagecat.util.Constants;
import org.eclipselabs.garbagecat.util.jdk.Analysis;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil.LogEventType;
import org.eclipselabs.garbagecat.util.jdk.JdkUtil.PreprocessActionType;
import org.eclipselabs.garbagecat.util.jdk.Jvm;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class TestG1PreprocessAction extends TestCase {
public void testLogLineG1EvacuationPause() {
String logLine = "2.192: [GC pause (G1 Evacuation Pause) (young)";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRootRegionScanWaiting() {
String logLine = " [Root Region Scan Waiting: 112.3 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineParallelTime() {
String logLine = " [Parallel Time: 12.6 ms, GC Workers: 6]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcWorker() {
String logLine = " [GC Worker (ms): 387,2 387,4 386,2 385,9 386,1 386,2 386,9 386,4 386,4 "
+ "386,8 386,1 385,2 386,1";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcWorkerStart() {
String logLine = " [GC Worker Start Time (ms): 807.5 807.8 807.8 810.1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcWorkerStartJdk8() {
String logLine = " [GC Worker Start (ms): Min: 2191.9, Avg: 2191.9, Max: 2191.9, Diff: 0.1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineExtRootScanning() {
String logLine = " [Ext Root Scanning (ms): Min: 2.7, Avg: 3.0, Max: 3.5, Diff: 0.8, Sum: 18.1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineUpdateRs() {
String logLine = " [Update RS (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineProcessedBuffers() {
String logLine = " [Processed Buffers : 2 1 0 0";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineProcessedBuffersJdk8() {
String logLine = " [Processed Buffers: Min: 0, Avg: 8.0, Max: 39, Diff: 39, Sum: 48]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineScanRs() {
String logLine = " [Scan RS (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineObjectCopy() {
String logLine = " [Object Copy (ms): Min: 9.0, Avg: 9.4, Max: 9.8, Diff: 0.8, Sum: 56.7]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineTermination() {
String logLine = " [Termination (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcWorkerOther() {
String logLine = " [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.2]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcWorkerTotal() {
String logLine = " [GC Worker Total (ms): Min: 12.5, Avg: 12.5, Max: 12.6, Diff: 0.1, Sum: 75.3]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcWorkerEnd() {
String logLine = " [GC Worker End Time (ms): 810.1 810.2 810.1 810.1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcWorkerEndJdk8() {
String logLine = " [GC Worker End (ms): Min: 2204.4, Avg: 2204.4, Max: 2204.4, Diff: 0.0]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineCodeRootFixup() {
String logLine = " [Code Root Fixup: 0.0 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineCodeRootPurge() {
String logLine = " [Code Root Purge: 0.0 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineCodeRootMigration() {
String logLine = " [Code Root Migration: 0.8 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineCodeRootScanning() {
String logLine = " [Code Root Scanning (ms): Min: 0.0, Avg: 0.2, Max: 0.4, Diff: 0.4, Sum: 0.8]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineCodeRootMarking() {
String logLine = " [Code Root Marking (ms): Min: 0.1, Avg: 1.8, Max: 3.7, Diff: 3.7, Sum: 7.2]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineClearCt() {
String logLine = " [Clear CT: 0.1 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineCompleteCsetMarking() {
String logLine = " [Complete CSet Marking: 0.0 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineOther() {
String logLine = " [Other: 0.9 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineOtherJdk8() {
String logLine = " [Other: 8.2 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineChooseCSet() {
String logLine = " [Choose CSet: 0.0 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRefProc() {
String logLine = " [Ref Proc: 7.9 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRefEnq() {
String logLine = " [Ref Enq: 0.1 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineFreeCSet() {
String logLine = " [Free CSet: 0.0 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSum() {
String logLine = " Sum: 4, Avg: 1, Min: 1, Max: 1]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMarkStackScanning() {
String logLine = " [Mark Stack Scanning (ms): 0.0 0.0 0.0 0.0";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineTerminationAttempts() {
String logLine = " [Termination Attempts : 1 1 1 1";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineTerminationAttemptsNoSpaceBeforeColon() {
String logLine = " [Termination Attempts: Min: 274, Avg: 618.2, Max: 918, Diff: 644, Sum: 11127]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineAvg() {
String logLine = " Avg: 1.1, Min: 0.0, Max: 1.5] 0.0, Min: 0.0, Max: 0.0]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogEvacuationFailure() {
String logLine = " [Evacuation Failure: 2381.8 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRetainMiddleJdk8() {
String logLine = " [Eden: 128.0M(128.0M)->0.0B(112.0M) Survivors: 0.0B->16.0M "
+ "Heap: 128.0M(30.0G)->24.9M(30.0G)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRetainMiddleYoung() {
String logLine = " [ 29M->2589K(59M)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRetainMiddleDuration() {
String logLine = ", 0.0209631 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRetainMiddleDurationWithToSpaceExhaustedTrigger() {
String logLine = " (to-space exhausted), 0.3857580 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRetainMiddleDurationWithToSpaceOverflowTrigger() {
String logLine = " (to-space overflow), 0.77121400 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGCLockerInitiatedGC() {
String logLine = "5.293: [GC pause (GCLocker Initiated GC) (young)";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineToSpaceExhausted() {
String logLine = "27997.968: [GC pause (young) (to-space exhausted), 0.1208740 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineFullGC() {
String logLine = "105.151: [Full GC (System.gc()) 5820M->1381M(30G), 5.5390169 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungInitialMark() {
String logLine = "2970.268: [GC pause (G1 Evacuation Pause) (young) (initial-mark)";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSATBFiltering() {
String logLine = " [SATB Filtering (ms): Min: 0.0, Avg: 0.1, Max: 0.4, Diff: 0.4, Sum: 0.4]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogRemark() {
String logLine = "2971.469: [GC remark 2972.470: [GC ref-proc, 0.1656600 secs], 0.2274544 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogMixed() {
String logLine = "2973.338: [GC pause (G1 Evacuation Pause) (mixed)";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogMixedNoTrigger() {
String logLine = "3082.652: [GC pause (mixed), 0.0762060 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogCleanup() {
String logLine = "2972.698: [GC cleanup 13G->12G(30G), 0.0358748 secs]";
String nextLogLine = " [Times: user=0.33 sys=0.04, real=0.17 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineConcurrent() {
String logLine = "27744.494: [GC concurrent-mark-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineConcurrentWithBeginningColon() {
String logLine = ": 16705.217: [GC concurrent-mark-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungPauseWithToSpaceExhaustedTrigger() {
String logLine = "27997.968: [GC pause (young) (to-space exhausted), 0.1208740 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungPauseDoubleTriggerToSpaceExhausted() {
String logLine = "6049.175: [GC pause (G1 Evacuation Pause) (young) (to-space exhausted), 3.1713585 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineFullGcNoTrigger() {
String logLine = "27999.141: [Full GC 18G->4153M(26G), 10.1760410 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMixedYoungPauseWithConcurrentRootRegionScanEnd() {
String logLine = "4969.943: [GC pause (young)4970.158: [GC concurrent-root-region-scan-end, 0.5703200 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMixedYoungPauseWithConcurrentWithDatestamps() {
String logLine = "2016-02-09T06:17:15.619-0500: 27744.381: [GC pause (young)"
+ "2016-02-09T06:17:15.732-0500: 27744.494: [GC concurrent-root-region-scan-end, 0.3550210 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMixedYoungPauseWithConcurrentCleanupEnd() {
String logLine = "6554.823: [GC pause (young)6554.824: [GC concurrent-cleanup-end, 0.0029080 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1ErgonomicsWithDatestamp() {
String logLine = "2016-02-11T17:26:43.599-0500: 12042.669: [G1Ergonomics (CSet Construction) start choosing "
+ "CSet, _pending_cards: 250438, predicted base time: 229.38 ms, remaining time: 270.62 ms, target "
+ "pause time: 500.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1ErgonomicsWithDatestampNoSemiColon() {
String logLine = "2016-02-11T18:50:24.070-0500 16705.217: [G1Ergonomics (CSet Construction) start choosing "
+ "CSet, _pending_cards: 273946, predicted base time: 242.44 ms, remaining time: 257.56 ms, target "
+ "pause time: 500.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungPauseWithG1Ergonomics() {
String logLine = "72945.823: [GC pause (young) 72945.823: [G1Ergonomics (CSet Construction) start choosing "
+ "CSet, _pending_cards: 497394, predicted base time: 66.16 ms, remaining time: 433.84 ms, target "
+ "pause time: 500.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungPauseWithG1ErgonomicsAndDateStamps() {
String logLine = "2016-02-16T01:02:06.283-0500: 16023.627: [GC pause (young)2016-02-16T01:02:06.338-0500: "
+ "16023.683: [G1Ergonomics (CSet Construction) start choosing CSet, _pending_cards: 36870, predicted "
+ "base time: 143.96 ms, remaining time: 856.04 ms, target pause time: 1000.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungPauseWithTriggerWithG1ErgonomicsDoubleTimestampAndDateStamps() {
String logLine = "2017-03-21T15:05:53.717+1100: 425001.630: [GC pause (G1 Evacuation Pause) (young)"
+ "2017-03-21T15:05:53.717+1100: 425001.630: 425001.630: [G1Ergonomics (CSet Construction) start "
+ "choosing CSet, _pending_cards: 3, predicted base time: 45.72 ms, remaining time: 304.28 ms, target "
+ "pause time: 350.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungInitialMarkWithDatestamp() {
String logLine = "2017-01-20T23:18:29.561-0500: 1513296.434: [GC pause (young) (initial-mark), "
+ "0.0225230 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungInitialMarkWithG1Ergonomics() {
String logLine = "2016-02-11T15:22:23.213-0500: 4582.283: [GC pause (young) (initial-mark) 4582.283: "
+ "[G1Ergonomics (CSet Construction) start choosing CSet, _pending_cards: 6084, predicted base time: "
+ "41.16 ms, remaining time: 458.84 ms, target pause time: 500.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoungInitialMarkTriggerG1HumongousAllocationWithG1Ergonomics() {
String logLine = "2017-02-02T01:55:56.661-0500: 860.367: [GC pause (G1 Humongous Allocation) (young) "
+ "(initial-mark) 860.367: [G1Ergonomics (CSet Construction) start choosing CSet, _pending_cards: "
+ "3305091, predicted base time: 457.90 ms, remaining time: 42.10 ms, target pause time: 500.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMixedWithG1Ergonomics() {
String logLine = "2016-02-11T16:06:59.987-0500: 7259.058: [GC pause (mixed) 7259.058: [G1Ergonomics (CSet "
+ "Construction) start choosing CSet, _pending_cards: 273214, predicted base time: 74.01 ms, "
+ "remaining time: 425.99 ms, target pause time: 500.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMixedHumongousAllocationToSpaceExhausted() {
String logLine = "2017-06-22T12:25:26.515+0530: 66155.261: [GC pause (G1 Humongous Allocation) (mixed) "
+ "(to-space exhausted), 0.2466797 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineConcurrentCleanupEndWithDatestamp() {
String logLine = "2016-02-11T18:15:35.431-0500: 14974.501: [GC concurrent-cleanup-end, 0.0033880 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSingleConcurrentMarkStartBlock() {
String logLine = "[GC concurrent-mark-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineGcConcurrentRootRegionScanEndMissingTimestamp() {
String logLine = "[GC concurrent-root-region-scan-end, 0.6380480 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineBeginningYoungConcurrent() {
String logLine = "2016-02-16T01:05:36.945-0500: 16233.809: [GC pause (young)2016-02-16T01:05:37.046-0500: "
+ "16233.910: [GC concurrent-root-region-scan-end, 0.5802520 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineTimesBlock() {
String logLine = " [Times: user=0.33 sys=0.04, real=0.17 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineTimesBlockWithSpaceAtEnd() {
String logLine = " [Times: user=0.33 sys=0.04, real=0.17 secs] ";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1Cleanup() {
String logLine = "1.515: [GC cleanup 165M->165M(110G), 0.0028925 secs]";
String nextLogLine = "2.443: [GC pause (GCLocker Initiated GC) (young) (initial-mark) 1061M->52M(110G), "
+ "0.0280096 secs]";
Assert.assertFalse("Log line recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, nextLogLine));
}
public void testLogLineStringDedupFixup() {
String logLine = " [String Dedup Fixup: 1.6 ms, GC Workers: 18]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineStringDedupFixupQueueFixup() {
String logLine = " [Queue Fixup (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineStringDedupFixupTableFixup() {
String logLine = " [Table Fixup (ms): Min: 0.0, Avg: 0.1, Max: 1.3, Diff: 1.3, Sum: 1.3]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRedirtyCards() {
String logLine = " [Redirty Cards: 0.6 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineHumongousRegister() {
String logLine = " [Humongous Register: 0.1 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineHumongousReclaim() {
String logLine = " [Humongous Reclaim: 0.0 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRemarkWithFinalizeMarkingAndUnloading() {
String logLine = "5.745: [GC remark 5.746: [Finalize Marking, 0.0068506 secs] 5.752: "
+ "[GC ref-proc, 0.0014064 secs] 5.754: [Unloading, 0.0057674 secs], 0.0157938 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineLastExec() {
String logLine = " [Last Exec: 0.0118158 secs, Idle: 0.9330710 secs, Blocked: 0/0.0000000 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineInspected() {
String logLine = " [Inspected: 10116]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSkipped() {
String logLine = " [Skipped: 0( 0.0%)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineHashed() {
String logLine = " [Hashed: 3088( 30.5%)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineKnown() {
String logLine = " [Known: 3404( 33.6%)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineNew() {
String logLine = " [New: 6712( 66.4%) 526.1K]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineDuplicated() {
String logLine = " [Deduplicated: 3304( 49.2%) 197.2K( 37.5%)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineYoung() {
String logLine = " [Young: 3101( 93.9%) 173.8K( 88.1%)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineOld() {
String logLine = " [Old: 203( 6.1%) 23.4K( 11.9%)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineTotalExec() {
String logLine = " [Total Exec: 2/0.0281081 secs, Idle: 2/9.1631547 secs, Blocked: 2/0.0266213 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineTable() {
String logLine = " [Table]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMemoryUsage() {
String logLine = " [Memory Usage: 745.2K]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSize() {
String logLine = " [Size: 16384, Min: 1024, Max: 16777216]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineEntries() {
String logLine = " [Entries: 26334, Load: 160.7%, Cached: 0, Added: 26334, Removed: 0]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineResizeCount() {
String logLine = " [Resize Count: 4, Shrink Threshold: 10922(66.7%), Grow Threshold: 32768(200.0%)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineRehashCount() {
String logLine = " [Rehash Count: 0, Rehash Threshold: 120, Hash Seed: 0x0]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineAgeThreshold() {
String logLine = " [Age Threshold: 3]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineQueue() {
String logLine = " [Queue]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineDropped() {
String logLine = " [Dropped: 0]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSpaceDetailsWithPerm() {
String logLine = " [Eden: 143.0M(1624.0M)->0.0B(1843.0M) Survivors: 219.0M->0.0B "
+ "Heap: 999.5M(3072.0M)->691.1M(3072.0M)], [Perm: 175031K->175031K(175104K)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSpaceNoDetailsWithoutPerm() {
String logLine = " [Eden: 4096M(4096M)->0B(3528M) Survivors: 0B->568M Heap: 4096M(16384M)->567M(16384M)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullCombinedConcurrentRootRegionScanStart() {
String logLine = "88.123: [Full GC (Metadata GC Threshold) 88.123: [GC concurrent-root-region-scan-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineFullCombinedConcurrentRootRegionScanEndWithDuration() {
String logLine = "93.315: [Full GC (Metadata GC Threshold) 93.315: "
+ "[GC concurrent-root-region-scan-end, 0.0003872 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineEndOfFullCollection() {
String logLine = " 1831M->1213M(5120M), 5.1353878 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineSpaceDetailsWithMetaspace() {
String logLine = " [Eden: 0.0B(1522.0M)->0.0B(2758.0M) Survivors: 244.0M->0.0B "
+ "Heap: 1831.0M(5120.0M)->1213.5M(5120.0M)], [Metaspace: 396834K->324903K(1511424K)]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1YoungInitialMarkTriggerMetaGcThreshold() {
String logLine = "87.830: [GC pause (Metadata GC Threshold) (young) (initial-mark), 0.2932700 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineMiddleG1FullWithSizeInformation() {
String logLine = " 1831M->1213M(5120M), 5.1353878 secs]";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
G1PreprocessAction action = new G1PreprocessAction(null, logLine, null, null, context);
String preprocessedLine = "1831M->1213M(5120M), 5.1353878 secs]";
Assert.assertEquals("Preprocessing failed.", preprocessedLine, action.getLogEntry());
}
public void testLogLineG1FullTriggerLastDitchCollection2SpacesAfterTrigger() {
String logLine = "98.150: [Full GC (Last ditch collection) 1196M->1118M(5120M), 4.4628626 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullTriggerJvmTiForcedGarbageCollection() {
String logLine = "102.621: [Full GC (JvmtiEnv ForceGarbageCollection) 1124M->1118M(5120M), 3.8954775 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullTriggerMetaDataGcThresholdMixedConcurrentRootRegionScanEnd() {
String logLine = "290.944: [Full GC (Metadata GC Threshold) 290.944: "
+ "[GC concurrent-root-region-scan-end, 0.0003793 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullTriggerMetaDataGcThresholdMixedConcurrentRootRegionScanEndPrependedColon() {
String logLine = ": 7688.541: [Full GC (Metadata GC Threshold) 2016-10-12T11:56:49.416+0200: "
+ "7688.541: [GC concurrent-root-region-scan-end, 0.0003847 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullCombinedConcurrentRootRegionScanStartMissingTimestamp() {
String logLine = "298.027: [Full GC (Metadata GC Threshold) [GC concurrent-root-region-scan-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullTriggerMetaDataGcThreshold() {
String logLine = "4708.816: [Full GC (Metadata GC Threshold) 801M->801M(5120M), 3.5048336 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1YoungInitialMarkTriggerGcLockerInitiatedGc() {
String logLine = "6896.482: [GC pause (GCLocker Initiated GC) (young) (initial-mark), 0.0525160 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1YoungConcurrentTriggerG1HumongousAllocation() {
String logLine = "2017-06-22T13:55:45.753+0530: 71574.499: [GC pause (G1 Humongous Allocation) (young)"
+ "2017-06-22T13:55:45.771+0530: 71574.517: [GC concurrent-root-region-scan-end, 0.0181265 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1ConcurrentWithDatestamp() {
String logLine = "2016-02-09T06:17:15.377-0500: 27744.139: [GC concurrent-root-region-scan-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineFullGcPrintClassHistogram() {
String priorLogLine = "";
String logLine = "49689.217: [Full GC49689.217: [Class Histogram (before full gc):";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"49689.217: [Full GC49689.217: [Class Histogram (before full gc):", event.getLogEntry());
}
public void testLogLinePrintClassHistogramSpaceAtEnd() {
String priorLogLine = "";
String logLine = "49709.036: [Class Histogram (after full gc): ";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", "49709.036: [Class Histogram (after full gc):",
event.getLogEntry());
}
public void testLogLineYoungPause() {
String priorLogLine = "";
String logLine = "785,047: [GC pause (young), 0,73936800 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineYoungPauseMixedConccurrentMarkEnd() {
String priorLogLine = "";
String logLine = "188935.313: [GC pause (G1 Evacuation Pause) (young)"
+ "188935.321: [GC concurrent-mark-end, 0.4777427 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, priorLogLine, nextLogLine));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", "188935.313: [GC pause (G1 Evacuation Pause) (young)",
event.getLogEntry());
}
public void testLogLineErgonomicsDatestampDoubleTimestamp() {
String logLine = "2016-02-12T00:05:06.348-0500: 35945.418: 35945.418: [G1Ergonomics (CSet Construction) "
+ "start choosing CSet, _pending_cards: 279876, predicted base time: 236.99 ms, remaining time: "
+ "263.01 ms, target pause time: 500.00 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineErgonomicsDoubleTimestamp() {
String logLine = "16023.683: 16023.683: [G1Ergonomics (CSet Construction) add young regions to CSet, "
+ "eden: 76 regions, survivors: 7 regions, predicted young region time: 123.54 ms]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1RemarkDatestamps() {
String logLine = "2016-03-14T16:06:13.991-0700: 5.745: [GC remark 2016-03-14T16:06:13.991-0700: 5.746: "
+ "[Finalize Marking, 0.0068506 secs] 2016-03-14T16:06:13.998-0700: 5.752: [GC ref-proc, "
+ "0.0014064 secs] 2016-03-14T16:06:14.000-0700: 5.754: [Unloading, 0.0057674 secs], 0.0157938 secs]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullDoubleDatestamps() {
String logLine = "2016-10-12T09:53:38.901+0200: 2016-10-12T09:53:38.901+0200: 298.027: 298.027: "
+ "[Full GC (Metadata GC Threshold) [GC concurrent-root-region-scan-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineConsurrentDatestampTimestampDatestamp() {
String logLine = "2016-10-12T11:56:49.415+0200: 7688.541: 2016-10-12T11:56:49.415+0200"
+ "[GC concurrent-root-region-scan-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineConsurrentDatestampDatestampTimestampTimestamp() {
String logLine = "2016-10-12T11:37:28.396+0200: 2016-10-12T11:37:28.396+0200: 6527.522: "
+ "6527.522: [GC concurrent-root-region-scan-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineConsurrentDatestampDatestampTimestampTimestampNoColonNoSpace() {
String logLine = "2016-10-12T11:39:07.893+0200: 2016-10-12T11:39:07.893+0200: "
+ "6627.019: 6627.019[GC concurrent-root-region-scan-start]";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineG1FullDatestamp() {
String logLine = "2016-10-31T14:09:15.030-0700: 49689.217: [Full GC"
+ "2016-10-31T14:09:15.030-0700: 49689.217: [Class Histogram (before full gc):";
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
}
public void testLogLineFullMixedConcurrentNoSpaceAfterTrigger() {
String logLine = "2017-02-27T02:55:32.523+0300: 35911.404: [Full GC (Allocation Failure)"
+ "2017-02-27T02:55:32.524+0300: 35911.405: [GC concurrent-root-region-scan-end, 0.0127300 secs]";
String nextLogLine = "2017-02-27T02:55:32.524+0300: 35911.405: [GC concurrent-mark-start]";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-02-27T02:55:32.523+0300: 35911.404: [Full GC (Allocation Failure)", event.getLogEntry());
}
public void testLogLineFullMixedConcurrentDatestampDatestampTimestampTimestamp() {
String logLine = "2017-06-22T16:03:36.126+0530: 2017-06-22T16:03:36.126+0530: 79244.87279244.872: : "
+ "[Full GC (Metadata GC Threshold) [GC concurrent-root-region-scan-start]";
String nextLogLine = "2017-06-22T16:03:36.126+0530: 79244.872: [GC concurrent-root-region-scan-end, "
+ "0.0002076 secs]";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-06-22T16:03:36.126+0530: 79244.872: [Full GC (Metadata GC Threshold) ", event.getLogEntry());
}
public void testLogLineFullMixedConcurrentScrambledDateTimeStamps() {
String logLine = "2017-06-22T16:35:58.032+0530: 81186.777: 2017-06-22T16:35:58.032+0530: "
+ "[Full GC (Metadata GC Threshold) 81186.777: [GC concurrent-root-region-scan-start]";
String nextLogLine = "2017-06-22T16:35:58.033+0530: 81186.778: [GC concurrent-root-region-scan-end, "
+ "0.0008790 secs]";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-06-22T16:35:58.032+0530: 81186.777: [Full GC (Metadata GC Threshold) ", event.getLogEntry());
}
public void testLogLineConcurrentWithDatestamp() {
String logLine = "2017-02-27T02:55:32.524+0300: 35911.405: [GC concurrent-mark-start]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-02-27T02:55:32.524+0300: 35911.405: [GC concurrent-mark-start]", event.getLogEntry());
}
public void testLogLineMiddleInitialMark() {
String logLine = " (initial-mark), 0.12895600 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.", logLine, event.getLogEntry());
}
public void testLogLineMixedYoungPauseWithConcurrentRootRegionScanEndWithDatestamps() {
String logLine = "2017-06-01T03:09:18.078-0400: 3978.886: [GC pause (GCLocker Initiated GC) (young)"
+ "2017-06-01T03:09:18.081-0400: 3978.888: [GC concurrent-root-region-scan-end, 0.0059070 secs]";
String nextLogLine = "";
Set<String> context = new HashSet<String>();
Assert.assertTrue("Log line not recognized as " + JdkUtil.PreprocessActionType.G1.toString() + ".",
G1PreprocessAction.match(logLine, null, null));
List<String> entangledLogLines = new ArrayList<String>();
G1PreprocessAction event = new G1PreprocessAction(null, logLine, nextLogLine, entangledLogLines, context);
Assert.assertEquals("Log line not parsed correctly.",
"2017-06-01T03:09:18.078-0400: 3978.886: [GC pause (GCLocker Initiated GC) (young)",
event.getLogEntry());
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_PAUSE.
*
*/
public void testG1PreprocessActionG1YoungPauseLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset32.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertEquals("Inverted parallelism event count not correct.", 0, jvmRun.getInvertedParallelismCount());
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_PAUSE with G1_EVACUATION_PAUSE trigger.
*
*/
public void testG1PreprocessActionG1EvacuationPauseLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset34.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_PAUSE with GCLOCKER_INITIATED_GC trigger.
*
*/
public void testG1PreprocessActionG1YoungPauseWithGCLockerInitiatedGCLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset35.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertEquals("Inverted parallelism event count not correct.", 1, jvmRun.getInvertedParallelismCount());
Assert.assertTrue(Analysis.WARN_PARALLELISM_INVERTED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PARALLELISM_INVERTED));
}
/**
* Test <code>G1PreprocessAction</code> for G1_FULL_GC.
*
*/
public void testG1PreprocessActionG1FullGCLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset36.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue(Analysis.ERROR_EXPLICIT_GC_SERIAL_G1 + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_EXPLICIT_GC_SERIAL_G1));
Assert.assertFalse(Analysis.ERROR_SERIAL_GC_G1 + " analysis incorrectly identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_SERIAL_GC_G1));
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_INITIAL_MARK.
*
*/
public void testG1PreprocessActionYoungInitialMarkLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset37.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_INITIAL_MARK.
*
*/
public void testG1PreprocessActionG1InitialMarkWithCodeRootLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset43.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
}
/**
* Test <code>G1PreprocessAction</code> for G1_REMARK.
*
*/
public void testG1PreprocessActionRemarkLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset38.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_REMARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_REMARK));
}
/**
* Test <code>G1PreprocessAction</code> for G1_MIXED_PAUSE with G1_EVACUATION_PAUSE trigger.
*
*/
public void testG1PreprocessActionMixedPauseLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset39.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_MIXED_PAUSE));
}
/**
* Test <code>G1PreprocessAction</code> for G1_CLEANUP.
*
*/
public void testG1PreprocessActionCleanupLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset40.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CLEANUP.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CLEANUP));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT.
*
*/
public void testG1PreprocessActionConcurrentLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset44.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_PAUSE with TO_SPACE_EXHAUSTED trigger.
*
*/
public void testG1PreprocessActionToSpaceExhaustedLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset45.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue(Analysis.ERROR_G1_EVACUATION_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_G1_EVACUATION_FAILURE));
}
/**
* Test <code>G1PreprocessAction</code> for G1_MIXED_PAUSE with no trigger.
*
*/
public void testG1PreprocessActionMixedPauseNoTriggerLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset46.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_MIXED_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_MIXED_PAUSE));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT.
*
*/
public void testG1PreprocessActionYoungConcurrentLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset47.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungPauseWithG1ErgonomicsLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset48.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_INITIAL_MARK with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungInitialMarkWithG1ErgonomicsLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset49.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_PAUSE with TRIGGER_TO_SPACE_EXHAUSTED with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungPauseTriggerToSpaceExhaustedWithG1ErgonomicsLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset50.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue(Analysis.ERROR_G1_EVACUATION_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_G1_EVACUATION_FAILURE));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungPauseWithG1ErgonomicsLogging2() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset51.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungPauseWithG1ErgonomicsLogging3() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset52.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test <code>G1PreprocessAction</code> for G1_YOUNG_INITIAL_MARK with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungInitialMarkWithTriggerAndG1ErgonomicsLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset53.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue(Analysis.ERROR_G1_EVACUATION_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_G1_EVACUATION_FAILURE));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungPauseWithG1ErgonomicsLogging4() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset54.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungPauseWithG1ErgonomicsLogging5() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset55.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test <code>G1PreprocessAction</code> for mixed G1_YOUNG_PAUSE and G1_CONCURRENT with ergonomics.
*
*/
public void testG1PreprocessActionG1YoungPauseWithG1ErgonomicsLogging6() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset57.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertTrue(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue(JdkUtil.LogEventType.G1_CONCURRENT.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_CONCURRENT));
Assert.assertTrue(JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_YOUNG_PAUSE));
}
/**
* Test to ensure it does not falsely erroneously preprocess.
*
*/
public void testG1CleanupG1InitialMark() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset62.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertTrue(JdkUtil.LogEventType.G1_CLEANUP.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_CLEANUP));
Assert.assertTrue(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_YOUNG_INITIAL_MARK));
}
/**
* Test for G1_REMARK with JDK8 details.
*
*/
public void testRemarkWithFinalizeMarkingAndUnloading() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset63.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_REMARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_REMARK));
}
/**
* Test for G1_CONCURRENT string deduplication.
*
*/
public void testConcurrentStringDeduplicatonLogging() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset64.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test for G1_FULL across 3 lines with details.
*
*/
public void testG1Full3Lines() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset65.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue(Analysis.WARN_PRINT_GC_CAUSE_NOT_ENABLED + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_GC_CAUSE_NOT_ENABLED));
Assert.assertFalse(Analysis.WARN_PRINT_GC_CAUSE_MISSING + " analysis incorrectly identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_PRINT_GC_CAUSE_MISSING));
}
/**
* Test preprocessing G1_FULL triggered by TRIGGER_LAST_DITCH_COLLECTION.
*
*/
public void testG1FullLastDitchCollectionTrigger() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset74.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue(JdkUtil.TriggerType.LAST_DITCH_COLLECTION.toString() + " trigger not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_METASPACE_ALLOCATION_FAILURE));
}
/**
* Test preprocessing G1_FULL triggered by TRIGGER_JVMTI_FORCED_GARBAGE_COLLECTION.
*
*/
public void testG1FullJvmTiForcedGarbageCollectionTrigger() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset75.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue(JdkUtil.TriggerType.JVMTI_FORCED_GARBAGE_COLLECTION.toString() + " trigger not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_EXPLICIT_GC_JVMTI));
}
/**
* Test preprocessing G1 concurrent missing timestamp.
*
*/
public void testG1ConcurrentMissingTimestamp() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset76.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test preprocessing G1 concurrent missing timestamp but has colon.
*
*/
public void testG1ConcurrentMissingTimestampExceptColon() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset77.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test preprocessing G1_FULL missing timestamp.
*
*/
public void testG1FullMissingTimestamp() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset78.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test preprocessing G1_FULL missing timestamp but has colon.
*
*/
public void testG1FullMissingTimestampExceptColon() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset79.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test preprocessing G1_FULL missing timestamp but has colon.
*
*/
public void testG1FullPrependedColon() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset80.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
}
/**
* Test preprocessing G1_FULL with CLASS_HISTOGRAM.
*
*/
public void testG1FullWithPrintClassHistogram() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset93.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.CLASS_HISTOGRAM.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.CLASS_HISTOGRAM));
Assert.assertTrue(Analysis.WARN_CLASS_HISTOGRAM + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.WARN_CLASS_HISTOGRAM));
// G1_FULL is caused by CLASS_HISTOGRAM
Assert.assertFalse(Analysis.ERROR_SERIAL_GC_G1 + " analysis incorrectly identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_SERIAL_GC_G1));
}
/**
* Test preprocessing G1_YOUNG_PAUSE with no size details (whole number units).
*
*/
public void testG1YoungPauseNoSizeDetails() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset97.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
}
/**
* Test preprocessing G1_YOUNG_PAUSE with double trigger and Evacuation Failure details.
*
*/
public void testG1YoungPauseEvacuationFailure() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset100.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_YOUNG_PAUSE.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_YOUNG_PAUSE));
Assert.assertTrue(Analysis.ERROR_G1_EVACUATION_FAILURE + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_G1_EVACUATION_FAILURE));
}
public void testFullGcMixedConcurrent() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset116.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 3, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_FULL_GC.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_FULL_GC));
Assert.assertTrue("Log line not recognized as " + JdkUtil.LogEventType.G1_CONCURRENT.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.G1_CONCURRENT));
Assert.assertTrue(
"Log line not recognized as " + JdkUtil.LogEventType.APPLICATION_STOPPED_TIME.toString() + ".",
jvmRun.getEventTypes().contains(JdkUtil.LogEventType.APPLICATION_STOPPED_TIME));
Assert.assertTrue(Analysis.ERROR_SERIAL_GC_G1 + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_SERIAL_GC_G1));
}
public void testG1YoungInitialMark() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset127.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 1, jvmRun.getEventTypes().size());
Assert.assertTrue(JdkUtil.LogEventType.G1_YOUNG_INITIAL_MARK.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_YOUNG_INITIAL_MARK));
}
public void testFullMixedConcurrentScrambledDateTimestamps() {
// TODO: Create File in platform independent way.
File testFile = new File("src/test/data/dataset134.txt");
GcManager gcManager = new GcManager();
File preprocessedFile = gcManager.preprocess(testFile, null);
gcManager.store(preprocessedFile, false);
JvmRun jvmRun = gcManager.getJvmRun(new Jvm(null, null), Constants.DEFAULT_BOTTLENECK_THROUGHPUT_THRESHOLD);
Assert.assertEquals("Event type count not correct.", 2, jvmRun.getEventTypes().size());
Assert.assertFalse(JdkUtil.LogEventType.UNKNOWN.toString() + " collector identified.",
jvmRun.getEventTypes().contains(LogEventType.UNKNOWN));
Assert.assertTrue(JdkUtil.LogEventType.G1_FULL_GC.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_FULL_GC));
Assert.assertTrue(JdkUtil.LogEventType.G1_CONCURRENT.toString() + " collector not identified.",
jvmRun.getEventTypes().contains(LogEventType.G1_CONCURRENT));
Assert.assertTrue(Analysis.ERROR_SERIAL_GC_G1 + " analysis not identified.",
jvmRun.getAnalysis().contains(Analysis.ERROR_SERIAL_GC_G1));
}
}
| cd7c1afa1d57b8a5b8c4f46f7bc8df9ef3cbcd2d | [
"Markdown",
"Java"
] | 18 | Java | doctau/garbagecat | 3417907e5da75a27cdc2385d9d29a7c2e304b6cd | 0b189daf09497611d9c70d5fe1fa3ddc9d8a6634 | |
refs/heads/main | <file_sep>from .card import Card
from .deck import Deck
from .deckCard import DeckCard
from .discard import Discard
from .discardCard import DiscardCard
from .game import Game
from .gameType import GameType
from .hand import Hand
from .handCard import HandCard
from .playerGame import PlayerGame
from .round import Round
from .roundScore import RoundScore
<file_sep>from django.db import models
class HandCard(models.Model):
hand = models.ForeignKey('Hand', on_delete=models.CASCADE)
card = models.ForeignKey('Card', on_delete=models.CASCADE)
revealed = models.BooleanField()
<file_sep>from django.db import models
from django.contrib.auth.models import User
class PlayerGame(models.Model):
player = models.ForeignKey(User, on_delete=models.DO_NOTHING)
game = models.ForeignKey('Game', on_delete=models.CASCADE)
order = models.IntegerField()<file_sep># Generated by Django 3.2.5 on 2021-07-28 22:53
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('card_golfapi', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='game',
name='round',
field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='Game', to='card_golfapi.round'),
),
migrations.AlterField(
model_name='round',
name='game',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Round', to='card_golfapi.game'),
),
]
<file_sep>from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.contrib.auth.models import User
class Game(models.Model):
playerCount = models.IntegerField(validators=[MinValueValidator(2), MaxValueValidator(4)],)
gameType = models.ForeignKey('GameType', on_delete=models.DO_NOTHING)
needPlayers = models.BooleanField()
complete = models.BooleanField()
playerAction = models.ForeignKey(User, related_name='PlayerAction', on_delete=models.DO_NOTHING)
round = models.ForeignKey('Round', related_name='Game', on_delete=models.DO_NOTHING)
winner = models.ForeignKey(User, related_name='winner', on_delete=models.DO_NOTHING, null=True)
<file_sep>from django.db import models
class Discard(models.Model):
game = models.ForeignKey('Game', on_delete=models.CASCADE)
<file_sep>from django.db import models
class GameType(models.Model):
name = models.CharField(max_length=250)
cardCount = models.IntegerField()
<file_sep>from django.db import models
class Round(models.Model):
open = models.BooleanField()
name = models.IntegerField()
game = models.ForeignKey('Game', related_name='Round', on_delete=models.CASCADE)<file_sep>from django.db import models
from django.contrib.auth.models import User
class Hand(models.Model):
player = models.ForeignKey(User, on_delete=models.DO_NOTHING)
game = models.ForeignKey('Game', on_delete=models.CASCADE)
score = models.IntegerField()<file_sep># Generated by Django 3.2.5 on 2021-07-28 22:46
from django.conf import settings
import django.core.validators
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='Card',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('suite', models.CharField(max_length=15)),
('name', models.CharField(max_length=15)),
('score', models.IntegerField()),
('image', models.URLField()),
],
),
migrations.CreateModel(
name='Deck',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='Game',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('playerCount', models.IntegerField(validators=[django.core.validators.MinValueValidator(2), django.core.validators.MaxValueValidator(4)])),
('needPlayers', models.BooleanField()),
('complete', models.BooleanField()),
],
),
migrations.CreateModel(
name='GameType',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=250)),
('cardCount', models.IntegerField()),
],
),
migrations.CreateModel(
name='Hand',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('score', models.IntegerField()),
('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.game')),
('player', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Round',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('open', models.BooleanField()),
('name', models.IntegerField()),
('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Game', to='card_golfapi.game')),
],
),
migrations.CreateModel(
name='RoundScore',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('score', models.IntegerField()),
('player', models.ForeignKey(null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
('round', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='card_golfapi.round')),
],
),
migrations.CreateModel(
name='PlayerGame',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order', models.IntegerField()),
('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.game')),
('player', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='HandCard',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('revealed', models.BooleanField()),
('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.card')),
('hand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.hand')),
],
),
migrations.AddField(
model_name='game',
name='gameType',
field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='card_golfapi.gametype'),
),
migrations.AddField(
model_name='game',
name='playerAction',
field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='PlayerAction', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='game',
name='round',
field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='Round', to='card_golfapi.round'),
),
migrations.AddField(
model_name='game',
name='winner',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='winner', to=settings.AUTH_USER_MODEL),
),
migrations.CreateModel(
name='DiscardCard',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.card')),
('deck', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.deck')),
],
),
migrations.CreateModel(
name='Discard',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.game')),
],
),
migrations.CreateModel(
name='DeckCard',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.card')),
('deck', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.deck')),
],
),
migrations.AddField(
model_name='deck',
name='game',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='card_golfapi.game'),
),
]
<file_sep>
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from rest_framework import routers
from card_golfapi.views import register_user, login_user
router = routers.DefaultRouter(trailing_slash=False)
urlpatterns = [
path('register', register_user),
path('login', login_user),
path('', include(router.urls)),
path('api-ath', include('rest_framework.urls', namespace='rest_framework')),
path('admin/', admin.site.urls),
]
<file_sep>from django.db import models
class Card(models.Model):
suite = models.CharField(max_length=15)
name = models.CharField(max_length=15)
score = models.IntegerField()
image = models.URLField(blank=True)<file_sep>from django.db import models
class DeckCard(models.Model):
deck = models.ForeignKey('Deck', on_delete=models.CASCADE)
card = models.ForeignKey('Card', on_delete=models.CASCADE)
<file_sep>from django.db import models
from django.contrib.auth.models import User
class RoundScore(models.Model):
round = models.ForeignKey('Round', on_delete=models.DO_NOTHING)
player = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True)
score = models.IntegerField() | 3edfe09a97b5bb300388617a40b73784fa1f9a4e | [
"Python"
] | 14 | Python | Daniel-L-Ross/card_golf | a7bc8ab99462224dda69f41cc287ab16618b8c3b | 4cc20a4cb5c68eaf47417e6ae7ec688f8b4f7a00 | |
refs/heads/main | <repo_name>limelody/LLLInventoryScrap<file_sep>/README.md
# Lululemon Inventory Scraper
Find OOS items in-store with web scraping
Since only the app shows all stores with inventory, and items out of stock online don't show up in the app, need to check through all store locations in browser to find stock. But guessing cities is difficult (like how I forget to check Victoria, BC every time).
Python script does the following:
- Gets all cities with stores throughout Canada (this is bad design, should fix this. but i hate text files and dynamically checking for updated stores isn't _that_ bad)
- For a particular item (colour + size), checks every city for inventory and outputs all stores with stock at the end
## Pre-run Instructions:
Requirements:
* Chrome 87
* Windows
Install the appropriate chromedriver [here](https://sites.google.com/a/chromium.org/chromedriver/downloads) and change line 10 if it's not downloaded into this repo. If not on Windows, just get the appropriate OS binary. Similarly, can switch Chrome to a different browser, and also fix line 10 to be `webdriver.Firefox()` or something.
Install Selenium:
``` pip install selenium ```
## Run Instructions:
```python inventory.py```
When prompted, type the full URL (with colour and size selected).
Example: ```https://shop.lululemon.com/p/womens-joggers/Dance-Studio-Jogger-29/_/prod9000211?color=47780&sz=10```
(I know this is also bad design but it's easier for me to run on subsequent different items because who in the right mind is going to check the same item over and over again)
After execution finishes, will output a list of all stores with stock (add in phone numbers later because they're not working now).
Like all web scrapers, might break if the site changes ¯\\\_( ͠° ͟ʖ °͠ )\_/¯
<file_sep>/inventory.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located
import time
url = input("Enter product url: ")
with webdriver.Chrome('chromedriver') as driver:
wait = WebDriverWait(driver, 10)
# city scrapping
driver.get("https://shop.lululemon.com/stores/all-lululemon-stores")
wait.until(presence_of_element_located((By.CLASS_NAME,"state-section-container")))
# let it load out so i can see
time.sleep(5)
driver.find_element_by_css_selector("#filter-all-store-locations").click()
driver.find_element_by_css_selector("#filter-all-store-locations > option:nth-child(1)").click()
# let it load out so i can see
time.sleep(5)
locations = driver.find_elements_by_class_name("lll-font-body-secondary")
cities = set()
for store in locations:
cities.add((store.text).split(":")[0])
# #product
driver.get(url)
wait.until(presence_of_element_located((By.CLASS_NAME, "purchase-method__bopis__link")))
driver.find_element(By.CLASS_NAME, "purchase-method__bopis__link").click()
wait.until(presence_of_element_located((By.CLASS_NAME, "select-menu__selected")))
store_names = set()
# wrap in city loop
for city in cities:
input_bar = driver.find_element_by_class_name("search-bar__input")
input_bar.send_keys(Keys.CONTROL + "a")
input_bar.send_keys(Keys.DELETE)
input_bar.send_keys(city)
driver.find_element_by_class_name("search-bar__search-button").click()
time.sleep(5)
try:
# nothing to see here
err = driver.find_element_by_class_name("error-message")
continue
except:
pass
try:
bopis_list = driver.find_element_by_class_name("store-list")
bopis_stores = bopis_list.find_elements_by_class_name("store-list__item")
for store in bopis_stores:
store_name = store.find_element_by_class_name("radio-btn__label").text
# NOT WORKING
# store_phone = store.find_element_by_class_name("store-details__phone")
# phone = store_phone.find_element_by_tag_name("a").text
# print(phone) #BLANK
# full_str = store_name + ": " + phone
store_names.add(store_name)
except:
pass
try:
in_person_list = driver.find_element_by_class_name("store-list--unavailable")
in_person_stores = in_person_list.find_elements_by_class_name("store-list__item")
for store in in_person_stores:
store_name = store.find_element_by_class_name("radio-btn__label").text
# store_phone = store.find_element_by_class_name("store-details__phone")
# phone = store_phone.find_element_by_class_name("inline-link").text
# full_str = store_name + ": " + phone
store_names.add(store_name)
except:
pass
if (len(store_names) != 0):
print(store_names)
else:
print("No in-store stock") | d9b32512a5d9e161bb818baf10bcb6869a7e0cff | [
"Markdown",
"Python"
] | 2 | Markdown | limelody/LLLInventoryScrap | 09a2955dd1805bee6588cbbb8f5be7fa8b5a2139 | 30377a2c1e1071d4f756fbe8252690b853601b54 | |
refs/heads/master | <repo_name>deniojunior/analisador-lexico-sql<file_sep>/README.md
# analisador-lexico-sql
Analisador Léxico Simples de SQL.
# Executar
Clone o repositório e execute a classe Main.java
# Dependências
JDK 1.7+
<file_sep>/src/view/Main.java
package view;
import roles.Language;
import java.util.ArrayList;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
* @author deniojunior
*/
public class Main extends javax.swing.JFrame {
private ArrayList<String[]> palavrasReservadas;
/** Creates new form Main **/
public Main() {
initComponents();
this.setLocationRelativeTo(null);
palavrasReservadas = Language.getInstance().initSQLTokensLexems();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jlbSQL = new javax.swing.JLabel();
jbtAnalisar = new javax.swing.JButton();
jbtLimpar = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jtbTabela = new javax.swing.JTable();
jScrollPane3 = new javax.swing.JScrollPane();
jtpSql = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jlbSQL.setText("Insira o código SQL:");
jbtAnalisar.setText("Analisar");
jbtAnalisar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtAnalisarActionPerformed(evt);
}
});
jbtLimpar.setText("Limpar");
jbtLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtLimparActionPerformed(evt);
}
});
jtbTabela.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Token", "Lexema"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(jtbTabela);
jScrollPane3.setViewportView(jtpSql);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
.addComponent(jlbSQL, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3)))
.addGroup(layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(jbtAnalisar, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(43, 43, 43)
.addComponent(jbtLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlbSQL)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbtAnalisar)
.addComponent(jbtLimpar))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
public String formataSql(String sql){
String caracteres = "*();',.";
String pt1 = "", pt2 = "";
String carac = "";
for(int i = 0; i < sql.length(); i++){
carac = "" + sql.charAt(i);
System.out.println("Carac: " + carac);
if(caracteres.contains(carac)){
pt1 = (String)sql.subSequence(0, i);
pt2 = (String)sql.subSequence((i+1), sql.length());
sql = pt1 + " " + carac + " " + pt2;
i++;
}
}
System.out.println("SQL Formatada: " + sql);
return(sql);
}
private void jbtAnalisarActionPerformed(java.awt.event.ActionEvent evt) {
String sql = formataSql(jtpSql.getText());
int controlTabela = 0;
String tabela[][] = new String[50][2];
for(int i = 0; i < 50; i++){
tabela[i][0] = "";
tabela[i][1] = "";
}
String comando[] = sql.split(" ");
boolean palavraReservada = false;
boolean aspasAbertas = false;
for(int i = 0; i < comando.length; i++){
System.out.println("Comando[" + i + "]: " + comando[i]);
palavraReservada = false;
for(int j = 0; j < palavrasReservadas.size(); j++){
if(comando[i].equalsIgnoreCase(palavrasReservadas.get(j)[0])){
if(comando[i].contains("'")){
if(!aspasAbertas){
tabela[controlTabela][0] = "<ASPAS_ABRE>";
aspasAbertas = true;
}else{
tabela[controlTabela][0] = "<ASPAS_FECHA>";
aspasAbertas = false;
}
}else{
tabela[controlTabela][0] = palavrasReservadas.get(j)[1];
}
tabela[controlTabela][1] = comando[i];
controlTabela++;
palavraReservada = true;
break;
}
}
if(!palavraReservada){
try{
float num = Float.parseFloat(comando[i]);
tabela[controlTabela][0] = "<VALOR_NUMERICO>";
tabela[controlTabela][1] = comando[i];
controlTabela++;
}catch(NumberFormatException ex){
if(!comando[i].isEmpty()){
if(comando[i-1].contains("'") || comando[i-2].contains("'")){
tabela[controlTabela][0] = "<STRING>";
tabela[controlTabela][1] = comando[i];
controlTabela++;
}else{
tabela[controlTabela][0] = "<ID>";
tabela[controlTabela][1] = comando[i];
controlTabela++;
}
}
}
}
}
String[] colunas = {"Token", "Lexema"};
DefaultTableModel modelo = (DefaultTableModel) jtbTabela.getModel();
modelo.setColumnIdentifiers(colunas);
for(int i = 0; i < 50; i++){
if(!tabela[i][0].isEmpty()){
Object[] objetos = new Object[2];
objetos[0] = tabela[i][0];
objetos[1] = tabela[i][1];
modelo.addRow(objetos);
}
}
jtbTabela.setModel(modelo);
organizaCelulas();
jbtAnalisar.setEnabled(false);
}
private void jbtLimparActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel modelo = (DefaultTableModel) jtbTabela.getModel();
int tamanhoTabela = jtbTabela.getRowCount();
for(int i = 0; i < tamanhoTabela; i++){
modelo.removeRow(0);
}
jtbTabela.setModel(modelo);
jtpSql.setText("");
jbtAnalisar.setEnabled(true);
}
public void organizaCelulas(){
DefaultTableCellRenderer cellRenderCod = new DefaultTableCellRenderer();
cellRenderCod.setHorizontalAlignment(SwingConstants.CENTER);
jtbTabela.getColumnModel().getColumn(0).setCellRenderer(cellRenderCod);
jtbTabela.getColumnModel().getColumn(1).setCellRenderer(cellRenderCod);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton jbtAnalisar;
private javax.swing.JButton jbtLimpar;
private javax.swing.JLabel jlbSQL;
private javax.swing.JTable jtbTabela;
private javax.swing.JTextPane jtpSql;
} | a764755497095520907f0115c9eb1dee06900428 | [
"Markdown",
"Java"
] | 2 | Markdown | deniojunior/analisador-lexico-sql | 61dc3c884dc7cd8a6fbecee02b2d4497d668f282 | 10531fb58137f6532a6b508dd3b9ef9955212c6e | |
refs/heads/master | <repo_name>trongtq178/store-with-nextjs-moltin<file_sep>/readme.txt
1. Tham khảo: https://www.youtube.com/watch?v=rmevNGXVK0c&list=PLci1bAwknnOSbWbkIIZ5D9tbNS6Og2lug&index=1
2. Cần tạo tài khoản moltin
3. Chạy website: npm run dev<file_sep>/components/Header.js
import Link from 'next/link';
import {Menu, Container, Image} from 'semantic-ui-react';
import Head from 'next/head';
import Router from 'next/router';
import NProgress from 'nprogress';
Router.onRouterChangeStart = url => NProgress.start();
Router.onRouterChangeComplete = url => NProgress.done();
Router.onRouterChangeError = url => NProgress.done();
export default () => (
<React.Fragment>
<Head>
<link rel="stylesheet" type="text/css" href="/static/nprogress.css" />
</Head>
<Menu inverted fixed='top' size='huge'>
<Container text>
<Link href='/' prefetch passHref>
<Menu.Item as='a' header>
<Image
size='mini'
src='../static/moltin-light-hex.png'
style={{marginRight: '1.5em'}}
/>
Nextjs Store
</Menu.Item>
</Link>
<Link href='/register' prefetch passHref>
<Menu.Item as='a'>
Sign up
</Menu.Item>
</Link>
<Link href='/login' prefetch passHref>
<Menu.Item as='a'>
Sign in
</Menu.Item>
</Link>
<Link href='/cart' prefetch passHref>
<Menu.Item position="right" as='a' header>
Cart
</Menu.Item>
</Link>
</Container>
</Menu>
</React.Fragment>
) | c3184fd8869bfbea6f554f7c3f7a019437dd3326 | [
"JavaScript",
"Text"
] | 2 | Text | trongtq178/store-with-nextjs-moltin | 05eb9696bb08237891d4e733a5fcce066840e27d | 30e97806e50c4dd1619b306aa3fc4212f331cf16 | |
refs/heads/master | <repo_name>johnnycrusher/WSJ-News-Archiver<file_sep>/news_archivistWSJ.py
#-----Statement of Authorship----------------------------------------#
#
# This is an individual assessment item. By submitting this
# code I agree that it represents my own work. I am aware of
# the University rule that a student must not act in a manner
# which constitutes academic dishonesty as stated and explained
# in QUT's Manual of Policies and Procedures, Section C/5.3
# "Academic Integrity" and Section E/2.1 "Student Code of Conduct".
#
# Student no: 9154566
# Student name: <NAME>
#
# NB: Files submitted without a completed copy of this statement
# will not be marked. Submitted files will be subjected to
# software plagiarism analysis using the MoSS system
# (http://theory.stanford.edu/~aiken/moss/).
#
#--------------------------------------------------------------------#
#-----Task Description-----------------------------------------------#
#
# News Archivist
#
# In this task you will combine your knowledge of HTMl/XML mark-up
# languages with your skills in Python scripting, pattern matching
# and Graphical User Interface development to produce a useful
# application for maintaining and displaying archived news or
# current affairs stories on a topic of your own choice. See the
# instruction sheet accompanying this file for full details.
#
#--------------------------------------------------------------------#
#-----Imported Functions---------------------------------------------#
#
# Below are various import statements that were used in our sample
# solution. You should be able to complete this assignment using
# these functions only.
# Import the function for opening a web document given its URL.
from urllib.request import urlopen
# Import the function for finding all occurrences of a pattern
# defined via a regular expression, as well as the "multiline"
# and "dotall" flags.
from re import findall, MULTILINE, DOTALL
# A function for opening an HTML document in your operating
# system's default web browser. We have called the function
# "webopen" so that it isn't confused with the "open" function
# for writing/reading local text files.
from webbrowser import open as webopen
# An operating system-specific function for getting the current
# working directory/folder. Use this function to create the
# full path name to your HTML document.
from os import getcwd
# An operating system-specific function for 'normalising' a
# path to a file to the path-naming conventions used on this
# computer. Apply this function to the full name of your
# HTML document so that your program will work on any
# operating system.
from os.path import normpath
# Import the standard Tkinter GUI functions.
from tkinter import *
# Import the SQLite functions.
from sqlite3 import *
# Import the date and time function.
from datetime import datetime
import matplotlib
matplotlib.use('Agg')
#
#--------------------------------------------------------------------#
#-----Student's Solution---------------------------------------------#
#
# Put your solution at the end of this file.
#
# Name of the folder containing your archived web documents. When
# you submit your solution you must include the web archive along with
# this Python program. The archive must contain one week's worth of
# downloaded HTML/XML documents. It must NOT include any other files,
# especially image files.
internet_archive = 'WSJ_Tech'
####### HTML Generation Section ###############
def find_article_image(article, which_head_line):
#Open and Read the archive file
news_page = open(article).read()
#Using Regex to extract the image URL
article_image = findall('http.*?jpg',news_page)
#Return the image URL for specified article
return article_image[which_head_line-1]
def find_article_name(article, which_head_line):
#Open and Read the archive file
news_page = open(article).read()
#Using Regex to extract news article title
article_name = findall('<title>(.*?)<\/title>', news_page)
#Return the article title for specified article
return article_name[which_head_line+1]
def find_article_description(article, which_head_line):
#Open and Read the archive file
news_page = open(article).read()
#Using Regex to extract the desciption
article_description = findall('<description>(.*?)<\/description>',news_page)
#Return the article description for specified article
return article_description[which_head_line]
def find_article_link(article, which_head_line):
#Open and Read the archive file
news_page = open(article).read()
#Using Regex to extract URL of the Article
article_link = findall('http.*?logy',news_page)
#Return the URL for specified article
return article_link[which_head_line-1]
def find_article_time(article, which_head_line):
#Open and Read the archive file
news_page = open(article).read()
#Using Regex to extract the publish date of the article
article_date = findall('<pubDate>(.*?)<\/pubDate>',news_page)
#Return the publish date for the speicifed article
return article_date[which_head_line]
def write_news_articles(article,which_news_number):
#Open and Read the archive file
news_page = open(article).read()
#Base Template for news article section
news_articles_section = '''
<h3>number. Article</h3>
<img src = "Article_Image">
<p id = "text">Description</p>
<p id = "text"><b>Full Story:</b><a href="article_Link">article_Link</a></p>
<p id = "text"><b>Dateline:</b>DateTime</p>
'''
#Find the article image
article_image = find_article_image(article,which_news_number)
#Detects if the article image still exist
try:
urlopen(article_image)
except:
#If it doesn't exist then replace the image tag with image not avaliable text
news_articles_section = news_articles_section.replace('<img src = "Article_Image">',
'<p id = "noImage">Sorry,image '+ article_image[41:len(article_image)] + ' not found!</p>')
#Replace the article image text with the actual image URL
news_articles_section = news_articles_section.replace('Article_Image', article_image)
#Find the article name and replace the article name text with the actual article name
article_name = find_article_name(article,which_news_number)
news_articles_section = news_articles_section.replace("Article",article_name)
#Replace number with the actual number
news_articles_section = news_articles_section.replace("number",str(which_news_number))
#Find the article description and replace the article description text with the article description
article_description = find_article_description(article,which_news_number)
news_articles_section = news_articles_section.replace("Description", article_description)
#Find the article line and replace the article_Link text with the article link
article_link = find_article_link(article,which_news_number)
news_articles_section = news_articles_section.replace("article_Link",article_link)
#find the article publish date and replace DateTime text with article publish date
article_date = find_article_time(article,which_news_number)
news_articles_section = news_articles_section.replace("DateTime",article_date)
#return the news article section as a string
return news_articles_section
def write_entire_page(article, article_date):
#allow access to global variables
global archive_dates
global html_pages
#template document for the whole html file
template='''
<HTML>
<Head>
<style>
html {
margin: 0;
padding: 0;
background-color: #777;
}
body {
width: 60%;
margin: 0 auto;
font: 100% Arial, Helvetica, sans-serif;
padding: 1em 50px;
background: lightblue;
}
h1 {
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 2.5em;
font-weight: normal;
font-style: italic;
text-align: center;
margin: 0 0 .4em;
color: darkcyan;
padding: 5px 10px;
}
h2 {font-family:'Times New Roman', Times, serif;
font-size: 2em;
font-weight: normal;
text-align: center}
h3 {font-family: Cambria, Cochin, Georgia, Times, Times New Roman, serif;
font-size: 1.5em;
font-weight: normal;
text-align: center}
img{
display: block;
margin-left: auto;
margin-right: auto;
padding : 15px 5px;
}
#startPage{
margin-left : 25%;
margin-right: 25%;
}
#noImage{
text-align: center;
margin:0 auto;
width: 45%;
border: 1px solid black;
}
#text{
line-height: 1.6;
width: 100%;
margin: 0;
margin-bottom: 1em;
}
</style>
<Title>The Wall Street Journal Technology</Title>
</Head>
<Body>
<h1 allign="center">The Wall Street Journal Technology Archive</h1>
<h2>Date</h2>
<img src= 'Main_Image' width = "436" height = "64">
<p id = "startPage"><b>News Source:</b><a href="SourceURL">SourceURL</a></p>
<p id = "startPage"><b>Arcivist:</b> <NAME></p>
'''
#Closing tags for the html file
closing_tags = '''
</Body>
</HTML>
'''
#Define the main image URL and replace it with Main_Image text
main_image ='http://online.wsj.com/img/wsj_sm_logo.gif'
template = template.replace('Main_Image',main_image)
sourceURL = "http://www.wsj.com/xml/rss/3_7455.xml"
template = template.replace('SourceURL', sourceURL)
#For loop to find which article date it is and replace it
for page in range(0,len(html_pages)-1):
if (article_date == html_pages[page]):
template = template.replace('Date', archive_dates[page])
break
elif(page >= len(html_pages)-2):
template = template.replace('Date', 'Latest News')
#Intilise list for news segmants
news_segmant = []
#Generate the 10 news segmants
for SubArticles in range(0,10):
news_segmant.append(write_news_articles(article,SubArticles+1))
#Open the empty html document and set the property to write
extracted_archive = open("extracted_archive.html",'w')
#Write the base template for the article
extracted_archive.write(template)
#Writing the news segmants into the html document
for article in news_segmant:
extracted_archive.write(article)
#Write the html closing tags into the html document
extracted_archive.write(closing_tags)
extracted_archive.close()
################# GUI Section #################
def extract_news():
#allow access to these global variables
global internet_archive
global lastest_downloaded
global has_archive
global event_checkbox
global log_counter
global connection
#Grabs the current selection for the Listbox
which_option = display_choice()
# Show Error if Latest File has not been archive
if (latest_downloaded == False and which_option =='Latest.html' ):
instruction_label['text'] = 'Error:Latest news has not been downloaded'
else:
#Set the path of the internet archive
path = normpath(getcwd() + '/' + internet_archive)
#Grabs the archive file name based on listbox selection
article = display_choice()
#Define path for the archived document
article_path = normpath(path + '/' + article)
#Write entire page
write_entire_page(article_path, article)
#Change the instruction text
instruction_label['text'] = 'News extrated from archive'
has_archive = True
#Check if checkbox is ticked if ticked then add an entry in the sql data base
if(event_checkbox.get() == 1):
log_counter += 1
sql_query_extract = "INSERT INTO Event_Log VALUES(" + str(log_counter) + \
",'News extracted from archive')"
event_log.execute(sql_query_extract)
connection.commit()
def display_news():
#allow access to these global variables
global has_archive
global event_checkbox
global log_counter
global connection
#Check if it has any extracted archives
if (not has_archive):
instruction_label['text'] = "Please choose a date to archive..."
else:
#Define path to extracted archive
path = normpath(getcwd()+'/extracted_archive.html')
#Open Extracted archive
webopen(path)
#Change instruction label
instruction_label['text'] = "Choose another day's news you would like to extract..."
#Check if checkbox is ticked if ticked then add an entry in the sql data base
if(event_checkbox.get() == 1):
log_counter += 1
sql_query_display = "INSERT INTO Event_Log VALUES(" + str(log_counter) + \
",'Extracted news displayed in web broswer')"
event_log.execute(sql_query_display)
connection.commit()
def archive_news():
#allow access to these global variables
global internet_archive
global latest_downloaded
global event_checkbox
global log_counter
global connection
url = 'http://www.wsj.com/xml/rss/3_7455.xml'
#Open the URL
latest_copy = urlopen(url)
#Read the page contents
latest_page_contents = latest_copy.read().decode('UTF-8')
#Define the internet archive path
internet_archive_path = normpath(getcwd() + '/' + internet_archive )
#Define internet archive latest file path
latest_archive_path = normpath(internet_archive + '/latest.html')
#Open the latest arhcive html doc and set to writing mode
latest_html_page = open(latest_archive_path,'w', encoding = 'UTF-8')
#Write page contents
latest_html_page.write(latest_page_contents)
latest_html_page.close()
#Change instruction text
instruction_label['text'] = "Downloaded latest news..."
latest_downloaded = True
#Check if checkbox is ticked if ticked then add an entry in the sql data base
if(event_checkbox.get() == 1):
log_counter += 1
sql_query_archive = "INSERT INTO Event_Log VALUES(" + str(log_counter) + \
",'Latest news downloaded and store in archive')"
event_log.execute(sql_query_archive)
connection.commit()
def display_choice():
#allow access to these global variables
global archive_dates
global html_pages
global connection
#Define current selection
if (archive_dates_list.curselection() != ()):
#For loop to interate all the archive dates
for page in range(0,len(archive_dates)):
#Check if archive dates match the archive_dates list
if(archive_dates_list.get(archive_dates_list.curselection()) == archive_dates[page]):
#set document to html page name
document = html_pages[page]
break
#return html document name
return document
def activate_logger():
#allow access to these global variables
global event_checkbox
global first_time
global event_log
global log_counter
global connection
#Check if checkbox is ticked
if (event_checkbox.get() == 1):
log_counter += 1
#connect to SQL Data Base
connection = connect(database = "event_log.db")
event_log = connection.cursor()
#Execute SQL Query
sql_query_on = "INSERT INTO Event_Log VALUES(" + str(log_counter) + ",'Event logging switched on')"
event_log.execute(sql_query_on)
#Commit the SQL Query to the Database
connection.commit()
first_time = False
elif(event_checkbox.get() == 0 and first_time == False):
log_counter += 1
#Execute SQL Query
sql_query_off = "INSERT INTO Event_Log VALUES(" + str(log_counter) + ",'Event logging switched off')"
event_log.execute(sql_query_off)
#Commit the SQL Query to the Database
connection.commit()
#Close the connection to the data base
event_log.close()
connection.close()
#Global Vars
archive_dates = ['Thu, 12th Oct 2017','Fri, 13th Oct 2017','Sat, 14th Oct 2017',
'Tue, 17th Oct 2017','Wed, 18th Oct 2017', 'Thu, 19th Oct 2017',
'Fri, 20th Oct 2017','Latest']
html_pages = ['Thu_12th_Oct.html','Fri_13th_Oct.html','Sat_14th_Oct.html',
'Tue_17th_Oct.html','Wed_18th_Oct.html','Thu_19th_Oct.html',
'Fri_20th_Oct.html','Latest.html']
has_archive = False
latest_downloaded = False
first_time = True
log_counter = 0
#Clear Database
connection = connect(database = "event_log.db")
event_log = connection.cursor()
event_log.execute("DELETE FROM Event_Log")
connection.commit()
event_log.close()
connection.close()
#Intialise tkinter window
main_window = Tk()
main_window.title('The Wall Street Journal Technology Archive')
main_window.configure(bg = 'Ivory')
#Create button for extract news
extract_news_button = Button(main_window,
height = 2,
width = 12,
wraplength = 80,
justify = LEFT,
text = "Extract news from archive",
command = extract_news,
bg = 'Ivory')
#Create button for display news
display_news_button = Button(main_window,
height = 2,
width = 12,
wraplength = 80,
justify = LEFT,
text = "Display news extracted",
command = display_news,
bg = 'Ivory')
#Create button for archive news
archive_news_button = Button(main_window,
height = 2,
width = 12,
wraplength = 80,
justify = LEFT,
text = "Archive the latest news",
command = archive_news,
bg = 'Ivory')
#Create label for the instruction
instruction_label = Label(main_window,
text = "Choose which day's news to extract...",
font = ("Helvetica",20),
wraplength = 350,
bg = 'Ivory')
#Create Label for the WSJ label
WSJ_label = Label(main_window,
text = "The Wall Street Journal Technology",
font = ("Helvetica",12),
bg = 'Ivory')
#Create Listbox for archive dates
archive_dates_list = Listbox(main_window,
height = len(archive_dates),
font = ("Helvetica",15))
#add dates in the archive dates
for dates in archive_dates:
archive_dates_list.insert(END,dates)
#setup variable to monitor event checkbox
event_checkbox = IntVar()
#Create checkbox for event logger
event_logger_checkbox = Checkbutton(main_window,
text = "Log Events",
variable = event_checkbox,
command = activate_logger,
bg = 'Ivory')
#Create Image for the GUI
WSJ_logo = PhotoImage(file='The Wall Street Journal Logo.gif')
WSJ_logo_label = Label(main_window, image = WSJ_logo)
#Using Geometry Packer to pack objects into the window
margin_size = 5
archive_dates_list.grid(padx = margin_size, pady = margin_size,
row = 1, column = 1, rowspan = 10)
extract_news_button.grid(padx = margin_size, pady = margin_size,
row = 1,column = 2)
display_news_button.grid(padx = margin_size, pady = margin_size,
row = 2,column = 2)
archive_news_button.grid(padx = margin_size, pady = margin_size,
row = 3,column = 2)
event_logger_checkbox.grid(padx = margin_size, pady = margin_size,
row = 4, column = 2)
instruction_label.grid(padx=margin_size, pady = margin_size,
row = 0, column = 1, columnspan = 2)
WSJ_label.grid(padx = margin_size, pady = margin_size,
row = 4, column = 0)
WSJ_logo_label.grid(padx = margin_size,pady = margin_size,
row = 0, column = 0, rowspan = 4)
# Start the event loop
main_window.mainloop()<file_sep>/WSJ_Tech/Fri_13th_Oct.html
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" >
<channel>
<title>WSJ.com: WSJD</title>
<link>http://online.wsj.com</link>
<description>WSJD - Technology</description>
<language>en-us</language>
<copyright>copyright © 2017 Dow Jones & Company, Inc.</copyright>
<lastBuildDate>Fri, 13 Oct 2017 04:46:02 EDT</lastBuildDate>
<image>
<title>WSJ.com: WSJD</title>
<url>http://online.wsj.com/img/wsj_sm_logo.gif</url>
<link>http://online.wsj.com</link>
</image>
<atom:link href="http://online.wsj.com" rel="self" type="application/rss+xml" />
<!--Item 1 of Technology_Lead_Story_1 -->
<item>
<title>Samsung Expects Another Quarter of Record Profit; CEO to Resign</title>
<guid isPermaLink="false">SB10211587508256054745704583449670469396266</guid>
<link>https://www.wsj.com/articles/samsung-expects-another-quarter-of-record-profits-1507853202?mod=rss_Technology</link>
<description>Samsung Electronics, continuing to see roaring demand for its components, is forecasting third-quarter profits will be the company’s highest ever. Chief Executive <NAME>, who has overseen the firm’s lucrative components business, also said he will resign.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO637_30k8J_G_20171012231429.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Fri, 13 Oct 2017 03:11:29 EDT</pubDate>
</item>
<!--Item 2 of Technology_Lead_Story_1 -->
<item>
<title>Amazon Suspends Entertainment Chief Roy Price</title>
<guid isPermaLink="false">SB10211587508256054745704583449713388523892</guid>
<link>https://www.wsj.com/articles/amazon-suspends-entertainment-chief-roy-price-1507855558?mod=rss_Technology</link>
<description>Amazon.com suspended the head of its entertainment studio, Roy Price, in the wake of allegations of mismanagement and sexual harassment and criticism of his close business relationship with <NAME>.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO611_AMAZON_G_20171012202236.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Fri, 13 Oct 2017 02:49:40 EDT</pubDate>
</item>
<!--Item 3 of Technology_Lead_Story_1 -->
<item>
<title>Cord-Cutters Sap AT&T's TV Business</title>
<guid isPermaLink="false">SB10211587508256054745704583448622863979176</guid>
<link>https://www.wsj.com/articles/cord-cutters-sap-at-ts-tv-business-1507809030?mod=rss_Technology</link>
<description>AT&T continues to lose pay-TV customers despite a wave of new subscribers to its streaming service, a trend that could spell trouble for the entertainment industry.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO271_1Qfkm_G_20171012073510.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 21:36:39 EDT</pubDate>
</item>
<!--Item 4 of Technology_Lead_Story_1 -->
<item>
<title>Equifax Removes Webpage to Investigate Possible Hacking</title>
<guid isPermaLink="false">SB10211587508256054745704583449152776466558</guid>
<link>https://www.wsj.com/articles/equifax-removes-webpage-to-investigate-possible-hacking-1507831144?mod=rss_Technology</link>
<description>Embattled Equifax Inc. has moved one of its webpages offline as the company looks into whether hackers tried to breach its systems this week. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-UZ957_0908_C_G_20170908082721.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 23:55:05 EDT</pubDate>
</item>
<!--Item 5 of Technology_Lead_Story_1 -->
<item>
<title>Outcome, a Hot Tech Startup, Misled Advertisers With Manipulated Information, Sources Say</title>
<guid isPermaLink="false">SB11898474094085844247404583435182347847790</guid>
<link>https://www.wsj.com/articles/outcome-a-hot-tech-startup-misled-advertisers-with-manipulated-information-sources-say-1507834627?mod=rss_Technology</link>
<description>With funding from <NAME> and Google’s parent, the Chicago-based firm reported a $5.5 billion valuation. The company says it is reviewing allegations against employees and has strengthened policies.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN571_1010OU_G_20171011061226.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Fri, 13 Oct 2017 00:02:06 EDT</pubDate>
</item>
<!--Item 6 of Technology_Lead_Story_1 -->
<item>
<title><NAME> Has a Secret Defender on Twitter: His Wife</title>
<guid isPermaLink="false">SB10211587508256054745704583449000502258768</guid>
<link>https://www.wsj.com/articles/roger-goodell-has-a-secret-defender-on-twitter-his-wife-1507839658?mod=rss_Technology</link>
<description>When media outlets wrote about the NFL commissioner, an anonymous tweeter hit back. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO362_1012GO_G_20171012122414.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>FREE</category>
<pubDate>Thu, 12 Oct 2017 22:21:48 EDT</pubDate>
</item>
<!--Item 7 of Technology_Lead_Story_1 -->
<item>
<title>HP Forecasts a Good 2018 for Profit</title>
<guid isPermaLink="false">SB11734116578048104032604583449670706937876</guid>
<link>https://www.wsj.com/articles/hp-forecasts-a-good-2018-for-profit-1507852700?mod=rss_Technology</link>
<description>HP Inc. expects 2018 to be another good year, with profit projections beating Wall Street expectations, and it’s pledging to continue to return most of its cash to shareholders.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO599_2JRxW_G_20171012194126.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 19:58:22 EDT</pubDate>
</item>
<!--Item 8 of Technology_Lead_Story_1 -->
<item>
<title>New Worry For CEOs: A Career-Ending Cyberattack</title>
<guid isPermaLink="false">SB10383365917693684297404583445591393602484</guid>
<link>https://www.wsj.com/articles/cybersecurity-tops-priority-list-for-ceos-after-string-of-high-profile-hacks-1507821018?mod=rss_Technology</link>
<description>Cyber threats have zoomed to the top of chief executives’ worry lists for fear a data breach could cost them their jobs and take down their businesses.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN972_3fnrP_G_20171011154459.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 15:55:19 EDT</pubDate>
</item>
<!--Item 9 of Technology_Lead_Story_1 -->
<item>
<title>Facebook to Disclose Targets of Russia-Backed Election Ads</title>
<guid isPermaLink="false">SB10211587508256054745704583448811025832172</guid>
<link>https://www.wsj.com/articles/facebook-to-disclose-what-groups-were-targets-of-russia-backed-election-ads-1507819693?mod=rss_Technology</link>
<description>Facebook will disclose the types of people targeted by Russian-backed election ads, operating chief <NAME> said, adding that the social-media site was manipulated in a way it shouldn’t have been.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO290_2WMAw_G_20171012094151.jpg"
type="image/jpeg"
medium="image"
height="368"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 22:05:53 EDT</pubDate>
</item>
<!--Item 10 of Technology_Lead_Story_1 -->
<item>
<title>Friends Donate $30 Million Toward Gates Center at University of Washington</title>
<guid isPermaLink="false">SB10211587508256054745704583449141149612294</guid>
<link>https://www.wsj.com/articles/friends-donate-30-million-toward-gates-center-at-university-of-washington-1507838892?mod=rss_Technology</link>
<description>Friends of Bill and <NAME> donated $30 million to name a computer science building at the University of Washington after the first couple of Microsoft, the school said. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO420_32tnU_G_20171012142222.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>FREE</category>
<pubDate>Thu, 12 Oct 2017 16:08:15 EDT</pubDate>
</item>
<!--Item 11 of Technology_Lead_Story_1 -->
<item>
<title>Cyberattack Captures Data on U.S. Weapons in Four-Month Assault</title>
<guid isPermaLink="false">SB10211587508256054745704583448442107414984</guid>
<link>https://www.wsj.com/articles/cyberattack-captures-data-on-u-s-weapons-in-four-month-assault-1507806261?mod=rss_Technology</link>
<description>A cyberattacker nicknamed “Alf” gained access to an Australian defense contractor’s computers and began a four-month raid that snared data on sophisticated U.S. weapons systems. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO260_2YFQY_G_20171012065033.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 19:27:38 EDT</pubDate>
</item>
<!--Item 12 of Technology_Lead_Story_1 -->
<item>
<title>New York Landlords Have to Work Harder to Profit From Airbnb</title>
<guid isPermaLink="false">SB10211587508256054745704583449030608000320</guid>
<link>https://www.wsj.com/articles/new-york-landlords-have-to-work-harder-to-profit-from-airbnb-1507834113?mod=rss_Technology</link>
<description>It is getting more difficult to turn a profit renting out a New York City apartment on Airbnb, according to a new study that could ease fears of landlords converting the city’s housing stock into a sea of de facto hotel rooms.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO383_2EHAH_G_20171012130311.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 16:29:22 EDT</pubDate>
</item>
<!--Item 13 of Technology_Lead_Story_1 -->
<item>
<title>New York AG <NAME> Probing Deloitte Hack</title>
<guid isPermaLink="false">SB10211587508256054745704583448782285851800</guid>
<link>https://www.wsj.com/articles/new-york-ag-eric-schneiderman-probing-deloitte-hack-1507815035?mod=rss_Technology</link>
<description>The New York attorney general’s office is looking into the cyberbreach at Deloitte that the giant accounting firm says compromised information on a small number of its clients.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO285_3eF2s_G_20171012092113.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 11:55:21 EDT</pubDate>
</item>
<!--Item 14 of Technology_Lead_Story_1 -->
<item>
<title>Alibaba Sizes Up Facebook, Amazon With R&D Funding Splurge</title>
<guid isPermaLink="false">SB10383365917693684297404583446173987790606</guid>
<link>https://www.wsj.com/articles/alibaba-sizes-up-facebook-amazon-with-r-d-funding-surge-1507707466?mod=rss_Technology</link>
<description>Chinese e-commerce company Alibaba says it will nearly triple spending on research and development, to more than $15 billion over the next three years, as it seeks to keep pace with Western rivals such as Alphabet and Amazon.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN549_3fQHJ_G_20171011025906.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Wed, 11 Oct 2017 22:02:58 EDT</pubDate>
</item>
<!--Item 15 of Technology_Lead_Story_1 -->
<item>
<title>Qualcomm Is Fined $773 Million by Taiwan Over Patent Practices</title>
<guid isPermaLink="false">SB10211587508256054745704583447220319783766</guid>
<link>https://www.wsj.com/articles/qualcomm-is-fined-773-million-by-taiwan-over-patent-practices-1507748723?mod=rss_Technology</link>
<description>Qualcomm was fined about $773 million by the Taiwanese government, the latest setback as the chip maker defends its patent-licensing business against an international wave of regulatory and legal challenges. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN918_2P4N9_G_20171011150116.jpg"
type="image/jpeg"
medium="image"
height="370"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Wed, 11 Oct 2017 15:08:14 EDT</pubDate>
</item>
<!--Item 16 of Technology_Lead_Story_1 -->
<item>
<title>Companies Ask Supreme Court to Hear Gay-Rights Case</title>
<guid isPermaLink="false">SB10383365917693684297404583445701816366308</guid>
<link>https://www.wsj.com/articles/companies-ask-supreme-court-to-hear-gay-rights-case-1507730401?mod=rss_Technology</link>
<description>Apple, <NAME> and dozens of other businesses asked the Supreme Court to find that federal law bars discrimination based on sexual orientation, putting them at odds with the Trump administration.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN410_DISCRI_G_20171010214735.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Wed, 11 Oct 2017 20:50:34 EDT</pubDate>
</item>
<!--Item 1 of Technology_Lead_Story_2 -->
<item>
<title>A Hairy Problem for Apps: Delivering Crabs Fast---and Alive</title>
<guid isPermaLink="false">SB10211587508256054745704583448480621909270</guid>
<link>https://www.wsj.com/articles/need-fresh-hairy-crabs-there-are-rival-apps-for-that-1507807304?mod=rss_Technology</link>
<description>E-commerce titans Alibaba and JD.com are competing to deliver hairy crabs fast and alive to customers, as they try to capture the leading edge in delivering fresh food.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VO242_2Squ0_G_20171012053102.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Fri, 13 Oct 2017 04:45:51 EDT</pubDate>
</item>
<!--Item 2 of Technology_Lead_Story_2 -->
<item>
<title>To-Do List Apps: 5 Easy Tricks for Using Them Better</title>
<guid isPermaLink="false">SB11791610971150393684804583442822110276936</guid>
<link>https://www.wsj.com/articles/to-do-list-apps-5-easy-tricks-to-using-them-better-1507839586?mod=rss_Technology</link>
<description>Everyone is relying on to-do list apps. But experts like ‘Getting Things Done’ productivity guru <NAME> say we can get more out of them. Here’s how</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN271_Todo_O_G_20171010165421.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>FREE</category>
<pubDate>Thu, 12 Oct 2017 16:33:33 EDT</pubDate>
</item>
<!--Item 3 of Technology_Lead_Story_2 -->
<item>
<title>How to Slack Like a Pro</title>
<guid isPermaLink="false">SB10211587508256054745704583446872316907046</guid>
<link>https://www.wsj.com/articles/how-to-slack-like-a-pro-1507745803?mod=rss_Technology</link>
<description>The future of workplace communication is here. Thank you, Slack—the best thing to happen to office chitchat since the water-cooler.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN697_YOUGOT_G_20171011113217.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>FREE</category>
<pubDate>Thu, 12 Oct 2017 09:56:11 EDT</pubDate>
</item>
<!--Item 4 of Technology_Lead_Story_2 -->
<item>
<title>Beijing Pushes for a Direct Hand in China's Big Tech Firms</title>
<guid isPermaLink="false">SB10211587508256054745704583446732582976340</guid>
<link>https://www.wsj.com/articles/beijing-pushes-for-a-direct-hand-in-chinas-big-tech-firms-1507758314?mod=rss_Technology</link>
<description>The Chinese government is pushing some of its biggest tech companies—including Tencent, Weibo and a unit of Alibaba—to give the state a stake in them and a direct role in corporate decisions.</description>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 11:32:20 EDT</pubDate>
</item>
<!--Item 1 of Technology_Featured_Stories_3 -->
<item>
<title>'Ridiculous Mistake' Helped North Korea Steal Secret U.S. War Plans</title>
<guid isPermaLink="false">SB10211587508256054745704583446651201132848</guid>
<link>https://www.wsj.com/articles/north-korea-allegedly-used-antivirus-software-to-steal-defense-secrets-1507736060?mod=rss_Technology</link>
<description>A breach of South Korea’s military database in which suspected North Korean hackers pilfered defense secrets originated in compromised third-party cybersecurity software and was made possible by an unintended connection to the internet. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN600_NKCYBE_G_20171011090312.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 04:01:07 EDT</pubDate>
</item>
<!--Item 2 of Technology_Featured_Stories_3 -->
<item>
<title>Amazon Welcomes Teens, Gives Parents the Purse Strings</title>
<guid isPermaLink="false">SB10383365917693684297404583446033141994400</guid>
<link>https://www.wsj.com/articles/amazon-welcomes-teens-with-new-parent-controlled-shopping-allowance-1507726803?mod=rss_Technology</link>
<description>Amazon’s new program, launched Wednesday, lets parents manage—and fund—online-shopping accounts for their teens. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN461_2cAxE_G_20171011010947.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Wed, 11 Oct 2017 22:43:11 EDT</pubDate>
</item>
<!--Item 3 of Technology_Featured_Stories_3 -->
<item>
<title>How Smartphones Hijack Our Minds</title>
<guid isPermaLink="false">SB11973195686415373603904583431173622222096</guid>
<link>https://www.wsj.com/articles/how-smartphones-hijack-our-minds-1507307811?mod=rss_Technology</link>
<description>Research suggests that as the brain grows dependent on phone technology, the intellect weakens. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VL791_SMARTP_G_20171006105737.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>FREE</category>
<pubDate>Sat, 07 Oct 2017 11:34:57 EDT</pubDate>
</item>
<!--Item 4 of Technology_Featured_Stories_3 -->
<item>
<title>Apple Strikes Deal With Spielberg's Amblin for 'Amazing Stories' Reboot</title>
<guid isPermaLink="false">SB10383365917693684297404583445092383505844</guid>
<link>https://www.wsj.com/articles/apple-signs-content-deal-with-steven-spielberg-1507656455?mod=rss_Technology</link>
<description>Apple is betting on acclaimed director and producer <NAME> for its first major foray into creating original video content. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VN135_3eMOi_G_20171010131710.jpg"
type="image/jpeg"
medium="image"
height="370"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Tue, 10 Oct 2017 17:40:59 EDT</pubDate>
</item>
<!--Item 5 of Technology_Featured_Stories_3 -->
<item>
<title><NAME> on How to Get to Gender Equality</title>
<guid isPermaLink="false">SB11004722923079933770204583433701298062338</guid>
<link>https://www.wsj.com/articles/sheryl-sandberg-on-how-to-get-to-gender-equality-1507608721?mod=rss_Technology</link>
<description>The Facebook chief operating officer and founder of LeanIn.Org says the first step is realizing how far we have to go. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/WW-AA745_SANDBE_G_20171005153924.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>FREE</category>
<pubDate>Tue, 10 Oct 2017 23:02:57 EDT</pubDate>
</item>
<!--Item 6 of Technology_Featured_Stories_3 -->
<item>
<title>SpaceX Has Successful Launch As It Ramps Up Operational Tempo</title>
<guid isPermaLink="false">SB10383365917693684297404583442741198136554</guid>
<link>https://www.wsj.com/articles/spacex-has-successful-launch-as-it-ramps-up-operational-tempo-1507557834?mod=rss_Technology</link>
<description>Space Exploration Technologies blasted 10 commercial satellites into orbit, completing the first of a pair of consecutive launches slated from opposite coasts in roughly two days. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VM472_3dfeQ_G_20171009093050.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Tue, 10 Oct 2017 07:42:39 EDT</pubDate>
</item>
<!--Item 7 of Technology_Featured_Stories_3 -->
<item>
<title>Amazon Has a Luxury Problem</title>
<guid isPermaLink="false">SB12661405825356173294704583428972789069856</guid>
<link>https://www.wsj.com/articles/amazon-has-a-luxury-problem-1507460401?mod=rss_Technology</link>
<description>Swatch and other high-end brands are staying away from Amazon’s online marketplace, saying it undermines the strict control that is key to maintaining a sense of exclusivity—and keeping prices high. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VL869_luxama_G_20171006140638.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Thu, 12 Oct 2017 06:21:41 EDT</pubDate>
</item>
<!--Item 8 of Technology_Featured_Stories_3 -->
<item>
<title>Alphabet Gets Approval for Giant Balloons to Restore Puerto Rico's Wireless Service</title>
<guid isPermaLink="false">SB11898474094085844247404583439243374185874</guid>
<link>https://www.wsj.com/articles/alphabet-gets-approval-for-giant-balloons-to-restore-puerto-ricos-wireless-service-1507409362?mod=rss_Technology</link>
<description>The FCC issued Alphabet Inc. an experimental license for Project Loon, a balloon network that could restore connectivity to hurricane-battered Puerto Rico. </description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VM140_2BlC2_G_20171007154538.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Sat, 07 Oct 2017 20:00:23 EDT</pubDate>
</item>
<!--Item 9 of Technology_Featured_Stories_3 -->
<item>
<title>Behind Tesla's Production Delays: Parts of Model 3 Were Made by Hand</title>
<guid isPermaLink="false">SB11569820067392243519004583434992341436994</guid>
<link>https://www.wsj.com/articles/behind-teslas-production-delays-parts-of-model-3-were-being-made-by-hand-1507321057?mod=rss_Technology</link>
<description>Tesla blamed “production bottlenecks” for making only a fraction of the promised 1,500 Model 3s. Unknown to analysts, investors and the hundreds of thousands of customers who signed up to buy it, as recently as early September major portions of the Model 3 were still being banged out by hand.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VL797_tesla1_G_20171006110823.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>FREE</category>
<pubDate>Sun, 08 Oct 2017 07:56:20 EDT</pubDate>
</item>
<!--Item 10 of Technology_Featured_Stories_3 -->
<item>
<title><NAME> Drove Intel's Computing Dominance</title>
<guid isPermaLink="false">SB11898474094085844247404583435251970477418</guid>
<link>https://www.wsj.com/articles/paul-otellini-drove-intels-computing-dominance-1507300202?mod=rss_Technology</link>
<description>As Intel CEO <NAME> presided over advances in semiconductor design that cemented the company’s dominance in the computers found in countless homes and businesses around the world. He died Oct. 2 at 66.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VL308_otelli_G_20171005133523.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Fri, 06 Oct 2017 18:11:45 EDT</pubDate>
</item>
<!--Item 11 of Technology_Featured_Stories_3 -->
<item>
<title>Chip Makers Are Adding 'Brains' Alongside Cameras' Eyes</title>
<guid isPermaLink="false">SB12661405825356173294704583429072792279716</guid>
<link>https://www.wsj.com/articles/chip-makers-are-adding-brains-alongside-cameras-eyes-1507114801?mod=rss_Technology</link>
<description>Chip companies are adding greater smarts to cameras, spurring a new generation of machines that not only capture imagery but interpret and act on what they see.</description>
<media:content xmlns:media="http://search.yahoo.com/mrss"
url="http://s.wsj.net/public/resources/images/BN-VK244_smart1_G_20171003140007.jpg"
type="image/jpeg"
medium="image"
height="369"
width="553">
<media:description>image</media:description>
</media:content>
<category>PAID</category>
<pubDate>Sat, 07 Oct 2017 20:11:22 EDT</pubDate>
</item>
</channel>
</rss>
<!-- fastdynapage - secj2kwebappp09 - Fri 10/13/17 - 04:46:02 EDT -->
| e67744c7fb14f7387d790c9358ee5bb8c8f6457b | [
"Python",
"HTML"
] | 2 | Python | johnnycrusher/WSJ-News-Archiver | bc244a64e6ed660fb7d78763490f553f7b8833e4 | 12e927560014937ce1d25da15b11a4ed09dae4fd | |
refs/heads/master | <repo_name>egoisticum/single-spa-portal-example-vue-example<file_sep>/README.md
Fork of [single-spa-portal-example](https://github.com/egoisticum/single-spa-portal-example-vue-example) with VueJS more features such as:
- VueRouter implemented
- Redux implemented in vue4app project<file_sep>/app4vue/src/singleSpaEntry.js
import Vue from "vue";
import singleSpaVue from "single-spa-vue";
import App from "./App.vue";
import VueRouter from 'vue-router';
var routes = require('./router/routes').routes;
Vue.config.productionTip = false;
// Router thingy start
Vue.use(VueRouter);
const router = new VueRouter({
base: "/#/app4/",
mode: 'history',
routes,
});
window.router = router;
// Router thingy end
//Vue registration
const vueLifecycles = singleSpaVue({
Vue,
appOptions: {
el: "#app4",
router,
render: h => h(App)
}
});
export const bootstrap = [vueLifecycles.bootstrap];
export function mount(props) {
console.log(props);
createDomElement();
Vue.mixin({
data: function () {
return {
props: props
}
}
})
return vueLifecycles.mount(props);
}
export const unmount = [vueLifecycles.unmount];
function createDomElement() {
// Make sure there is a div for us to render into
let el = document.getElementById("app4");
if (!el) {
el = document.createElement("div");
el.id = "app4";
document.body.appendChild(el);
}
return el;
}
//Components importing
import Root from './pages/Root.vue'
import Test from './pages/Test.vue'
import Test2 from './pages/Test2.vue' | 737c0f911435376be709f2ac59b8ab2e60182c8c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | egoisticum/single-spa-portal-example-vue-example | 521a11d3a74007ef65267b2e44184003b23aec8e | 228f1ac961a48d175f8133d1457e8e43a91f8e84 | |
refs/heads/main | <file_sep>package repository
import (
"encoding/json"
"errors"
"github.com/RobertGumpert/vkr-pckg/dataModel"
"github.com/RobertGumpert/vkr-pckg/runtimeinfo"
)
type SQLRepository struct {
storage *ApplicationStorageProvider
}
func (s *SQLRepository) AddNumbersIntersections(intersections []dataModel.NumberIssueIntersectionsModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(&intersections).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) AddNumberIntersections(intersection *dataModel.NumberIssueIntersectionsModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(intersection).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) GetNumberIntersectionsForRepository(repositoryID uint) ([]dataModel.NumberIssueIntersectionsModel, error) {
var intersections []dataModel.NumberIssueIntersectionsModel
if err := s.storage.SqlDB.Where("repository_id = ?", repositoryID).Find(&intersections).Error; err != nil {
return intersections, err
}
return intersections, nil
}
func (s *SQLRepository) GetNumberIntersectionsForPair(repositoryID, comparableRepositoryID uint) (dataModel.NumberIssueIntersectionsModel, error) {
var intersection dataModel.NumberIssueIntersectionsModel
if err := s.storage.SqlDB.Where("repository_id = ? AND comparable_repository_id = ?", repositoryID, comparableRepositoryID).Find(&intersection).Error; err != nil {
return intersection, err
}
return intersection, nil
}
func (s *SQLRepository) AddRepository(repository *dataModel.RepositoryModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(repository).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) AddRepositories(repositories []dataModel.RepositoryModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(&repositories).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) AddNearestRepositories(repositoryId uint, nearest dataModel.NearestRepositoriesJSON) error {
bts, err := json.Marshal(nearest)
if err != nil {
return err
}
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
var model = dataModel.NearestRepositoriesModel{
RepositoryID: repositoryId,
Repositories: bts,
}
if err := tx.Create(&model).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) UpdateNearestRepositories(repositoryId uint, nearest dataModel.NearestRepositoriesJSON) error {
return nil
}
func (s *SQLRepository) GetRepositoryByName(name string) (dataModel.RepositoryModel, error) {
var repository dataModel.RepositoryModel
if err := s.storage.SqlDB.Where("name = ?", name).First(&repository).Error; err != nil {
return repository, err
}
return repository, nil
}
func (s *SQLRepository) GetRepositoryByID(repositoryId uint) (dataModel.RepositoryModel, error) {
var repository dataModel.RepositoryModel
if err := s.storage.SqlDB.Where("id = ?", repositoryId).First(&repository).Error; err != nil {
return repository, err
}
return repository, nil
}
func (s *SQLRepository) GetNearestRepositories(repositoryId uint) (dataModel.NearestRepositoriesJSON, error) {
var (
repository dataModel.NearestRepositoriesModel
nearest dataModel.NearestRepositoriesJSON
)
if err := s.storage.SqlDB.Where("repository_id = ?", repositoryId).First(&repository).Error; err != nil {
return nearest, err
}
if err := json.Unmarshal(repository.Repositories, &nearest); err != nil {
return nearest, err
}
return nearest, nil
}
func (s *SQLRepository) GetAllRepositories() ([]dataModel.RepositoryModel, error) {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
var model []dataModel.RepositoryModel
if err := tx.Find(&model).Error; err != nil {
tx.Rollback()
return model, err
}
return model, tx.Commit().Error
}
func (s *SQLRepository) RewriteAllNearestRepositories(repositoryId []uint, models []dataModel.NearestRepositoriesJSON) error {
return nil
}
func (s *SQLRepository) AddIssue(issue *dataModel.IssueModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(issue).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) AddIssues(issues []dataModel.IssueModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(&issues).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) GetNearestIssuesForPairRepositories(mainRepositoryID, secondRepositoryID uint) ([]dataModel.NearestIssuesModel, error) {
var model []dataModel.NearestIssuesModel
if err := s.storage.SqlDB.Where("repository_id = ? AND repository_id_nearest_issue = ?", mainRepositoryID, secondRepositoryID).Find(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) AddNearestIssues(nearest dataModel.NearestIssuesModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(&nearest).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) AddListNearestIssues(nearest []dataModel.NearestIssuesModel) error {
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(&nearest).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (s *SQLRepository) GetIssueByID(issueId uint) (dataModel.IssueModel, error) {
var model dataModel.IssueModel
if err := s.storage.SqlDB.Where("id = ?", issueId).First(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) GetIssuesOnlyGroupRepositories(repositoryId ...uint) ([]dataModel.IssueModel, error) {
var (
model []dataModel.IssueModel
id = make([]uint, 0)
)
id = append(id, repositoryId...)
if err := s.storage.SqlDB.Where("repository_id IN ?", id).Find(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) GetIssuesBesidesGroupRepositories(repositoryId ...uint) ([]dataModel.IssueModel, error) {
var (
model []dataModel.IssueModel
id = make([]uint, 0)
)
id = append(id, repositoryId...)
if err := s.storage.SqlDB.Where("repository_id NOT IN ?", id).Find(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) GetIssueRepository(repositoryId uint) ([]dataModel.IssueModel, error) {
var model []dataModel.IssueModel
if err := s.storage.SqlDB.Where("repository_id = ?", repositoryId).Find(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) GetNearestIssuesForIssue(issueId uint) ([]dataModel.NearestIssuesModel, error) {
var model []dataModel.NearestIssuesModel
if err := s.storage.SqlDB.Where("issue_id = ?", issueId).Find(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) GetNearestIssuesForRepository(repositoryId uint) ([]dataModel.NearestIssuesModel, error) {
var model []dataModel.NearestIssuesModel
if err := s.storage.SqlDB.Where("repository_id = ?", repositoryId).Find(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) AddKeyWord(keyWord string, position int64, repositories dataModel.RepositoriesIncludeKeyWordsJSON) (dataModel.RepositoriesKeyWordsModel, error) {
var model dataModel.RepositoriesKeyWordsModel
bts, err := json.Marshal(repositories)
if err != nil {
return model, err
}
model = dataModel.RepositoriesKeyWordsModel{
KeyWord: keyWord,
Repositories: bts,
}
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Create(&model).Error; err != nil {
tx.Rollback()
return model, err
}
return model, tx.Commit().Error
}
func (s *SQLRepository) UpdateKeyWord(keyWord string, position int64, repositories dataModel.RepositoriesIncludeKeyWordsJSON) (dataModel.RepositoriesKeyWordsModel, error) {
var model dataModel.RepositoriesKeyWordsModel
bts, err := json.Marshal(repositories)
if err != nil {
return model, err
}
model = dataModel.RepositoriesKeyWordsModel{
KeyWord: keyWord,
Repositories: bts,
}
tx := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Updates(&model).Error; err != nil {
tx.Rollback()
return model, err
}
return model, tx.Commit().Error
}
func (s *SQLRepository) GetKeyWord(keyWord string) (dataModel.RepositoriesKeyWordsModel, error) {
var model dataModel.RepositoriesKeyWordsModel
if err := s.storage.SqlDB.Where("key_word = ?", keyWord).First(&model).Error; err != nil {
return model, err
}
return model, nil
}
func (s *SQLRepository) GetAllKeyWords() ([]dataModel.RepositoriesKeyWordsModel, error) {
return nil, nil
}
func (s *SQLRepository) RewriteAllKeyWords(models []dataModel.RepositoriesKeyWordsModel) error {
return nil
}
func (s *SQLRepository) HasEntities() error {
db := s.storage.SqlDB.Begin()
entities := []interface{}{
&dataModel.RepositoryModel{},
&dataModel.IssueModel{},
&dataModel.NearestIssuesModel{},
&dataModel.NearestRepositoriesModel{},
&dataModel.RepositoriesKeyWordsModel{},
&dataModel.NumberIssueIntersectionsModel{},
}
for _, entity := range entities {
if exist := db.Migrator().HasTable(entity); !exist {
return errors.New("Non exist table. ")
}
}
return nil
}
func (s *SQLRepository) CreateEntities() error {
db := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
db.Rollback()
}
}()
if err := db.Migrator().CreateTable(
&dataModel.RepositoryModel{},
&dataModel.IssueModel{},
&dataModel.NearestIssuesModel{},
&dataModel.NearestRepositoriesModel{},
&dataModel.RepositoriesKeyWordsModel{},
&dataModel.NumberIssueIntersectionsModel{},
); err != nil {
db.Rollback()
return err
}
return db.Commit().Error
}
func (s *SQLRepository) Migration() error {
db := s.storage.SqlDB.Begin()
defer func() {
if r := recover(); r != nil {
db.Rollback()
}
}()
if err := db.AutoMigrate(
&dataModel.RepositoryModel{},
&dataModel.IssueModel{},
&dataModel.NearestIssuesModel{},
&dataModel.NearestRepositoriesModel{},
&dataModel.RepositoriesKeyWordsModel{},
&dataModel.NumberIssueIntersectionsModel{},
); err != nil {
db.Rollback()
return err
}
return db.Commit().Error
}
func (s *SQLRepository) CloseConnection() error {
db, err := s.storage.SqlDB.DB()
if err != nil {
return err
}
err = db.Close()
if err != nil {
return err
}
return nil
}
func NewSQLRepository(storage *ApplicationStorageProvider) *SQLRepository {
repository := &SQLRepository{storage: storage}
err := repository.HasEntities()
if err != nil {
err := repository.CreateEntities()
if err != nil {
runtimeinfo.LogFatal(err)
}
}
err = repository.Migration()
if err != nil {
runtimeinfo.LogFatal(err)
}
return repository
}
| 9f9c0c97ebb1ea7910763aea8f830ce4cce6f6d7 | [
"Go"
] | 1 | Go | RobertGumpert/vkr_class_uml | 818416e3ab6c4d8f4cb5b821ba12f082ae856f3f | bb1387addda704580ea542a3c43ee70a063c6e9a | |
refs/heads/main | <repo_name>sdalu/face-no-more<file_sep>/lib/face-no-more.rb
# coding: utf-8
require 'securerandom'
require 'digest'
require 'rmagick'
# Generate avatar
#
# ~~~ruby
# require 'face-no-more'
#
# FaceNoMore.generate(:cat, "<EMAIL>", format: :jpg, size: 256)
# FaceNoMore.generate(:bird, 12345678910)
# ~~~
module FaceNoMore
# @!visibility private
IMAGES_DIR = File.join(__dir__, '..', 'data', 'images')
# @!visibility private
# NOTE: - Limited to 16 parts
# - Keep sizes sorted from small to big
DESCRIPTIONS = {
:cat => {
:author => '<NAME>',
:license => 'CC-BY',
:src => 'https://www.peppercarrot.com/extras/html/2016_cat-generator/',
:sizes => [ 256 ],
:partname => "%<part>s_%<id>d.png",
:parts => { :body => 1..15,
:fur => 1..10,
:eyes => 1..15,
:mouth => 1..10,
:accessorie => 1..20 },
},
:bird => {
:author => '<NAME>',
:license => 'CC-BY',
:src => 'https://www.peppercarrot.com/extras/html/2019_bird-generator/',
:sizes => [ 256 ],
:partname => "%<part>s_%<id>d.png",
:parts => { :tail => 1..9,
:hoop => 1..10,
:body => 1..9,
:wing => 1..9,
:eyes => 1..9,
:bec => 1..9,
:accessorie => 1..20, },
},
:abstract => {
:author => '<NAME>',
:license => 'CC-BY',
:src => 'https://www.peppercarrot.com/extras/html/2017_abstract-generator/',
:sizes => [ 256 ],
:partname => "%<part>s_%<id>d.png",
:parts => { :body => 1..15,
:fur => 1..10,
:eyes => 1..15,
:mouth => 1..10, },
},
:mobilizon => {
:author => '<NAME>',
:license => 'CC-BY',
:src => 'https://www.peppercarrot.com/extras/html/2020_mobilizon-generator/',
:sizes => [ 256, 1024 ],
:partname => "%<part>s_%<id>02d.png",
:parts => { :body => 1..25,
:nose => 1..10,
:tail => 1..5,
:eyes => 1..10,
:mouth => 1..10,
:accessories => 1..20,
:misc => 1..20,
:hat => 1..20, },
},
:'8bit-female' => {
:author => 'matveyco',
:src => 'https://github.com/matveyco/8biticon',
:path => '8bit/female',
:sizes => [ 400 ],
:partname => "%<part>s%<id>d.png",
:parts => { :face => 1..4,
:clothes => 1..59,
:mouth => 1..17,
:head => 1..33,
:eye => 1..53, },
},
:'8bit-male' => {
:author => 'matveyco',
:src => 'https://github.com/matveyco/8biticon',
:path => '8bit/male',
:sizes => [ 400 ],
:partname => "%<part>s%<id>d.png",
:parts => { :face => 1..4,
:clothes => 1..65,
:mouth => 1..26,
:hair => 1..36,
:eye => 1..32, },
},
}
# List of supported avatar types
TYPES = DESCRIPTIONS.keys.freeze
# Return the number of different avatar possible
#
# @param type type of avatar
#
# @return [Integer]
#
def self.possibilities(type)
DESCRIPTIONS.fetch(type) {
raise ArgumentError, "unsupported type (#{type})"
}[:parts].map {|part, range| range.last - range.first }
.reduce(:*)
end
# Generate an avatar
#
# @param type [Symbol] type of avatar
# @param seed [String,Array<Integer>,Integer,nil] seed
# @param format [:Symbol] picture format (as defined in ImageMagick)
# @param quality [Integer] picture quality (1..100)
# @param size [Integer] picture size
#
# @return [String]
#
def self.generate(type, seed = nil, format: :png, quality: 90, size: 256)
desc = DESCRIPTIONS.fetch(type) {
raise ArgumentError, "unsupported type (#{type})" }
parts = desc[:parts]
sizes = desc[:sizes]
path = File.join(IMAGES_DIR, desc[:path] || type.to_s)
partsize = sizes.find {|s| size > s } || sizes.last
seedbytes = case seed
when nil then SecureRandom.random_bytes(16).bytes
when String then Digest::MD5.digest(seed).bytes
when Array then seed
when Integer then parts.map {|_, r|
count = r.end - r.begin + 1
seed, val = seed.divmod(count)
val }
end
if parts.size > seedbytes.size
raise ArgumentError, "seed doesn't hold enough elements"
end
files = parts.each_with_index.map {|(part, range), index|
mod = (range.end - range.begin) + 1
id = range.first + seedbytes[index] % mod
File.join(path, partsize.to_s,
desc[:partname] % { :part => part, :id => id })
}
Magick::ImageList.new(*files).flatten_images
.change_geometry!("#{size}x#{size}") { |cols, rows, me|
me.thumbnail!(cols, rows)
}.to_blob {|me| me.format = format.to_s
me.quality = quality }
end
end
<file_sep>/README.md
Description
===========
Allow generating avatar pictures from ruby.
The supported avatar type are: `cat`, `bird`, `abstract`, `mobilizon`,
`8bit-female` and `8bit-male`.






Examples
========
~~~ruby
require 'face-no-more'
# Number of possible avatars
count = FaceNoMore.possibilities(:mobilizon)
# Generate avatar picture
jpg = FaceNoMore.generate(:cat, "<EMAIL>", format: :jpg, size: 256)
png = FaceNoMore.generate(:bird, 12345678910)
~~~
Artworks
========
* `cat`, `bird`, `abstract` and `mobilizon` are from [<NAME>][2]
licensed under [CC-By 4.0][4]
* `8bit-female` and `8bit-male` are from [matveyco][3]
[2]: http://www.peppercarrot.com
[3]: https://github.com/matveyco/8biticon
[4]: http://creativecommons.org/licenses/by/4.0/
<file_sep>/face-no-more.gemspec
# -*- encoding: utf-8 -*-
require_relative 'lib/face-no-more/version'
Gem::Specification.new do |s|
s.name = 'face-no-more'
s.version = FaceNoMore::VERSION
s.summary = "Generate avatars"
s.description = <<~EOF
Generate avatars from artwork assets.
Included 5 different types of artwork: cat, bird, abstract, mobilizon, and 8bit.
EOF
s.homepage = 'https://gitlab.com/sdalu/face-no-more'
s.license = 'MIT'
s.authors = [ "<NAME>" ]
s.email = [ '<EMAIL>' ]
s.files = %w[ README.md face-no-more.gemspec ] +
Dir['lib/**/*.rb'] + Dir['data/**']
s.add_dependency 'rmagick'
s.add_development_dependency 'yard', '~>0'
s.add_development_dependency 'rake', '~>13'
end
| 99bde8193a279b9992a849a2226727e4d80bcf54 | [
"Markdown",
"Ruby"
] | 3 | Ruby | sdalu/face-no-more | f5356a627a9485a45908f69fca300bcd9c772172 | 61406cecbe1bf699c9e7754b9d4aa7cdecc3510e | |
refs/heads/master | <repo_name>Zertz/sherby-messenger<file_sep>/client/pages/index.js
import App from "../components/App";
import Head from "../components/Head";
import Messenger from "../components/Messenger";
export default () => (
<App>
<Head>
<title>Sherby Messenger</title>
</Head>
<Messenger />
</App>
);
<file_sep>/server/index.js
if (process.env.NODE_ENV !== "production") {
require("dotenv-safe").config();
}
const crypto = require("crypto");
const http = require("http");
const { MongoClient, ObjectId } = require("mongodb");
const db = process.env.SHERBY_MESSENGER_MONGODB_DB;
let client;
let watcher;
(async () => {
try {
client = await MongoClient.connect(
process.env.SHERBY_MESSENGER_MONGODB_URI,
{
useNewUrlParser: true
}
);
} catch (e) {
console.error(e);
}
})();
const server = http.createServer();
const io = require("socket.io")(server);
let connectedUsers = 0;
io.on("connection", socket => {
if (!watcher) {
watcher = client
.db(db)
.collection("Messages")
.watch({ fullDocument: "updateLookup" })
.on("change", ({ documentKey, fullDocument, operationType }) => {
switch (operationType) {
case "delete": {
socket.broadcast.emit("message:delete", documentKey._id);
break;
}
case "insert": {
socket.broadcast.emit("message:create", fullDocument);
break;
}
case "update": {
socket.broadcast.emit("message:update", fullDocument);
break;
}
}
});
}
socket.emit("user:connect", ++connectedUsers);
socket.emit("user:token", crypto.randomBytes(32).toString("hex"));
socket.broadcast.emit("user:connect", connectedUsers);
socket.once("disconnect", () => {
socket.broadcast.emit("user:connect", --connectedUsers);
});
socket.on("message:create", async data => {
try {
const { message, token } = JSON.parse(data);
if (!token) {
return;
}
const trimmedMessage = message.trim();
if (trimmedMessage.length === 0) {
return;
}
await client
.db(db)
.collection("Messages")
.insertOne({ message: trimmedMessage, token, createdAt: new Date() });
} catch (e) {
console.error(e);
}
});
socket.on("message:read", async () => {
try {
const messages = await client
.db(db)
.collection("Messages")
.find()
.sort({
createdAt: 1
})
.limit(50)
.toArray();
socket.emit("message:read", JSON.stringify(messages));
} catch (e) {
console.error(e);
}
});
socket.on("message:update", async data => {
try {
const { _id, message, token } = JSON.parse(data);
if (!ObjectId.isValid(_id) || !message || !token) {
return;
}
await client
.db(db)
.collection("Messages")
.updateOne(
{ _id: ObjectId(_id), token },
{
$set: {
message,
updatedAt: new Date()
}
}
);
} catch (e) {
console.error(e);
}
});
socket.on("message:delete", async data => {
try {
const { _id, token } = JSON.parse(data);
if (!ObjectId.isValid(_id) || !token) {
return;
}
await client
.db(db)
.collection("Messages")
.removeOne({ _id: ObjectId(_id), token });
} catch (e) {
console.error(e);
}
});
});
server.listen(3300);
<file_sep>/mongodb/index.js
const ReplSet = require("mongodb-topology-manager").ReplSet;
(async () => {
const bind_ip = "localhost";
const replSet = new ReplSet(
"mongod",
[
{
options: { port: 31000, dbpath: `${__dirname}/data/db/31000`, bind_ip }
},
{
options: { port: 31001, dbpath: `${__dirname}/data/db/31001`, bind_ip }
},
{
options: { port: 31002, dbpath: `${__dirname}/data/db/31002`, bind_ip }
}
],
{ replSet: "rs0" }
);
await replSet.purge();
await replSet.start();
console.info("MongoDB started!");
})();
<file_sep>/client/components/Messenger.js
import React, { Fragment, PureComponent } from "react";
import io from "socket.io-client";
import MessageList from "./MessageList";
class Messenger extends PureComponent {
state = { connectedUsers: 0, message: "", socket: null, token: null };
componentDidMount() {
const socket = io(process.env.SHERBY_MESSENGER_WS_URL);
const token = window.localStorage.getItem("user:token");
socket.on("user:connect", this.handleConnect);
this.setState(
{
socket
},
() => {
if (token) {
this.handleToken(token);
} else {
socket.on("user:token", this.handleToken);
}
}
);
}
componentWillUnmount() {
const { socket } = this.state;
socket.off("user:connect", this.handleConnect);
socket.close();
}
handleChange = e => {
const {
target: { name, value }
} = e;
this.setState({ [name]: value });
};
handleConnect = connectedUsers => {
this.setState({
connectedUsers
});
};
handleSubmit = e => {
const { message, socket, token } = this.state;
e.preventDefault();
socket.emit("message:create", JSON.stringify({ message, token }));
this.setState({
message: ""
});
};
handleToken = token => {
const { socket } = this.state;
socket.off("user:token", this.handleToken);
localStorage.setItem("user:token", token);
this.setState({
token
});
};
render() {
const { connectedUsers, message, socket, token } = this.state;
return (
<section>
<style jsx>{`
section {
display: flex;
flex-direction: column;
overflow: hidden;
position: absolute;
top: 0.5em;
right: 0.5em;
bottom: 0.5em;
left: 0.5em;
}
.User {
font-size: 1rem;
margin-bottom: 0.5em;
text-align: center;
word-wrap: break-word;
}
form {
display: flex;
flex-shrink: 0;
}
input,
button {
border: 1px solid #ccc;
}
input {
flex-grow: 1;
font-size: 1rem;
margin-right: 0.5em;
padding: 1em;
}
button[type="submit"] {
flex-shrink: 0;
cursor: pointer;
font-size: 1rem;
padding: 1em;
}
`}</style>
<div className="User">
<p>{token ? token : "Connecting..."}</p>
<p>{`Utilisateurs: ${connectedUsers}`}</p>
</div>
<MessageList socket={socket} token={token} />
<form onSubmit={this.handleSubmit}>
<input
autoComplete="off"
autoFocus
type="text"
name="message"
value={message}
onChange={this.handleChange}
/>
<button type="submit">Envoyer</button>
</form>
</section>
);
}
}
export default Messenger;
<file_sep>/client/components/MessageList.js
import React, { PureComponent } from "react";
import io from "socket.io-client";
import Message from "./Message";
class MessageList extends PureComponent {
state = { messages: [] };
componentWillReceiveProps(nextProps) {
const { socket, token } = this.props;
if (!token && nextProps.token) {
socket.on("message:read", this.handleRead);
socket.emit("message:read");
}
}
componentWillUnmount() {
const { socket } = this.props;
socket.off("message:create", this.handleCreate);
socket.off("message:update", this.handleUpdate);
socket.off("message:delete", this.handleDelete);
}
handleCreate = message => {
this.setState(
prevState => ({
messages: prevState.messages.concat(message)
}),
() => {
this.ref.scrollTop = this.ref.scrollHeight;
}
);
};
handleRead = messages => {
const { socket } = this.props;
socket.off("message:read", this.handleRead);
this.setState(
{
messages: JSON.parse(messages)
},
() => {
this.ref.scrollTop = this.ref.scrollHeight;
socket.on("message:create", this.handleCreate);
socket.on("message:update", this.handleUpdate);
socket.on("message:delete", this.handleDelete);
}
);
};
handleUpdate = message => {
this.setState(prevState => ({
messages: prevState.messages.map(m => {
if (m._id === message._id) {
return {
...m,
...message
};
}
return m;
})
}));
};
handleDelete = _id => {
this.setState(prevState => ({
messages: prevState.messages.filter(m => m._id !== _id)
}));
};
render() {
const { socket, token } = this.props;
const { messages } = this.state;
return (
<div className="MessageList" ref={ref => (this.ref = ref)}>
<style jsx>{`
.MessageList {
display: flex;
flex-direction: column;
align-items: flex-start;
flex-grow: 1;
background-color: #fefefe;
font-size: 1rem;
margin-bottom: 0.5em;
overflow-x: hidden;
overflow-y: scroll;
padding: 0.5em;
}
hr {
margin: 0.5em 0;
padding: 0;
}
`}</style>
{messages.map(message => (
<Message
key={message._id}
message={message}
socket={socket}
token={token}
/>
))}
</div>
);
}
}
export default MessageList;
<file_sep>/README.md
# sherby-messenger
## Getting started
1. Install [Node LTS or Current](https://nodejs.org/en/)
1. Install [Yarn](https://yarnpkg.com/en/docs/install)
1. Run `yarn install`
1. Run `yarn mongodb`
1. Wait until it says "MongoDB started!"
1. In another terminal, run `yarn server`
1. In another terminal, run `yarn client`
1. Open a browser at http://localhost:3500
<file_sep>/server/.env.example
SHERBY_MESSENGER_MONGODB_DB=
SHERBY_MESSENGER_MONGODB_URI=
| d72a6a27bc4daba3a1868570b5a1de8c2ab049aa | [
"JavaScript",
"Markdown",
"Shell"
] | 7 | JavaScript | Zertz/sherby-messenger | ee41d17cd61800bc7b4aed938968b4e79f0b76cf | 1f9383343837ae615c3b68cef7b56363fa38681e | |
refs/heads/master | <repo_name>anwesh-sarkar/m4-4-react--effects<file_sep>/src/hooks/useKeydown.hook.js
import React from "react";
const useKeydown = (code, callback) => {
let handleKeyDown = (event) => {
if (event.code === code) {
callback();
}
};
React.useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
});
};
export default useKeydown;
<file_sep>/src/components/Item.js
import React from "react";
import styled from "styled-components";
const Item = ({ name, cost, value, isFirst, numOwned, handleClick }) => {
const itemRef = React.useRef(null);
React.useEffect(() => {
if (isFirst) {
itemRef.current.focus();
}
}, []);
return (
<Wrapper onClick={handleClick} ref={itemRef}>
<div>
<Name>{name}</Name>
<ItemBuy>
Cost: {cost} cookies. Produces {value} cookies/second.
</ItemBuy>
</div>
<NumOwned>{numOwned}</NumOwned>
</Wrapper>
);
};
const Wrapper = styled.button`
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: space-between;
text-align: left;
padding: 10px 0;
width: 500px;
background: transparent;
border: none;
border-bottom-style: solid;
color: white;
`;
const Name = styled.h2`
font-size: 2em;
`;
const ItemBuy = styled.p`
font-size: 1.2em;
padding-right: 10px;
color: lightgray;
`;
const NumOwned = styled.div`
font-size: 3em;
`;
export default Item;
| ef7ebc74b5a058013b2ac83451f8974edabf309e | [
"JavaScript"
] | 2 | JavaScript | anwesh-sarkar/m4-4-react--effects | f9b0c7a26dcc770b69cad4f2f053dab7aa5d3ed2 | 4cfc5da62e15d32d129387fe7077824124750eb6 | |
refs/heads/master | <repo_name>juliezimmer/portfolio_boilerplate<file_sep>/src/components/Header.js
import React from 'react';
// requires named export, NavLink in the file because it's used in the header.
import { NavLink } from 'react-router-dom';
// this header needs to be rendered on every single page, unlike the other components in routes.
const Header = () => (
<header>
<h1>Portfolio</h1>
<NavLink to="/" activeClassName="is-active" exact={true}>
Home
</NavLink>
<NavLink to="/portfolio" activeClassName="is-active" exact={true}>
Portfolio
</NavLink>
<NavLink to="/contact" activeClassName="is-active">
Contact
</NavLink>
</header>
);
// This set-up will allow <Header /> to show up on every page that's rendered. By putting it before <Switch />, it will be rendered every time on the page that has the matching path.
export default Header;<file_sep>/src/components/PortfolioItemPage.js
import React from 'react';
// id will be used on this page for params
const PortfolioItem = (props) => (
<div>
<h1>An app I've created</h1>
<p>The app has an id of {props.match.params.id} </p>
</div>
);
export default PortfolioItem; | 38fab38dcb12868a94da10e5b62762e58ff03594 | [
"JavaScript"
] | 2 | JavaScript | juliezimmer/portfolio_boilerplate | 0cb3bb3864fac72fa628d8e95191d212c4d553dd | f5adb3a556a4c3f177b7885ef4a0c2e92e4214b6 | |
refs/heads/master | <repo_name>ao-lab/angularjs-dev-media<file_sep>/15-Acesso-a-dados-usando-$resource/controllers.js
app.controller('IndexController', ['$scope', 'Livros', function ($scope, Livros) {
$scope.list = function () {
Livros.get(function (data) {
console.log(data);
});
};
$scope.read = function (id) {
Livros.get({id: id}, function (data) {
console.log(data);
});
};
$scope.save = function () {
var Livro = {
"id" : 40,
"titulo" : "Curso de AngularJS",
};
Livros.save({}, Livro);
};
}]);<file_sep>/12-Diretivas-basicas/controllers.js
app.controller('IndexController', ['$scope', function ($scope) {
$scope.x = false;
$scope.html = 'Usamos <b>angular-sanitize</b> para imprimir HTML.';
$scope.myClass = 'text-info';
$scope.myImage = 'http://placehold.it/50x50/000';
}]);<file_sep>/07-Loops-usando-ngRepeat/controllers.js
app.controller('IndexController', ['$scope', function ($scope) {
$scope.users = [];
$scope.users.push({status: 'true', name: 'Neto', age: '58'});
$scope.users.push({status: 'true', name: 'Ceni', age: '50'});
$scope.users.push({status: 'true', name: 'Paulo', age: '30'});
$scope.users.push({status: 'true', name: 'Farliene', age: '28'});
$scope.users.push({status: 'true', name: 'Alex', age: '26'});
$scope.users.push({status: 'true', name: 'Keliene', age: '25'});
$scope.users.push({status: 'true', name: 'Lainy', age: '22'});
$scope.users.push({status: 'true', name: 'Dandara', age: '12'});
$scope.add = function () {
$scope.users.push({status: 'true', name: $scope.f.name, age: $scope.f.age});
$scope.cls();
};
$scope.cls = function () {
$scope.f.name = '';
$scope.f.age = '';
};
}]);<file_sep>/11-ngRoute/modules.js
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
controller: 'HomeController',
'templateUrl': 'views/home.html'
}).when('/products', {
controller: 'ProductsController',
'templateUrl': 'views/products.html'
}).when('/products/:id', {
controller: 'ProductsShowController',
'templateUrl': 'views/product.html'
}).otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);<file_sep>/26-AngularUI-ui.bootstrap/app.js
var app = angular.module('app', ['ngAnimate', 'ui.bootstrap']);
app.controller('IndexController', ['$scope', function ($scope) {
$scope.accordions = [
{heading: 'Título Dinâmico 1', body: 'Conteudo Dinâmico 1'},
{heading: 'Título Dinâmico 2', body: 'Conteudo Dinâmico 2'}
];
$scope.create = function (acc) {
$scope.accordions.push(acc);
$scope.acc = {heading: '', body: ''};
};
}]);<file_sep>/09-Service-e-Factory/controllers.js
app.controller('SumController', ['$scope', 'MathService', function ($scope, MathService) {
console.log(MathService.sum(10, 5));
}]);
app.controller('SubController', ['$scope', 'MathService', 'User', function ($scope, MathService, User) {
console.log(MathService.sub(10, 5));
$scope.user = new User();
}]);
app.controller('UserController', ['$scope', 'User', function ($scope, User) {
$scope.user = new User();
}]);<file_sep>/11-ngRoute/controllers.js
app.controller('IndexController', ['$scope', '$route', '$routeParams', '$location', function ($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$routeParams = $routeParams;
$scope.$location = $location;
}]).controller('HomeController', ['$scope', function ($scope) {
console.log('Tela inicial...');
}]).controller('ProductsController', ['$scope', function ($scope) {
console.log('Lista de Produtos...');
}]).controller('ProductsShowController', ['$scope', '$routeParams', function ($scope, $routeParams) {
$scope.params = $routeParams;
console.log('Produto ' + $scope.params.id + '...');
}]);<file_sep>/22-AngularUI-ui.highlight-e-ui.mask/app.js
var app = angular.module('app', ['ngSanitize', 'ui.mask', 'ui.highlight']);
app.controller('IndexController', ['$scope', function ($scope) {
$scope.text = 'Será que vai funcionar!';
$scope.maskCpf = '999.999.999-99';
$scope.maskPhone = '(99) 9999-9999';
// 9 - somente numeros
// A - somente letras
// * - qualquer coisa
}]);<file_sep>/18-$location/app.js
var app = angular.module('app', []);
app.controller('IndexController', ['$scope', '$location', function ($scope, $location) {
$scope.$location = $location;
$scope.see = function (id) {
console.log('Entrou no id ' + id);
$location.search({id: id});
};
$scope.$watch('$location.search().id', function (id) {
console.log('Mudou para id ' + id);
});
}]);
app.config(['$locationProvider', function ($locationProvider) {
$locationProvider.html5Mode({
enabled: true, requireBase: false
}).hashPrefix('#');
//$locationProvider.html5Mode(true);
}]);
<file_sep>/16-AngularJS-vs-jQuery/controllers.js
app.directive('tooltip', function () {
return {
restrict: 'ACE',
link: function (scope, element, attr) {
element.attr('container', 'body');
element.attr('data-placement', attr.tooltip);
element.tooltip({'html': true});
}
};
});
app.controller('IndexController', ['$scope', function ($scope) {
}]);<file_sep>/14-Requisicoes-assincronas-usando-$http/controllers.js
app.controller('IndexController', ['$scope', '$http', function ($scope, $http) {
$scope.data = [];
$scope.list = function () {
$http.get('data.json').success(function (data) {
$scope.data = data;
}).error(function () {
alert('Erro ao tentar ler data.json');
});
};
//------------------------------------------------------------------------------------------------------------------
$scope.icon = '';
$scope.description = '';
$scope.city = 'Brasília';
$scope.server = 'http://api.openweathermap.org/data/2.5/weather?appid=2de143494c0b295cca9337e1e96b00e0&units=metric&q=';
$scope.weather = [];
$scope.search = function () {
$http.get($scope.server + $scope.city).success(function (data) {
$scope.weather = data;
$scope.icon = data.weather[0].icon;
$scope.description = data.weather[0].description;
}).error(function () {
alert('Erro ao tentar ler data.json');
});
};
}]);<file_sep>/09-Service-e-Factory/factories.js
app.factory('User', function () {
console.log('Criando UserFactory....');
var User = function () {
console.log('Instanciando UserFactory....');
this.name = 'Alex';
this.age = '25';
this.hello = function () {
return 'Olá ' + this.name + '!';
};
};
return User;
});<file_sep>/09-Service-e-Factory/services.js
app.service('MathService', [function () {
console.log('Criando MathService....');
this.sum = function (v1, v2) {
console.log('Somando com MathService....');
return v1 + v2;
};
this.sub = function (v1, v2) {
console.log('Subtraindo com MathService....');
return v1 - v2;
};
}]);<file_sep>/17-Animations/app.js
var app = angular.module('app', ['ngAnimate']);
app.controller('IndexController', ['$scope', function ($scope) {
$scope.items = [1, 2, 3, 4, 5];
$scope.add = function () {
if ($scope.items.indexOf($scope.item) == -1) {
$scope.items.push($scope.item);
}
};
}]);<file_sep>/20-Plugins/app.js
var app = angular.module('app', ['pascalprecht.translate']);
app.config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('pt-BR', {
TITLE: 'Seja Bem-Vindo!',
DESCRIPTION: 'Página Inicial.',
BTN_OK: 'Botão OK',
BTN_CANCEL: 'Botão CANCELAR',
BTN_ENGLISH: 'English',
BTN_PORTUGUESE: 'Português'
});
$translateProvider.translations('en', {
TITLE: 'Wellcome!',
DESCRIPTION: 'First Page.',
BTN_OK: 'OK Button',
BTN_CANCEL: 'CANCEL Button',
BTN_ENGLISH: 'English',
BTN_PORTUGUESE: 'Português'
});
$translateProvider.preferredLanguage('en');
}]);
app.controller('IndexController', ['$scope', '$translate', function ($scope, $translate) {
$scope.lang = function (lang) {
$translate.use(lang);
};
}]);<file_sep>/15-Acesso-a-dados-usando-$resource/modules.js
var app = angular.module('app', ['ngResource']);
app.factory('Livros', ['$resource', function ($resource) {
var server = 'http://parceiros.bomaluno.loc/beneficios/:id';
return $resource(server, {id: '@id'});
}]);<file_sep>/api/upload.php
<?php
if (!empty($_FILES)) {
$source = $_FILES['file']['tmp_name'];
$new = __DIR__ . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES['file']['name'];
move_uploaded_file($source, $new);
echo json_encode(['answer' => 'File transfer completed.']);
} else {
echo json_encode(['answer' => 'No files!']);
}<file_sep>/24-AngularUI-Google-Maps/app.js
var app = angular.module('app', ['uiGmapgoogle-maps']);
//app.config(['uiGmapGoogleMapApiProvider', function (GoogleMapApiProviders) {
//
// GoogleMapApiProviders.configure({
// china: true
// });
//
//}]);
app.controller('IndexController', ['$scope', function ($scope) {
$scope.map = {
zoom: 12,
center: {
latitude: -15.8,
longitude: -47.9
}
};
$scope.marker = {
id: 0,
coords: $scope.map.center
};
}]);
<file_sep>/10-Filter/filters.js
app.filter('Hello', function () {
return function (name) {
return 'Olá ' + name + ' !';
}
}); | 29041c7dc5b25bb9cf2dec0437ec58ffa76f1421 | [
"JavaScript",
"PHP"
] | 19 | JavaScript | ao-lab/angularjs-dev-media | 360fb1fcec686ffaa466f00ce2d9fe09200757f6 | c64a5986f8abc995fe1d288ff983581fadcb7169 | |
refs/heads/master | <repo_name>saqib1707/RattleSnake<file_sep>/LargeCoachingInstitute/coachingtemp.py
import json
import os
max_batchstrength=3
noofbatches=4
class RattleSnake:
def __init__(self):
self.nametoadd=""
self.phone_no=""
self.marks=0
self.batch=None
self.username=""
self.password=""
def checkFileEmpty(self):
if os.stat("StudentRecords.txt").st_size == 0:
print "Empty File!!!Please add members to perform these operations"
return True
else:
return False
def addStudent(self):
listobj=[]
count=0
string=""
myModifiedList=""
#noofStudents=input("How many students data u want to add ?? >>> ")
#for i in range(noofStudents):
self.nametoadd=raw_input("\nEnter student name to be added >>> ")
self.phone_no=raw_input("Enter phone no:")
with open("StudentRecords.txt") as readStudentFile:
if self.checkFileEmpty()==False:
jsonData=json.load(readStudentFile)
if len(jsonData) in range(1,4):
self.batch=1
elif len(jsonData) in range(4,8):
self.batch=2
elif len(jsonData) in range(8,12):
self.batch=3
elif len(jsonData) in range(11,15):
self.batch=4
else:
self.batch=1
data= {"name":self.nametoadd,"phoneno":self.phone_no,"marks":self.marks,"batch":self.batch,"username":self.username,"password":<PASSWORD>}
listobj.append(data)
with open('StudentRecords.txt','a') as appendStudentFile:
json.dump(listobj,appendStudentFile)
with open('StudentRecords.txt') as readStudentFile:
textdata=readStudentFile.read()
for char in textdata:
if count==1:
string+=char
if string=="][":
count=2
char=','
if char==']':
count+=1
string+=char
else:
myModifiedList+=char
if count==2:
continue
if count==1 or count==3:
myModifiedList+=']'
with open('StudentRecords.txt','w') as file:
file.write(myModifiedList)
jsonData=json.load(open("StudentRecords.txt"))
open("StudentRecords.txt",'w').write(json.dumps(jsonData,indent=4))
def removeStudent(self):
if self.checkFileEmpty()==True:
return
with open('StudentRecords.txt') as readStudentFile:
jsonData1=json.load(readStudentFile)
nooftimes=input("How many student data u want to delete >>> ")
for i in range(nooftimes):
found=False
#jsonfile=json.load(open("StudentRecords.txt"))
if jsonData1==[]:
print "Student Database already empty!!!No more members to delete"
break
self.nameToRemove=raw_input("Enter student name to be removed from Database >>> ")
for i in range(len(jsonData1)):
if jsonData1[i]["name"]==self.nameToRemove :
jsonData1.pop(i)
print "%s deleted from Database "%self.nameToRemove
found=True
break
if found==False:
print "\n%s not in the DataBase\n" %self.nameToRemove
open('StudentRecords.txt','w').write(json.dumps(jsonData1,indent=4))
os.system("pause")
def showListOfStudents(self):
listObj=[]
with open('StudentRecords.txt') as infile:
if self.checkFileEmpty()==False:
data=json.load(infile)
for i in range(len(data)):
dictionary={"name":data[i]['name'],"phoneno":data[i]['phoneno'],"marks":data[i]['marks'],"batch":data[i]['batch']}
listObj.append(dictionary)
with open('Info.txt','w') as readFile:
json.dump(listObj,readFile,indent=4)
os.system('Info.txt')
infile.close()
def modifyData(self):
with open('StudentRecords.txt') as infile:
if self.checkFileEmpty()==False:
jsonData=json.load(infile)
self.dataToModify=raw_input("\nEnter student name whose data has to be modified >>> ")
modification=True
for i in range(len(jsonData)):
if jsonData[i]["name"]==self.dataToModify :
print "Press 1 to modify Student Name"
print "Press 2 to modify Student phone_no"
modify_choice=input(">>> ")
if modify_choice==1:
jsonData[i]["name"]=raw_input("Enter Modified Name:")
elif modify_choice==2:
jsonData[i]["phone"]=raw_input("Enter Modified Phone no:")
else:
print "Wrong choice"
modification=False
if modification==True:
print "Data Modified for %s"%self.dataToModify
open("StudentRecords.txt",'w').write(json.dumps(jsonData,indent=4))
infile.close()
os.system("pause")
# Interface to access data of coaching students
def accessStuData():
while(True):
print "\nPress 1 to Add Students to the Database"
print "Press 2 to Remove students from the Database"
print "Press 3 to Print all the students in the Database"
print "Press 4 to modify the basic info of students"
print "Press 0 to go back to the previous menu"
obj=RattleSnake()
inputchoice=input(">>> ")
if inputchoice==1:
obj.addStudent()
elif inputchoice==2:
obj.removeStudent()
elif inputchoice==3:
obj.showListOfStudents()
elif inputchoice==4:
obj.modifyData()
else:
break
return
<file_sep>/Error.py
def showError():
print "Wrong Input"
<file_sep>/LargeCoachingInstitute/TeacherInterface.py
import json,Error,getpass,os
class TeacherInterface:
def __init__(self):
print
def checkBatchEmpty(self,batch):
with open('StudentRecords.txt') as readStudentFile:
jsonData2=json.load(readStudentFile)
for i in range(len(jsonData2)):
if jsonData2[i]['batch']==batch:
return False
print "Batch is empty"
return True
def showListOfStudents(self,batch):
if self.checkBatchEmpty(batch)==True:
return
listOfStudent=[]
with open('StudentRecords.txt') as readStudentFile:
jsonData2=json.load(readStudentFile)
for i in range(len(jsonData2)):
if jsonData2[i]['batch']==batch:
#listOfStudent.append(jsonData2[i]['name'])
print jsonData2[i]['name']," : ",jsonData2[i]['marks']
def uploadMarks(self,batch):
if self.checkBatchEmpty(batch)==True:
return
print "Upload Student Marks for the Latest Test"
with open('StudentRecords.txt') as readStudentFile:
jsonData2=json.load(readStudentFile)
for i in range(len(jsonData2)):
if jsonData2[i]['batch']==batch:
jsonData2[i]['marks']=input(jsonData2[i]['name'])
open('StudentRecords.txt','w').write(json.dumps(jsonData2,indent=4))
print "Marks Uploaded Successfully"
os.system("pause")
with open('TeacherRecords.txt') as readTeacherFile:
jsonData1=json.load(readTeacherFile)
for i in range(len(jsonData1)):
if jsonData1[i]['batch']==batch:
jsonData1[i]['is_Marks_Updated']="True"
open('TeacherRecords.txt','w').write(json.dumps(jsonData1,indent=4))
def modifyMarks(self,batch):
if self.checkBatchEmpty(batch)==True:
return
is_Modified=False
print "Enter student name whose marks has to be modified"
name=raw_input(">>>")
with open('StudentRecords.txt') as readStudentFile:
jsonData2=json.load(readStudentFile)
for i in range(len(jsonData2)):
if jsonData2[i]['name']==name and jsonData2[i]['batch']==batch:
jsonData2[i]['marks']=input('Enter modified marks >>> ')
is_Modified=True
print "Marks Modified for %s"%name
os.system("pause")
break
if is_Modified==False:
print "Modification Failure!!!Student not found"
open('StudentRecords.txt','w').write(json.dumps(jsonData2,indent=4))
def main():
batch=None
username=raw_input("Username >>>")
pwd=<PASSWORD>("<PASSWORD> >>>")
with open('TeacherRecords.txt') as readTeacherFile:
jsonData1=json.load(readTeacherFile)
for i in range(len(jsonData1)):
if jsonData1[i]['username']==username and jsonData1[i]['password']==pwd :
batch=jsonData1[i]['batch']
print "\n",jsonData1[i]['name']," -Batch ",batch,"\n","Access Granted"
if jsonData1[i]['is_Marks_Updated']=="False":
print "Reminder to upload the latest test marks"
break
if batch==None:
print "Access Denied"
print "Username or password or both are incorrect!!!Please try again"
return
while True:
print "\n1. See the list of students in ur batch"
print "2. Upload marks of the Latest Test"
print "3. Modify marks of individual student"
print "0. Quit"
choice=input(">>>")
obj=TeacherInterface()
if choice==1:
obj.showListOfStudents(batch)
elif choice==2:
obj.uploadMarks(batch)
elif choice==3:
obj.modifyMarks(batch)
elif choice==0:
break
else:
Error.showError()
if __name__=="__main__":
main()
<file_sep>/LargeCoachingInstitute/StudentLogin.py
import json
import getpass
import os
#to check whether the StudentRecords file is completely empty or not
def checkFileEmpty():
if os.stat("StudentRecords.txt").st_size == 0:
print "Empty File!!!Please add members to perform these operations"
return True
else:
return False
#for student to login(if signed up) to view their current marks and batch details
def login():
found=False
if checkFileEmpty()==True: #checks whether the file is empty or not
return
username=raw_input("User Name >>>")
pwd=<PASSWORD>.getpass("Password >>>")
with open('StudentRecords.txt') as readFile:
jsonData=json.load(readFile)
for i in range(len(jsonData)):
if jsonData[i]['username']==username and jsonData[i]['password']==pwd:
#show his username,marks ,rank and current batch
found=True
print "\n",jsonData[i]['name'],"\nMarks:",jsonData[i]['marks'],"\tBatch:",jsonData[i]['batch'],"\n"
if found==False:
print "\nNot registered or not admitted yet!!!If Registered ,then Sign Up!!!\n"
#for students who have been admitted
def signUp():
found=False
countOfTry=0
if checkFileEmpty()==True: #checks whether the file is empty or not
return
name=raw_input("Name >>>")
phoneno=raw_input("Phone No >>>")
with open('StudentRecords.txt') as readStudentFile:
jsonData=json.load(readStudentFile)
for i in range(len(jsonData)):
if jsonData[i]['name']==name and jsonData[i]['phoneno']==phoneno and jsonData[i]['username']=="" and jsonData[i]['password']=="":
found=True
username=raw_input("UserName >>>")
pwd=<PASSWORD>.getpass("Password >>>")
confirmpwd=getpas.getpass("Confirm Password >>>")
if pwd!=confirmpwd:
print "Password don't match!!!Try Again(max. 3 times)"
countOfTry+=1
if countOfTry==2:
break
else:
#Register the student username and password
print "\nRegistration complete!!! Now Login to view your Current Status\n"
os.system("pause")
jsonData[i]['username']=username
jsonData[i]['password']=pwd
open('StudentRecords.txt','w').write(json.dumps(jsonData,indent=4))
break
if found==False:
print "\nNot admitted yet or data filled incorrectly or already registered\n"
while(True):
print "Press 1 to Login to view Results"
print "Press 2 to Sign Up for the first time"
print "Press 0 to exit"
choicethree=input(">>> ")
if choicethree==1:
login()
elif choicethree==2:
signUp()
elif choicethree==0:
break
else:
Error.showError()
<file_sep>/LargeCoachingInstitute/administrator.py
import json
import coachingtemp
import os
import Error
class Administrator:
def __init__(self):
print
def startNewTest(self):
flag=True
with open('TeacherRecords.txt','r') as readTeacherFile:
jsonData=json.load(readTeacherFile)
for i in range(len(jsonData)):
if jsonData[i]['is_Marks_Updated']=="None":
flag=False
jsonData[i]['is_Marks_Updated']="False"
if flag==False:
print "New Test could not be started now.Reminders to teachers who have not submitted marksheet"
os.system("pause")
return
print "Start a new Test"
with open('TeacherRecords.txt') as readTeacherFile:
jsonData=json.load(readTeacherFile)
for i in range(len(jsonData)):
jsonData[i]['is_Marks_Updated']="None"
open('TeacherRecords.txt','w').write(json.dumps(jsonData,indent=4))
def reMapping(self):
count=0
listObj=[]
with open('TeacherRecords.txt','r') as readTeacherFile:
jsonData=json.load(readTeacherFile)
for i in range(len(jsonData)):
if jsonData[i]['is_Marks_Updated']!="True":
print "All students marks has not be uploaded!! ReMapping could not be done now"
os.system("pause")
return
print "ReMapping of students"
i=1
with open('StudentRecords.txt','r') as readStudentFile:
jsonData=json.load(readStudentFile)
jsonDataSorted=sorted(jsonData,key=lambda k:k['marks'],reverse=True)
for j in range(len(jsonDataSorted)):
count+=1
if count%5==0:
i+=1
count+=1
jsonDataSorted[j]['batch']=i
open('StudentRecords.txt','w').write(json.dumps(jsonDataSorted,indent=4))
#showing the shuffled data
for i in range(len(jsonDataSorted)):
datadict={'name':jsonDataSorted[i]['name'],'marks':jsonDataSorted[i]['marks'],"batch":jsonDataSorted[i]['batch']}
listObj.append(datadict)
json.dump(listObj,open('MarkSheet.txt','w'))
jsonDataSorted=json.load(open('MarkSheet.txt'))
open('MarkSheet.txt','w').write(json.dumps(jsonDataSorted,indent=4))
os.system('MarkSheet.txt')
def AdmInterface(choice):
AdmObj=Administrator()
if choice==2:
AdmObj.startNewTest() #upload marks for all the students
elif choice==3:
AdmObj.reMapping() #Shuffle students and allot them batches
while(True):
print "\nPress 1 to Access the Coaching Students Database"
print "Press 2 to start a new test(give reminders to teachers)"
print "Press 3 for Batch Allotment"
print "Press 0 to exit"
choicefour=input(">>>")
if choicefour==1:
coachingtemp.accessStuData()
elif choicefour==2 or choicefour==3:
AdmInterface(choicefour)
elif choicefour==0:
break
else:
Error.showError()
<file_sep>/coaching_temp.py
import json
import os
class RattleSnake:
def __init__(self):
self.nametoadd=""
self.phone_no=""
self.marks=0
self.batch=None
self.username=""
self.password=""
def checkFileEmpty(self):
if os.stat("C:\Users\Saqib\Desktop\Snake\Records.txt").st_size == 0:
print "Empty File!!!Please add members to perform these operations"
return True
else:
return False
def addStudent(self):
listobj=[]
count=0
string=""
myModifiedList=""
noofStudents=input("How many students data u want to add >>> ")
for i in range(noofStudents):
self.nametoadd=raw_input("\nEnter student name to be added >>> ")
self.phone_no=raw_input("Enter phone no:")
data= {"stu_name":self.nametoadd,"stu_phoneno":self.phone_no,"stu_marks":self.marks,"stu_batch":self.batch,"stu_username":self.username,"stu_password":self.<PASSWORD>}
listobj.append(data)
with open('C:\Users\Saqib\Desktop\Snake\Records.txt','a') as file:
json.dump(listobj,file)
with open('C:\Users\Saqib\Desktop\Snake\Records.txt','r') as file:
textdata=file.read()
for char in textdata:
if count==1:
string+=char
if string=="][":
count=2
char=','
if char==']':
count+=1
string+=char
else:
myModifiedList+=char
if count==2:
continue
if count==1 or count==3:
myModifiedList+=']'
with open('C:\Users\Saqib\Desktop\Snake\Records.txt','w') as file:
file.write(myModifiedList)
jsonData=json.load(open("C:\Users\Saqib\Desktop\Snake\Records.txt"))
open("C:\Users\Saqib\Desktop\Snake\Records.txt",'w').write(json.dumps(jsonData,indent=4))
def removeStudent(self):
with open('C:\Users\Saqib\Desktop\Snake\Records.txt') as infile:
if self.checkFileEmpty()==False:
jsonfile=json.load(infile)
nooftimes=input("How many student data u want to delete >>> ")
for i in range(nooftimes):
found=False
#jsonfile=json.load(open("C:\Users\Saqib\Desktop\Snake\Records.txt"))
if jsonfile==[]:
print "Student Database already empty!!!No more members to delete"
break
self.nameToRemove=raw_input("Enter student name to be removed from Database >>> ")
for i in range(len(jsonfile)):
if jsonfile[i]["stu_name"]==self.nameToRemove :
jsonfile.pop(i)
print "%s deleted from Database "%self.nameToRemove
found=True
break
if found==False:
print "\n%s not in the DataBase\n" %self.nameToRemove
open("C:\Users\Saqib\Desktop\Snake\Records.txt",'w').write(json.dumps(jsonfile,indent=4))
def printListOfStudents(self):
listObj=[]
with open('C:\Users\Saqib\Desktop\Snake\Records.txt') as infile:
if self.checkFileEmpty()==False:
data=json.load(infile)
for i in range(len(data)):
dictionary={"stu_name":data[i]['stu_name'],"stu_phoneno":data[i]['stu_phoneno'],"stu_marks":data[i]['stu_marks'],"stu_batch":data[i]['stu_batch']}
listObj.append(dictionary)
with open('C:\Users\Saqib\Desktop\Snake\Info.txt','w') as readFile:
json.dump(listObj,readFile,indent=4)
os.system('C:\Users\Saqib\Desktop\Snake\Info.txt')
infile.close()
def modifyData(self):
with open('C:\Users\Saqib\Desktop\Snake\Records.txt') as infile:
if self.checkFileEmpty()==False:
jsonData=json.load(infile)
self.dataToModify=raw_input("Enter student name whose data has to be modified >>> ")
modification=True
for i in range(len(jsonData)):
if jsonData[i]["stu_name"]==self.dataToModify :
print "Press 1 to modify Student Name"
print "Press 2 to modify Student phone_no"
print "Press 3 to modify Student marks"
print "Press 4 to modify Student batch"
modify_choice=input("Enter ur choice >>> ")
if modify_choice==1:
jsonfile[i]["stu_name"]=raw_input("Enter Modified Name:")
elif modify_choice==2:
jsonfile[i]["stu_phone"]=raw_input("Enter Modified Phone no:")
elif modify_choice==3:
jsonfile[i]["stu_marks"]=raw_input("Enter Modified marks :")
elif modify_choice==4:
jsonfile[i]["stu_batch"]=raw_input("Enter new batch:")
else:
print "Wrong choice"
modification=False
if modification==True:
print "Data Modified for %s"%self.dataToModify
open("C:\Users\Saqib\Desktop\Snake\Records.txt",'w').write(json.dumps(jsonfile,indent=4))
infile.close()
# Interface to access data of coaching students
def accessStuData():
while(True):
print "Press 1 to Add Students to the Database"
print "Press 2 to Remove students from the Database"
print "Press 3 to Print all the students in the Database"
print "Press 4 to modify the data of students"
print "Press any other key to go back to the previous menu"
obj=RattleSnake()
inputchoice=input("Enter ur choice >>> ")
if inputchoice==1:
obj.addStudent()
elif inputchoice==2:
obj.removeStudent()
elif inputchoice==3:
obj.printListOfStudents()
elif inputchoice==4:
obj.modifyData()
else:
break
return
<file_sep>/StudentLogin.py
import json
import getpass
def login():
found=False
username=raw_input("User Name >>>")
pwd=getpass.getpass("Password >>>")
with open('C:\Users\Saqib\Desktop\Snake\Records.txt') as readFile:
jsonData=json.load(readFile)
if jsonData==[]:
print "Student database empty"
return
for i in range(len(jsonData)):
if jsonData[i]['stu_username']==username and jsonData[i]['stu_password']==pwd:
#show his username,marks ,rank and current batch
found=True
print "\n",jsonData[i]['stu_name'],"\nMarks:",jsonData[i]['stu_marks'],"\tBatch:",jsonData[i]['stu_batch'],"\n"
if found==False:
print "\nNot registered or not admitted yet!!!If Registered ,then Sign Up!!!\n"
#for the first time users.
def signUp():
found=False
name=raw_input("Name >>>")
phoneno=raw_input("Phone No >>>")
with open('C:\Users\Saqib\Desktop\Snake\Records.txt') as readFile:
jsonData=json.load(readFile)
for i in range(len(jsonData)):
if jsonData[i]['stu_name']==name and jsonData[i]['stu_phoneno']==phoneno:
found=True
username=raw_input("UserName >>>")
pwd=getpass.getpass("Password >>>")
confirmpwd=getpass.getpass("Confirm Password >>>")
if pwd!=confirmpwd:
print "Password don't match!!!"
else:
#Register the student username and password
print "\nRegistration complete\n"
jsonData[i]['stu_username']=username
jsonData[i]['stu_password']=pwd
open('C:\Users\Saqib\Desktop\Snake\Records.txt','w').write(json.dumps(jsonData,indent=4))
break
if found==False:
print "\nNot admitted yet or data filled incorrectly\n"
while(True):
print "Press 1 to Login to view Results"
print "Press 2 to Sign Up for the first time"
print "Press 0 to exit"
choicethree=input(">>> ")
if choicethree==1:
login()
elif choicethree==2:
signUp()
elif choicethree==0:
break
else:
Error.showError()
<file_sep>/administrator.py
import json
import coaching_temp
import os
import Error
class Administrator:
def __init__(self):
#print "In init of administrator"
print ""
print ""
def uploadMarks(self):
print "Upload of Students' Marks"
listObj=[]
with open('C:\Users\Saqib\Desktop\Snake\Records.txt') as readFile:
jsonFile=json.load(readFile)
readFile.close()
with open('C:\Users\Saqib\Desktop\Snake\Records.txt','w') as writeFile:
for i in range(len(jsonFile)):
jsonFile[i]['stu_marks']=raw_input("Enter marks for %s :"%jsonFile[i]['stu_name'])
datadict={'stu_name':jsonFile[i]['stu_name'],'stu_phoneno':jsonFile[i]['stu_phoneno'],'stu_marks':jsonFile[i]['stu_marks'],"stu_batch":jsonFile[i]['stu_batch'],"stu_username":jsonFile[i]['stu_username'],"stu_password":jsonFile[i]["stu_password"]}
listObj.append(datadict)
json.dump(listObj,writeFile)
writeFile.close()
with open('C:\Users\Saqib\Desktop\Snake\Records.txt') as readFile:
jsonFile=json.load(readFile)
open('C:\Users\Saqib\Desktop\Snake\Records.txt','w').write(json.dumps(jsonFile,indent=4))
#jsonFile=json.load(open('C:\Users\Saqib\Desktop\Snake\MarkSheet.txt'))
#open('C:\Users\Saqib\Desktop\Snake\MarkSheet.txt','w').write(json.dumps(jsonFile,indent=4))
#os.system('C:\Users\Saqib\Desktop\Snake\MarkSheet.txt')
def reMapping(self):
count=0
i=1
listObj=[]
print "ReMapping of students"
with open('C:\Users\Saqib\Desktop\Snake\Records.txt','r') as readFile:
jsonFile=json.load(readFile)
jsonFileSorted=sorted(jsonFile,key=lambda k:k['stu_marks'],reverse=True)
for j in range(len(jsonFileSorted)):
count+=1
if count%4==0:
i+=1
jsonFileSorted[j]['stu_batch']=i
open('C:\Users\Saqib\Desktop\Snake\Records.txt','w').write(json.dumps(jsonFileSorted,indent=4))
#showing the shuffled data
for i in range(len(jsonFileSorted)):
datadict={'stu_name':jsonFileSorted[i]['stu_name'],'stu_marks':jsonFileSorted[i]['stu_marks'],"stu_batch_alloted":jsonFileSorted[i]['stu_batch']}
listObj.append(datadict)
json.dump(listObj,open('C:\Users\Saqib\Desktop\Snake\MarkSheet.txt','w'))
jsonFileSorted=json.load(open('C:\Users\Saqib\Desktop\Snake\MarkSheet.txt'))
open('C:\Users\Saqib\Desktop\Snake\MarkSheet.txt','w').write(json.dumps(jsonFileSorted,indent=4))
os.system('C:\Users\Saqib\Desktop\Snake\MarkSheet.txt')
def AdmInterface(choice):
AdmObj=Administrator()
if choice==2:
AdmObj.uploadMarks() #upload marks for all the students
elif choice==3:
AdmObj.reMapping() #Shuffle students and allot them batches
while(True):
print "Press 1 to Access the Coaching Students Database"
print "Press 2 to Upload the New MarkSheet of the latest Test"
print "Press 3 to shuffle the Students based on their marks"
print "Press 0 to exit"
choicefour=input(">>>")
if choicefour==1:
coaching_temp.accessStuData()
elif choicefour==2 or choicefour==3:
AdmInterface(choicefour)
elif choicefour==0:
break
else:
Error.showError()
| c0edf9018e07a142ecc2b60242634fcf3b3acac1 | [
"Python"
] | 8 | Python | saqib1707/RattleSnake | df8b0159b3450a539aec23f369fe9a7c2fc65155 | 4ceb6563ac048ff3b4b776a0985bda4a6a9b647c | |
refs/heads/master | <repo_name>byee322/survey_gorilla<file_sep>/public/js/application.js
$(document).ready(function() {
$('.survey-name').on('submit', function(e){
e.preventDefault();
$.post("/create_survey", $("#create-survey").serialize())
.done(function(data){
$('.survey-name').hide();
$('.survey-questions').html(data);
$('button[name="add_q"]').on('click', function(e){
e.preventDefault();
$('.questions').append('<div class="question"><span>Question : </span><input type="text" name="survey[][title]" style="width: 70%;"><div class="answers"><input type="text" name="survey[][answers][]" placeholder="answer"> <input type="text" name="survey[][answers][]" placeholder="answer"></div><button type="submit" name="add_a">Add Answer</button></div>');
});
$('.questions').on('click', 'button[name="add_a"]', function(e){
e.preventDefault();
$(this).parent().find('.answers').append(' <input type="text" name="survey[][answers][]" placeholder="answer">');
});
});
});
});
<file_sep>/db/seeds.rb
user = User.create :name => "test",
:email => "<EMAIL>",
:password => "<PASSWORD>"
survey1 = user.surveys.create :title => "Colors"
question1 = survey1.questions.create :question => "What is your favorite color?"
question1.answers.create :answer => "Red"
answer1 = question1.answers.create :answer => "Green"
question1.answers.create :answer => "Blue"
answer1.responses.create :user_id => user.id
question2 = survey1.questions.create :question => "What is your favorite drink?"
question2.answers.create :answer => "Water"
answer2 = question2.answers.create :answer => "Beer"
question2.answers.create :answer => "Wine"
answer2.responses.create :user_id => user.id, :survey_id => 1
<file_sep>/app/models/survey.rb
class Survey < ActiveRecord::Base
validates_presence_of :title
belongs_to :user
has_many :questions
end
<file_sep>/app/models/answer.rb
class Answer < ActiveRecord::Base
validates_presence_of :answer
belongs_to :question
has_many :responses
end
<file_sep>/app/controllers/index.rb
get '/' do
erb :index
end
get '/create_survey/:id' do |id|
@user = User.find(id)
erb :create_survey
end
post '/create_survey' do
@survey = Survey.create(params[:user])
erb :make_questions, layout: false
end
get '/make_questions/:id' do |id|
@survey = Survey.find(id)
erb :make_questions
end
post '/make_questions/:id' do |id|
@survey = Survey.find(id)
params[:survey].each do |question|
q_title = question["title"] #q1
ques = Question.create(question: q_title)
@survey.questions << ques
q_answers = question["answers"] # [a1, a2]
q_answers.each do |answer|
ans = Answer.create(answer: answer)
ques.answers << ans
end
end
redirect '/dashboard'
end
get '/dashboard' do
if current_user
@surveys = Survey.all
@surveys_answered = @user.surveys
erb :dashboard
else
redirect '/'
end
end
get '/create_survey/:id' do |id|
erb :create_survey
end
get '/take_survey/:id' do
@survey = Survey.find(params[:id]) # remove this stuff and put into take_survey post
@question_bank = @survey.questions
@answer_bank = @survey.questions.first.answers
erb :take_survey
end
post '/survey_submit' do
survey_id = params.shift.pop
if params
params.values.each do |answer_id|
Response.create(user_id: session[:user_id], survey_id: survey_id, answer_id: answer_id)
redirect '/dashboard'
end
else
redirect '/take_survey/#{:id}'
end
end
# User.first.surveys.first.questions.first.answers.first.responses
<file_sep>/app/models/response.rb
class Response < ActiveRecord::Base
belongs_to :answer
belongs_to :user
belongs_to :survey
end
<file_sep>/db/migrate/20130705113824_create_tables.rb
class CreateTables < ActiveRecord::Migration
def change
create_table :users do |t|
t.text :name
t.text :email
t.string :password_digest
end
create_table :surveys do |t|
t.integer :user_id
t.text :title
end
create_table :questions do |t|
t.integer :survey_id
t.text :question
end
create_table :answers do |t|
t.integer :question_id
t.text :answer
end
create_table :responses do |t|
t.integer :user_id
t.integer :answer_id
t.integer :survey_id
end
end
end
<file_sep>/README.md
survey_gorilla
==============
Using nested forms and dynamically adding questions and answers through ajax.
DBC Weekend challenge - Completed with a group of 3 over a weekend.
Built form scratch a working sign-up/login survey creator. You can make your own survey and add questions and answers. You can also take surveys.
<file_sep>/app/controllers/login.rb
before '/dashboard/*' do
redirect '/' unless session[:user_id]
end
get '/login' do
erb :login
end
post '/login' do
@user = User.find_by_email(params[:login][:email])
if @user.try(:authenticate, params[:login][:password])
session[:user_id] = @user.id
erb :dashboard
else
redirect '/login'
end
end
post '/signup' do
if params[:signup][:password] == params[:signup][:confirmation]
data = {:name => params[:signup][:name],
:email => params[:signup][:email],
:password => params[:signup][:password]}
@user = User.create data
session[:user_id] = @user.id
erb :dashboard
else
redirect '/login'
end
end
get '/logout' do
session.clear
redirect '/'
end
<file_sep>/app/models/question.rb
class Question < ActiveRecord::Base
# validates_presence_of :question
belongs_to :survey
has_many :answers
end
| 2f5dcf8178682adbf8a7f591a6f9e64670c95b1b | [
"JavaScript",
"Ruby",
"Markdown"
] | 10 | JavaScript | byee322/survey_gorilla | 48f9f592b54bad9959454ee86ff9dfd01ed0d7b1 | a028db762b8176f32616b44062356b04426e68ac | |
refs/heads/master | <file_sep>package com.hiren.ecommerce;
import com.hiren.ecommerce.Modules.AppModule;
import com.hiren.ecommerce.Modules.NetModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {AppModule.class, NetModule.class})
public interface NetComponet {
void inject(MainActivity activity);
}
<file_sep>package com.hiren.ecommerce.TypeConverters;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hiren.ecommerce.Models.Tax;
import com.raizlabs.android.dbflow.converter.TypeConverter;
import java.util.List;
public class TaxTypeConverter extends TypeConverter<String, Tax> {
@Override
public String getDBValue(Tax model) {
if(model != null) {
Gson gson = new Gson();
return gson.toJson(model);
}
else
return "";
}
@Override
public Tax getModelValue(String data) {
Gson gson = new Gson();
Tax taxes = gson.fromJson(data, new TypeToken<List<Tax>>(){}.getType());
return taxes;
}
}
<file_sep>
package com.hiren.ecommerce;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import com.google.gson.Gson;
import com.hiren.ecommerce.Models.Category;
import com.hiren.ecommerce.Models.Product;
import com.hiren.ecommerce.Models.ProductModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
public static final String CATEGORYID = "CategoryId";
@Inject SharedPreferences sharedPreferences;
@Inject OkHttpClient okHttpClient;
@Inject Retrofit retrofit;
SwipeRefreshLayout swipeRefreshLayout;
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
ProductModel productModel;
ArrayList<Category> categories;
CategoriesAdapter categoriesAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApp) getApplication()).getNetComponent().inject(this);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
updateData();
}
});
recyclerView = (RecyclerView) findViewById(R.id.categoriesRV);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
categories = new ArrayList<>();
fetchData();
categoriesAdapter = new CategoriesAdapter(categories);
recyclerView.setAdapter(categoriesAdapter);
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
Category category = categories.get(position);
if(category.getChildCategories().size() > 0) {
categories.clear();
for (Category cat :
productModel.getCategories()) {
for (int i = 0; i < category.getChildCategories().size(); i++) {
if (cat.getId() == category.getChildCategories().get(i)) {
categories.add(cat);
}
}
}
categoriesAdapter.notifyDataSetChanged();
}
else {
Intent intent = new Intent(MainActivity.this, ProductListActivity.class);
intent.putExtra(CATEGORYID, category.getId());
startActivity(intent);
}
}
});
/*// Enable caching for OkHttp
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(getApplication().getCacheDir(), cacheSize);
OkHttpClient.Builder client = new OkHttpClient.Builder().cache(cache);
// Used for caching authentication tokens
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Instantiate Gson
Gson gson = new GsonBuilder().create();
GsonConverterFactory converterFactory = GsonConverterFactory.create(gson);
// Build Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(converterFactory)
.client(client.build()) // custom client
.build();*/
}
void fetchData(){
Request request = new Request.Builder()
.url("https://stark-spire-93433.herokuapp.com/json")
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
final String responseData = response.body().string();
Gson gson = new Gson();
productModel = gson.fromJson(responseData, ProductModel.class);
productModel.save();
for (Category category :
productModel.getCategories()) {
if (category.getChildCategories().size() > 0) {
categories.add(category);
}
}
for (int i = 0; i < categories.size(); i++) {
for (int j = 0; j < categories.size(); j++) {
if(categories.get(i).getChildCategories().contains(categories.get(j).getId())){
categories.remove(j);
j--;
}
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
categoriesAdapter.notifyDataSetChanged();
}
});
}
});
}
void updateData(){
fetchData();
swipeRefreshLayout.setRefreshing(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh :
swipeRefreshLayout.setRefreshing(true);
updateData();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>
package com.hiren.ecommerce.Models;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.hiren.ecommerce.ProductDatabase;
import com.hiren.ecommerce.TypeConverters.CategoryTypeConverter;
import com.hiren.ecommerce.TypeConverters.RankingTypeConverter;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
@Table(database = ProductDatabase.class)
public class ProductModel extends BaseModel {
@PrimaryKey
@Column
private int id = 1;
@SerializedName("categories")
@Expose
@Column(typeConverter = CategoryTypeConverter.class)
private List<Category> categories = null;
@SerializedName("rankings")
@Column(typeConverter = RankingTypeConverter.class)
@Expose
private List<Ranking> rankings = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Ranking> getRankings() {
return rankings;
}
public void setRankings(List<Ranking> rankings) {
this.rankings = rankings;
}
}
<file_sep>package com.hiren.ecommerce;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hiren.ecommerce.Models.Product;
import java.util.List;
import java.util.zip.Inflater;
public class ProductsAdapter extends RecyclerView.Adapter {
List<Product> products;
ProductsAdapter(List<Product> data) {
this.products = data;
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
TextView productName;
public ProductViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.product_title);
}
public TextView getProductName() {
return productName;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_view, parent, false);
ProductViewHolder viewHolder = new ProductViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Product product = products.get(position);
((ProductViewHolder) holder).getProductName().setText(product.getName());
}
@Override
public int getItemCount() {
return products.size();
}
}
<file_sep>package com.hiren.ecommerce.TypeConverters;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hiren.ecommerce.Models.Category;
import com.raizlabs.android.dbflow.converter.TypeConverter;
import java.util.List;
public class CategoryTypeConverter extends TypeConverter<String, List<Category>> {
@Override
public String getDBValue(List<Category> model) {
if(model != null) {
Gson gson = new Gson();
return gson.toJson(model);
}
else
return "";
}
@Override
public List<Category> getModelValue(String data) {
Gson gson = new Gson();
List<Category> categories = gson.fromJson(data, new TypeToken<List<Category>>(){}.getType());
return categories;
}
}
| 72f3a9d512a0ab74deafb102bbd5e2df6fd6d733 | [
"Java"
] | 6 | Java | hirennagaria/ECommerce | 20a575d117856cce594fbc5344f0f28a51690161 | f4623d3c930a2156dd6199b202035939af05373e | |
refs/heads/master | <file_sep>import throttle from 'lodash/throttle'
import debounce from 'lodash/debounce'
import * as viewport from "../utilities/viewport";
export class Video {
constructor() {
this.$placeholders = $('.lazy-video-placeholder');
if ( !this.$placeholders.length ) return;
this.initialize();
this.removePersistedVideos();
document.addEventListener('turbo:before-cache', () => {
this.turnOffEventListeners();
}, { once: true });
}
removePersistedVideos() {
document.querySelectorAll('.turbo-persist-video').forEach((video) => {
video.pause();
video.src = '';
video.remove();
video = null;
});
}
turnOffEventListeners() {
this.$videos.each((index, video) => {
if ( video.classList.contains('turbo-persist-video') ) return;
video.pause();
video.src = '';
video.remove();
video = null;
});
this.$videos = null;
this.$placeholders.removeClass('lazy-video-initialized');
App.$window.off('resize.lazyLoadVideo scroll.lazyLoadVideo');
}
initialize() {
if ( !this.$placeholders.length ) return;
this.$placeholders.each(function() {
var $placeholder = $(this);
if ( $placeholder.hasClass('lazy-video-initialized') ) return;
var videoHTML = $placeholder.attr('data-video-tag-html');
var $video = $(videoHTML);
if ( $placeholder.hasClass('desktop-video') && App.breakpoint.isMobile() ) return;
if ( $placeholder.hasClass('mobile-video') && !App.breakpoint.isMobile() ) return;
var video = $video[0];
var srcFull = $video.attr('data-src');
var srcMobile = $video.attr('data-src-mobile');
var src;
if ( App.breakpoint.isMobile() && srcMobile ) {
src = srcMobile;
} else {
src = srcFull;
}
$video.addClass('lazy-video').attr('src', src);
$placeholder.addClass('lazy-video-initialized').hide().after($video);
$video.one('loadedmetadata', function() {
$video.closest('.video-jumpfix').addClass('has-loadedmetadata');
});
});
this.$videos = $('.lazy-video');
var checkForVisibility = () => {
if ( !this.$videos || !this.$videos.length ) return;
this.$videos.each((index, element) => {
var $video = $(element);
var video = $video[0];
var autoplay = $video.attr('autoplay');
var isInHero = $video.closest('#hero-viewport-container').length;
var isVisible = false;
if ( !autoplay || autoplay == 'false' ) {
$video.data('lazy-load-video-autoplay-disabled', true);
return;
}
if ( isInHero ) {
if ( App.scrollTop < App.windowHeight / 2 ) {
isVisible = true;
}
} else if ( viewport.isVisible(video) ) {
if ( $video.data('has-been-paused-by-user') ) return;
if ( $video.data('hasFinishedPlaying') == true && ( !loop || loop == 'false' ) ) return;
isVisible = true;
}
if ( isVisible && !$video.is(':visible') ) {
isVisible = false;
}
if ( isVisible ) {
var playPromise = video.play();
if ( playPromise !== undefined ) {
playPromise.then(function() {
// Automatic playback started
}).catch(function(error) {
// Auto-play was prevented
console.warn('Error playing video', error);
});
}
} else {
video.pause();
}
});
};
App.$window.on('resize.lazyLoadVideo', debounce(checkForVisibility, 500));
App.$window.on('scroll.lazyLoadVideo', throttle(checkForVisibility, 500));
checkForVisibility();
var $disabledVideos = this.$placeholders.filter(function() {
return $(this).data('lazy-load-video-autoplay-disabled') == true;
});
if ( this.$placeholders.length == $disabledVideos.length ) {
this.turnOffEventListeners();
}
}
}
// Export an init function that looks for and instantiates the module on pageload
export default (() => {
App.pageLoad.push(() => {
new Video();
});
$(function() {
App.$document.on('click.lazyLoadVideo', '.lazy-video', function() {
var $video = $(this);
if ( $video[0].paused ) {
$video.data('has-been-paused-by-user', false);
$video[0].play();
} else {
$video.data('has-been-paused-by-user', true);
$video[0].pause();
}
});
});
})();
App.$document.on('click.lazyLoadVideo', '.video-controls__control', function() {
var $control = $(this);
var $scope = $control.closest('[data-video-scope]');
var $audioOn = $scope.find('.video-controls__audio-on');
var $audioOff = $scope.find('.video-controls__audio-off');
var $video = $scope.find('video').filter(':visible');
if ( $video[0].muted ) {
$video[0].muted = false;
$audioOn.hide();
$audioOff.show();
} else {
$video[0].muted = true;
$audioOn.show();
$audioOff.hide();
}
});
<file_sep>In a new Rails app running Forest:
```
rm package.json
cd app/assets
git clone <EMAIL>:dylanfisher/forest-assets.git
mv forest-assets/package.json ../../
rm -rf javascripts
rm -rf ../javascript
rm -rf stylesheets
rm -rf config
rm -rf forest-assets/.git
rm forest-assets/.gitignore
rm forest-assets/README.md
mv forest-assets/* ./
mkdir ../javascript
mv javascripts/* ../javascript
rmdir javascripts
rmdir forest-assets
cd ../../
```
<file_sep>// External links
App.isExternalLink = function($el) {
var documentHost = document.location.href.split('/')[2];
var internalLinkExceptions = ['mailto:', 'tel:', 'sms:', 'javascript:'];
var href = $el.attr('href');
var link = $el.get(0).href;
var linkHost = link.split('/')[2];
var internalLinkMatches = $.map(internalLinkExceptions, function(d) {
if ( href ) {
return href.indexOf(d) != -1;
} else {
return true;
}
});
return linkHost != documentHost && ( $.inArray(true, internalLinkMatches) === -1 );
};
App.pageLoad.push(function() {
$('a').each(function() {
var $link = $(this);
if ( App.isExternalLink($link) ) {
var target = $link.attr('target');
if ( !target ) {
target = '_blank';
}
$link.attr('target', '_blank')
.addClass('external-link');
}
});
});
<file_sep>// Smooth scroll
import { gsap } from "gsap";
import { ScrollToPlugin } from "gsap/ScrollToPlugin";
gsap.registerPlugin(ScrollToPlugin);
App.pageLoad.push(function() {
if ( location.hash.length > 1 ) {
var hash = location.hash.substr(1);
var $el = $('[name="' + hash + '"], #' + hash).first();
if ( $el.attr('data-default-jump-link') != undefined ) return;
// carousel modules can mess up spacing of page, so wait a second before scrolling
setTimeout(function() {
if ( $el.length ) App.scrollTo($el);
}, 250);
}
});
$(document).on('click', 'a[href*="#"]:not([href="#"])', function(e) {
// If you want to disable the call to `e.preventDefault()` you can add a ` data-default-jump-link` attribute to the link.
// This is good if e.g. you want to enable the default history behavior for jump links.
// <a href="#jump-link" data-default-jump-link>the hash in this jump link get's added to the current URL as usual</a>
var $target = $(e.target);
if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'' ) && location.hostname == this.hostname && location.search == this.search) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if ( target.length ) {
var offset = parseInt( $target.attr('data-smooth-scroll-offset') );
App.scrollTo(target, offset);
if ( $(this).attr('data-default-jump-link') == undefined ) {
e.preventDefault();
}
}
}
});
App.scrollTo = function(targetOrPosition, offset, callback) {
var smoothScrollOffset = (offset || offset == 0) ? offset : 0;
var duration = 1.5;
var scrollTop;
if ( isNaN(targetOrPosition) ) {
if ( !targetOrPosition.length ) {
console.warn('Can\'t find target to scroll to.', targetOrPosition);
return;
} else {
scrollTop = targetOrPosition.offset().top - smoothScrollOffset;
}
} else {
scrollTop = targetOrPosition;
}
gsap.to(window, {
duration: duration,
scrollTo: scrollTop,
ease: 'power4.out',
onComplete: function() {
if ( callback ) callback();
}
});
};
| 849643a026b3684169dbe01dc9a09d22f4199ae1 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | dylanfisher/forest-assets | ece569d9e6c0156d660e91feb3e5c1361d165df9 | 681ebfdfc0095332b16633e41cbe8573be4aaf9f | |
refs/heads/master | <repo_name>intere/UITestKit<file_sep>/UITestKit.podspec
#
# Lint this before submitting:
# `pod lib lint --allow-warnings UITestKit.podspec`
#
Pod::Spec.new do |s|
s.name = 'UITestKit'
s.version = '0.1.2'
s.summary = 'Programmatic UI Tests (not using the Apple UI Test Framework). XCTest-based tests.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
This library solves the problem of having to maintain Apple's UI Tests, but lets you automate UI Tests for
integration testing. By using this library, you are no longer subject to the limitations of the UI Tests
that Apple provides a framework for. You can run UI Tests as part of a normal Unit Test target. The strategy
is similar to many other language UI Testing frameworks, timers and conditional checks. See the example project
to see how it starts you off.
I wrote this library, because it's the basic building blocks that I've used in so many iOS projects now.
I've had issues with the Apple UI Test framework and it's time to apply the DRY (Don't Repeat Yourself)
principle.
DESC
s.homepage = 'https://github.com/intere/UITestKit'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<NAME>' => '<EMAIL>' }
s.source = { :git => 'https://github.com/intere/UITestKit.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/intere'
s.ios.deployment_target = '9.0'
s.swift_version = '4.2'
s.source_files = 'UITestKit/**/*'
s.frameworks = 'XCTest'
end
<file_sep>/Example/UITestKit_ExampleTests/ExampleBaseUITest.swift
//
// ExampleBaseUITest.swift
// UITestKit_ExampleTests
//
// Created by <NAME> on 11/5/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
@testable import UITestKit_Example
import UITestKit
import XCTest
class ExampleBaseUITest: UITestKitBase {
/// Gets you the `MyTabBarVC` if it's visible
var myTabBarVC: MyTabBarVC? {
return tabBarVC as? MyTabBarVC
}
/// Gets you the `CircleTabVC` if it's the topVC
var circleTabVC: CircleTabVC? {
return topVC as? CircleTabVC
}
/// Gets you the `SquareTabVC` if it's the topVC
var squareTabVC: SquareTabVC? {
return topVC as? SquareTabVC
}
/// Gets the `ShapesTableViewController`
var shapeTableVC: ShapesTableViewController? {
return topVC as? ShapesTableViewController
}
}
// MARK: - API
extension ExampleBaseUITest {
@discardableResult
/// Opens the Circle Tab.
///
/// - Returns: The CircleTab if we were able to open it.
func openCircleTab() -> CircleTabVC? {
guard let myTabBarVC = myTabBarVC else {
XCTFail(topVCScreenshot)
return nil
}
myTabBarVC.selectedIndex = 0
XCTAssertTrue(waitForCondition({ self.circleTabVC != nil }, timeout: 10), topVCScreenshot)
return circleTabVC
}
@discardableResult
/// Opens the Square Tab.
///
/// - Returns: The SquareTab if we were able to open it.
func openSquareTab() -> SquareTabVC? {
guard let myTabBarVC = myTabBarVC else {
XCTFail(topVCScreenshot)
return nil
}
myTabBarVC.selectedIndex = 1
XCTAssertTrue(waitForCondition({ self.squareTabVC != nil }, timeout: 10), topVCScreenshot)
return squareTabVC
}
@discardableResult
/// Opens the shape tab and hands you back the VC.
///
/// - Returns: The `ShapesTableViewController`
func openShapeTab() -> ShapesTableViewController? {
guard let myTabBarVC = myTabBarVC else {
XCTFail(topVCScreenshot)
return nil
}
myTabBarVC.selectedIndex = 2
XCTAssertTrue(waitForCondition({ self.shapeTableVC != nil}, timeout: 10), topVCScreenshot)
return shapeTableVC
}
}
<file_sep>/UITestKit/Classes/UITestKitBase.swift
//
// UITestKitBase.swift
// UITestKit
//
// Created by <NAME> on 11/5/17.
//
import Foundation
import UIKit
import XCTest
open class UITestKitBase: TestKitBase {
/// Should the `pauseForUIDebug` function actually pause?
/// This variable is useful for when you want to watch a UI Run
open var shouldPauseUI = false
/// If `shouldPauseUI` is enabled, this is how long a `pauseForUIDebug()` call lasts (in seconds).
open var pauseTimer: TimeInterval = 0.5
/// if `pauseForUIDebug` is enabled, then this will pause for `pauseTimer` seconds
/// if not, then it is a no-op.
open func pauseForUIDebug() {
guard shouldPauseUI else {
return
}
waitForDuration(pauseTimer)
}
/// Tells you the type of the top ViewController
open var topVCType: String {
guard let topVC = topVC else {
return "No Top VC"
}
return String(describing: topVC.classForCoder)
}
/// Gets you the VC that is the currently visible VC (top)
open var topVC: UIViewController? {
return type(of: self).topVC
}
/// Takes a screenshot and returns the filename that it wrote to (which contains the topVCType)
open var topVCScreenshot: String {
guard let screenshot = UIApplication.shared.screenShot else {
return topVCType
}
let time = Int(Date().timeIntervalSince1970 * 1000)
let filename = "/tmp/\(topVCType)_\(time).png"
do {
guard let pngData = screenshot.pngData() else {
return topVCType
}
try pngData.write(to: URL(fileURLWithPath: filename))
return filename
} catch {
print("ERROR writing file \(filename): \(error.localizedDescription)")
}
return topVCType
}
/// Gets you a reference to the TabBarVC for the app (so you can set
/// what tab is visible, get the currently presented VC, etc)
open var tabBarVC: UITabBarController? {
guard let rootVC = UIApplication.shared.keyWindow?.rootViewController else {
return nil
}
if let tabVC = rootVC as? UITabBarController {
return tabVC
}
return nil
}
/// Gets you the VC that is the currently visible VC (top)
open class var topVC: UIViewController? {
let visibleVC = getVisibleViewController()
if let navVC = visibleVC as? UINavigationController {
return navVC.topViewController
}
if let tabVC = visibleVC as? UITabBarController {
if let navVC = tabVC.selectedViewController as? UINavigationController {
return navVC.topViewController
}
return tabVC.selectedViewController
}
return visibleVC
}
/// Traverses the provided `rootViewController` to find the currently visible view controller.
///
/// - Parameter rootViewController: The root Viewcontroller to search.
/// - Returns: The currently visible ViewController if it could be determined.
open class func getVisibleViewController(_ rootViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
var rootVC = rootViewController
if rootVC == nil {
rootVC = UIApplication.shared.keyWindow?.rootViewController
}
if rootVC?.presentedViewController == nil {
return rootVC
}
if let presented = rootVC?.presentedViewController {
if presented.isKind(of: UINavigationController.self) {
let navigationController = presented as! UINavigationController
return getVisibleViewController(navigationController.viewControllers.last!)
}
if presented.isKind(of: UITabBarController.self) {
let tabBarController = presented as! UITabBarController
return tabBarController.selectedViewController!
}
return getVisibleViewController(presented)
}
return nil
}
/// Disables UI Animations
open func disableAnimations() {
UIView.setAnimationsEnabled(false)
}
/// Enables UI Animations
open func enableAnimations() {
UIView.setAnimationsEnabled(true)
}
/// Modally presents the provided view controller (without animations).
///
/// - Parameter viewController: The view controller you want to present.
open func presentModally(viewController: UIViewController) {
topVC?.present(viewController, animated: false)
}
}
extension UIApplication {
/// Takes a screenshot of the application.
var screenShot: UIImage? {
return keyWindow?.layer.screenShot
}
}
extension CALayer {
/// Takes a screenshot of the layer.
var screenShot: UIImage? {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
}
<file_sep>/Example/UITestKit_ExampleTests/ShapeTests.swift
//
// ShapeTests.swift
// UITestKit_ExampleTests
//
// Created by <NAME> on 12/29/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
@testable import UITestKit_Example
import XCTest
class ShapeTests: XCTestCase {
func testShapeImages() {
for shape in Shape.allCases {
XCTAssertNotNil(shape.image, "\(shape) does not have an image")
}
}
}
<file_sep>/UITestKit/Classes/TestKitBase.swift
//
// TestKitBase.swift
// UITestKit
//
// Created by <NAME> on 11/5/17.
//
import XCTest
/// A Base Class that provides some very basic functions for sleeping arbitrarily and waiting for a specific condition to occur (or timing out if that doesn't happen)
open class TestKitBase: XCTestCase {
/// Waits for the desired amount of time (and frees up the UI thread while it waits)
///
/// - Parameter timeout: The length of time to wait for
public func waitForDuration(_ timeout: TimeInterval) {
waitForCondition({ false }, timeout: timeout)
}
/// Waits for the provided condition block to evaluate to true, or the timeout amount of time to elapse.
///
/// - Parameters:
/// - condition: The block to evaluate for truthy/falsy.
/// - timeout: The length of time to stop querying the block and just return false.
/// - Returns: True if the block evaluated truthy in the allotted time, false otherwise.
@discardableResult
public func waitForCondition(_ condition: () -> Bool, timeout: TimeInterval) -> Bool {
var done = false
let startTime = NSDate()
while !done {
RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
done = condition()
if done {
break
}
if -startTime.timeIntervalSinceNow > timeout {
return false
}
}
return true
}
}
<file_sep>/Example/UITestKit/ViewControllers/Views/ShapeTableViewCell.swift
//
// ShapeTableViewCell.swift
// UITestKit_Example
//
// Created by <NAME> on 12/29/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Cartography
import UIKit
class ShapeTableViewCell: UITableViewCell {
var shape: Shape? {
didSet {
contentChanged()
}
}
let titleLabel = UILabel()
let shapeImageView = UIImageView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
buildCell()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
buildCell()
}
override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text = nil
shapeImageView.image = nil
}
}
// MARK: - Implementation
private extension ShapeTableViewCell {
func buildCell() {
[titleLabel, shapeImageView].forEach { contentView.addSubview($0) }
constrain(contentView, titleLabel, shapeImageView) { view, titleLabel, shapeImageView in
shapeImageView.top == view.top + 4
shapeImageView.left == view.left + 16
shapeImageView.bottom == view.bottom - 4
shapeImageView.width == 80
shapeImageView.height == 80
titleLabel.left == shapeImageView.right + 16
titleLabel.right == view.right - 16
titleLabel.centerY == shapeImageView.centerY
}
}
func contentChanged() {
guard let shape = shape else {
return
}
titleLabel.text = shape.rawValue
shapeImageView.image = shape.image
}
}
<file_sep>/Example/Podfile
use_frameworks!
platform :ios, '9.3'
target 'UITestKit_Example' do
pod 'Cartography'
target 'UITestKit_ExampleTests' do
inherit! :search_paths
pod 'UITestKit', :path => '../'
end
end
<file_sep>/README.md
<img src="https://github.com/intere/UITestKit/blob/master/Example/UITestKit/Media.xcassets/AppLogo.imageset/AppLogo.png?raw=true" width="150">
# UITestKit
### An iOS Library for UI Testing
## Features
- UI Testing from a vanilla `XCTest` target
- Enable / Disable UI Animations
- Take screenshots on test assertion failures
- `waitForCondition` function to free up the UI thread and wait for your block condition to become true (or timeout and move on)
- `pauseForUIDebug()` function to allow you to pause a (configurable) amount of time between steps in your tests
- function becomes a no-op when `shouldPauseUI` is false (the default)
- variables to get you the top view controller
- Example App to demonstrate capabilities
[](https://travis-ci.org/intere/UITestKit)
[](https://intere.github.io/UITestKit/index.html)
[](http://cocoadocs.org/docsets/UITestKit)
[](https://cocoapods.org/pods/UITestKit)
[](https://cocoapods.org/pods/UITestKit) [](https://cocoapods.org/pods/UITestKit)
## Why not use XCUITests?
- UITestKit lets you interact with the application code directly from test code
- Easier mocking of model objects
- Easier invocation of ViewControllers
- Lower level access to your application
- UITestKit provides convenience variables for taking screenshots from failures
- UITestKit can be far less rigid than XCUITests
## Example
To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements
- iOS 9.0 or higher
## Installation
UITestKit is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod 'UITestKit'
```
### Code Examples
```swift
/// Pre-test initialization
override func setUp() {
super.setUp()
// Don't show view transitions - this will help prevent timing related failures
disableAnimations()
// pause when pauseForUIDebug() is called
shouldPauseUI = true
// how long to pause for when pauseForUIDebug() is called
pauseTimer = 0.3
// Now do other setup tasks
}
```
```swift
/// Tests logging in to the application
func testLoginSuccess() {
// Verify that we're at the Main VC or fail and take a screenshot
XCTAssertTrue(waitForCondition({ self.mainVC != nil }, timeout: 3), topVCScreenshot)
pauseForUIDebug()
mainVC?.loadEmailLoginScreen()
// Verify that we're at the Sign in VC or fail and take a screenshot
XCTAssertTrue(waitForCondition({ self.signInVC != nil}, timeout: 1), topVCScreenshot)
pauseForUIDebug()
// Simulate typing email
if let emailText = signInVC?.emailText {
emailText.text = "<EMAIL>"
pauseForUIDebug()
}
// simulate typing password
if let passwordText = signInVC?.passwordText {
passwordText.text = "<PASSWORD>"
pauseForUIDebug()
}
// log in
signInVC?.login()
// Verify that we've signed in successfully and are at the Welcome VC or fail and take a screenshot
XCTAssertTrue(waitForCondition({ self.welcomeVC != nil}, timeout: 5), topVCScreenshot)
}
```
### Best Practices
- It is recommended to create a `BaseUITest` class that specializes `UITestKitBase` and provides convenience variables for your application's view controllers:
```swift
/// Gets you the `SquareTabVC` if it's the topVC
var squareTabVC: SquareTabVC? {
return topVC as? SquareTabVC
}
/// Gets the `ShapesTableViewController`
var shapeTableVC: ShapesTableViewController? {
return topVC as? ShapesTableViewController
}
```
- It is recommend that you use the screenshot capability when checking for specific UI's to be visible or in a specific UI state:
```swift
XCTAssertTrue(waitForCondition({ self.shapeTableVC != nil }, timeout: 1), topVCScreenshot)
```
`topVCScreenshot` will produce failures like this:

`The Screenshot that is produced will look something like the following:`
<img src="https://user-images.githubusercontent.com/2284832/50541754-4f373300-0b69-11e9-9db8-f5f9e7a4b779.png" width="300">
## Author
[<NAME>](https://github.com/intere) | [Eric's Github Site](https://intere.github.io/)
## License
UITestKit is available under the MIT license. See the [LICENSE file](https://raw.githubusercontent.com/intere/UITestKit/master/LICENSE) for more info.
<file_sep>/Example/UITestKit_ExampleTests/ShapeTableTests.swift
//
// ShapeTableTests.swift
// UITestKit_ExampleTests
//
// Created by <NAME> on 12/29/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
@testable import UITestKit_Example
import XCTest
class ShapeTableTests: ExampleBaseUITest {
override func setUp() {
super.setUp()
disableAnimations()
shouldPauseUI = true
pauseTimer = 0.3
openCircleTab()
}
override func tearDown() {
shouldPauseUI = false
openCircleTab()
enableAnimations()
super.tearDown()
}
func testShapesTable() {
openShapeTab()
XCTAssertTrue(waitForCondition({ self.shapeTableVC != nil }, timeout: 1), topVCScreenshot)
guard let shapeTableVC = shapeTableVC else {
return XCTFail("No ShapeTableVC")
}
pauseForUIDebug()
XCTAssertEqual(0, shapeTableVC.tableView.numberOfRows(inSection: 0), "Wrong number of rows")
guard let rightButton = shapeTableVC.navigationItem.rightBarButtonItem else {
return XCTFail("No right button or action")
}
for index in 0..<Shape.allCases.count {
shapeTableVC.addShape(rightButton)
XCTAssertEqual(index+1, shapeTableVC.tableView.numberOfRows(inSection: 0), topVCScreenshot)
pauseForUIDebug()
}
for _ in 0..<5 {
shapeTableVC.addShape(rightButton)
XCTAssertEqual(Shape.allCases.count, shapeTableVC.tableView.numberOfRows(inSection: 0), topVCScreenshot)
}
pauseForUIDebug()
}
}
<file_sep>/Example/UITestKit/Models/Shape.swift
//
// Shape.swift
// UITestKit_Example
//
// Created by <NAME> on 12/29/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
enum Shape: String, CaseIterable {
case triangle
case circle
case square
case rhombus
case star
case pentagon
case rectangle
case ellipse
var image: UIImage? {
return UIImage(named: rawValue)
}
/// Info about the shape.
/// **Sources:
/// - https://www.smartickmethod.com/blog/math/geometry/geometric-plane-shapes/
/// - Wikipedia
var description: String {
switch self {
case .triangle:
return "The triangle is a shape that is formed by 3 straight lines that are called sides. There are different ways of classifying triangles, according to their sides or angles."
case .circle:
return "The circle is a shape that can be made by tracing a curve that is always the same distance from a point that we call the center. The distance around a circle is called the circumference of the circle."
case .rectangle:
return "The rectangle is a shape that has 4 sides. The distinguishing characteristic of a rectangle is that all 4 angles measure 90 degrees."
case .rhombus:
return "The rhombus is a shape formed by 4 straight lines. Its 4 sides measure the same length but, unlike the rectangle, any of all 4 angles measure 90 degrees."
case .square:
return "The square is a type of rectangle, but also a type of rhombus. It has characteristics of both of these. That is to say, all 4 angles are right angles, and all 4 sides are equal in length."
case .star:
return "In geometry, a star polygon is a type of non-convex polygon. Only the regular star polygons have been studied in any depth; star polygons in general appear not to have been formally defined."
case .pentagon:
return "In geometry, a pentagon (from the Greek πέντε pente and γωνία gonia, meaning five and angle) is any five-sided polygon or 5-gon. The sum of the internal angles in a simple pentagon is 540°."
case .ellipse:
return "In mathematics, an ellipse is a curve in a plane surrounding two focal points such that the sum of the distances to the two focal points is constant for every point on the curve. As such, it is a generalization of a circle, which is a special type of an ellipse having both focal points at the same location. The shape of an ellipse (how \"elongated\" it is) is represented by its eccentricity, which for an ellipse can be any number from 0 (the limiting case of a circle) to arbitrarily close to but less than 1."
}
}
}
<file_sep>/Example/UITestKit/ViewControllers/ShapesTableViewController.swift
//
// ShapesTableViewController.swift
// UITestKit_Example
//
// Created by <NAME> on 12/29/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
class ShapesTableViewController: UITableViewController {
var shapes = [Shape]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(ShapeTableViewCell.self, forCellReuseIdentifier: "Shape")
navigationController?.setNavigationBarHidden(false, animated: false)
navigationController?.navigationItem.rightBarButtonItem?.target = self
navigationController?.navigationItem.rightBarButtonItem?.action = #selector(addShape(_:))
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shapes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Shape", for: indexPath)
guard let shapeCell = cell as? ShapeTableViewCell else {
return cell
}
shapeCell.shape = shapes[indexPath.row]
return shapeCell
}
}
// MARK: - User Actions
extension ShapesTableViewController {
@IBAction
func addShape(_ source: UIBarButtonItem) {
guard shapes.count < Shape.allCases.count else {
return
}
shapes.append(Shape.allCases[shapes.count])
tableView.reloadData()
tableView.scrollToRow(at: IndexPath(row: shapes.count-1, section: 0), at: .bottom, animated: UIView.areAnimationsEnabled)
if shapes.count == Shape.allCases.count {
source.isEnabled = false
}
}
}
<file_sep>/Example/UITestKit_ExampleTests/UITestKit_ExampleTests.swift
//
// UITestKit_ExampleTests.swift
// UITestKit_ExampleTests
//
// Created by <NAME> on 11/5/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import SafariServices
import UITestKit
import XCTest
class UITestKit_ExampleTests: ExampleBaseUITest {
override func setUp() {
super.setUp()
shouldPauseUI = true
pauseTimer = 1
XCTAssertNotNil(myTabBarVC, "We couldn't find the root tab view")
}
override func tearDown() {
openCircleTab()
super.tearDown()
}
}
// MARK: - Circle Tab
extension UITestKit_ExampleTests {
func testOpenCircleTab() {
XCTAssertNotNil(openCircleTab(), topVCScreenshot)
// Pause, long enough to see it
pauseForUIDebug()
}
func testOpenSquareTab() {
XCTAssertNotNil(openSquareTab(), topVCScreenshot)
// Pause, long enough to see it
pauseForUIDebug()
}
}
// MARK: - Safari Tab (Modal VC)
extension UITestKit_ExampleTests {
func testOpenSafariVC() {
topVC?.present(SFSafariViewController(url: URL(string: "https://www.google.com")!), animated: true, completion: nil)
XCTAssertTrue(waitForCondition({ self.topVC is SFSafariViewController }, timeout: 1), topVCScreenshot)
pauseForUIDebug()
(topVC as? SFSafariViewController)?.dismiss(animated: true, completion: nil)
XCTAssertTrue(waitForCondition({ !(self.topVC is SFSafariViewController) }, timeout: 1), "The SFSafariVC didn't dismiss")
}
}
| 75cf9793b87fc07a0740cc7d819972b43f309140 | [
"Swift",
"Ruby",
"Markdown"
] | 12 | Ruby | intere/UITestKit | df88817d71123a2c21860119d08aed34427d6501 | 97d6e94e4643ada58f5670deb4e0b77c49971263 | |
refs/heads/master | <file_sep><section id="superSizedSlider" class="scrollMenu">
<a id="prevslide" class="load-item"></a>
<a id="nextslide" class="load-item"></a>
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="slidecaption"></div>
</div>
</div>
</div>
</section>
<section id="content">
<section class="color0">
<div class="container">
<div class="row">
<div class="col-md-6 pt40" data-nekoanim="fadeInLeftBig" data-nekodelay="200">
<img src="<?php echo base_url('assets/frontend/images/'.$content_list['section-one']['content_media']); ?>" alt="" class="img-responsive" />
</div>
<div class="col-md-5 col-md-offset-1 pt40 mt40">
<h1><?php echo $content_list['section-one']['content_header']; ?></h1>
<p><?php echo $content_list['section-one']['content_body']; ?></p>
</div>
</div>
</div>
</section>
<section class="color1">
<div class="container">
<div class="row">
<div class="col-md-5 pt40 mt40">
<h1><?php echo $content_list['section-two']['content_header']; ?></h1>
<p><?php echo $content_list['section-two']['content_body']; ?></p>
</div>
<div class="col-md-6 col-md-offset-1 pt40 pb40" data-nekoanim="fadeInRightBig" data-nekodelay="300">
<img src="<?php echo base_url('assets/frontend/images/'.$content_list['section-two']['content_media']); ?>" alt="" class="img-responsive"/>
</div>
</div>
</div>
</section>
<section id="projectQuoteSection" class="pt40 pb40 color2">
<div class="container">
<div class="row">
<div class="col-md-12 mb30 text-center" data-nekoanim="fadeInDown" data-nekodelay="300">
<h1><?php echo $content_list['section-three']['content_header']; ?></h1>
<p><?php echo $content_list['section-three']['content_body']; ?></p>
</div>
</div>
</div>
</section><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>สนามฟุตบอล Play Maker | Backend</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="<?php echo base_url('assets/backend/css/bootstrap.min.css'); ?>" rel="stylesheet" type="text/css">
<link href="<?php echo base_url('assets/backend/css/sb-admin.css'); ?>" rel="stylesheet" type="text/css">
<style type="text/css">
#page-wrapper { min-height: 600px; }
</style>
<script type="text/javascript" src="<?php echo base_url('assets/backend/js/jquery-1.11.0.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/backend/js/bootstrap.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/backend/js/view.'.$current_page.'.js'); ?>"></script>
</head>
<body>
<div id="wrapper">
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo site_url('backend/dashboard'); ?>">สนามฟุตบอล Play Maker | Backend</a>
</div>
<ul class="nav navbar-right top-nav">
<li>
<a href="javascript: void(0);"><span class="glyphicon glyphicon-user"></span> <?php echo $user_data['username']; ?></a>
</li>
<li>
<a href="<?php echo site_url('backend/do_signout'); ?>"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
</li>
</ul>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<?php
foreach ($menu_list as $menu) {
$attr = ($menu['option_key'] === $current_page)? ' class="active"': NULL;
$display = explode("|", $menu['option_value']);
?>
<li <?php echo $attr; ?>>
<a href="<?php echo site_url('backend/'.$menu['option_key']); ?>"><span class="glyphicon <?php echo $display[1]; ?>"></span> <?php echo $display[0]; ?></a>
</li>
<?php } ?>
</ul>
</div>
</nav>
<div id="page-wrapper">
<div class="container-fluid"><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Backend extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
if ($this->session->userdata('user_data') === "") {
redirect('backend/signin', 'refresh');
} else {
redirect('backend/dashboard', 'refresh');
}
}
public function signin() {
$params['signin_status'] = ($this->uri->segment(3))? $this->uri->segment(3): NULL;
$this->load->view('backend/signin_view', $params);
}
public function do_signin() {
$username = $this->input->post('input-username');
$password = $this-><PASSWORD>->post('input-<PASSWORD>');
$user = $this->user_model->user_authentication($username, $password);
if (count($user) > 0) {
$this->session->set_userdata('user_data', $user);
redirect('backend', 'refresh');
} else {
redirect('backend/signin/failed', 'refresh');
}
}
public function do_signout() {
$this->session->sess_destroy();
redirect('backend', 'refresh');
}
public function dashboard() {
$params['user_data'] = $this->session->userdata('user_data');
$params['current_page'] = ($this->uri->segment(2))? $this->uri->segment(2): 'dashboard';
$params['menu_list'] = $this->utility_model->get_option_by_type('backend_menu');
$this->load->view('backend/header_view', $params);
$this->load->view('backend/dashboard_view', $params);
$this->load->view('backend/footer_view', $params);
}
public function slider() {
$params['user_data'] = $this->session->userdata('user_data');
$params['current_page'] = ($this->uri->segment(2))? $this->uri->segment(2): 'dashboard';
$params['add_photo_status'] = ($this->uri->segment(3))? $this->uri->segment(3): NULL;
$params['menu_list'] = $this->utility_model->get_option_by_type('backend_menu');
$params['super_sized_slider_list'] = $this->utility_model->get_option_by_type('super_sized_slider');
$this->load->view('backend/header_view', $params);
$this->load->view('backend/slider_view', $params);
$this->load->view('backend/footer_view', $params);
}
public function do_insert_photo() {
$params['user_data'] = $this->session->userdata('user_data');
$config['upload_path'] = './assets/frontend/images/slider/super/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = false;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
foreach($_FILES['userfile'] as $o_k => $o_v) {
foreach($o_v as $i_k => $i_v) {
$_FILES['userfile'.$i_k][$o_k] = $i_v;
}
}
unset($_FILES['userfile']);
foreach($_FILES as $key => $value) {
if ($this->upload->do_upload($key)) {
$photo = $this->upload->data();
$sql = 'insert into pm_options values (null, now(), lower(?), now(), lower(?), ?, ?, ?, ?, ?);';
$data = array(
$params['user_data']['username'],
$params['user_data']['username'],
'super_sized_slider',
$photo['file_name'],
'Photo Description',
0,
'Y'
);
$query = $this->db->query($sql, $data);
$params['update_result'] = $query;
} else {
$params['update_result'] = FALSE;
}
}
$display = ($params['update_result'])? 'succeed': 'failed';
redirect('backend/slider/'.$display, 'refresh');
}
public function do_edit_photo() {
if ($this->uri->segment(3)) {
$params['user_data'] = $this->session->userdata('user_data');
$photo_description = $this->input->post('input-photo-description');
$sql = 'update pm_options ';
$sql .= 'set last_updated = now(), last_updated_by = ?, option_value = ? ';
$sql .= 'where option_type = ? ';
$sql .= 'and option_key = ? ';
$sql .= 'limit 1;';
$data = array(
$params['user_data']['username'],
$photo_description,
'super_sized_slider',
$this->uri->segment(3)
);
$this->db->query($sql, $data);
redirect('backend/slider', 'refresh');
}
}
public function do_delete_photo() {
if ($this->uri->segment(3)) {
$sql = 'delete from pm_options where option_type = ? and option_key = ?;';
$data = array('super_sized_slider', $this->uri->segment(3));
if ($this->db->query($sql, $data)) {
if (unlink('./assets/frontend/images/slider/super/'.$this->uri->segment(3))) {
redirect('backend/slider', 'refresh');
}
}
}
}
public function contents() {
$params['user_data'] = $this->session->userdata('user_data');
$params['current_page'] = ($this->uri->segment(2))? $this->uri->segment(2): 'contents';
$params['menu_list'] = $this->utility_model->get_option_by_type('backend_menu');
$this->load->view('backend/header_view', $params);
$this->load->view('backend/contents_view', $params);
$this->load->view('backend/footer_view', $params);
}
public function users() {
$params['user_data'] = $this->session->userdata('user_data');
$params['current_page'] = ($this->uri->segment(2))? $this->uri->segment(2): 'contents';
$params['menu_list'] = $this->utility_model->get_option_by_type('backend_menu');
$this->load->view('backend/header_view', $params);
$this->load->view('backend/users_view', $params);
$this->load->view('backend/footer_view', $params);
}
public function setting() {
$params['user_data'] = $this->session->userdata('user_data');
$params['current_page'] = ($this->uri->segment(2))? $this->uri->segment(2): 'contents';
$params['menu_list'] = $this->utility_model->get_option_by_type('backend_menu');
$this->load->view('backend/header_view', $params);
$this->load->view('backend/setting_view', $params);
$this->load->view('backend/footer_view', $params);
}
}
/* End of file backend.php */
/* Location: ./application/controllers/backend.php */<file_sep><!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"><![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<meta charset="utf-8">
<title><?php echo $web_meta_list['title']; ?></title>
<meta name="description" content="<?php echo $web_meta_list['description']; ?>">
<meta name="author" content="<?php echo $web_meta_list['author']; ?>">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/bootstrap/css/bootstrap.min.css'); ?>">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Roboto:100,300,400">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/supersized/css/supersized.css'); ?>" media="screen">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/supersized/theme/supersized.shutter.css'); ?>" media="screen">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/animation-framework/animate.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/magnific-popup/magnific-popup.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/owl.carousel/owl-carousel/owl.carousel.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/owl.carousel/owl-carousel/owl.transitions.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/owl.carousel/owl-carousel/owl.theme.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/js-plugin/appear/nekoAnim.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/font-icons/custom-icons/css/custom-icons.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/css/layout.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/css/sea-green.css'); ?>">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/frontend/css/custom.css'); ?>">
<!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->
<script src="<?php echo base_url('assets/frontend/js/modernizr-2.6.1.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/respond/respond.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/jquery/jquery-1.10.2.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/jquery-ui/jquery-ui-1.8.23.custom.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/bootstrap/js/bootstrap.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/easing/jquery.easing.1.3.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/owl.carousel/owl-carousel/owl.carousel.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/magnific-popup/jquery.magnific-popup.min.js'); ?>"></script>
<?php if ($current_view === 'home') { ?>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/supersized/js/supersized.3.2.7.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/supersized/theme/supersized.shutter.min.js'); ?>"></script>
<script type="text/javascript">
$(function($){
"use strict";
if($('#superSizedSlider').length){
$('#superSizedSlider').height($(window).height());
$.supersized({
// Functionality
slideshow : 1, // Slideshow on/off
autoplay : 1, // Slideshow starts playing automatically
start_slide : 1, // Start slide (0 is random)
stop_loop : 0, // Pauses slideshow on last slide
random : 0, // Randomize slide order (Ignores start slide)
slide_interval : 12000, // Length between transitions
transition : 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 1000, // Speed of transition
new_window : 1, // Image links open in new window/tab
pause_hover : 0, // Pause slideshow on hover
keyboard_nav : 1, // Keyboard navigation on/off
performance : 1, // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
image_protect : 1, // Disables image dragging and right click with Javascript
// Size & Position
min_width : 0, // Min width allowed (in pixels)
min_height : 0, // Min height allowed (in pixels)
vertical_center : 1, // Vertically center background
horizontal_center : 1, // Horizontally center background
fit_always : 0, // Image will never exceed browser width or height (Ignores min. dimensions)
fit_portrait : 1, // Portrait images will not exceed browser height
fit_landscape : 0, // Landscape images will not exceed browser width
// Components
slide_links : 'blank', // Individual links for each slide (Options: false, 'num', 'name', 'blank')
thumb_links : 0, // Individual thumb links for each slide
thumbnail_navigation : 0, // Thumbnail navigation
slides: [ // Slideshow Images
<?php
foreach ($super_sized_slider_list as $key => $value) {
echo "{image : './assets/frontend/images/slider/super/$value[option_key]', title : '<h1>$value[option_value]</h1>', thumb : '', url : ''}";
echo (($key + 1) !== count($super_sized_slider_list))? ',': NULL;
}
?>
],
// Theme Options
progress_bar: 0, // Timer for each slide
mouse_scrub: 0
});
}
});
</script>
<?php } ?>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/isotope/jquery.isotope.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/isotope/jquery.isotope.sloppy-masonry.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/neko-contact-ajax-plugin/js/jquery.form.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/neko-contact-ajax-plugin/js/jquery.validate.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/parallax/js/jquery.stellar.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/appear/jquery.appear.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js-plugin/toucheeffect/toucheffects.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/frontend/js/custom.js'); ?>"></script>
</head>
<body class="activateAppearAnimation header5">
<div id="globalWrapper">
<header class="navbar-fixed-top">
<div id="preHeader" class="hidden-xs">
<div class="container">
<div class="row">
<div class="col-xs-6"></div>
<div class="col-xs-6">
<div id="contactBloc" class="clearfix">
<ul class="socialNetwork">
<?php
foreach ($social_network_list as $social_network) {
$social_network_item = (strpos($social_network['option_value'], '|') !== 0)? explode('|', $social_network['option_value']): $social_network['option_value'];
?>
<li><a href="<?php echo $social_network_item[0]; ?>" class="tips" title="follow me on <?php echo $social_network['option_key']; ?>"><i class="<?php echo $social_network_item[1]; ?>"></i></a></li>
<?php } ?>
</ul>
<span class="contactPhone"><i class="icon-phone"></i><?php echo $contact_us_list['phone'];?></span>
</div>
</div>
</div>
</div>
</div>
<div id="mainHeader" role="banner">
<div class="container">
<nav class="navbar navbar-default scrollMenu" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo site_url('home'); ?>"><img src="<?php echo base_url('assets/frontend/images/'.$web_meta_list['main_logo']); ?>"/></a>
</div>
<div class="collapse navbar-collapse" id="mainMenu">
<ul class="nav navbar-nav pull-right">
<?php
foreach ($menu_list as $menu) {
$attr = ($menu['option_key'] === $current_view)? ' active': NULL;
?>
<li class="primary">
<a href="<?php echo site_url($menu['option_key']); ?>" class="firstLevel<?php echo $attr; ?>"><?php echo $menu['option_value'] ?></a>
</li>
<?php } ?>
</ul>
</div>
</nav>
</div>
</div>
</header><file_sep><div class="row">
<div class="col-lg-12">
<input type="hidden" id="site_url" value="<?php echo site_url(); ?>">
<h1 class="page-header">Slider</h1>
<ol class="breadcrumb">
<li><a href="<?php echo site_url('backend/dashboard');?>"><span class="glyphicon glyphicon-dashboard"></span> Dashboard</a></li>
<li class="active"><span class="glyphicon glyphicon-picture"></span> Slider</li>
</ol>
<p class="text-right">
<button class="btn btn-success" data-toggle="modal" data-target="#add-photo-modal"><span class="glyphicon glyphicon-plus"></span> Add Photo</button>
</p>
<?php
if ($add_photo_status) {
if ($add_photo_status === 'succeed') {
echo '<div class="alert alert-success" role="alert">Add Photo Succeed</div>';
} else {
echo '<div class="alert alert-danger" role="alert">Add Photo Failed</div>';
}
}
?>
</div>
</div>
<div class="row">
<?php foreach($super_sized_slider_list as $super_sized_slider) { ?>
<div class="col-lg-3">
<a class="thumbnail get-photo-modal" href="#photo-modal" data-photo-description="<?php echo $super_sized_slider['option_value']; ?>" data-photo-name="<?php echo $super_sized_slider['option_key']; ?>" data-photo-row-id="<?php echo $super_sized_slider['row_id']; ?>" data-toggle="modal">
<img alt="<?php echo $super_sized_slider['option_value']; ?>" src="<?php echo base_url('assets/frontend/images/slider/super/'.$super_sized_slider['option_key']); ?>">
</a>
</div>
<?php } ?>
</div>
<div class="modal fade" id="add-photo-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" action="<?php echo site_url('backend/do_insert_photo'); ?>" accept-charset="utf-8" method="post" role="form">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myModalLabel" class="modal-title">Add Photo</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="file" multiple="" name="userfile[]">
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
<input type="submit" value="Save Changes" name="input-add-photos" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="photo-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Photo</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-7"></div>
<div class="col-xs-5">
<div class="text-right">
<div class="btn-group btn-group-sm">
<a class="btn btn-default" id="edit-photo-description" href="javascript: void(0);">Edit</a>
<a class="btn btn-default" id="do-delete-photo" href="">Delete This Photo</a>
</div>
</div>
<form class="form-horizontal" role="form" method="post" accept-charset="utf-8" action="" id="edit-photo-description-form">
<label for="input-photo-description">Photo description:</label>
<textarea class="form-control" rows="4" name="input-photo-description" id="input-photo-description"></textarea>
<br>
<input class="btn btn-primary" name="input-edit-photo" type="submit" value="Save Changes">
</form>
</div>
</div>
</div>
</div>
</div>
</div><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Content_Model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function get_content_by_type($in_option_type, $in_rebuild_flag = 'n') {
$sql = "select row_id, content_type, alias_name, content_header, content_body, content_media, active_flag ";
$sql .= "from pm_contents ";
$sql .= "where content_type = 'home' ";
$sql .= "and active_flag = 'Y' ";
$sql .= "order by row_id, alias_name;";
$query = $this->db->query($sql, $in_option_type);
if ($in_rebuild_flag === 'n') {
return $query->result_array();
} else {
foreach ($query->result_array() as $row) {
$result_array[$row['alias_name']] = $row;
}
return $result_array;
}
}
}
/* End of file content_model.php */
/* Location: ./application/models/content_model.php */<file_sep><section id="page">
<header class="page-header">
<div class="container">
<div class="row">
<div class="col-sm-6">
<h1><?php echo ucwords(str_replace('-', ' ', $current_view)); ?></h1>
<p>Lorem ipsum dolor sit amet,</p>
</div>
<div class="col-sm-6 hidden-xs">
<ul id="navTrail">
<li><a href="index.html">Home</a></li>
<li id="navTrailLast"><?php echo ucwords(str_replace('-', ' ', $current_view)); ?></li>
</ul>
</div>
</div>
</div>
</header>
<section id="content" class="mt30 pb30">
<div class="container">
<div class="row">
<div class="col-md-8">
<article class="post clearfix">
<div class="postPic">
<div class="imgBorder mb15">
<a href="blog-post.html"><img src="<?php echo base_url('assets/frontend/images/blog/blog-pic2.jpg'); ?>" alt="" class="img-responsive"/></a>
</div>
</div>
<div class="row">
<section class="col-sm-12 col-xs-12">
<h2><a href="blog-post.html">Okay, Houston, we’ve had a problem here</a></h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor lacus ac justo varius in vehicula nibh mattis. Aenean ac diam metus. Aliquam tempor tincidunt pretium. Suspendisse bibendum, sapien venenatis vestibulum commodo, eros lectus iaculis magna, sit amet pellentesque ligula turpis a nibh... <a href="blog-post.html" class="readMore">read more</a>
</p>
<ul class="entry-meta">
<li class="entry-date"><a href="#"><i class="icon-pin"></i> 12 Oct. 2027</a></li>
<li class="entry-author"><a href="#"><i class="icon-male"></i> Admin</a></li>
</ul>
</section>
</div>
</article>
<hr class="lineLines mb40 mt30">
<article class="post clearfix">
<div class="postPic">
<div class="imgBorder mb15">
<a href="blog-post.html"><img src="<?php echo base_url('assets/frontend/images/blog/blog-pic2.jpg'); ?>" alt="" class="img-responsive"/></a>
</div>
</div>
<div class="row">
<section class="col-sm-12 col-xs-12">
<h2><a href="blog-post.html">I feel fine. How about you?</a></h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor lacus ac justo varius in vehicula nibh mattis. Aenean ac diam metus. Aliquam tempor tincidunt pretium. Suspendisse bibendum, sapien venenatis vestibulum commodo, eros lectus iaculis magna, sit amet pellentesque ligula turpis a nibh... <a href="blog-post.html" class="readMore">read more</a>
</p>
<ul class="entry-meta">
<li class="entry-date"><a href="#"><i class="icon-pin"></i> 12 Oct. 2027</a></li>
<li class="entry-author"><a href="#"><i class="icon-male"></i> Admin</a></li>
</ul>
</section>
</div>
</article>
</div>
<!-- Sidebar -->
<aside class="col-md-4">
<section>
<h1>Latest news from planet earth</h1>
<p>Nullam sed tortor odio. Suspendisse tincidunt dictum nisi, nec convallis odio lacinia ac. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.</p>
</section>
<section class="widget">
<h3>Categories</h3>
<ul class="list-unstyled iconList">
<li><a href="#">Solace of a lonely highway</a></li>
<li><a href="#">Write with purpose</a></li>
<li><a href="#">Tree on a lake</a></li>
<li><a href="#">Don’t stop questioning</a></li>
<li><a href="#">Overheard this morning</a></li>
</ul>
</section>
<section class="widget">
<h3>Archives</h3>
<ul class="list-unstyled iconList">
<li><a href="#">March 2012</a></li>
<li><a href="#">September 2011</a></li>
<li><a href="#">July 2011</a></li>
<li><a href="#">June 2011</a></li>
</ul>
</section>
</aside>
</div>
</div>
</section>
</section><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$route['home'] = 'frontend/home';
$route['(playmaker-academy|rate-and-promotion)'] = 'frontend/home/content';
$route['(league-and-tournament|new-and-event)'] = 'frontend/home/list_content';
$route['contact-us'] = 'frontend/home/contact_us';
$route['404_override'] = '';
/* End of file routes.php */
/* Location: ./application/config/routes.php */<file_sep> <footer id="footerWrapper" class="footer3">
<section id="mainFooter">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="footerWidget text-center">
<h1 class="bigTitle text-center"><?php echo $contact_us_list['phone'];?></h1>
<address class="text-center"><?php echo $contact_us_list['address'];?></address>
<ul class="socialNetwork">
<?php
foreach ($social_network_list as $social_network) {
$social_network_item = (strpos($social_network['option_value'], '|') !== 0)? explode('|', $social_network['option_value']): $social_network['option_value'];
?>
<li><a href="<?php echo $social_network_item[0]; ?>" class="tips" title="" data-original-title="follow me on <?php echo $social_network['option_key']; ?>"><i class="<?php echo $social_network_item[1]; ?> iconRounded iconSmall"></i></a></li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
</section>
<section id="footerRights">
<div class="container">
<div class="row">
<div class="col-md-12">
<p>Copyright © 2014 <a href="<?php echo site_url('/'); ?>" target="blank"><?php echo $web_meta_list['copyright']; ?></a> / All rights reserved.</p>
</div>
</div>
</div>
</section>
</footer>
</div>
</body>
</html><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Utility_Model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function get_option_by_type($in_option_type, $in_rebuild_flag = 'n') {
$sql = "select row_id, option_key, option_value ";
$sql .= "from pm_options ";
$sql .= "where option_type = lower(?) ";
$sql .= "order by option_sequence, option_key";
$query = $this->db->query($sql, $in_option_type);
if ($in_rebuild_flag === 'n') {
return $query->result_array();
} else {
foreach ($query->result_array() as $row) {
$result_array[$row['option_key']] = $row['option_value'];
}
return $result_array;
}
}
public function get_default_language($arg) {
if ($arg === FALSE) {
$default_language = $this->get_option_by_type('default_language', 'customize');
return $default_language['language'];
} else {
return $arg;
}
}
}
/* End of file utility_model.php */
/* Location: ./application/models/utility_model.php */<file_sep><div class="row">
<div class="col-lg-12">
<h1 class="page-header">Users</h1>
<ol class="breadcrumb">
<li><a href="<?php echo site_url('backend/dashboard');?>"><span class="glyphicon glyphicon-dashboard"></span> Dashboard</a></li>
<li class="active"><span class="glyphicon glyphicon-user"></span> Users</li>
</ol>
</div>
</div><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$route['home'] = 'frontend/index';
$route['contact-us'] = 'frontend/contact_us';
$route['(playmaker-academy|rate-and-promotion)'] = 'frontend/content';
$route['(league-and-tournament|new-and-event)'] = 'frontend/list_content';
$route['default_controller'] = 'frontend';
$route['404_override'] = '';
/* End of file routes.php */
/* Location: ./application/config/routes.php */<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_Model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function user_authentication($in_user_login, $in_user_password) {
$sql = "select u.row_id user_id, u.username, u.password, u.last_signin ";
$sql .= "from pm_users u ";
$sql .= "where u.username = ? ";
$sql .= "and u.password = md5(?) ";
$sql .= "limit 1";
$query = $this->db->query($sql, array($in_user_login, $in_user_password));
return $query->row_array();
}
}
/* End of file user_model.php */
/* Location: ./application/models/user_model.php */<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Frontend extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$params['current_view'] = ($this->uri->segment(1))? $this->uri->segment(1): 'home';
$params['web_meta_list'] = $this->utility_model->get_option_by_type('web_meta', 'y');
$params['contact_us_list'] = $this->utility_model->get_option_by_type('contact_us', 'y');
$params['social_network_list'] = $this->utility_model->get_option_by_type('social_network');
$params['menu_list'] = $this->utility_model->get_option_by_type('menu');
$params['super_sized_slider_list'] = $this->utility_model->get_option_by_type('super_sized_slider');
$params['content_list'] = $this->content_model->get_content_by_type('super_sized_slider', 'y');
// echo '<pre>';
// print_r($params);
// echo '</pre>';
$this->load->view('frontend/header_view', $params);
$this->load->view('frontend/home_view', $params);
$this->load->view('frontend/footer_view', $params);
}
public function content() {
$params['current_view'] = ($this->uri->segment(1))? $this->uri->segment(1): 'home';
$params['web_meta_list'] = $this->utility_model->get_option_by_type('web_meta', 'y');
$params['contact_us_list'] = $this->utility_model->get_option_by_type('contact_us', 'y');
$params['social_network_list'] = $this->utility_model->get_option_by_type('social_network');
$params['menu_list'] = $this->utility_model->get_option_by_type('menu');
$this->load->view('frontend/header_view', $params);
$this->load->view('frontend/content_view', $params);
$this->load->view('frontend/footer_view', $params);
}
public function list_content() {
$params['current_view'] = ($this->uri->segment(1))? $this->uri->segment(1): 'home';
$params['web_meta_list'] = $this->utility_model->get_option_by_type('web_meta', 'y');
$params['contact_us_list'] = $this->utility_model->get_option_by_type('contact_us', 'y');
$params['social_network_list'] = $this->utility_model->get_option_by_type('social_network');
$params['menu_list'] = $this->utility_model->get_option_by_type('menu');
$this->load->view('frontend/header_view', $params);
$this->load->view('frontend/list_content_view', $params);
$this->load->view('frontend/footer_view', $params);
}
public function contact_us() {
$params['current_view'] = ($this->uri->segment(1))? $this->uri->segment(1): 'home';
$params['web_meta_list'] = $this->utility_model->get_option_by_type('web_meta', 'y');
$params['contact_us_list'] = $this->utility_model->get_option_by_type('contact_us', 'y');
$params['social_network_list'] = $this->utility_model->get_option_by_type('social_network');
$params['menu_list'] = $this->utility_model->get_option_by_type('menu');
$this->load->view('frontend/header_view', $params);
$this->load->view('frontend/contact_us_view', $params);
$this->load->view('frontend/footer_view', $params);
}
}
/* End of file frontend.php */
/* Location: ./application/controllers/frontend.php */ | 52e31bc6254936dee66a51f929bfb7bc9ac16706 | [
"PHP"
] | 14 | PHP | ibarboon/playmakerfanclub | 559787fe0bdd84ea15f04592912ff74b17674d79 | 9e0266bfec5674035c5d22aab37af2bb6485217b | |
refs/heads/master | <repo_name>kurazu/corridor<file_sep>/README.md
# corridor
Blender Python
<file_sep>/corridor.py
import collections
import bpy
Point = collections.namedtuple('Point', ('x', 'y', 'z'))
class Shape(list):
def __init__(self, x, y, z):
super().__init__()
self.names = {}
self.add(x, y, z, 'start')
def add(self, x, y, z, name):
assert name not in self.names
point = Point(x, y, z)
self.append(point)
self.names[name] = point
return point
def dx(self, dx, name):
tail = self[-1]
return self.add(tail.x + dx, tail.y, tail.z, name)
def dy(self, dy, name):
tail = self[-1]
return self.add(tail.x, tail.y + dy, tail.z, name)
def dz(self, dz, name):
tail = self[-1]
return self.add(tail.x, tail.y, tail.z + dz, name)
def point_by_name(self, name):
point = self.names[name]
return self.index(point)
def faces(self):
return [list(range(len(self)))]
objects = []
def mesh(func):
name = func.__name__
verts = func()
faces = verts.faces()
mesh = bpy.data.meshes.new(name + ' mesh')
obj = bpy.data.objects.new(name, mesh)
mesh.from_pydata(verts, [], faces)
objects.append(obj)
return obj
def floor_shape(verts):
verts.dy(3.7, 'north')
verts.dx(1.95, 'east')
verts.dy(-0.08 - 1 - 1.66, 'south')
verts.dx(1.48, 'bathroom')
verts.dy(-0.96, 'back')
verts.dx(-3.43, 'west')
def rect(v, dx=None, dy=None, dz=None):
assert(len(list(filter(None, [dx, dy, dz]))) == 2)
if dx is None:
v.dy(dy, 'bottom')
v.dz(dz, 'east')
v.dy(-dy, 'top')
v.dz(-dz, 'west')
elif dy is None:
v.dx(dx, 'bottom')
v.dz(dz, 'south')
v.dx(-dx, 'top')
v.dz(-dz, 'north')
else:
assert(False)
@mesh
def floor():
v = Shape(0, 0, 0)
floor_shape(v)
return v
@mesh
def ceiling():
verts = Shape(0, 0, 2.51)
floor_shape(verts)
return verts
@mesh
def back_wall():
verts = Shape(3.43, 0, 0)
rect(verts, dy=0.96, dz=2.51)
return verts
@mesh
def outer_wall_left():
v = Shape(0, 0, 0)
rect(v, dy=1.43, dz=2.51)
return v
@mesh
def outer_wall_top():
v = Shape(0, 1.43, 2.51)
rect(v, dy=1.0, dz=-0.46)
return v
@mesh
def outer_wall_right():
v = Shape(0, 2.43, 0)
rect(v, dy=1.27, dz=2.51)
return v
@mesh
def south_wall_left():
v = Shape(1.95, 0.96, 0)
rect(v, dy=1.66, dz=2.51)
return v
@mesh
def south_wall_top():
v = Shape(1.95, 3.7 - 0.08 - 1.0, 2.05)
rect(v, dy=1.0, dz=0.46)
return v
@mesh
def south_wall_right():
v = Shape(1.95, 3.7 - 0.08, 0)
rect(v, dy=0.08, dz=2.51)
return v
@mesh
def west_wall_left():
v = Shape(3.43, 0, 0)
rect(v, dx=-1.46, dz=2.51)
return v
@mesh
def west_wall_top():
v = Shape(3.43 - 1.46, 0, 2.05)
rect(v, dx=-1.05, dz=0.46)
return v
@mesh
def west_wall_right():
v = Shape(0.92, 0, 0)
rect(v, dx=-0.92, dz=2.51)
return v
@mesh
def bathroom_wall_top():
v = Shape(3.43, 0.96, 2.05)
rect(v, dx=-0.945, dz=0.46)
return v
@mesh
def bathroom_wall_side():
v = Shape(3.43 - 0.945, 0.96, 0)
rect(v, dx=-0.535, dz=2.51)
return v
@mesh
def east_wall_left():
v = Shape(0, 3.7, 0)
rect(v, dx=1.005, dz=2.51)
return v
@mesh
def east_wall_top():
v = Shape(1.005, 3.7, 2.05)
rect(v, dx=0.945, dz=0.46)
return v
def main():
scene = bpy.context.scene
for obj in objects:
scene.objects.link(obj)
if __name__ == '__main__':
main()
| e7e6b2c25cabb181f3b35c8f162a3e367ac836fd | [
"Markdown",
"Python"
] | 2 | Markdown | kurazu/corridor | f7ff027acf3dd1f8bec9c48ed6e64e61b6d72398 | 8b089f522cafb36e61fd2712fc115be91e310c88 | |
refs/heads/master | <repo_name>mjclements/BrainEx-UI<file_sep>/BrainEx/brainex/server.js
//Add packages
var express = require('express');
var app = express();
var multer = require('multer');
var cors = require('cors');
//cors configuration
app.use(cors({
origin: ['http://localhost:3000'],
credentials: true
}));
//app.use(express.static(__dirname + "/public"));
//add files uploaded to the UI into a folder named PreprocessedDataFiles with original file name
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'PreprocessedDataFiles')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
});
//upload multiple files at once
var upload = multer({ storage: storage }).array('file');
app.get('/',function(req,res){
res.render(__dirname + '/public/index.html')
});
app.post('/upload',function(req, res) {
console.log(req.body);
//upload files and send error messages to console if any
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err)
} else if (err) {
return res.status(500).json(err)
}
return res.status(200).send(req.file) //file must be the same name as the
// "name" property in App.js for choosing a file
})
});
//Run on specific port
app.listen(8000, function() {
console.log('App running on port 8000');
});
<file_sep>/README.md
# BrainEx-UI
This project aims to develop a user-interface for BrainEx using HCI practices to enable fNIRS researchers to explore and analyze large datasets. The target users were identified through interviews with lab staff and developing user personas. Through iterative design, prototypes of increasing complexity and detail were designed, evaluated, and refined to satisfy user needs while fulfilling system requirements. The final user-interface developed from these design specifications and initial implementation will reflect all user feedback while accomplishing the tool’s main goal.
# Demo
Here is a demo video of the initial framework and functionality of BrainEx:

# Tutorial
1. Clone or download the project
2. Open the project in the Pycharm IDE
3. Open the terminal and run the command: **npm install** to install all the project modules and dependencies
* To run the application in Pycharm, open two terminals. One for running the frontend and one for running the backend. Make sure you are in the “brainex” folder (the command is: cd brainex)
* Starting frontend command: **npm start**
* After running the frontend, the message in the terminal will say “Compiled successfully. Server is now running on localhost:3000”
* Starting backend command: **node server.js**
* After running the backend, the message in the terminal will say “App is running on port 8000”
4. Once the application automatically opens up on the website (“localhost:3000”), you will see the homepage of BrainEx
5. To upload an already preprocessed dataset, click on “Choose File” and select multiple CSV files. You can also choose a single CSV file. Note that if you try to choose any other file type, it will not work and you will encounter an error.
* You will see that the “No file chosen” will change to the name of the file you chose
6. After choosing the file, click on “Add”
7. Once you do this, go to the project directory and under the folder named “PreprocessedDataFiles”, you will see that the files that you chose from your local directory will be added to the server of the website
8. To start preprocessing a new dataset, click on the button named “Preprocess a new dataset”
9. You can then click on the navigation buttons in the rest of the screens labeled as “back”, “next”, etc to get from one screen to another
# Project Directory
* BrainEx-V1
* The “test_db” folder is the database for BrainEx built from [this project](https://github.com/ApocalyVec/Genex)
* “ItalyPower.csv” contains an example of the fNIRS time series sequences
* “Test.py” is the file to run through BrainEx as the command line tool. Use this script to copy and paste sections of the code into the python console and go through the database functionalities
* brainex - folder where all the frontend code is stored and the directory to be in in order to run the BrainEx application
* “Node_modules” are the node modules and project dependencies that are used by the project. This is added by typing the command: npm install in the terminal
* “PreprocessedDataFiles” is the folder that contains all the user file uploads from the homepage
* The “public” folder contains index.html. Index.html links to index.js (and it’s stylesheet called index.css) which is linked to App.js
* “Server.js” contains the express server code and the logic to do the file uploading functionality
* “Src” is the main folder with all the ReactJs code
* App.js is the main file of the application that executes the homepage as well as all the routers and navigation pages in the site. App.css is this file’s stylesheet
* The BrainEx image logo is located here
* The “components” folder has the rendering of all the other pages in the application. If a new page needs to be created, create and name the page in this folder, go to App.js, and create a Router link to the page you are creating.
<file_sep>/BrainEx/brainex/src/Components/BuildOptions.js
import React from "react";
import './BuildOptions.css';
import {Link} from "react-router-dom";
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import logo from "../brain.png";
const buildOptions = () => (
<Container className="container" style={{flex: 1, flexDirection: 'row', justifyContent: 'flex-start', width: '100%' }}>
<div style={{backgroundColor: '#3C99DC', width: '100%', height: '17%', position: 'absolute', left:'0.01%', top:'0%'}}>
<img src={logo} className="App-logo" alt="logo"/>
<h1 className="App-title">BrainEx</h1>
<h3 className="App-Version">Version 1.0.0</h3>
<h4 className="options">Preprocessing Options</h4>
</div>
<label htmlFor="dropdown" style={{position:'absolute', left:'45%', top:'22%'}}>Distance Type</label>
<div className="dropdown" style={{position:'absolute', left:'41.5%', top:'27%'}}>
<button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Choose a Distance
</button>
<div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a className="dropdown-item" href=" ">Warped Euclidean</a>
<a className="dropdown-item" href=" ">Warped Manhattan</a>
<a className="dropdown-item" href=" ">Warped Minkowski</a>
<a className="dropdown-item" href=" ">Warped Chebyshev</a>
</div>
</div>
<Button className="distHelp" style={{position:'absolute', left:'75%', top:'28%', borderColor: 'black', backgroundColor:'#0F5298'}}>?</Button>
<form>
<div className="form-group" style={{width: '40%', position:'absolute', left:'30%', top:'42%'}}>
<label htmlFor="formControlRange">Similarity Threshold</label>
<input type="range" className="form-control-range" id="formControlRange"/>
</div>
</form>
<Button className="simHelp" style={{position:'absolute', left:'75%', top:'43%', borderColor: 'black', backgroundColor:'#0F5298'}}>?</Button>
<form>
<div className="form-group" style={{width: '40%', position:'absolute', left:'30%', top:'60%'}}>
<label htmlFor="formControlRange">Length of Interest</label>
<input type="range" className="form-control-range" id="formControlRange"/>
</div>
</form>
<Button className="lenHelp" style={{position:'absolute', left:'75%', top:'61%', borderColor: 'black', backgroundColor:'#0F5298'}}>?</Button>
<Link to="/Components/BuildProgressMenu">
<Button className="startprocess btn-primary" style={{width: '20%', borderColor: 'black', backgroundColor:'#0F5298'}}>Start Preprocessing</Button>
</Link>
<Container className="Box"> </Container>
<Link to="/Components/csvViewer">
<Button className="back btn-primary" style={{width: '12%', borderColor: 'black', backgroundColor:'#0F5298'}}>Back</Button>
</Link>
</Container>
);
export default buildOptions;<file_sep>/BrainEx/brainex/src/App.js
import React, { Component } from 'react';
import logo from './brain.png';
import './App.css';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import Card from 'react-bootstrap/Card';
import csvViewer from './Components/csvViewer';
import BuildOptions from "./Components/BuildOptions";
import buildProgressMenu from "./Components/BuildProgressMenu";
import explorerPage from "./Components/ExplorerPages";
import queryFinder from "./Components/QueryFinder";
// function App() {
// return (
// <div className="App">
// <header className="App-header">
// <img src={logo} className="App-logo" alt="logo" />
// <p>
// Edit <code>src/App.js</code> and save to reload.
// </p>
// <a
// className="App-link"
// href="https://reactjs.org"
// target="_blank"
// rel="noopener noreferrer"
// >
// Learn React
// </a>
// </header>
// </div>
// );
// }
// const MainMenu = () => {
// return (
// <div>
// <Link to="/">
// <button>home</button>
// </Link>
// <Link to="/about">
// <button>About</button>
// </Link>
// <Link to="/code">
// <button>code</button>
// </Link>
// <Link to="/contact">
// <button>contact</button>
// </Link>
// <Link to="/info">
// <button>info</button>
// </Link>
// </div>
// );
// };
//rendering the Homepage
const Home = () => (
<Container className="container">
{/*top navbar with BrainEx logo*/}
<div style={{backgroundColor: '#3C99DC', width: '100%', height: '17%', position: 'absolute', left:'0.01%', top:'0%'}}>
<img src={logo} className="App-logo" alt="logo"/>
{/*<MainMenu/>*/}
<h1 className="App-title">BrainEx</h1>
<h3 className="App-Version">Version 1.0.0</h3>
<h4 className="homepage">Homepage</h4>
<Button className="Help" style={{backgroundColor: '#3C99DC', color:'#000000', borderColor: '#3C99DC'}}><u>Need Help?</u></Button>
</div>
<div style={{width: '40%', position: 'absolute', left:'47%', top:'30%'}}>
<h5 align="center">The tool that helps find the top similar matches in fNIRS time series sequences</h5>
</div>
<Link to="/Components/csvViewer">
<Button className="preprocess" style={{borderColor:'#000000', backgroundColor:'#0F5298'}}>Preprocess a new dataset</Button>
</Link>
{/* Container for files that have been uploaded to the server*/}
<Container className="csvFileInfo" style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-start', width: '31%'}}>
<div className="col-sm-4">
<div className="well">
<Card style={{backgroundColor: '#3C99DC', width: '328%', position: 'absolute', left:'-14%'}}>
<div className="card-body">
<h5 className="card-title">Start with an existing preprocessed dataset:</h5>
<div className="scrollable" style={{overflowY: 'auto', maxHeight: '210px'}}>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>SART1</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>SART2</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>SART3</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>SART4</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>SART5</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>SART6</Button>
</div>
</div>
</Card>
</div>
</div>
</Container>
</Container>
);
//handles the choose file button functionailty to select a file
class App extends Component {
onChangeHandler=event=>{
var files = event.target.files;
if(this.checkMimeType(event)) {
this.setState({
selectedFile: files
})
}
};
//handles the "Add" button functionality to add selected file to the server
onClickHandler = () => {
const data = new FormData();
for(var i=0; i<this.state.selectedFile.length; i++) {
data.append('file', this.state.selectedFile[i]);
}
console.log(data);
axios.post("http://localhost:8000/upload", data, {//parameter endpoint url, form data
}).then(res => { //print response status
console.log(res.statusText)
})
};
checkMimeType=(event)=>{
//get the file object
let files = event.target.files;
//define message container
let err = '';
const types = ['text/csv']; //file types allowed
for(var i = 0; i<files.length; i++) {
// compare file types and see if it matches
if (types.every(type => files[i].type !== type)) {
err += files[i].type+' is not a supported format\n'; // error message if file types don't match
}
}
if (err !== '') {
event.target.value = null; // remove selected file
console.log(err);
return false;
}
return true;
};
constructor(props) {
super(props);
this.state = {
selectedFile: null
}
}
render() {
return (
/* Router to start homepage*/
<Router>
<div className="App">
<div>
<Route exact path="/" component={Home} />
{/* Functionality for choosing files to upload to the server*/}
<div className="form-group files front" style={{ width: '30%', position: 'absolute', top:'320pt', left:'1%'}}>
<h5 align="center">Load another </h5>
<h5 align="center">preprocessed dataset:</h5>
<input type="file" name="file" className="form-control" multiple onChange={this.onChangeHandler} style={{width:'77%',backgroundColor: '#3C99DC', borderColor:'#3C99DC'}}/>
<div className="chooseFile">
Choose File
<input type="file" className="hide_file"/>
</div>
<Button className="addfile btn-primary" style={{ width: '18%', position: 'absolute', top:'48pt', left:'75%', borderColor:'#000000', backgroundColor:'#0F5298'}} onClick={this.onClickHandler}>Add</Button>
</div>
{/* Routers for page navigation*/}
<Route exact path="/Components/csvViewer" component={csvViewer} />
<Route exact path="/Components/BuildOptions" component={BuildOptions} />
<Route exact path="/Components/BuildProgressMenu" component={buildProgressMenu} />
<Route exact path="/Components/ExplorerPages" component={explorerPage} />
<Route exact path="/Components/QueryFinder" component={queryFinder} />
</div>
</div>
</Router>
)
}
}
export default App;
<file_sep>/BrainEx/brainex/src/Components/ExplorerPages.js
import React from "react";
import {Link} from "react-router-dom";
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import logo from "../brain.png";
const explorerPage = () => (
<Container className="container" style={{flex: 1, flexDirection: 'row', justifyContent: 'flex-start', width: '100%' }}>
<div style={{backgroundColor: '#3C99DC', width: '100%', height: '17%', position: 'absolute', left:'0.01%', top:'0%'}}>
<img src={logo} className="App-logo" alt="logo"/>
<h1 className="App-title">BrainEx</h1>
<h3 className="App-Version">Version 1.0.0</h3>
<h4 className="options" style={{position:'absolute', top:'39%', left:'52%'}}>Explorer Pages</h4>
</div>
<div className="btnContainer btn-group" role="group" style={{position:'absolute', top:'16.6%', left:'0.01%'}}>
<Link to="/">
<Button type="button" className="btn btn-secondary" style={{borderColor: 'black', backgroundColor:'#0F5298'}}>Load Dataset</Button>
</Link>
<Link to="/Components/ExplorerPages">
<Button type="button" className="btn btn-secondary" style={{borderColor: 'black', backgroundColor:'#0F5298'}}>Explore Data</Button>
</Link>
<Link to="/Components/QueryFinder">
<Button type="button" className="btn btn-secondary" style={{borderColor: 'black', backgroundColor:'#0F5298'}}>Find Similar Sequences</Button>
</Link>
</div>
<Container className="Box" style={{backgroundColor:'#FFFFFF', width:'18rem', height:'12rem', position:'absolute', left:'1%', top:'65%'}}> </Container>
</Container>
);
export default explorerPage;<file_sep>/BrainEx/brainex/src/Components/csvViewer.js
import React from "react";
import './csvViewer.css';
import {Link} from "react-router-dom";
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import logo from "../brain.png";
import Card from 'react-bootstrap/Card';
const csvViewer = () => (
<Container className="container">
<div style={{backgroundColor: '#3C99DC', width: '100%', height: '17%', position: 'absolute', left:'0.01%', top:'0%'}}>
<img src={logo} className="App-logo" alt="logo"/>
<h1 className="App-title">BrainEx</h1>
<h3 className="App-Version">Version 1.0.0</h3>
<h4 className="viewer">CSV Viewer</h4>
</div>
<Container className="csvFile" style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-start', width: '31%'}}>
<div className="col-sm-4">
<div className="well">
<Card style={{backgroundColor: '#3C99DC', width: '328%', position: 'absolute', left:'-14%'}}>
<div className="card-body">
<h5 className="card-title">Previously imported unpreprocessed CSV Files</h5>
<div className="scrollable" style={{overflowY: 'auto', maxHeight: '210px'}}>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>Dataset1</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>Dataset2</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>Dataset3</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>Dataset4</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>Dataset5</Button>
<p> </p>
<Button style={{ borderColor: 'black', width: '100%', backgroundColor:'#0F5298'}}>Dataset6</Button>
</div>
</div>
</Card>
</div>
</div>
</Container>
<Link to="/">
<Button className="back btn-primary" style={{width: '10%', position: 'absolute', top: '90%', left: '33%', backgroundColor:'#0F5298', borderColor: 'black'}}>Back</Button>
</Link>
<Link to="/Components/BuildOptions">
<Button className="nextbtn btn-primary" style={{width: '10%', position: 'absolute', top: '90%', left: '88%', backgroundColor:'#0F5298', borderColor: 'black'}}>Next</Button>
</Link>
</Container>
);
export default csvViewer; | 505bd3b88b1cfe4802dbe2a4a390a93325d13a2e | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | mjclements/BrainEx-UI | 38c149ad5b2f0448edb362e6bd5c83c63623f745 | 32e6aef10a739697cef440f706bbe6bdc724d41b | |
refs/heads/main | <file_sep># Adotes
Site fictício para adoção de cachorros e gatos de rua, e filhotes cujos donos queiram doar.<hr>
Tecnologias usadas: HTML, CSS, Javascript e Bootstrap
Ao entrar no site, o usuário se depara com a página inicial
<img src="imagens/menuInicial.JPG">
No canto superior direito tem-se a opção "Vitrine", onde será mostrado todos os animais cadastrados no sistema que ainda não foram adotados.
<img src="imagens/vitrine.JPG">
Mas para que o usuário possa fazer o cadastro de animais e entrar em contato com quem divulgou algum, deve-se fazer o cadastro no sistema e fazer login.
<img src="imagens/cadastroUsuario.JPG">
Depois de logado, será exibido para o usuário os dados de contato de quem fez alguma publicação (para algum animal doméstico que o dono esteja querendo doar seus filhotes, por exemplo), e também poderá fazer o cadastro de algum cachorro ou gato, preenchendo o formulário.
<img src="imagens/cadastroAnimais.JPG">
Para ir à aplicação no GitHub Pages, acesse
https://gustas01.github.io/Adotes/
<file_sep>const racas = ["Afegão Hound","Affenpinscher","Airedale Terrier","Akita","American Staffordshire Terrier","Basenji","Basset Hound","Beagle","Beagle Harrier","Bearded Collie","Bedlington Terrier","Bichon Frisé","Bloodhound","Bobtail","Boiadeiro Australiano","Boiadeiro Bernês","Border Collie","Border Terrier","Borzoi","Boston Terrier","Boxer","Buldogue Francês","Buldogue Inglês","Bull Terrier","Bulmastife","Cairn Terrier","Cane Corso","Cão de Água Português","Cão de Crista Chinês","Cavalier King Charles Spaniel","Chesapeake Bay Retriever","Chihuahua",
"Chow Chow","Cocker Spaniel Americano","Cocker Spaniel Inglês","Collie","Coton de Tuléar","Dachshund","Dálmata","Dandie Dinmont Terrier","Dobermann","Dogo Argentino","Dogue Alemão","Fila Brasileiro", "Pelo Duro", "Pelo Liso","Foxhound Inglês","Galgo Escocês","Galgo Irlandês","Golden Retriever","Grande Boiadeiro Suiço","Greyhound","Grifo da Bélgica","Husky Siberiano","Jack Russell Terrier","King Charles","Komondor","Labradoodle","Labrador Retriever","Lakeland Terrier","Leonberger","Lhasa Apso","Lulu da Pomerânia","Malamute do Alasca","Maltês",
"Mastife","Mastim Napolitano","Mastim Tibetano","Norfolk Terrier","Norwich Terrier","Papillon","Pastor Alemão","Pastor Australiano","Pinscher Miniatura","PitBull","Poodle","Pug","Rottweiler","Sem Raça", "ShihTzu","Silky Terrier","Skye Terrier","Staffordshire Bull Terrier","Terra Nova","Terrier Escocês","Tosa","Vira-lata","Weimaraner","Cardigan","Pembroke","West Highland White Terrier","Whippet","Xoloitzcuintli","Yorkshire Terrier"]
const tamanhos = ["pequeno", "normal", "grande"]
let temRaca
let pessoa = []
let animal = []
class Local{
constructor(rua, bairro, CEP, cidade, estado){
this.rua = rua
this.numero = numero
this.bairro = bairro
this.cidade = cidade
this.estado = estado
this.cep = CEP
}
}
class Animal extends Local{
constructor(cor, tamanho, raca, filhote = false){
super(cidade, estado)
this.cor = cor
this.tamanho = tamanho
this.raca = raca
this.filhote = filhote
}
get cor(){
return this.cor
}
get raca(){
return this.raca
}
set raca(raca){
for(let r of racas)
if(raca === r)
temRaca = true
if (temRaca)
this.raca = raca
}
get tamanho(){
return this.tamanho
}
set tamanho(tam){
for(let t of tamanhos)
if(tam === t)
this.tamanho = tamanho
}
}
class Pessoa extends Local{
constructor(nome, cpf, telefone, rua, numero, bairro, cidade, estado, cep){
super(rua, numero, bairro, cidade, estado, cep)
this.nome = nome
this.cpf = cpf
this.telefone = telefone
}
}
function cadastrarPessoa(){
pessoa.push({
nome: document.querySelector("#nomeCadastro").value,
cpf: document.querySelector("#cpfCadastro").value,
telefone: document.querySelector("#telefoneCadastro").value,
rua: document.querySelector("#ruaCadastro").value,
numero: document.querySelector("#numeroCadastro").value,
bairro: document.querySelector("#bairroCadastro").value,
cidade: document.querySelector("#cidadeCadastro").value,
estado: document.querySelector("#estadoCadastro").value,
cep: document.querySelector("#cepCadastro").value
})
alert("Usuário cadastrado com sucesso!")
// console.log("chamando função do botão")
}
function cadastrarAnimal(){
animal.push({
titulo: document.querySelector("#animalTitulo").value,
cachorro: document.querySelector("#cachorro").checked,
gato: document.querySelector("#gato").checked,
domestico: document.querySelector("#domestico").checked,
deRua: document.querySelector("#deRua").checked,
filhote: document.querySelector("#filhote").checked,
descricaoAnimal: document.querySelector("#animalDescricao").value,
descricaoAnimalQualquer: document.querySelector("#animalDescricaoQualquer").value,
local: document.querySelector("#animalLocal").value
})
alert("Animal cadastrado com sucesso!")
// console.log("chamando função do botão")
}
// console.log(pessoa)
| bbd15cbf427785e19e34eb038f66a265005d7ec7 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | gustas01/Adotes | 9f90c3c2477a49d3a57518fc66c19e6cfcacd67a | cd93f614dce05be2c4424bff801a002b9190d47f | |
refs/heads/master | <file_sep>/*
* connect(ScanTime, SIGNAL(timeout()), discoveryAgent, SLOT(stop()));
* connect(discoveryAgent, SIGNAL(canceled()), this, SLOT(startScan()));
*
*
*
*
*
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
#include <QTimer>
#include "androidrfcomm.h"
#include <QFile>
#include <QFileInfo>
#include <QTextFormat>
#include <QTime>
#include <QtNetwork>
#include <QMenu>
#include <QDebug>
MainWindow::MainWindow(QString rfcommmac, AndroidRfComm *bluecom,QWidget *parent) :
DeviceRfcomm(rfcommmac),rfcomm(bluecom),QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
player = new QMediaPlayer;
ScanTime = new QTimer(this);
ScanTime2 = new QTimer(this);
ScanTime3 = new QTimer(this);
QTimer::singleShot(700, this, SLOT(TimeToInit()));
connect(&client, SIGNAL(newMessage(QString,QString)),
this, SLOT(appendMessage(QString,QString)));
connect(ScanTime, SIGNAL(timeout()), this, SLOT(sendping()));
connect(ScanTime2, SIGNAL(timeout()), this, SLOT(PingTest()));
connect(ScanTime3, SIGNAL(timeout()), this, SLOT(ping()));
Timer_reception_PC();
myNickName = client.nickName();
tableFormat.setBorder(0);
nbrping = 0;
}
void MainWindow::ping()
{
nbrping++;
if (nbrping == 30)
{
nbrping = 0;
RfcommReload();
}
if(PingState)
{
PingState = 0;
}
else if (PingState == 0)
{
QProcess::execute("svc wifi enable");
}
QTimer::singleShot(3500, this, SLOT(sendping()));
}
void MainWindow::sendping()
{
client.sendMessage(IDMACHINE + "ping");
ScanTime2->start(5000);
}
void MainWindow::PingTest()
{
qDebug() << "PING TEST\n PING TEST\nPING TEST\nPING TEST\n PING TEST\nPING TEST\n";
if (PingState == 0)
{
QProcess::execute("svc wifi disable");
}
ping();
}
void MainWindow::ChangeRfcommTel()
{
if (WIFISTATE)
{
WIFISTATE = 0;
QProcess::execute("svc wifi enable");
}
else
{
WIFISTATE = 1;
QProcess::execute("svc wifi disable");
}
}
//=============================================================================||
void MainWindow::appendMessage(const QString &from, const QString &message)
{
if (from.isEmpty() || message.isEmpty())
return;
if (message.mid(0,2).contains(IDMACHINE))
{
if (message.contains("!H"))
{
toldmewhatIshoulddo("H");
rfcomm -> sendLine ("$H" + IDMACHINE + IDPUPITRE + IDBPTABLETTE);
}
else if (message.contains("!L15"))
qApp->quit();
else if (message.contains("!L"))
rfcomm -> sendLine("$L" + IDMACHINE + IDPUPITRE + message.mid(4,2) + "00" );
else if (message.contains("!V"))
toldmewhatIshoulddo(message.mid(3,5));
else if (message.contains("!OIFG"))
{
if (ui->pushButton->isHidden())
OIFG = 0;
else if (!(ui->pushButton->isHidden()))
OIFG = 1;
if (OIFG == 0)
{
OIFG = 1;
toldmewhatIshoulddo("F");
rfcomm -> sendLine("$F" + IDMACHINE + IDPUPITRE + IDBPTABLETTE);
}
else
{
OIFG = 0;
toldmewhatIshoulddo("G");
rfcomm -> sendLine("$G" + IDMACHINE + IDPUPITRE + IDBPTABLETTE);
}
}
else if (message.contains("pong"))
{
toldmewhatIshoulddo("pong");
}
}
}
void MainWindow::toldmewhatIshoulddo(QString Com)
{
QFile fichier9(GENERALPATH + "img/hs.png");
QString volume(Com.mid(0,1));
if(Com.contains("F"))
{
bfr = true;
ui->pushButton->show();
}
else if(Com.contains("G"))
{
bfr = false;
ui->pushButton->hide();
}
else if(Com.contains("H")) //affichage hors service
{
ui->pushButton->hide();
ui->pushButton_2->hide();
ui->pushButton_3->hide();
ui->pushButton_4->hide();
ui->pushButton_5->hide();
ui->pushButton_6->hide();
ui->pushButton_7->hide();
ui->STOP->hide();
if(fichier9.exists())
{
ui->centralWidget->setStyleSheet("background-image: url( /storage/emulated/0/Download/Pupitre/img/hs.png)");
ui->centralWidget->show();
}
player->stop();
MyTimer(); // lancement timer
}
else if (Com.contains("#C"))
changemyconfig(Com);
else if (Com.contains("pong"))
{
PingState = 1;
}
if (volume.contains("V"))
{
SonString = Com.mid(1); // enleve le "V"
qDebug() << SonString;
SonValue = SonString.toInt(&ok);
player->setVolume(SonValue);
}
}
void MainWindow::TimeToInit() // INITIALISATION
{ /*********************lecture config***************************/
QString texte;
GENERALPATH = "/storage/emulated/0/Download/Pupitre/";
QFile fichier(GENERALPATH + "config/config.text");
if(fichier.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream flux(&fichier);
IDMACHINE = flux.readLine();
IDPUPITRE = flux.readLine();
IDBPTABLETTE = flux.readLine();
// VOLUME = flux.readLine();
TEMPHS = flux.readLine().toInt(&ok,10);
}
fichier.close();
OIFG = 1;
VOLUME = 100;
BASEVOLUME = VOLUME;
height = this->geometry().height();
width = this->geometry().width();
heightP = height/100;
widthP = width/100;
TestNumber = 0;
CycleNumber = 0;
Recapok = 0;
PingState = 0;
ui->gridLayoutWidget->setGeometry(0,0,width,height);
ui->horizontalSpacer->changeSize(widthP*12,heightP * 1,QSizePolicy::Maximum,QSizePolicy::Maximum);
ui->horizontalSpacer_4->changeSize(widthP*2,heightP * 1,QSizePolicy::Maximum,QSizePolicy::Maximum);
ui->horizontalSpacer_3->changeSize(widthP*2,heightP * 1,QSizePolicy::Maximum,QSizePolicy::Maximum);
ui->horizontalSpacer_9->changeSize(widthP*2,heightP * 1,QSizePolicy::Maximum,QSizePolicy::Maximum);
ui->horizontalSpacer_11->changeSize(widthP*2,heightP * 1,QSizePolicy::Maximum,QSizePolicy::Maximum);
ui->verticalSpacer->changeSize(widthP*1,heightP * 15,QSizePolicy::Maximum,QSizePolicy::Maximum);
ui->verticalSpacer_2->changeSize(widthP*1,heightP * 10,QSizePolicy::Maximum,QSizePolicy::Maximum);
ui->verticalSpacer_3->changeSize(widthP*1,heightP * 15,QSizePolicy::Maximum,QSizePolicy::Maximum);
WIFISTATE = 0;
LastDevice = "0";
QProcess::execute("svc wifi disable");
InitMyButton();
//ui->list->hide();
ping();
}
void MainWindow::RfcommReload()
{
qDebug() << " try rfcomm";
rfcomm->connect(DeviceRfcomm);
}
/**********************reception rfcomm regulierement *****************/
void MainWindow::itstime()
{
QString Com(rfcomm->receiveLine(100,500));
if (!Com.isEmpty())
{
qDebug() << "rfcomm \n rfcomm \n";
if (Com.contains("#F"))
toldmewhatIshoulddo("F");
else if (Com.contains("#G"))
toldmewhatIshoulddo("G");
else if (Com.contains("#H"))
toldmewhatIshoulddo("H");
else if (Com.contains("#V"))
toldmewhatIshoulddo(Com.mid(1,3));
else if (Com.contains("#C"))
toldmewhatIshoulddo(Com);
rfcomm->sendLine("$" + IDMACHINE + IDPUPITRE + IDBPTABLETTE +"OK");
}
}
/***********************Reception provenance pc par rfcomm toute les secondes************************/
void MainWindow::Timer_reception_PC()
{
QTimer *timer2 = new QTimer(this);
connect(timer2, SIGNAL(timeout()), this, SLOT(itstime()));
timer2->start(1000);
}
/***********************tempo reaffichage icones apres hors service*************************/
void MainWindow::MyTimer()
{
QTimer::singleShot(TEMPHS*1000, this, SLOT(MyTimerSlot()));
}
void MainWindow::MyTimerSlot()
{
if (bfr==true)
ui->pushButton->show();
ui->pushButton_2->show();
ui->pushButton_3->show();
ui->pushButton_4->show();
ui->pushButton_5->show();
ui->pushButton_6->show();
ui->pushButton_7->show();
ui->STOP->show();
ui->centralWidget->setStyleSheet("background-image: url(/storage/emulated/0/Download/Pupitre/img/f.png)");
}
void MainWindow::InitMyButton()
{
int Num(1);
QAndroidJniObject mediaDir = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;");
QAndroidJniObject mediaPath = mediaDir.callObjectMethod( "getAbsolutePath", "()Ljava/lang/String;" );
QString dataAbsPath = mediaPath.toString()+"/Download/Pupitre/" + Num + ".png";
QAndroidJniEnvironment env;
// fond d'ecran
QFile fichier8(GENERALPATH + "img/f.png");
if(fichier8.exists())
ui->centralWidget->setStyleSheet("background-image: url(" + GENERALPATH + "img/f.png)");
//Bouton 1
QFile fichier(GENERALPATH + "img/1.png");
if(fichier.exists())
ui->pushButton->setStyleSheet("background-image: url(" + GENERALPATH + "img/1.png)");
//Bouton2
QFile fichier1(GENERALPATH + "img/2.png");
if(fichier1.exists())
ui->pushButton_2->setStyleSheet("background-image: url( " + GENERALPATH + "img/2.png)");
//Bouton3
QFile fichier2(GENERALPATH + "img/3.png");
if(fichier2.exists())
ui->pushButton_3->setStyleSheet("background-image: url( " + GENERALPATH + "img/3.png)");
//Bouton4
QFile fichier3(GENERALPATH + "img/4.png");
if(fichier3.exists())
ui->pushButton_4->setStyleSheet("background-image: url( " + GENERALPATH + "img/4.png)");
//Bouton5
QFile fichier4(GENERALPATH + "img/5.png");
if(fichier4.exists())
ui->pushButton_5->setStyleSheet("background-image: url( " + GENERALPATH + "img/5.png)");
//Bouton6
QFile fichier5(GENERALPATH + "img/6.png");
if(fichier5.exists())
ui->pushButton_6->setStyleSheet("background-image: url( " + GENERALPATH + "img/6.png)");
//Bouton7
QFile fichier6(GENERALPATH + "img/7.png");
if(fichier6.exists())
ui->pushButton_7->setStyleSheet("background-image: url( " + GENERALPATH + "img/7.png)");
//Bouton stop
QFile fichier7(GENERALPATH + "img/8.png");
if(fichier7.exists())
ui->STOP->setStyleSheet("background-image: url( " + GENERALPATH + "img/8.png)");
}
void MainWindow::changemyconfig(QString Com)
{
QString idmachine = Com.mid(2,2);
QString idpupitre = Com.mid(4,2);
QString idbptablette = Com.mid(6,2);
QString volume = Com.mid(8,2);
QString tempo = Com.mid(10,3);
QString texte = idmachine + "\n" + idpupitre + "\n" + idbptablette + "\n" + volume + "\n" + tempo;
QFile FichierConf(GENERALPATH + "config/config.text");
QTextStream flux(&FichierConf);
if(FichierConf.exists())
{
FichierConf.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
flux << texte;
}
FichierConf.close();
}
void MainWindow::on_pushButton_clicked()
{
rfcomm->sendLine("$L" + IDMACHINE + IDPUPITRE + IDBPTABLETTE + "01");
player->stop();
player->setVolume(VOLUME);
player->setMedia(QUrl::fromLocalFile(GENERALPATH + "son/1.mp3"));
player->play();
VOLUME = BASEVOLUME;
}
void MainWindow::on_pushButton_2_clicked()
{
rfcomm->sendLine("$L" + IDMACHINE + IDPUPITRE + IDBPTABLETTE + "02");
player->stop();
player->setMedia(QUrl::fromLocalFile(GENERALPATH + "son/2.mp3"));
player->play();
VOLUME = BASEVOLUME;
}
void MainWindow::on_pushButton_3_clicked()
{
rfcomm->sendLine("$L" + IDMACHINE + IDPUPITRE + IDBPTABLETTE + "03");
player->stop();
player->setVolume(VOLUME);
player->setMedia(QUrl::fromLocalFile(GENERALPATH + "son/3.mp3"));
player->play();
VOLUME = BASEVOLUME;
}
void MainWindow::on_pushButton_4_clicked()
{
rfcomm->sendLine("$L" + IDMACHINE + IDPUPITRE + IDBPTABLETTE + "04");
player->stop();
player->setMedia(QUrl::fromLocalFile(GENERALPATH + "son/4.mp3"));
player->play();
VOLUME = BASEVOLUME;
}
void MainWindow::on_pushButton_5_clicked()
{
rfcomm->sendLine("$L" + IDMACHINE + IDPUPITRE + IDBPTABLETTE + "05");
player->stop();
player->setMedia(QUrl::fromLocalFile(GENERALPATH + "son/5.mp3"));
player->play();
VOLUME = BASEVOLUME;
}
void MainWindow::on_pushButton_6_clicked()
{
rfcomm->sendLine("$L" + IDMACHINE + IDPUPITRE + IDBPTABLETTE + "06");
player->stop();
player->setMedia(QUrl::fromLocalFile(GENERALPATH + "son/6.mp3"));
player->play();
VOLUME = BASEVOLUME;
}
void MainWindow::on_pushButton_7_clicked()
{
rfcomm->sendLine("$L" + IDMACHINE + IDPUPITRE + IDBPTABLETTE + "07");
player->stop();
player->setMedia(QUrl::fromLocalFile(GENERALPATH + "son/7.mp3"));
player->play();
VOLUME = BASEVOLUME;
}
void MainWindow::on_STOP_clicked()
{
VOLUME = BASEVOLUME;
player->stop();
}
MainWindow::~MainWindow()
{
delete ui;
}
<file_sep># Tablette_Pupitre
| 501acf7d465d135a6b65a754c36989f097571958 | [
"Markdown",
"C++"
] | 2 | C++ | cbureau/Tablette_Pupitre | fceb2a192ede3b8fe923336d1f834158c7a42ddf | 61a4db0f7852775a01377d6a9b7e51b97778299d | |
refs/heads/master | <file_sep># github-finder-profile
<file_sep>$(function(){
$('#searchUser').on('keyup', function(e){
let username = e.target.value;
$.ajax({
url: 'https://api.github.com/users/'+ username,
data:{
client_id:'f3ef447f472fc9dae81e',
client_secret:'<KEY>'
}
}).done(function(user){
$.ajax({
url:"https://api.github.com/users/"+ username+"/repos",
data:{
client_id:'f3ef447f472fc9dae81e',
client_secret:'<KEY>',
sort: 'created: asc',
per_page:5
}
}).done(function(repos){
$.each(repos, function(index, repo){
$('#repos').append(`
<div class="well">
<div class="row">
<div class="col-md-7">
<strong>${repo.name}</strong>: ${repo.description}
</div>
<div class="col-md-3">
<span class="label label-default">Forks: ${repo.forks_count}</span>
<span class="label label-primary">Просмотрело: ${user.watchers_count}</span>
<span class="label label-success">Звезд:${user.stargazers_count}</span>
</div>
<div class="col-md-2">
<a href="${repo.html_url}" target="_blank" class="btn btn-default">Посмотреть</a>
</div>
</div>
</div>
`);
});
});
$('#profile').html(`
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">${user.name}</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3">
<img style="width: 100%"class="thumpnail" src="${user.avatar_url}">
<hr>
<a target="_blank" class="btn btn-primary btn-block" href="${user.html_url}">Просмотреть профиль</a>
</div>
<div class="col-md-9">
<span class="label label-default">Репозиториев: ${user.public_repos}</span>
<span class="label label-primary">Gits: ${user.public_gits}</span>
<span class="label label-success">Подписчики:${user.followers}</span>
<span class="label label-info">Подписан на:${user.following}</span>
<br><br>
<ul class="list-group">
<li class="list-group-item">Компания: ${user.company}</li>
<li class="list-group-item">Блог: ${user.blog}</li>
<li class="list-group-item">Местоположение: ${user.location}</li>
<li class="list-group-item">Created at: ${user.created_at}</li>
</ul>
</div>
</div>
</div>
</div>
<h3 class="page-header">Последние репозитории</h3>
<div id="repos"></div>
`);
});
});
}) | ce23949e89cd4ec961e4233b0e31f85fa51eb7bd | [
"Markdown",
"JavaScript"
] | 2 | Markdown | brian7346/github-finder-profile | 08c3a890f0bd4620fc906fe5f2a89eaf3e7ede71 | 610135225673d16b7be893d8e0430bf0edd6e733 | |
refs/heads/main | <repo_name>RGabrielR/AeroContest<file_sep>/components/redux/reducers/rootReducer.js
import { combineReducers } from "redux";
import productsReducer from "./productsReducer";
import userReducer from './userReducer'
const rootReducer = combineReducers({
products: productsReducer,
user: userReducer
});
export default rootReducer;<file_sep>/components/frontendComponents/elements/sortBarStyles.js
const sortBarStyles = {
control: (base, state) => ({
...base,
background: "#316FBE",
// Overwrittes the different states of border
borderColor: state.isFocused ? "#76711A" : "#316FBE",
// Removes weird border around container
boxShadow: state.isFocused ? null : null,
"&:hover": {
// Overwrittes the different states of border
borderColor: state.isFocused ? "#76711A" : "#316FBE"
},
}),
};
export default sortBarStyles;<file_sep>/components/frontendComponents/elements/options.js
const options = [
{value: 'predefined', label: 'predefined'},
{value: 'highest', label: 'highest'},
{value: 'lowest', label: 'lowest'},
{value: 'canAfford', label: 'canAfford'},
{value: 'cannotAfford', label: 'cannotAfford'}
];
export default options;<file_sep>/components/redux/reducers/userReducer.js
import * as t from '../types';
const initialState = {
loading: false,
user: {},
error: ''
}
const userReducer = (state = initialState , action) => {
switch(action.type) {
case t.FETCH_USER_REQUEST:
return {
...state,
loading: false
}
case t.FETCH_USER_SUCCESS:
return {
loading: true,
user: action.payload,
error: ''
}
case t.FETCH_USER_ERROR:
return {
loading: true,
user: [],
error: action.payload
}
default:
return state;
}
}
export default userReducer;<file_sep>/components/redux/actions/productActions.js
import * as t from '../types';
export const fetchProducts = () => {
return (dispatch) => {
fetch('https://coding-challenge-api.aerolab.co/products',
{ headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY
}}
).then(p => p.json())
.then(data => {
const productsFetch = data
dispatch(fetchProductsSuccess(productsFetch))
})
.catch(error =>
dispatch(fetchProductsError(error)))
};
}
export const fetchProductsRequest = () => {
return {
type: t.FETCH_PRODUCTS_REQUEST
}
};
export const fetchProductsSuccess = products => {
return {
type: t.FETCH_PRODUCTS_SUCCESS,
payload: products
}
};
export const fetchProductsError = error => {
return {
type: t.FETCH_PRODUCTS_ERROR,
payload: error
}
};
export const sortingHighest= products => {
return (dispatch) => {
fetch('https://coding-challenge-api.aerolab.co/products',
{ headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY
}}
).then(p => p.json())
.then(data => {
const productsSorted = data.sort((a, b) => (b.cost - a.cost))
dispatch(productsSortedHighest(productsSorted))
})
}
}
export const productsSortedHighest = products => {
return {
type: t.PRODUCTS_SORTED_HIGHEST,
payload: products
}
}
export const sortingLowest= products => {
return (dispatch) => {
fetch('https://coding-challenge-api.aerolab.co/products',
{ headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY
}}
).then(p => p.json())
.then(data => {
const productsSorted = data.sort((a, b) => (a.cost - b.cost))
dispatch(productsSortedLowest(productsSorted))
})
}
}
export const productsSortedLowest = products => {
return {
type: t.PRODUCTS_SORTED_LOWEST,
payload: products
}
}
export const sortingPredefined= () => {
return (dispatch) => {
fetch('https://coding-challenge-api.aerolab.co/products',
{ headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY
}}
).then(p => p.json())
.then(data => {
const productsFetch = data
dispatch(fetchProductsSuccess(productsFetch))
})
.catch(error =>
dispatch(fetchProductsError(error)))
};
}
export const productsSortedPredefined = products => {
return {
type: t.PRODUCTS_SORTED_PREDEFINED,
payload: products
}
}
export const sortCanAfford = (points) => {
return (dispatch) => {
fetch('https://coding-challenge-api.aerolab.co/products',
{ headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY
}}
).then(p => p.json())
.then(data => {
const affordableProducts = data.filter(prod => prod.cost < points);
dispatch(affordableArray(affordableProducts));
})
}
}
export const affordableArray = products => {
return {
type: t.AFFORDABLE_ARRAY,
payload: products
}
}
export const sortCannotAfford = points => {
return (dispatch) => {
fetch('https://coding-challenge-api.aerolab.co/products',
{ headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY
}}
).then(p => p.json())
.then(data => {
const unaffordableProducts = data.filter(prod => prod.cost > points);
dispatch(unaffordableArray(unaffordableProducts));})
}
}
export const unaffordableArray = products => {
return {
type: t.AFFORDABLE_ARRAY,
payload: products
}
}<file_sep>/components/frontendComponents/User.js
import React, { useEffect } from "react";
import { connect } from "react-redux";
import {
fetchUser,
buy1000,
buy5000,
buy7500,
} from "../redux/actions/userActions";
import Swal from "sweetalert2";
import Image from "next/image";
import Link from "next/link";
const User = (props) => {
const {
user
} = props.user;
useEffect(() => {
props.fetchUser();
}, []);
if (!user) return <div className="lds-circle"> </div>;
const buythousandpoints = () => {
props.buy1000();
Swal.fire("Perfect!", "You gain 1000 points!", "success");
};
const buyfivehundredpoints = () => {
props.buy5000();
Swal.fire("Perfect!", "You gain 5000 points!", "success");
};
const buyseventhousandfivehundredpoints = () => {
props.buy7500();
Swal.fire("Perfect!", "You gain 7500 points!", "success");
};
return (
<div className="bg-gradient-to-r from-green-400 to-blue-500 text-white navbar">
<section className="flex flex-col items-center">
<div className=" flex flex-row">
<h1 className="text-5xl pl-4 cursor-default self-center pb-4 mr-10">
{user.name}
</h1>
<div className="tooltip mt-2">
<Link href="/redeemed-products">
<Image
className="cursor-pointer"
width="100"
height="90"
src="/tesoro.png"
/>
</Link>
<h5 className="pl-2 cursor-default">Reddemed products!</h5>
</div>
</div>
<div className="ml-2 mt-4 bg-gradient-to-r from-gray-400 to-blue-300 hover:from-blue-300 hover:to-gray-400 rounded-lg cursor-default">
<h3 className="m-1 px-4 py-1 border-4 rounded-lg text-black bg-white bg-opacity-80 text-2xl">
{user.points + " "}
points
</h3>
</div>
</section>
<div className="flex flex-col md:flex-row lg:flex-row md:flex-row xl:flex-row 2xl:flex-row justify-evenly items-center w-full items-start 2xl:-mt-6 lg:-mt-6 xl:-mt-6 ">
<div
onClick={() => buythousandpoints()}
className=" bg-gradient-to-r from-gray-400 to-blue-300 hover:from-blue-300 hover:to-gray-400 m-1 px-4 py-1 border-4 rounded-lg text-black border-gray-600 cursor-pointer"
>
buy 1000 points
</div>
<div
onClick={() => buyseventhousandfivehundredpoints()}
className="middle-button bg-gradient-to-r from-gray-400 to-blue-300 hover:from-blue-300 hover:to-gray-400 m-1 px-4 py-1 border-4 rounded-lg text-black border-gray-600 cursor-pointer lg:ml-3 xl:ml-3 2xl:ml-3 order-last md:order-none lg:order-none xl:order-none 2xl:order-none"
>
buy 7500 points
</div>
<div
onClick={() => buyfivehundredpoints()}
className="bg-gradient-to-r from-gray-400 to-blue-300 hover:from-blue-300 hover:to-gray-400 m-1 px-4 py-1 border-4 rounded-lg text-black border-gray-600 cursor-pointer "
>
buy 5000 points
</div>
</div>
</div>
);
};
const mapStateToProps = (state) => ({
user: state.user,
});
const mapDispatchToProps = (dispatch) => {
return {
fetchUser: () => {
dispatch(fetchUser());
},
buy1000: () => {
dispatch(buy1000());
},
buy5000: () => {
dispatch(buy5000());
},
buy7500: () => {
dispatch(buy7500());
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(User);
<file_sep>/components/redux/actions/userActions.js
import * as t from '../types';
export const fetchUser = () => {
return (dispatch) => {
fetch('https://coding-challenge-api.aerolab.co/user/me',
{ headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY
}}
).then(p => p.json())
.then(data => {
const userFetch = data
dispatch(fetchUserSuccess(userFetch))
})
.catch(error =>
dispatch(fetchUserError(error)))
};
}
export const fetchUserSuccess = user => {
return {
type: t.FETCH_USER_SUCCESS,
payload: user
}
};
export const fetchUserError = error => {
return {
type: t.FETCH_USER_ERROR,
payload: error
}
};
export const buy1000 = () => {
return async (dispatch) => {
await fetch('https://coding-challenge-api.aerolab.co/user/points',
{
method: 'POST',
headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY,
"Content-Type": "application/json"
},
body: JSON.stringify({"amount": 1000})
}
);
dispatch(fetchUser());
console.log("llego aca")
}
};
export const buy5000 = () => {
return async (dispatch) => {
await fetch('https://coding-challenge-api.aerolab.co/user/points',
{
method: 'POST',
headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY,
"Content-Type": "application/json"
},
body: JSON.stringify({"amount": 5000})
}
);
dispatch(fetchUser());
console.log("llego aca")
}
};
export const buy7500 = () => {
return async (dispatch) => {
await fetch('https://coding-challenge-api.aerolab.co/user/points',
{
method: 'POST',
headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY,
"Content-Type": "application/json"
},
body: JSON.stringify({"amount": 7500})
}
);
dispatch(fetchUser());
console.log("llego aca")
}
}
<file_sep>/components/redux/actions/redeemActions.js
import * as t from '../types';
import {fetchUser} from './userActions';
export const redeemProduct = id => {
return async (dispatch) => {
await fetch('https://coding-challenge-api.aerolab.co/redeem',
{
method: 'POST',
headers: {
'Authorization': process.env.NEXT_PUBLIC_AUTHKEY,
"Content-Type": "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({"productId": id})
}
);
console.log(id);
dispatch(fetchUser());
}
}
| ec71023a9cb7428afb67699a56732273d690360e | [
"JavaScript"
] | 8 | JavaScript | RGabrielR/AeroContest | ea9cb9e9b6a8513ce5f58c2898cf118638da0b56 | 13ef36a6cb103b313ccb00b03155cb63f877908d | |
refs/heads/main | <file_sep>CC=gcc
DIRS=build build/client build/server
all: print_vars client server
print_vars:
@echo "Using C compiler: " $(CC)
client: src/client.c build
$(CC) -o build/client/$@ $<
server: src/server.c build
$(CC) -o build/server/$@ $< -lpthread
clean:
$(shell rm -rf $(DIRS))
build:
$(shell mkdir -p $(DIRS))
<file_sep>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
static void print_command()
{
printf("\nEnter file name to be uploaded to server\n");
printf("$>");
}
static void print_usage()
{
printf("Client application must be started with following arguments\n");
printf("./client <IP_OF_SERVER> <PORT>\n");
}
static int connect_to_server(char* ip, char* port, int socket_fd)
{
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(ip);
servaddr.sin_port = htons(atoi(port));
for (int i = 1; i <= 10; ++i) {
if (connect(socket_fd, (struct sockaddr*)&servaddr, sizeof(servaddr))) {
printf("Connection failed retrying, attempt %d!\n", i);
sleep(2);
}
else
return 0;
}
return -1;
}
int main(int argc, char* argv[])
{
if (argc != 3) {
print_usage();
exit(1);
}
char* ip = argv[1];
char* port = argv[2];
FILE* file = NULL;
char buffer[4096];
while (1) {
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd == -1) {
perror("Error: ");
exit(1);
}
int rc = connect_to_server(ip, port, socket_fd);
if (rc == -1) {
printf("Connection to %s:%s failed terminating application!\n", ip, port);
close(socket_fd);
exit(1);
}
print_command();
// Optimization name points to buffer + 1 address
// From buffer perspective name will be stored buffer+1
// This is used to reuse resources since buffer[0] will containt file name size
char* name = buffer + 1;
// Handle CTRL + D and CTRL+Z in safe manner
if (scanf("%s", name) == EOF) {
clearerr(stdin);
continue;
}
buffer[0] = strlen(name);
// Opening file using 'rb' option since we do not actually need to modify file content.
file = fopen(name, "rb");
if (file == NULL) {
printf("Could not open file %s", buffer);
close(socket_fd);
continue;
}
printf("File: %s, Size of message: %d\n", buffer, (int)strlen(buffer));
if (send(socket_fd, buffer, buffer[0] + 1, 0) < 0) {
perror("Error: ");
close(socket_fd);
continue;
}
while (!feof(file)) {
// Reuse same buffer since it's max Buffer size 4096 as we need it
int n = fread(buffer, 1, 4096, file);
if (send(socket_fd, buffer, n, 0) < 0) {
perror("Error: ");
close(socket_fd);
continue;
}
}
fclose(file);
close(socket_fd);
}
return 0;
}
<file_sep># DSA
Homework for DSA
Requirements:
make
gcc compiler (with PTHREAD support)
Build:
- make all
- make client (Compile only client application)
- make server (Compile only server application)
- make clean (Clean build directory)
Applications are installed inside build directory build/client/ build/server/ under name client and server respectively.
Usage of client application
- ./client ip port
- eg: ./client 127.0.0.1 1337
Usage of server application
- ./server port MODE(THREAD || PROC)
- eg: ./server 1337 THREAD
MODE:
Server application can run in two modes
- 1. THREAD: Each new client that connnects to application will be handled in different thread.
- 2. PROC: Each new client that connects to application will be handled in new proccess.
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
enum operation_mode {
THREAD = 0,
PROC = 1,
};
struct thread_arguments {
int client_socket_fd;
};
enum operation_mode OPERATION_MODE = PROC;
static void handler_internal(int client_fd)
{
char buf[4096];
// Read 1 byte that indicates size of file name.
char file_name_size;
int n = recv(client_fd, &file_name_size, 1, 0);
// Always prepare yourself for worst
if (n == 0 || n == -1) {
close(client_fd);
return;
}
// Read file_name_size bytes from socket to form a file name.
n = recv(client_fd, buf, file_name_size, 0);
// Always prepare yourself for worst
if (n == 0 || n == -1) {
close(client_fd);
return;
}
printf("Creating file %s\n", buf);
FILE* file = NULL;
file = fopen(buf, "wb");
if (file == NULL) {
close(client_fd);
perror("Error: ");
return;
}
while ((n = recv(client_fd, buf, 4096, 0)) && n != 0) {
fwrite(buf, sizeof(char), n, file);
}
fclose(file);
close(client_fd);
printf("Succes!\n");
}
void* thread_handler(void* thread_args)
{
pthread_detach(pthread_self());
int client_fd = ((struct thread_arguments*)thread_args)->client_socket_fd;
free(thread_args);
handler_internal(client_fd);
return NULL;
}
static void handler(int client_socket_fd)
{
if (OPERATION_MODE == THREAD) {
pthread_t tid;
struct thread_arguments* thread_args;
if ((thread_args = (struct thread_arguments*)malloc(sizeof(struct thread_arguments))) == NULL) {
perror("Error: ");
exit(1);
}
thread_args->client_socket_fd = client_socket_fd;
pthread_create(&tid, NULL, thread_handler, (void*)thread_args);
}
else if (OPERATION_MODE == PROC) {
if (fork() == 0) {
handler_internal(client_socket_fd);
exit(0);
}
else {
perror("Error: ");
}
}
}
static void print_usage()
{
printf("Server application must be started with following arguments\n");
printf("./server <PORT> <MODE: THREAD || PROC >\n");
printf("Example ./server 1337 THREAD\n");
}
int main(int argc, char* argv[])
{
if (argc != 3) {
print_usage();
exit(1);
}
char* port = argv[1];
char* mode = argv[2];
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd == -1) {
perror("Error: ");
exit(1);
}
if (strcmp(mode, "THREAD") == 0) {
printf("Server will run in thread mode!\n");
OPERATION_MODE = THREAD;
}
else {
printf("Server will run in new proccess mode!\n");
OPERATION_MODE = PROC;
}
struct sockaddr_in server_addr;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(port));
printf("> Starting server...\n");
if (bind(socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("Error: ");
return 1;
}
if (listen(socket_fd, 10) < 0) {
perror("Error: ");
return 1;
}
while (1) {
printf("\nWaiting for connection!\n");
int client_socket_fd;
struct sockaddr_in client_address;
unsigned int client_lenght;
client_lenght = sizeof(client_address);
if ((client_socket_fd = accept(socket_fd, (struct sockaddr*)&client_address, &client_lenght))) {
printf("Handling client %s\n", inet_ntoa(client_address.sin_addr));
handler(client_socket_fd);
}
}
close(socket_fd);
return 0;
} | 93fa50ef47ae02205afd544177318a3825b1e0cd | [
"Markdown",
"C",
"Makefile"
] | 4 | Makefile | dosuperuser/DSA | 95b52ceba47105f328928f7ddf99befb38ece89b | 640d73e8082e0f39f24cf5cb1fb0aed30e73ed75 | |
refs/heads/master | <repo_name>Vanezio/testForPTM<file_sep>/README.md
# testForPTM
Field in this app presented as a table of divs or a 2d matrix of divs( hope that I'm correct in this definition ).<br/>
Searching function operate with indexes of cells and their rows.<br/>
To "delete" a cell I'm using a css property "visibility" with value "hidden", so cell will be hidden but it's place in a field will be saved.
Searching functions you can find at the bottom of the script at the .\scripts\index.js
Link on git hub pages https://vanezio.github.io/testForPTM/
Click: delete cell and all neighbour cells from the same group
<file_sep>/scripts/index.js
// field for cells
const field = document.querySelector('.play-field');
//Array with classes for different cell groups
const classesArr = ["flag", "circle", "cross", "square"]
//function returns random number
const randomiz = (amount) => {
return randomNumb = Math.round(Math.random()* (amount - 1) );
};
// !!!!!!!! P A R T O F T H E C O D E W H E R E F I E L D I S G E N E R A T E D !!!!!!!!!!!!!!!!!!!!!!
// function for generating new field of cells 6x7
function generateCells (){
// variables for rows and cells count
let rowsCount = 0,
cellCount = 0
// amount of cells on current field
let cellAmount = 6 * 7
while(rowsCount < 7){
// creating a row
let row = document.createElement("div")
row.className = "field-row"
// setting data attribute which contains row's index
row.setAttribute("data-number", `${rowsCount + 1}`)
field.appendChild(row)
while(cellCount < 6){
// creating a cell
let cell = document.createElement("div")
cell.className = "field-cell"
// setting data attribute which contains cell's index
cell.setAttribute("data-number", `${cellCount + 1}`)
// setting data attribute which contains cell's status '0'= without a group yet
cell.setAttribute("data-status", `0`)
//Event for left mouse button
cell.addEventListener("click", (event) => {
processCell(event.target)
})
row.appendChild(cell)
cellCount++
}
rowsCount++
// clear counter for the next row
cellCount = 0
}
// variable with all cells from the field
const cells = document.querySelectorAll('.field-cell');
// calling function which will set group for all of our cells
setCells(cellAmount, cells)
}
//function to set groups to all cells
const setCells = (amount, cellsArr) => {
// cell's counter
let cellsCount = 0;
while (cellsCount < amount) {
// variable with index of a random cell
const cellI = randomiz(amount);
// variable with index of a random group for previous chosen cell
const groupI = randomiz(4);
if (cellsArr[cellI].dataset.status !== '1') {
// data-status '1' marks cells which already have a group
cellsArr[cellI].dataset.status = '1';
// setting class of a chosen group
cellsArr[cellI].classList.add(`${classesArr[groupI]}`)
cellsCount++;
}
}
}
generateCells()
// !!!!!!!!!!!!!!!! F U N C T I O N S F O R S E A R C H I N G A N D D E L E T I N G A G R O U P O F C E L L S !!!!!!!!!!!!!!!!!!!!!!!!
//function to delete a cell and all neighbor cells from a same group around target element
function processCell(elem){
if(elem.dataset.status !== "2"){
// deleting a target cell from the field but saving it's place in a row
elem.style.visibility = "hidden"
// data-status '2' marks already processed cells
elem.setAttribute('data-status', '2')
// target cell's parent row
const elemParent = elem.parentElement
// target cell's index
const startPoint = +elem.dataset.number
// array with target's parent row's neighbour rows
const parentNNeighs = [elemParent.previousElementSibling, elemParent.nextElementSibling]
// array with target's and neighbour cells indexes
const neededCellsArr = [startPoint, startPoint - 1, startPoint + 1]
// calling function which will check all the neigbour cells
lookAround(neededCellsArr, elemParent, parentNNeighs, elem.classList[1])
}
}
// function which checks all cells around target element
function lookAround( numbers, mainRow, neighborRows, elemClass) {
// checking all vertical neighbours
neighborRows.forEach((row) => {
// checking if a row exist and if a cell is with the same class as our target cell
if(row && row.children[numbers[0] - 1].classList.contains(elemClass)){
// processing a cell
processCell(row.children[numbers[0] - 1])
}
})
// checking all horizontal neighbours
numbers.forEach((elem) => {
// checking if a cell exist and if a cell is with the same class as our target cell
if(elem > 0 && elem < 7 && mainRow.children[elem - 1].classList.contains(elemClass)){
// processing a cell
processCell(mainRow.children[elem - 1])
}
})
} | b7888df96bfae7b69e37d3da08637ed9a36e4864 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Vanezio/testForPTM | 72d36c21d3d1de6714d96d33c9cbe7697a20336c | a4155cdd8fdfaf5e68d547c48e8ba85404103ff5 | |
refs/heads/master | <repo_name>phillippaik/tapper<file_sep>/tapper/ViewController.swift
//
// ViewController.swift
// tapper
//
// Created by <NAME> on 3/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//sadad
import UIKit
class ViewController: UIViewController {
// Properties
var maxTaps = 0;
var currentTaps = 0;
// Outlets
@IBOutlet weak var overlayView: UIView!
@IBOutlet weak var logoImg: UIImageView!
@IBOutlet weak var howManyTapsText: UITextField!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var tapButton: UIButton!
@IBOutlet weak var tapsLabel: UILabel!
@IBAction func onPlayButtonPressed(sender: AnyObject) {
if howManyTapsText.text != nil && howManyTapsText.text != "" {
maxTaps = Int(howManyTapsText.text!)!;
currentTaps = 0;
logoImg.hidden = true
playButton.hidden = true
howManyTapsText.hidden = true
tapButton.hidden = false
tapsLabel.hidden = false
overlayView.hidden = false
updateTaps()
}
}
@IBAction func coinPressed(sender: AnyObject) {
currentTaps++
updateTaps()
if isGameOver() {
gameOver()
}
}
func gameOver(){
maxTaps = 0;
currentTaps = 0;
howManyTapsText.text = ""
logoImg.hidden = false
playButton.hidden = false
howManyTapsText.hidden = false
tapsLabel.hidden = true
tapButton.hidden = true
overlayView.hidden = true
}
func updateTaps() {
tapsLabel.text = "\(currentTaps) Taps"
}
func isGameOver() -> Bool {
if currentTaps >= maxTaps {
return true
} else {
return false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 31c45720c6b5987b7c342bde6923ec91b291aca4 | [
"Swift"
] | 1 | Swift | phillippaik/tapper | 91a9180b2e3e0afd91a8c28976c1dc6f6a5a166d | dc3396ce49d99d61a2ea145134e81425c9b634b2 | |
refs/heads/master | <file_sep>import React from 'react';
import './homepage.stylesheet.scss';
import { Switch ,Route, Link } from 'react-router-dom';
import Counter from './counter.component';
//Logos
import meditation from './assets/lifelogo.png';
import sprints from './assets/sprints.svg';
import money from './assets/money.svg';
//Bootstrap
import { Container, Row, Col, Button } from 'react-bootstrap';
//Documentation
//https://react-bootstrap.github.io/components/buttons/
class Home extends React.Component{
constructor(props){
super(props);
this.componentDidMount = this.componentDidMount.bind(this);
/*
Redirects
*/
this.redirectCounter = this.redirectCounter.bind(this);
this.redirectSprint = this.redirectSprint.bind(this);
}
redirectCounter(){
console.log(window.location.origin);
this.props.history.push("/counter");
}
redirectSprint(){
this.props.history.push("/sprint");
}
componentDidMount(){
}
render(){
return (
<Container>
<Row>
<h1 class="header">Life</h1>
</Row>
<Row>
<Col>
<h3>Spritual</h3>
</Col>
<Col>
<Button variant="light" onClick={this.redirectCounter}>
<img class="logo" src={meditation} alt="counter" />
</Button>
</Col>
</Row>
<Row>
<Col>
<h3>Sprint-Management</h3>
</Col>
<Col>
<Button variant="light" onClick={this.redirectSprint}>
<img class="logo" src={sprints} alt="sprint" />
</Button>
</Col>
</Row>
<Row>
<Col>
<h3>Money-Management</h3>
</Col>
<Col>
<Button variant="light">
<img class="logo" src={money} alt="Money" />
</Button>
</Col>
</Row>
</Container>
);
}
}
export default Home;<file_sep>var constants = {
server: '192.168.0.100',
//server: 'localhost',
port: 3030
};
module.exports = constants;<file_sep>import logo from './logo.svg';
import './App.css';
import { Switch ,Route, Link } from 'react-router-dom';
/*
App Components
*/
import Counter from './components/counter.component';
import Home from './components/homepage.component';
//import Sprint from './components/sprint/sprint.component';
import SprintBasic from './components/sprint/sprintbasic.component';
function App() {
return (
<div className="App">
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/counter' component={Counter} />
<Route exact path='/sprint' component={SprintBasic} />
</Switch>
</div>
);
}
export default App;
<file_sep>import React from 'react';
import './sprint.component.scss';
import { Button,Container,Row } from 'react-bootstrap';
import {SprintCreate} from './sprintcreate.component';
class Sprint extends React.Component{
constructor(){
super();
this.state = {
addtask:false,
tasks: []
}
this.handleAddTask = this.handleAddTask.bind(this);
this.insertNewTask = this.insertNewTask.bind(this);
}
handleAddTask(){
this.setState({
addtask: !this.state.addtask
});
}
insertNewTask(){
alert('comming');
/*var task = {
'title':'test',
'desc':'test1',
'progress':0.0,
'completed':false
}
var temp = this.state.tasks.push(task);
this.setState({
tasks : temp,
addtask:false
});*/
}
render(){
return(
<Container>
<Row>
<h1>Sprint</h1>
</Row>
<Row>
<SprintCreate
title="Sprint create"
addtask={this.state.addtask}
tasks={this.state.tasks}
handleAddTask={this.handleAddTask}
insertNewTask={this.insertNewTask}
/>
</Row>
</Container>
);
}
}
export default Sprint;<file_sep>import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaView, StyleSheet, Text, View, Image } from 'react-native';
export default function App() {
let PlayFairDisplayItalic = require('./assets/fonts/PlayfairDisplay-Italic.ttf')
return (
<SafeAreaView>
<View style={styles.container}>
<View style={styles.headerview}>
<Image style={styles.logo} source={require('./assets/lifelogo.png')} />
<Text style={styles.projectname}>Life</Text>
</View>
<View>
<Text>Body</Text>
</View>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
color:'black',
flexDirection:'column',
justifyContent:'flex-start'
},
headerview: {
backgroundColor:'#244068',
flexDirection:'row'
},
logo: {
height: 50,
width: 50
},
projectname: {
color:'black',
fontWeight: 'bold',
fontSize: 30,
fontFamily:'PlayFairDisplayItalic',
alignContent:'center'
}
});
<file_sep>#alpine image
FROM node:alpine
#working directory
WORKDIR /usr/app
#installation dependencies
#COPY ./package.json ./
#RUN npm install
#COPY ./index.js ./
#COPY src ./
COPY ./ ./
RUN rm -rf node_modules
RUN npm install
#npm start engine
CMD ["npm","start"]<file_sep>const mongoose = require('mongoose');
const CONSTANTS = require('./appconstants');
mongoose.connect(`mongodb://${CONSTANTS.DATABASE_SERVER}:${CONSTANTS.DATABASE_PORT}/${CONSTANTS.DATABASE}`,{useNewUrlParser: true, useUnifiedTopology: true});
/**
* Task schema
*/
var taskSchema = mongoose.Schema({
name: String,
desc: String,
progress: Number,
completed: Boolean,
start:{
type: Date,
default: Date.now
},
end: Date
});
/**
* Sprint schema
*/
var sprintSchema = mongoose.Schema({
name:String,
desc:String,
start:{
type:Date,
default:Date.now
},
end:Date,
tasksCount:Number,
progress:Number,
completed:Boolean,
tasks:[{
type: mongoose.Schema.Types.ObjectId,
ref:'Task'
}]
});
// Task & Sprint
var Task = mongoose.model('task',taskSchema);
var Sprint = mongoose.model('sprint',sprintSchema);
class SprintORM {
/**
* Creates the sprint and inserts the tasks. But not working
*/
async create(data){
//console.log("comming to data");
//console.log(mongoose.connection.readyState);
let promiseTask = function(resolve,reject){
this.insertAllTasks(data.tasks).then((tasksdata)=>{
var temp = [];
Object.keys(tasksdata).forEach(element=>{
temp.push(tasksdata[element]);
});
var sprint = new Sprint(data);
sprint.save().then(()=>{
resolve(sprint);
}).catch((err)=>{
reject(err);
});
}).catch((err)=>{
reject(err);
});
}
return await new Promise(promiseTask);
}
/**
*
* @param {Sprint} data
* This method should be called to create sprint
* Warning: must insert after tasks once inserted. Otherwise tasks will update use update method.
*/
insertSprint(data){
var promiseSprint = function(resolve,reject){
var sprint = new Sprint(data);
sprint.save().then(()=>{
resolve(sprint);
}).catch((err)=>{
reject(err);
});
}
return new Promise(promiseSprint);
}
/**
* This method used to get sprint completed tag
* @param {Sprint} completed
*/
async getSprintsByCompleted(completed){
var records = await Sprint.find().where('completed').in(completed).exec();
console.log(records);
return records;
}
/**
* This method will update the sprint
* @param {Sprint} sprint
*/
async updateSprint(sprint){
const filter = {"_id":sprint._id};
delete sprint["_id"];
let doc = await Sprint.findOneAndUpdate(filter,sprint,{new:true});
return doc;
}
/**
* This method will insert the tasks array
* @param {[Task]} tasks
*/
//https://www.tutorialkart.com/nodejs/mongoose/insert-multiple-documents-to-mongodb/
insertAllTasks(tasks){
var promiseTask = function(resolve,reject){
Task.collection.insertMany(tasks,function(err,docs){
if(err){
reject(err);
}else{
resolve(docs.insertedIds);
}
});
}
return new Promise(promiseTask);
}
/**
* This method will single task
* @param {Task} task
*/
singleTask(task){
var promiseTask = function(resolve,reject){
var temp = new Task(task);
temp.save().then(()=>{
resolve(temp._id);
}).catch(()=>{
reject("task not saved");
});
return;
}
return new Promise(temp);
}
/**
* This method will give array of tasks
* @param {Task} arr
*/
async getTasks(arr){
Task.findByIdAndUpdate
var records = await Task.find().where('_id').in(arr).exec();
console.log(records);
return records;
}
/**
* This will update single task
* @param {Task} task
*/
async updateTask(task){
const filter = {"_id":task._id};
delete task["_id"];
let doc = await Task.findOneAndUpdate(filter,task,{new:true});
return doc;
}
}
module.exports = SprintORM;<file_sep>var CONSTANTS = {
SERVERPORT: 3030,
DATABASE_SERVER: 'mongodb',
//DATABASE_SERVER: 'localhost',
//DATABASE_SERVER: '192.168.0.100',
DATABASE_PORT: 27017,
DATABASE:'LifeDev'
}
module.exports = CONSTANTS;<file_sep># Life
Life project
test
<file_sep>const express = require('express')
var cors = require('cors')
const app = express()
var bodyParser = require('body-parser')
app.use(cors())
app.use(bodyParser.json())
const SprintORM = require('./src/sprint')
const CONSTANTS = require('./src/appconstants');
/**
* Introduction Message will be printed
*/
app.get('/',function(req,res){
res.json({'Message':'Welcome to Life Backend Server'});
});
/**
* Sprint & Tasks insert
*/
app.post("/totalsprint",function(req,res){
var body = req.body;
body.taskcount = body.tasks.length;
body.start = new Date
body.tasks.forEach((task) => {
task.start= new Date
});
var sprint = new SprintORM();
sprint.create(body).then((data)=>{
res.status(201).json(body);
}).catch((err)=>{
res.status(500).json(err);
});
});
/**
* Creates the sprint
*/
app.post("/sprint",(req,res)=>{
var body = req.body;
body.taskcount = body.tasks.length;
body.start = new Date
var sprint = new SprintORM();
sprint.insertSprint(body).then((data)=>{
res.status(200).json(body);
}).catch((err)=>{
res.status(500).json(err);
});
});
/**
* Retrives the sprints which are open.
*/
app.get("/sprint/open",(req,res)=>{
res.setHeader('Content-Type','application/json');
var sprint = new SprintORM();
sprint.getSprintsByCompleted(false).then((records)=>{
res.status(200).json(records);
}).catch((err)=>{
res.status(500).json(err);
});
});
/**
* Retrives the sprints which are close.
*/
app.get("/sprint/close",(req,res)=>{
res.setHeader('Content-Type','application/json');
var sprint = new SprintORM();
sprint.getSprintsByCompleted(true).then((records)=>{
res.status(200).json(records);
}).catch((err)=>{
res.status(500).json(err);
});
});
/**
* sprint which updated
*/
app.put("/sprint/update",(req,res)=>{
var body = req.body;
var sprint = new SprintORM();
sprint.updateSprint(body).then((sprint)=>{
res.status(200).json(sprint);
}).catch((err)=>{
res.status(500).json(err);
});
});
/**
* Tasks will be created
*/
app.post("/tasks",(req,res)=>{
var body = req.body;
body.tasks.forEach((task)=>{
task.start = new Date
});
var sprint = new SprintORM();
sprint.insertAllTasks(body.tasks).then((data)=>{
res.status(200).json(body);
}).catch((err)=>{
res.status(500).json(err);
});
});
/**
* Retrives the tasks
*/
app.get("/tasks",(req,res)=>{
var body = req.body;
var sprint = new SprintORM();
sprint.getTasks(body.tasks).then((records)=>{
res.status(200).json(records);
}).catch((err)=>{
res.status(500).json(err);
});
});
/**
* update the task
*/
app.put("/task/update",(req,res)=>{
var body = req.body;
var sprint = new SprintORM();
sprint.updateTask(body).then((task)=>{
res.status(200).json(task);
}).catch((err)=>{
res.status(500).json(err);
});
});
app.listen(CONSTANTS.SERVERPORT);<file_sep>import React from 'react';
import './counter.stylesheet.scss';
class Counter extends React.Component{
constructor(props){
super(props);
this.state = {
counter: 5,
value:0
}
this.negative = this.negative.bind(this);
this.positive = this.positive.bind(this);
this.changeCounterValue = this.changeCounterValue.bind(this);
}
negative(){
var updatedValue = this.state.value-this.state.counter;
if(updatedValue < 0){
this.setState({
value: 0
});
}else{
this.setState({
value: updatedValue
});
}
}
positive(){
var updatedValue = this.state.value+this.state.counter;
this.setState({
value: updatedValue
});
}
changeCounterValue(e){
console.log(e);
var updatedValue = parseInt(e.target.value);
if(Number.isNaN(updatedValue) || updatedValue == undefined || updatedValue < 0){
updatedValue = 5;
}
this.setState({
counter: updatedValue
});
}
render(){
return (
<div class='row'>
<div class='col-md-12'>
<h1>Counter</h1>
<form>
<div class="form-group">
<button type="button" onClick={this.negative} class="btn btn-light" >-</button>
<input type="number" onChange={this.changeCounterValue} value={this.state.counter} min="0" max="1000" step="1"/>
<button type="button" onClick={this.positive} class="btn btn-light">+</button>
</div>
</form>
</div>
<div class='col-md-12'>
<p>{this.state.value}</p>
</div>
</div>
);
}
}
export default Counter;<file_sep>import React from 'react';
import { Button,Container,Row, Form } from 'react-bootstrap';
import {TaskCreate} from './taskcreate.component';
export const SprintCreate = props => (
<Container>
<Row>
<h1>{props.title}</h1>
</Row>
<Row>
<Form>
<Form.Group>
<Form.Label>Name </Form.Label>
<Form.Control type="text" placeholder="Enter Sprint Name" />
</Form.Group>
<Form.Group>
<Form.Label>Enter Description</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
<Form.Group>
<Button onClick={props.handleAddTask}>
+
</Button>
{props.addtask ?
<TaskCreate title='Task'
insertNewTask={props.insertNewTask} />
:
<p>{JSON.stringify(props)}</p>
}
</Form.Group>
{props.addtask ?
'' :
<Button variant="primary" type="submit">
Submit
</Button>
}
</Form>
</Row>
</Container>
); | f5a24102abae6284c53095a895abc42b6b0f2504 | [
"JavaScript",
"Dockerfile",
"Markdown"
] | 12 | JavaScript | ethender/Life | fb5001509892fa878c1387c560c4f5a3af3b34f7 | 4a9075d70c8db58bbd3d3608f7c99eb254259c6d | |
refs/heads/master | <file_sep>package com.example.acer.auctionsystem;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Pass extends AppCompatActivity {
Button btnMain;
//Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pass);
btnMain = (Button) findViewById(R.id.btnMain);
// btnSend=(Button)findViewById(R.id.btnSend);
btnMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Pass.this,MainActivity.class));
}
});
}
}
<file_sep>package com.example.acer.auctionsystem;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginScreen extends AppCompatActivity {
Button btnMain;
EditText txtId;//cevap yerindeki XXXX yazısının oldugu yer.
EditText txtPass;
Button btnLg;
Button button;
Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
btnMain =(Button)findViewById(R.id.btnMain);
btnLg =(Button)findViewById(R.id.btnLg);
txtId=(EditText)findViewById(R.id.txtYazi2);
txtPass=(EditText)findViewById(R.id.txtYazi3);
button =(Button)findViewById(R.id.button);
button2 =(Button)findViewById(R.id.button2);
final String User1="T";
final String User2="<NAME>";
final String Tech1="Tec Person";
final String Tech2="S<NAME>";
final String UserPass1="1";
final String UserPass2="<PASSWORD>";
final String TechPass1="<PASSWORD>";
final String TechPass2="<PASSWORD>";
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txtId.setText( Global.arrayListUseri.get(0));
txtPass.setText( Global.arrayListUserp.get(0));
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txtId.setText(Tech1);
txtPass.setText(TechPass1);
}
});
btnMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(LoginScreen.this,MainActivity.class));
}
});
btnLg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String Id= txtId.getText().toString();
String Pass =txtPass.getText().toString();
if(Id.equals(User1) && Pass.equals(UserPass1)||(Id.equals(User2) && Pass.equals(UserPass2))||Id.equals(Global.arrayListUseri.get(0)) && Pass.equals(Global.arrayListUserp.get(0))) {
startActivity(new Intent(LoginScreen.this, User.class));
}
if(Id.equals(Tech1) && Pass.equals(TechPass1)||(Id.equals(Tech2) && Pass.equals(TechPass2))){
startActivity(new Intent(LoginScreen.this, Tech.class));
}
}
});
}
}
<file_sep>package com.example.acer.auctionsystem;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends AppCompatActivity {
Button btnMain;
EditText Pass2;
EditText Pass;
EditText Yid;
EditText Mail;
String id;
String pass;
Button btnRegisterU;
Button btnRegisterV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
btnMain= (Button)findViewById(R.id.btnMain);
btnRegisterV =(Button)findViewById(R.id.btnRegisterv);
btnRegisterU =(Button)findViewById(R.id.btnRegisterU);
Yid=(EditText)findViewById(R.id.Yid);
Mail=(EditText)findViewById(R.id.Mail);
Pass=(EditText)findViewById(R.id.Pass);
Pass2=(EditText)findViewById(R.id.Pass2);
btnMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Register.this,MainActivity.class));
}
});
btnRegisterU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id= Yid.getText().toString();
Global.arrayListUseri.add(id);
Yid.setText("");
String pass= Pass.getText().toString();
Global.arrayListUserp.add(pass);
Pass.setText("");
Pass2.setText("");
Toast.makeText(getApplicationContext(), "User Registration Successful\n", Toast.LENGTH_LONG).show();
}
});
btnRegisterV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id= Yid.getText().toString();
Global.arrayListRegi.add(id);
Yid.setText("");
String pass= Pass.getText().toString();
Global.arrayListRegp.add(pass);
Pass.setText("");
Pass2.setText("");
Toast.makeText(getApplicationContext(), "Vendor Registration Successful\n", Toast.LENGTH_LONG).show();
}
});
}
}
| 8f308c1b96dd10c6ca915d7dd029e58d7bb57e0d | [
"Java"
] | 3 | Java | talhakkoc/Auction-System | 974c30f7ea9d0ba7ef6d7516477efddb9f8a3612 | 5838571ac16546059186c181f37c1d447b036b7e | |
refs/heads/master | <repo_name>mchauhanx/MobileAutomation<file_sep>/bin/src/main/resources/global.properties
global.environment.name=uat
global.browser.name= chrome
global.capability.platform=android
global.driver.wait = 10
global.capability.devicename=Nexus S
global.capability.deviceid=emulator-5554
global.capability.platform.version=7.0
global.capability.apppackage=com.uat.meedbankingclub
global.capability.appactivity=com.uat.meedbankingclub.MainActivity
<file_sep>/src/test/java/stepDefinations/GenericSteps.java
package stepDefinations;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.cucumber.listener.Reporter;
import com.gargoylesoftware.htmlunit.javascript.host.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebElement;
import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.After;
import cucumber.api.java.en.Given;
import io.appium.java_client.*;
import io.appium.java_client.android.Activity;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.StartsActivity;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.touch.offset.PointOption;
import net.prodigylabs.config.ObjectRepository;
import net.prodigylabs.driver.CapabilitiesGenerator;
import net.prodigylabs.handlers.ScreenshotHandler;
import net.prodigylabs.test.BaseTest;
import org.junit.Assert;
public class GenericSteps extends BaseTest{
//public AndroidDriver<MobileElement> driver;
WebDriver driver;
public WebDriverWait wait;
DesiredCapabilities caps = new DesiredCapabilities();
ScreenshotHandler screenshot = null;
String sName = null;
@Before
public void setup(Scenario scenario) throws Exception {
//System.out.println("Executing Before of Step Definition");
sName=scenario.getName();
}
//------------------LAUNCHING APP---------------------
@Given("^user launches the app in \"(.*?)\" device$")
public void user_launches_the_app_in_device(String platform) throws Throwable {
driver = CapabilitiesGenerator.getInstance().launchApp(platform);
screenshot = new ScreenshotHandler(driver);
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------ENTERING EMAIL---------------------
@Given("^user enters email \"(.*?)\"$")
public void user_enters_email(String arg1) throws Throwable {
wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("android.widget.EditText"))).sendKeys(arg1);
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------BUTTON CLICK---------------------
@Given("^user clicks on button \"([^\"]*)\"$")
public void user_clicks_on_button(String button_name) throws Throwable {
try
{
String button_value = button_name.split("_")[0];
Thread.sleep(1000);
driver.findElement(By.xpath("//*[contains(@text, '"+button_value+"')]")).click();;
}
catch(Exception e)
{
driver.findElement(ObjectRepository.getobjectLocator(button_name)).click();
System.out.println("Inside Catch , Success");
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------LABEL CLICK---------------------
@Given("^user clicks on label \"([^\"]*)\"$")
public void label(String label_name) throws Throwable {
try
{
driver.findElement(ObjectRepository.getobjectLocator(label_name)).click();
}
catch(Exception e)
{
String label_value = label_name.split("_")[0];
driver.findElement(By.xpath("//*[contains(@text, '"+label_value+"')]")).click();;
System.out.println("Inside Catch , Success");
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------ENTERING TEXT IN TEXTBOX ---------------------
@SuppressWarnings("rawtypes")
@Given("^user enters text \"([^\"]*)\" in textbox \"([^\"]*)\"$")
public void user_enters_text_in_textbox(String text_value, String textbox_name) throws Throwable {
try {
if(textbox_name.contentEquals("AMOUNT_TO_BE_MOVED") || textbox_name.contentEquals("AMOUNT_TO_BE_SENT"))
{
driver.findElement(ObjectRepository.getobjectLocator(textbox_name)).click();
driver.findElement(ObjectRepository.getobjectLocator(textbox_name)).sendKeys(text_value);
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.SPACE));
}
else
{
driver.findElement(ObjectRepository.getobjectLocator(textbox_name)).clear();
driver.findElement(ObjectRepository.getobjectLocator(textbox_name)).sendKeys(text_value);
}
}
catch(Exception e) {
driver.findElement(ObjectRepository.getobjectLocator(textbox_name)).clear();
driver.findElement(ObjectRepository.getobjectLocator(textbox_name)).sendKeys(text_value);
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------DROPDOWN SELCTION---------------------
@Given("^user selects option \"([^\"]*)\" from the dropdown \"([^\"]*)\"$")
public void user_selects_option_from_the_dropdown(String dropdown_value, String dropdown_name) throws Throwable {
try
{
driver.findElement(ObjectRepository.getobjectLocator(dropdown_name)).click();
Thread.sleep(2000);
driver.findElement(ObjectRepository.getobjectLocator(dropdown_value)).click();
}
catch(Exception e)
{
/*String dd_value = dropdown_name.split("_")[0];
driver.findElement(By.xpath("//*[contains(@text, '"+dd_value+"')]")).click();
String dnd_value = dropdown_value.split("_")[0];
driver.findElement(By.xpath("//*[contains(@text, '"+dnd_value+"')]")).click();
System.out.println("Inside Catch , Success"); */
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------RADIO BUTTON SELECTION---------------------
@Given("^user selects radio button \"([^\"]*)\"$")
public void user_selects_radio_button(String radiobutton_value) throws Throwable {
driver.findElement(ObjectRepository.getobjectLocator(radiobutton_value)).click();
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------FIELD LEVEL VALIDATION---------------------
@Given("^user validates \"([^\"]*)\" field with expected value as \"([^\"]*)\"$")
public void user_validates_field_with_expected_value_as(String actual, String expected) throws Throwable {
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
// actual = actual+ "_value";
String actual_argument = driver.findElement(ObjectRepository.getobjectLocator(actual)).getText();
Assert.assertEquals(expected, actual_argument);
}
//------------------SWIPE RIGHT---------------------
@Given("^user swipes right to select \"([^\"]*)\"$")
public void user_swipes_right_to_select(String account) throws Throwable {
@SuppressWarnings("rawtypes")
TouchAction touchAction = new TouchAction((PerformsTouchActions) driver); //for touch actions on mobile devices
if(account.equalsIgnoreCase("SAVINGS"))
{
//action.press(startx,starty).waitAction(1000).moveTo(startx,endy).release().perform();
touchAction.longPress(PointOption.point(290, 309)).moveTo(PointOption.point(0, 309)).release().perform();
}
else
{
touchAction.longPress(PointOption.point(290, 540)).moveTo(PointOption.point(0, 540)).release().perform();
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------SCROLL DOWN---------------------
@Given("^user scrolls down$")
public void user_scrolls_down() throws Throwable {
// Write code here that turns the phrase above into concrete actions
@SuppressWarnings("rawtypes")
TouchAction touchAction = new TouchAction((PerformsTouchActions) driver);
touchAction.longPress(PointOption.point(200, 550)).moveTo(PointOption.point(200, 200)).release().perform();
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------LINK CLICK---------------------
@Given("^user clicks on link \"([^\"]*)\"$")
public void user_clicks_on_link(String linkname) throws Throwable {
try {
driver.findElement(ObjectRepository.getobjectLocator(linkname)).click();
}
catch(Exception e)
{
wait.until(ExpectedConditions.visibilityOfElementLocated
(ObjectRepository.getobjectLocator(linkname))).click();
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------SELECTING CHECKBOX---------------------
@Given("^user selects checkbox \"([^\"]*)\"$")
public void user_selects_checkbox(String checkbox_name) throws Throwable {
try
{
driver.findElement(ObjectRepository.getobjectLocator(checkbox_name)).click();
}
catch (Exception e)
{
wait.until(ExpectedConditions.visibilityOfElementLocated
(ObjectRepository.getobjectLocator(checkbox_name))).click();
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------WAIT METHOD---------------------
@Given("^user waits for \"(.*?)\" seconds$")
public void user_waits_for_seconds(long arg1) throws Throwable
{
arg1 = arg1*1000;
Thread.sleep(arg1);
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------INDEX METHOD FOR TEXTBOX ---------------------
@Given("^user enters \"([^\"]*)\" in textbox at index \"([^\"]*)\"$")
public void user_enters_in_textbox_at_index(String text, int index) throws Throwable {
// Write code here that turns the phrase above into concrete actions
List<MobileElement> elements = driver.findElements(By.className("android.widget.EditText"));
System.out.println("Number of elements:" +elements.size());
for (int i=0; i<elements.size();i++)
{
System.out.println("textbox text:" + elements.get(i).getAttribute("text"));
if(elements.get(i).equals(index))
break;
}
elements.get(index).sendKeys(text);
elements.get(index).click();
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.SPACE));
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------INDEX METHOD FOR BUTTON--------------------
@Given("^user clicks on button at index \"([^\"]*)\"$")
public void user_clicks_on_button_at_index(int index) throws Throwable {
// Write code here that turns the phrase above into concrete actions
try
{
List<MobileElement> elements = driver.findElements(By.className("android.widget.Button"));
System.out.println("Number of elements:" +elements.size());
for (int i=0; i<elements.size();i++)
{
System.out.println("button text:" + elements.get(i).getAttribute("text"));
// elements.get(index).sendKeys(text);
if(elements.get(i).equals(index))
break;
}
elements.get(index).click();
}
catch(Exception e)
{
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------INDEX METHOD FOR CHECKBOX--------------------
@SuppressWarnings("unlikely-arg-type")
@Given("^user selects checkbox at index \"([^\"]*)\"$")
public void user_selects_checkbox_at_index(int index) throws Throwable {
// Write code here that turns the phrase above into concrete actions
List<MobileElement> elements = driver.findElements(By.className("android.widget.CheckBox"));
System.out.println("Number of elements:" +elements.size());
for (int i=0; i<elements.size();i++)
{
System.out.println("checkbox text:" + elements.get(i).getAttribute("text"));
if(elements.get(i).equals(index))
break;
}
elements.get(index).click();
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------INDEX METHOD FOR RADIOBUTTON--------------------
@Given("^user selects radiobutton at index \"([^\"]*)\"$")
public void user_selects_radiobutton_at_index(int index) throws Throwable {
// Write code here that turns the phrase above into concrete actions
List<MobileElement> elements = driver.findElements(By.className("android.widget.RadioButton"));
System.out.println("Number of elements:" +elements.size());
for (int i=0; i<elements.size();i++)
{
System.out.println("Radiobox text:" + elements.get(i).getAttribute("text"));
// elements.get(index).sendKeys(text);
if(elements.get(i).equals(index))
break;
}
elements.get(index).click();
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------INDEX METHOD FOR DROPDOWN--------------------
@Given("^user selects dropdown at index \"([^\"]*)\"$")
public void user_selects_dropdown_at_index(int index) throws Throwable {
// Write code here that turns the phrase above into concrete actions
List<MobileElement> elements = driver.findElements(By.xpath("//android.widget.Image[@text='custom arrow-down-btn']"));
System.out.println("Number of elements:" +elements.size());
for (int i=0; i<elements.size();i++)
{
//System.out.println("Dropdown text:" + elements.get(i).getAttribute("text"));
// elements.get(index).sendKeys(text);
if(elements.get(i).equals(index))
break;
}
elements.get(index).click();
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//------------------SWITCHING APPS--------------------
@SuppressWarnings({ "unchecked", "rawtypes" })
@Given("^user switches to \"([^\"]*)\" app to get \"([^\"]*)\" for account with email \"([^\"]*)\" and password \"([^\"]*)\"$")
public void user_switches_to_app_to_get_for_account_with_email_and_password(String app_name, String requirement, String email_id, String password) throws Throwable {
Thread.sleep(2000);
Activity activity;
String otp_value = null;
switch(app_name)
{
case "chrome":
activity = new Activity(ObjectRepository.getString("global.capability.chromeAppPackage"), ObjectRepository.getString("global.capability.chromeAppActivity"));
activity.setStopApp(false);
((AndroidDriver<MobileElement>) this.driver).startActivity(activity);
String domain = email_id.split("@")[1];
System.out.println("DOMAIN-- "+ domain);
// System.setProperty("webdriver.chrome.driver","\\src\\main\\resources\\chromedriver.exe");
if(domain.equalsIgnoreCase("gmail.com"))
{
try {
System.out.print("Inside Try block");
// driver.get("http://www.gmail.com");
driver.findElement(By.className("android.widget.EditText")).sendKeys("https://"+domain);
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.ENTER));
System.out.print("Exit try block");
}
catch(Exception e)
{
System.out.print("Inside catch block");
driver.findElement(By.xpath("//android.widget.EditText[@resource-id='com.android.chrome:id/url_bar']")).sendKeys("https://m.yopmail.come/");
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.ENTER));
Thread.sleep(2000);
}
}
else if(domain.equalsIgnoreCase("yopmail.com"))
{
activity = new Activity(ObjectRepository.getString("global.capability.chromeAppPackage"), ObjectRepository.getString("global.capability.chromeAppActivity"));
activity.setStopApp(false);
((AndroidDriver<MobileElement>) this.driver).startActivity(activity);
domain = email_id.split("@")[1];
Thread.sleep(1000);
driver.findElement(By.xpath("//android.widget.ImageButton[@resource-id='com.android.chrome:id/menu_button']")).click();
driver.findElement(By.xpath("//android.widget.TextView[@text='New tab']")).click();
Thread.sleep(1000);
driver.findElement(By.className("android.widget.EditText")).clear();
driver.findElement(By.className("android.widget.EditText")).sendKeys(domain);
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.ENTER));
Thread.sleep(1000);
driver.findElement(By.xpath("//android.widget.EditText[@resource-id='login']")).clear();
driver.findElement(By.xpath("//android.widget.EditText[@resource-id='login']")).sendKeys(email_id);
driver.findElement(By.xpath("//android.widget.Button[@index='0']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//android.view.View[contains(@text,'Meed')]")).click();
Thread.sleep(1000);
String otptext= driver.findElement(By.xpath("//android.view.View[contains(@text, 'Welcome to Meed ')]")).getText();
System.out.println("OTP TEXT is"+otptext);
String otp = domain = otptext.split(":")[1];
String[] temp = otp.split(" ");
otp_value= temp[1];
// System.out.println("OTP IS: " + otp_value[1]);
}
break;
case "message":
activity = new Activity(ObjectRepository.getString("global.capability.settingsAppPackage"), ObjectRepository.getString("global.capability.settingsAppActivity"));
activity.setStopApp(false);
((AndroidDriver<MobileElement>) this.driver).startActivity(activity);
driver.findElement(By.className("android.widget.LinearLayout")).click();
break;
}
Thread.sleep(2000);
//Re launch Meed App
activity = new Activity(ObjectRepository.getString("global.capability.NewMeedAppPackage"), ObjectRepository.getString("global.capability.NewMeedAppActivity"));
activity.setStopApp(false);
int j=3;
((AndroidDriver<MobileElement>) this.driver).startActivity(activity);
System.out.println("OTP is "+otp_value);
for(int i=0;i<otp_value.length();i++)
{
String temp = otp_value.substring(i, i+1);
// System.out.println("temp " +temp);
driver.findElement(By.xpath("//android.view.View[@index='"+j+"']")).click();
switch(temp)
{
case("1"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_1));
break;
case("2"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_2));
break;
case("3"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_3));
break;
case("4"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_4));
break;
case("5"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_5));
break;
case("6"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_6));
break;
case("7"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_7));
break;
case("8"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_8));
break;
case("9"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_9));
break;
case("0"): ((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.DIGIT_0));
break;
}
++j;
}
Thread.sleep(5000);
}
//------------------Switching to Message App to get OTP --------------------
@Given("^user switches to app \"([^\"]*)\" to get \"([^\"]*)\"$")
public void user_switches_to_app_to_get(String app_name, String app_data) throws Throwable {
Activity activity;
switch(app_name)
{
case "message":
activity = new Activity(ObjectRepository.getString("global.capability.settingsAppPackage"), ObjectRepository.getString("global.capability.settingsAppActivity"));
activity.setStopApp(false);
((AndroidDriver<MobileElement>) this.driver).startActivity(activity);
driver.findElement(By.className("android.widget.LinearLayout")).click();
break;
case"chrome":
break;
}
activity = new Activity(ObjectRepository.getString("global.capability.NewMeedAppPackage"), ObjectRepository.getString("global.capability.NewMeedAppActivity"));
activity.setStopApp(false);
((AndroidDriver<MobileElement>) this.driver).startActivity(activity);
Thread.sleep(5000);
}
//------------------CALENDAR SELCTIONS --------------------
@Given("^user selects \"([^\"]*)\" \"([^\"]*)\" \"([^\"]*)\" from calendar$")
public void user_selects_from_calendar(String month, int day, int year) throws Throwable {
// Write code here that turns the phrase above into concrete actions
Calendar mCalendar = Calendar.getInstance();
String current_month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());
System.out.println("MONTH VALUE IS RETREIVED AS --- " + current_month);
int current_day = mCalendar.get(Calendar.DAY_OF_MONTH);
System.out.println("Day VALUE IS RETREIVED AS --- " + current_day);
int current_year = mCalendar.get(Calendar.YEAR);
System.out.println("Year VALUE IS RETREIVED AS --- " + current_year);
int currentmonthInt = mCalendar.get(Calendar.DAY_OF_MONTH);
System.out.println("Month VALUE IS RETREIVED AS --- " + currentmonthInt);
// System.out.println("CURRENT DATE- " +driver.findElement(By.xpath("//android.view.View[contains(@text, 'Oct')]")).getText());
TouchAction touchAction = new TouchAction((PerformsTouchActions) driver);
if(year>current_year)
{
do
{
WebElement current_year_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+current_year +"']"));
int cyear_x = current_year_val.getLocation().getX();
int cyear_y = current_year_val.getLocation().getY();
int temp=current_year+1;
WebElement current_year_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+temp+"']"));
int year_x = current_year_oneahead.getLocation().getX();
int year_y = current_year_oneahead.getLocation().getY();
touchAction.longPress(PointOption.point(year_x, year_y)).moveTo(PointOption.point(cyear_x, cyear_y)).release().perform();
++current_year;
System.out.println("Current Year is :" + current_year);
}while (year>current_year);
}
else
{
}
//If month is given in digits
if(month.length()<=2)
{
int month_int = Integer.parseInt(month);
if(month_int>currentmonthInt)
{
do
{
WebElement current_mon_val, current_mon_oneahead;
int cmon_x, cmon_y, mon_x, mon_y, temp;
if(currentmonthInt<10)
{
current_mon_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+currentmonthInt +"']"));
cmon_x = current_mon_val.getLocation().getX();
cmon_y = current_mon_val.getLocation().getY();
}
else
{
current_mon_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+currentmonthInt +"']"));
cmon_x = current_mon_val.getLocation().getX();
cmon_y = current_mon_val.getLocation().getY();
}
temp=currentmonthInt+1;
if(temp<10)
{
current_mon_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+temp+"']"));
mon_x = current_mon_oneahead.getLocation().getX();
mon_y = current_mon_oneahead.getLocation().getY();
}
else
{
current_mon_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+temp+"']"));
mon_x = current_mon_oneahead.getLocation().getX();
mon_y = current_mon_oneahead.getLocation().getY();
}
touchAction.longPress(PointOption.point(mon_x, mon_y)).moveTo(PointOption.point(cmon_x, cmon_y)).release().perform();
++currentmonthInt;
System.out.println("Current Day is :" + currentmonthInt);
}while (month_int>currentmonthInt);
}
else if(month_int<currentmonthInt)
{
do
{
WebElement current_mon_val, current_mon_oneahead;
int cmon_x, cmon_y, mon_x, mon_y, temp;
if(currentmonthInt<10)
{
current_mon_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+currentmonthInt +"']"));
cmon_x = current_mon_val.getLocation().getX();
cmon_y = current_mon_val.getLocation().getY();
}
else
{
current_mon_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+currentmonthInt +"']"));
cmon_x = current_mon_val.getLocation().getX();
cmon_y = current_mon_val.getLocation().getY();
}
temp=currentmonthInt-1;
if(temp<10)
{
current_mon_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+temp+"']"));
mon_x = current_mon_oneahead.getLocation().getX();
mon_y = current_mon_oneahead.getLocation().getY();
}
else
{
current_mon_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+temp+"']"));
mon_x = current_mon_oneahead.getLocation().getX();
mon_y = current_mon_oneahead.getLocation().getY();
}
touchAction.longPress(PointOption.point(mon_x, mon_y)).moveTo(PointOption.point(mon_x, mon_y)).release().perform();
--currentmonthInt;
}while (month_int<currentmonthInt);
}
}
//If month value is in Alphabets
else
{
// Doing Touch action for Months
List<String> months = Arrays.asList("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
int indexOfCurrentMonth = 0; int indexofinputMonth =0;
System.out.println("Number of elements:" +months.size());
for (int i=0; i<months.size();i++)
{
if(months.get(i).contentEquals(current_month))
{
indexOfCurrentMonth=i;
}
else if (months.get(i).contentEquals(month))
{
indexofinputMonth=i;
}
}
System.out.println("Index of Current Month "+ indexOfCurrentMonth);
System.out.println("Index of Entered Month "+ indexofinputMonth);
if(indexofinputMonth>indexOfCurrentMonth)
{
do
{
WebElement current_month_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+current_month +"']"));
int cmonth_x = current_month_val.getLocation().getX();
int cmonth_y = current_month_val.getLocation().getY();
int temp=indexOfCurrentMonth+1;
WebElement current_month_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+months.get(temp)+"']"));
int month_x = current_month_oneahead.getLocation().getX();
int month_y = current_month_oneahead.getLocation().getY();
touchAction.longPress(PointOption.point(month_x, month_y)).moveTo(PointOption.point(cmonth_x, cmonth_y)).release().perform();
++indexOfCurrentMonth;
System.out.println("Current Month index is :" + indexOfCurrentMonth);
}while (indexofinputMonth>indexOfCurrentMonth);
}
else if (indexofinputMonth<indexOfCurrentMonth)
{
do
{
WebElement current_month_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+current_month +"']"));
int cmonth_x = current_month_val.getLocation().getX();
int cmonth_y = current_month_val.getLocation().getY();
int temp=indexOfCurrentMonth-1;
WebElement current_month_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+months.get(temp)+"']"));
int month_x = current_month_oneahead.getLocation().getX();
int month_y = current_month_oneahead.getLocation().getY();
touchAction.longPress(PointOption.point(month_x, month_y)).moveTo(PointOption.point(cmonth_x, cmonth_y)).release().perform();
--indexOfCurrentMonth;
System.out.println("Current Month index is :" + indexOfCurrentMonth);
}while (indexofinputMonth<indexOfCurrentMonth);
}
}
//Touch action for Day
if(day>current_day)
{
do
{
WebElement current_day_val, current_day_oneahead;
int cday_x, cday_y, day_x, day_y, temp;
if(current_day<10)
{
current_day_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+current_day +"']"));
cday_x = current_day_val.getLocation().getX();
cday_y = current_day_val.getLocation().getY();
}
else
{
current_day_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+current_day +"']"));
cday_x = current_day_val.getLocation().getX();
cday_y = current_day_val.getLocation().getY();
}
temp=current_day+1;
if(temp<10)
{
current_day_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+temp+"']"));
day_x = current_day_oneahead.getLocation().getX();
day_y = current_day_oneahead.getLocation().getY();
}
else
{
current_day_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+temp+"']"));
day_x = current_day_oneahead.getLocation().getX();
day_y = current_day_oneahead.getLocation().getY();
}
touchAction.longPress(PointOption.point(day_x, day_y)).moveTo(PointOption.point(cday_x, cday_y)).release().perform();
++current_day;
System.out.println("Current Day is :" + current_day);
}while (day>current_day);
}
else if(day<current_day)
{
do
{
WebElement current_day_val, current_day_oneahead;
int cday_x, cday_y, day_x, day_y, temp;
if(current_day<10)
{
current_day_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+current_day +"']"));
cday_x = current_day_val.getLocation().getX();
cday_y = current_day_val.getLocation().getY();
}
else
{
current_day_val = driver.findElement(By.xpath("//android.widget.Button[@text ='"+current_day +"']"));
cday_x = current_day_val.getLocation().getX();
cday_y = current_day_val.getLocation().getY();
}
temp=current_day-1;
if(temp<10)
{
current_day_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+0+temp+"']"));
day_x = current_day_oneahead.getLocation().getX();
day_y = current_day_oneahead.getLocation().getY();
}
else
{
current_day_oneahead = driver.findElement(By.xpath("//android.widget.Button[@text ='"+temp+"']"));
day_x = current_day_oneahead.getLocation().getX();
day_y = current_day_oneahead.getLocation().getY();
}
touchAction.longPress(PointOption.point(day_x, day_y)).moveTo(PointOption.point(cday_x, cday_y)).release().perform();
--current_day;
//System.out.println("Current Day is :" + current_day);
}while (day<current_day);
}
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
//---------------------SELECTING FROM LIST- Android specific-----
@Given("^user selects option \"([^\"]*)\" from the list$")
public void user_selects_option_from_the_list(String list_value) throws Throwable {
// Write code here that turns the phrase above into concrete actions
System.out.println("List name" + list_value);
driver.findElement(By.xpath("//android.view.View[@text='"+list_value+"']")).click();
}
//------------------INDEX METHOD FOR LABEL --------------------
@Given("^user select label \"([^\"]*)\" at index \"([^\"]*)\"$")
public void user_select_label_at_index(String label_name, int index) throws Throwable {
// Write code here that turns the phrase above into concrete actions
List<MobileElement> elements = driver.findElements(By.xpath("//*[@text='"+label_name+ "']"));
System.out.println("Number of elements:" +elements.size());
for (int i=0; i<elements.size();i++)
{
System.out.println("checkbox text:" + elements.get(i).getAttribute("text"));
if(elements.get(i).equals(index))
break;
}
elements.get(index).click();
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
}
@SuppressWarnings("rawtypes")
@Given("^user presses device \"([^\"]*)\" button$")
public void user_presses_device_button(String button_name) throws Throwable {
// Write code here that turns the phrase above into concrete actions
switch(button_name)
{
case "BACK":
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.BACK));
break;
case "ENTER":
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.ENTER));
break;
case "CAMERA":
((AndroidDriver) driver).pressKey(new KeyEvent(AndroidKey.CAMERA));
break;
}
}
@After()
public void tearDown() throws Exception {
System.out.println("Executing After of Step Defination");
Reporter.addScreenCaptureFromPath(screenshot.captureScreenShot(sName));
//driver.quit();
}
}
<file_sep>/bin/src/main/resources/allProperties.properties
propFiles=global.properties,objectRepository.properties | 87c98c266f8fb0c822a3df1211555af17867d7cf | [
"Java",
"INI"
] | 3 | INI | mchauhanx/MobileAutomation | 7af34b44c752c6c1fcfaf11481798be039cbb246 | 827aff303f219d305e1a9b72fe9d2232dc5bec7b | |
refs/heads/main | <repo_name>RupeshSeth/jobproject<file_sep>/README.md
# Test Project TASK INTRODUCTION
```
In this application its displays the orders received and its status - (Order Received,
Preparing , Ready to serve).
All the Orders are display in list view with order Id, Customer Name, No. of Items
ordered, Total Amount of the Order, Status of the Order and a clickable Change Status
button, that changes status of the order to the next state automatically on click.
```
## How to Install the Test Project TASK
```
Download the Test ProjectTask in your system using git clone command or download zip file provided in this repo
(https://github.com/RupeshSeth/jobproject)
```
## Project setup
```
npm install
```
#### Compiles and hot-reloads for development
```
npm run serve
```
```
user email-Id - <EMAIL>
```
## Dependencies
- VuetifyJS (CSS and javascript framework for vuejs)
- node-snackbar (to display the error and success message)
## LIVE Demo
(https://vigilant-hodgkin-6e9e13.netlify.app)
<file_sep>/src/router/index.ts
import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import auth$AuthLayout from '@/layout/AuthLayout.vue';
import auth$Login from '../views/Login.vue';
import testproject$Home from '../views/Home.vue';
import testproject$RootLayout from '@/layout/RootLayout.vue';
import testproject$Header from '@/views/nav/Header.vue';
import testproject$LeftNav from '@/views/nav/LeftNav.vue';
import testproject$Footer from '@/views/nav/Footer.vue';
Vue.use(VueRouter)
const routes: Array<RouteConfig> = [
{ path: '/auth', meta : {}, components : { default : auth$AuthLayout},
children : [
{ path: '', redirect: { name : 'Auth.Login'}},
{ path: 'login', meta : {}, name: 'Auth.Login', components : { default : auth$Login} }
] },
{path: '/', meta : {}, components : { default : testproject$RootLayout},
children : [
{ path: '/', redirect: { name : 'Auth.Login'}},
{ path: 'home', meta : {}, name: 'Root.Home', components : { header : testproject$Header, leftnav : testproject$LeftNav, footer : testproject$Footer, default : testproject$Home}}
]
}
]
const router = new VueRouter({
routes
})
export default router
<file_sep>/src/custom-filter.ts
import { Vue } from 'vue-property-decorator';
export default class CustomFilters {
public static setup() {
this.withBase();
this.toCurrency();
}
private static withBase() {
Vue.filter('withBase', (value: string) => {
// console.log('I am in custom filter: withBase : ');
// console.log(process.env.BASE_URL);
return process.env.BASE_URL + value;
});
}
private static toCurrency() {
Vue.filter('toCurrency', (value: number) => {
if (typeof value !== 'number') {
return value;
}
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'INR',
minimumFractionDigits: 0
});
return formatter.format(value);
});
}
}
<file_sep>/src/plugins/vuetify.ts
import Vue from 'vue';
import Vuetify from 'vuetify/lib';
import 'material-design-icons-iconfont/dist/material-design-icons.css'
Vue.use(Vuetify);
export default new Vuetify({
});
<file_sep>/src/main.ts
import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify';
import CustomFilters from './custom-filter';
// for message Bar to display the success, error message.
import 'node-snackbar/dist/snackbar.min.css';
import 'node-snackbar/dist/snackbar.min.js';
Vue.config.productionTip = false
CustomFilters.setup();
new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
| 3c07db56b8b25176057726270cfe5345e8746d2a | [
"Markdown",
"TypeScript"
] | 5 | Markdown | RupeshSeth/jobproject | 91ac53bdccfe4c37eeae9c5041b3366061c6afb1 | 506ad371f3a5bb22c71d116b2685e7a14c533d53 | |
refs/heads/master | <file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'login',
component: () => import(/* webpackChunkName: "about" */ '@/views/login')
},
{
path: '/register',
name: 'register',
component: () => import(/* webpackChunkName: "about" */ '@/views/register')
},
{
path: '/homePage',
name: 'homePage',
component: () => import(/* webpackChunkName: "about" */ '@/views/homePage')
},
{
path: '/supermarket',
name: 'supermarket',
component: () => import(/* webpackChunkName: "about" */ '@/views/supermarket')
},
{
path: '/supermarketDetail/:id',
name: 'supermarketDetail',
component: () => import(/* webpackChunkName: "about" */ '@/views/supermarket/details')
},
{
path: '/dataNavigate',
name: 'dataNavigate',
component: () => import(/* webpackChunkName: "about" */ '@/views/dataNavigate')
},
{
path: '/userInfor',
name: 'userInfor',
component: () => import(/* webpackChunkName: "about" */ '@/views/userInfor')
},
{
path: '/', // 默认进入路由
redirect: '/homePage' //重定向
},
]
const router = new VueRouter({
routes
})
router.beforeEach((to,from,next) => {
const queryStr = decodeURI(location.search)
let strs =[]
let userInfor ={}
if (queryStr.indexOf("?") != -1) {
var str = queryStr.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
if(strs[i].split("=")[0]=='username'){
userInfor.username = strs[i].split("=")[1]
sessionStorage.setItem('userInfor',JSON.stringify(userInfor))
}
if(strs[i].split("=")[0]=='token'){
setToken(strs[i].split("=")[1])
}
}
}
if(to.fullPath==='/login'){
next()
}else{
if(to.matched.some( m => m.meta.auth)){
if(getToken()){
next()
}else{
next({path:'/login',query:{ Rurl: to.fullPath} })
}
}else{
next()
}
}
})
router.afterEach((to,from,next)=>{
window.scrollTo(0,0)
})
export default router
<file_sep>import axios from 'axios'
import { Message } from 'element-ui'
import { getToken ,removeToken} from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000 // request timeout
})
service.interceptors.request.use(
config => {
if (getToken()) {
config.headers['Authorization'] = getToken()
// config.headers['Authorization'] = 'JWT '+ getToken()
}
return config
},
error => {
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (response.status === 200) {
if(res.code===5004){
}
return res
}
},
error => {
Message({
message:"服务拥挤,请稍后重试!",
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
| 9c3e7d44b4a3f81be7f4ffaed7895576a2f2fb43 | [
"JavaScript"
] | 2 | JavaScript | liberationt/exun | 5ed33459e20f01ebf8f7eec2395165a92b02fa56 | 8ad91c28775bc85c037e0cb9cbdfb91cc4058680 | |
refs/heads/main | <file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { UserProfileComponent } from './user-profile/user-profile.component';
import { OverviewComponent } from './overview/overview.component';
import { RepositoriesComponent } from './repositories/repositories.component';
import { ProjectsComponent } from './projects/projects.component';
import { PackagesComponent } from './packages/packages.component';
import { CardsComponent } from './cards/cards.component';
import { PlotlyViaCDNModule } from 'angular-plotly.js';
import { PipeModule } from '../pipe/pipe.module';
PlotlyViaCDNModule.setPlotlyVersion('latest');
@NgModule({
declarations: [HeaderComponent, FooterComponent, UserProfileComponent, OverviewComponent, RepositoriesComponent, ProjectsComponent, PackagesComponent, CardsComponent],
imports: [
CommonModule,
PlotlyViaCDNModule,
PipeModule
],
exports: [
HeaderComponent,
FooterComponent,
UserProfileComponent,
OverviewComponent,
ProjectsComponent,
RepositoriesComponent,
UserProfileComponent,
PackagesComponent,
CardsComponent
],
providers:[
]
})
export class ComponentsModule { }
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError, tap } from 'rxjs/operators';
import { EMPTY, of, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HttpClientCallService {
user_details = new BehaviorSubject<any>([]);
user_repos = new BehaviorSubject<any>([]);
user_projects = new BehaviorSubject<any>([]);
user_contributions = new BehaviorSubject<any>([]);
//Sample Varriables
token = '';
httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `bearer ${this.token}` }) };
constructor(
private httpClient: HttpClient,
) { }
//https://api.github.com/users/srujar
getUser(user_name): any {
return this.httpClient.get<any>(`https://api.github.com/users/${user_name}`).pipe(
tap(value => {
if (value) {
this.user_details.next(value);
}
}));
}
getUsersList(): any {
return this.httpClient.get<any>(`https://api.github.com/users`);
}
getUsersRepos(user_name): any {
return this.httpClient.get<any>(`https://api.github.com/users/${user_name}/repos`).pipe(
tap(value => {
if (value) {
this.user_repos.next(value);
}
}));
}
getUsersProjects(user_name): any {
let custom_httpOptions = { headers: new HttpHeaders({ Accept: ['application/vnd.github.spiderman-preview', "application/vnd.github.inertia-preview+json"] }) };
return this.httpClient.get<any>(`https://api.github.com/users/${user_name}/projects`, custom_httpOptions).pipe(
tap(value => {
if (value) {
this.user_projects.next(value);
}
}));
}
getUserContibutions(username, from_date, to_date): any {
let body = {
"query": `query {
user(login: "${username}") {
name
email
createdAt
contributionsCollection(from: "${from_date}", to: "${to_date}" ) {
contributionCalendar {
colors
totalContributions
weeks {
contributionDays {
color
contributionCount
date
weekday
}
firstDay
}
}
}
}
}`
}
return this.httpClient.post<any>('https://api.github.com/graphql', body, this.httpOptions)
.pipe(
map(value => {
if (value) {
this.user_contributions.next(value.data.user.contributionsCollection.contributionCalendar);
return value.data.user.contributionsCollection.contributionCalendar
}
}),
(catchError(error => {
return of({ 'is_error': true, error })
}))
);
}
}
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({
name: 'datePipe'
})
export class DatePipePipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
// console.log("value", value);
// let todays_date = new Date();
// console.log("todays_date", todays_date);
// let diff: any = moment.duration(moment(value).diff(moment(todays_date)));
// console.log("diff", diff);
// var days = parseInt(diff.asDays()); //84
// var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.
// hours = hours - days * 24; // 23 hours
// var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.
// minutes = minutes - (days * 24 * 60 + hours * 60); //20 minutes.
// console.log("days: ", days, " minutes: ", minutes);
if (value) {
return moment(value).format('DD/MM/YYYY');
} else {
return null;
}
}
}
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClientCallService } from 'src/app/service/http-client-call.service';
@Component({
selector: 'app-projects',
templateUrl: './projects.component.html',
styleUrls: ['./projects.component.scss']
})
export class ProjectsComponent implements OnInit, OnDestroy {
users_projects: any = [];
users_name: any;
projects_count: any = 0;
$user_projects: any;
$user_details: any;
constructor(
private httpClientCallService: HttpClientCallService
) { }
ngOnInit(): void {
this.$user_projects = this.httpClientCallService.user_projects.subscribe(data => {
this.projects_count = data.length;
this.users_projects = data;
})
this.$user_details = this.httpClientCallService.user_details.subscribe(data => {
this.users_name = data.name;
})
}
ngOnDestroy() {
if (this.$user_projects) { this.$user_projects.unsubscribe() }
if (this.$user_details) { this.$user_details.unsubscribe() }
}
}
<file_sep>import { HttpClientCallService } from './http-client-call.service';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router } from '@angular/router';
import { EMPTY, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Route } from '@angular/compiler/src/core';
@Injectable({
providedIn: 'root'
})
export class UserResolverService implements Resolve<any> {
constructor(
private router: Router,
private httpClientCallService: HttpClientCallService
) { }
resolve(route: ActivatedRouteSnapshot):Observable<any> {
let { user_name } = route.params;
return this.httpClientCallService
.getUser(user_name)
.pipe(
catchError(error => {
console.log("error", error);
this.router.navigateByUrl('user/not-found');
return EMPTY;
})
)
}
}
<file_sep>import { UserResolverService } from './../service/user-resolver.service';
import { UserNotFoundComponent } from './user-not-found/user-not-found.component';
import { UserComponent } from './user/user.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserDetailsComponent } from './user-details/user-details.component';
import { OverviewComponent } from '../components/overview/overview.component';
import { RepositoriesComponent } from '../components/repositories/repositories.component';
import { ProjectsComponent } from '../components/projects/projects.component';
import { PackagesComponent } from '../components/packages/packages.component';
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard', component: DashboardComponent
},
{
path: 'user',
component: UserComponent,
children: [
{
path: 'not-found',
component: UserNotFoundComponent
},
{
path: ':user_name',
component: UserDetailsComponent,
resolve: { user: UserResolverService },
children: [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'overview', component: OverviewComponent },
{ path: 'repo', component: RepositoriesComponent },
{ path: 'projects', component: ProjectsComponent },
{ path: 'packages', component: PackagesComponent }
]
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PagesRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpClientCallService } from 'src/app/service/http-client-call.service';
import * as moment from 'moment';
@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.scss']
})
export class UserDetailsComponent implements OnInit {
user_data: any;
constructor(
private activatedRoute: ActivatedRoute,
private httpClientCallService: HttpClientCallService
) { }
ngOnInit(): void {
this.activatedRoute.data.subscribe(data => {
this.user_data = data.user;
let from_date = new Date(moment('02-01-2021').format('DD/MM/YYYY')).toISOString();
let to_date = new Date(moment('01-12-2021').format('DD/MM/YYYY')).toISOString();
this.getContributions(data.user.login, from_date, to_date);
this.getProjects(data.user.login);
this.getUserRepos(data.user.login);
})
}
getContributions(user_name, from_date, to_date) {
this.httpClientCallService.getUserContibutions(user_name, from_date, to_date).subscribe();
}
getUserRepos(user_name) {
this.httpClientCallService.getUsersRepos(user_name).subscribe();
}
getProjects(user_name) {
this.httpClientCallService.getUsersProjects(user_name).subscribe();
}
}
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClientCallService } from 'src/app/service/http-client-call.service';
@Component({
selector: 'app-overview',
templateUrl: './overview.component.html',
styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit, OnDestroy {
array = [1, 2, 3, 4, 5];
users_repos: any = [];
user_contributions: any;
z_array: any = [];
x_array: any = [];
public graph = {
data: [
{
x: [],
y: ['Sat', 'Fri', 'Thu', 'Wed', 'Tue', 'Mon', 'Sun'],
z: [],
type: 'heatmap',
colorscale: [
[0, '#ebedf0'],
[10, '#9be9a8'],
[20, '#40c463'],
[30, '#30a14e'],
[100, '#216e39'],
],
showscale: false
},
],
// layout: { width: 320, height: 240, title: 'A Fancy Plot' },
// config : {responsive: true}
};
$user_repos: any;
$user_contributions: any;
constructor(
private httpClientCallService: HttpClientCallService
) { }
ngOnInit(): void {
this.$user_repos = this.httpClientCallService.user_repos.subscribe(data => {
this.users_repos = data.slice(0, 6);
})
this.$user_contributions = this.httpClientCallService.user_contributions.subscribe(data => {
this.user_contributions = data.totalContributions;
if (data.totalContributions) {
this.plotGraphData(data.weeks)
}
})
}
plotGraphData(data) {
let z_array = [];
let x_array = [];
for (let i = 0; i < 7; i++) {
z_array.push([]);
data.forEach((element, index) => {
if (!(element.contributionDays[i] == undefined || element.contributionDays[i] == null)) {
z_array[i].push(element.contributionDays[i].contributionCount)
} else {
z_array[i].push('NaN')
}
if (i == 0) {
x_array.push(index);
}
});
}
let sixth_ele = z_array[6][z_array[6].length - 1];
z_array[6][z_array[6].length - 1] = z_array[0][z_array[0].length - 1];
z_array[0][z_array[0].length - 1] = sixth_ele;
let fifth_ele = z_array[5][z_array[5].length - 1];
z_array[5][z_array[5].length - 1] = z_array[1][z_array[1].length - 1];
z_array[1][z_array[1].length - 1] = fifth_ele;
let fourth_ele = z_array[4][z_array[4].length - 1];
z_array[4][z_array[4].length - 1] = z_array[2][z_array[2].length - 1];
z_array[2][z_array[2].length - 1] = fourth_ele;
// z_array[z_array.length - 1] = z_array[z_array.length - 1].reverse();
// console.log("z_array.......", z_array);
// console.log("x_array.......", x_array);
this.x_array = x_array
this.z_array = z_array
this.graph.data[0].x = x_array;
this.graph.data[0].z = z_array;
}
ngOnDestroy() {
if (this.$user_repos) { this.$user_repos.unsubscribe() }
if (this.$user_contributions) { this.$user_contributions.unsubscribe() }
}
}
<file_sep>import { Router } from '@angular/router';
import { HttpClientCallService } from './../../service/http-client-call.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
users_list: any;
constructor(
private httpClientCallService: HttpClientCallService,
private router: Router
) { }
ngOnInit(): void {
this.httpClientCallService.getUsersList().subscribe(data => {
this.users_list = data;
})
}
selectUser(user_data) {
this.router.navigateByUrl(`/user/${user_data.login}`);
}
}
<file_sep>import { UserResolverService } from './../service/user-resolver.service';
import { HttpClientCallService } from './../service/http-client-call.service';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PagesRoutingModule } from './pages-routing.module';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ComponentsModule } from './../components/components.module';
import { UserComponent } from './user/user.component';
import { UserDetailsComponent } from './user-details/user-details.component';
import { UserNotFoundComponent } from './user-not-found/user-not-found.component';
import { HttpClientModule } from '@angular/common/http';
import { PlotlyViaCDNModule } from 'angular-plotly.js';
PlotlyViaCDNModule.setPlotlyVersion('latest');
// PlotlyViaCDNModule.plotlyBundle = null;
@NgModule({
declarations: [DashboardComponent, UserComponent, UserDetailsComponent, UserNotFoundComponent,
// DatePipePipe
],
imports: [
CommonModule,
PagesRoutingModule,
ComponentsModule,
PlotlyViaCDNModule
],
providers: [
UserResolverService
]
})
export class PagesModule { }<file_sep>import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-cards',
templateUrl: './cards.component.html',
styleUrls: ['./cards.component.scss']
})
export class CardsComponent implements OnInit {
@Input('repo_data') repo_data: any;
@Input('slector') slector: any;
@Input('users_name') users_name: any;
@Input('each_project') each_project: any;
@Input('index') index: any;
@Input('projects_count') projects_count: any;
constructor() { }
ngOnInit(): void {
}
}
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClientCallService } from 'src/app/service/http-client-call.service';
@Component({
selector: 'app-repositories',
templateUrl: './repositories.component.html',
styleUrls: ['./repositories.component.scss']
})
export class RepositoriesComponent implements OnInit, OnDestroy {
users_repos: any = []
$user_repos: any;
constructor(
private httpClientCallService: HttpClientCallService
) { }
ngOnInit(): void {
this.$user_repos = this.httpClientCallService.user_repos.subscribe(data => {
this.users_repos = data;
})
}
ngOnDestroy() {
if (this.$user_repos) { this.$user_repos.unsubscribe() }
}
}
| 961ea5c2235dc2bd65c9ebca229a519d2b5bb443 | [
"TypeScript"
] | 12 | TypeScript | srujar/Assignment | 4d4228411c0ae1400f9054a971da1df4f0c64dea | 35a287374cd8574f09abe2eac81222fa12d6042a | |
refs/heads/master | <repo_name>Tcarter350/WDI-Project<file_sep>/db/seeds.js
const mongoose = require('mongoose');
const User = require('../models/user');
let mongoUri = process.env.MONGODB_URI || 'mongodb://localhost/events-api';
mongoose.connect(mongoUri);
User.collection.drop();
User.create([{
firstName: "Mike",
lastName: "Beadle",
email: "<EMAIL>",
age: 25,
gender: "Male",
interestedIn: "Women",
postcode: "E1W 2RG",
lat: 51.5089393,
lng: -0.0614053,
fact: "I once auditioned to be the Milky Bar Kid",
profilePic: "http://www2.mmu.ac.uk/media/mmuacuk/content/images/health-professions/student-profile-simone-bianchi-piantini.jpg",
password: "<PASSWORD>",
passwordConfirmation: "<PASSWORD>"
},{
firstName: "Kate",
lastName: "Winton",
email: "<EMAIL>",
age: 28,
gender: "Female",
interestedIn: "Men",
postcode: "N17 0AP",
lat: 51.6028157,
lng: -0.070018,
fact: "I like to go bouldering in my spare time. I'm an adventurist!",
profilePic: "https://assets.entrepreneur.com/content/16x9/822/20150406145944-dos-donts-taking-perfect-linkedin-profile-picture-selfie-mobile-camera-2.jpeg",
password: "<PASSWORD>",
passwordConfirmation: "<PASSWORD>"
},{
firstName: "James",
lastName: "Patrick",
email: "<EMAIL>",
age: 36,
gender: "Male",
interestedIn: "Women",
postcode: "W1D 4HS",
lat: 51.5121345,
lng: -0.1346313,
fact: "Currently training to become an actor",
profilePic: "http://adesignaward.com/designer/402730e84c6706c1f1ef41c3dfea8a3be70fb187-big.jpg",
password: "<PASSWORD>",
passwordConfirmation: "<PASSWORD>"
},{
firstName: "Karl",
lastName: "Kris",
email: "<EMAIL>",
age: 52,
gender: "Male",
interestedIn: "Women",
postcode: "N7 7AJ",
lat: 51.5540315,
lng: -0.111013,
fact: "Originally from Germany!",
profilePic: "https://www.newschool.edu/uploadedImages/Parsons/Profiles/jamer_hunt_profile.jpg?n=4468",
password: "<PASSWORD>",
passwordConfirmation: "<PASSWORD>"
},{
firstName: "Ray",
lastName: "Gill",
email: "<EMAIL>",
age: 37,
gender: "Male",
interestedIn: "Men",
postcode: "SE1 6DP",
lat: 51.4918063,
lng: -0.1042003,
fact: "I won last years 'Sony Photographer of the Year'",
profilePic: "http://www.christopherxjjensen.com/wp-content/gallery/profile-pics/Profile-Pic_2014-09-07_1000px.jpg",
password: "<PASSWORD>",
passwordConfirmation: "<PASSWORD>"
},{
firstName: "Emily",
lastName: "Ngenwe",
email: "<EMAIL>",
age: 56,
gender: "Female",
interestedIn: "Men",
postcode: "BR3 4JP",
lat: 51.4081874,
lng: -0.0413848,
fact: "I attended Boston University where I majored in Literature and Equine Studies",
profilePic: "http://www.american.edu/uploads/profiles/large/agolini.png",
password: "<PASSWORD>",
passwordConfirmation: "<PASSWORD>"
},{
firstName: "Phoebe",
lastName: "Archer",
email: "<EMAIL>",
age: 30,
gender: "Female",
interestedIn: "Men/Women",
postcode: "NW7 3AL",
lat: 51.6435682,
lng: -0.2737067,
fact: "I'm allergic to zucchini!",
profilePic: "https://pbs.twimg.com/profile_images/2170585198/profile-pic_400x400.jpg",
password: "<PASSWORD>",
passwordConfirmation: "<PASSWORD>"
}], (err, users) => {
if(err) console.log("Error seeding users", err);
console.log(`${users.length} users created`);
mongoose.connection.close();
});
<file_sep>/README.md
# WDI-Project
<NAME>
Peter
| 8a0469159dca579506f3615ed2fe409144a88b3d | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Tcarter350/WDI-Project | ee900f809f9eb9e6f914db10c6393d121d5dfede | 6c0788897e42c26fe8775e3143168938e20375b1 | |
refs/heads/master | <file_sep>module HomeHelper
def tel_to(phone_number:, country_code:)
phone_number = number_to_phone phone_number, country_code: country_code
link_to phone_number, "tel:#{phone_number}"
end
end
<file_sep>require("@rails/ujs").start()
// require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
var jQuery = require("jquery");
global.$ = global.jQuery = jQuery;
window.$ = window.jQuery = jQuery;
import 'bootstrap'
import './jquery.easing.min'
import Splide from "@splidejs/splide";
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip()
import('./scripts')
new Splide('#image-slider', {
type: 'loop',
pagination: false,
classes: {
arrow: 'splide__arrow splide__custom_array_color'
}
}).mount();
$('li.dropdown a.dropdown-item').click(function () {
$(this).parent().dropdown('hide')
})
})
// document.addEventListener("turbolinks:load", () => {
// $('[data-toggle="tooltip"]').tooltip()
// import('./scripts')
// });
import "@fortawesome/fontawesome-free/js/all";
<file_sep>Rails.application.routes.draw do
root to: 'home#index'
scope '(:locale)', locale: /en|ru/ do
get '/', to: 'home#index', as: 'root_localized'
end
end
| 945c31078e8826dcdf44885d9f7523a495e063c6 | [
"JavaScript",
"Ruby"
] | 3 | Ruby | IvanRiazantsev/eva | 11261cbd74e6fa8d1ef3c1a6012d33642180a8a4 | 6f5c4b2c213dbdef8b3e28ea32d2ba87c9781eb2 | |
refs/heads/master | <file_sep>require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@company = companies(:test)
@user = @company.users.build(last_name: "睦男", first_name: "下田",email: "<EMAIL>",
affiliation: "営業部", position: "部長",
password: "<PASSWORD>", password_confirmation: "<PASSWORD>")
end
test "should be valid" do
assert @user.valid?
end
test "company id should be presend" do
@user.company_id = nil
assert_not @user.valid?
end
end
<file_sep>require 'test_helper'
class CompanyTest < ActiveSupport::TestCase
def setup
@company = Company.new(office_name: "Example Office", phone_number: "00-0000-0000",
zip_code: "111-11111", address1: "Example address", address2: "Example address2",
staff_name: "<NAME>", staff_mail_address: "<EMAIL>")
end
test "should be valid" do
assert @company.valid?
end
test "office_name should be present" do
@company.office_name = " "
assert_not @company.valid?
end
test "phone_number should be present" do
@company.phone_number = " "
assert_not @company.valid?
end
test "staff_mail_address validation should accept valid addresses" do
valid_addresses = %w[<EMAIL> <EMAIL> <EMAIL>-<EMAIL>
<EMAIL> <EMAIL>]
valid_addresses.each do |valid_address|
@company.staff_mail_address = valid_address
assert @company.valid?, "#{valid_address.inspect} should be valid"
end
end
test "staff_mail_address validation should reject invalid addresses" do
invalid_addresses = %w[<EMAIL>@<EMAIL>,com user_at_foo.org user.<EMAIL>.
<EMAIL> <EMAIL>]
invalid_addresses.each do |invalid_address|
@company.staff_mail_address = invalid_address
assert_not @company.valid?, "#{invalid_address.inspect} should be invalid"
end
end
end
<file_sep>class CreateTimeCards < ActiveRecord::Migration[5.0]
def change
create_table :time_cards do |t|
t.string :working_day
t.string :start_time
t.string :end_time
t.string :outing_time
t.string :return_time
t.string :remark
t.references :user, foreign_key: true
t.timestamps
end
add_index :time_cards, [:user_id, :created_at]
end
end
<file_sep>class Company < ApplicationRecord
has_many :users
validates :office_name, presence:true
validates :phone_number, presence:true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :staff_mail_address, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }
end
<file_sep>class User < ApplicationRecord
belongs_to :company
has_many :time_card
validates :company_id, presence: true
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
# 渡された文字列のハッシュ値を返す
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
end
<file_sep>class CreateCompanies < ActiveRecord::Migration[5.0]
def change
create_table :companies do |t|
t.string :office_name
t.string :phone_number
t.string :zip_code
t.string :address1
t.string :address2
t.string :staff_name
t.string :staff_mail_address
t.timestamps
end
end
end
<file_sep>class UsersController < ApplicationController
def new
session[:company_id] = params[:company_id]
@company = Company.find_by(id: params[:company_id])
@user = @company.users.build
end
def show
@user = User.find(params[:id]);
end
def create
@company = Company.find_by(id: session[:company_id])
@user = @company.users.build(user_params)
if @user.save
log_in @user
flash[:success] = "Welcom "
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:last_name, :first_name, :email,
:affiliation, :position,:password,
:password_confirmation)
end
end
| 5e1981fde6e9ad541a405daa70ebf2911ac8f67f | [
"Ruby"
] | 7 | Ruby | makama/timeise | 2faca1d740d9bdf6323a07ad5b7a2b6f0d5aa304 | 3ebc0280b6f927c966af2afb91b6bd22c4c2b868 | |
refs/heads/master | <repo_name>applecool/Django-Experiments<file_sep>/polls/tests.py
from django.test import TestCase
from .models import Question
import datetime
from django.utils import timezone
from django.core.urlresolvers import reverse
# Create your tests here.
class QuestionMethodTests(TestCase):
def test_published_recently_with_future_question(self):
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertEqual(future_question.was_published_in_last_7_days(), False)
def test_published_recently_with_recent_question(self):
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertEqual(recent_question.was_published_in_last_7_days, True)
class QuestionViewTests(TestCase):
def test_index_view_with_no_questions(self):
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "You haven't uploaded any questions yet.")
self.assertQuerysetEqual(response.context["latest_question_list"], [])
class QuestionIndexDetailTests(TestCase):
def test_detail_view_with_a_past_question(self):
past_question = create_question(question_text="Past question", days=-5)
response = self.client.get(reverse('polls:detail', args=(past_question.id,)))
self.assertContains(response,past_question.question_text, status_code=200)
<file_sep>/README.md
# Django-Experiments
Experiments with Django Framework and the resultant web applications
| ebf21b766e05d912bd9378103d977fdd74754105 | [
"Markdown",
"Python"
] | 2 | Python | applecool/Django-Experiments | be8abe06ae8b424842e956ce700dcb5a084ed4a0 | fa30340aea4004d7669f41067870d617bba606bd | |
refs/heads/master | <file_sep>package instrumentos;
public class vientoMadera extends Instrumentos implements lustrables,afinables{
public vientoMadera(String nombre, String descripcion) {
super(nombre,descripcion);
}
public void lustrarInstrumento() {
System.out.println(super.getNombreInstrumento() + " ha sido lustrado");
}
public void afinarInstrumento() {
System.out.println(super.getNombreInstrumento() + " ha sido afinado manualmente");
}
}
<file_sep>package estudiantes;
public class Estudiante {
private Integer legajo;
private String nombre;
public Estudiante(Integer legajo, String nombre) {
this.legajo = legajo;
this.nombre = nombre;
}
public Integer getLegajo() {
return legajo;
}
public void setLegajo(Integer legajo) {
this.legajo = legajo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
@Override
public String toString() {
return "Estudiante [legajo=" + legajo + ", nombre=" + nombre + "]";
}
}
<file_sep>package estudiantes;
import java.util.*;
public class Escuela {
private List<Estudiante> alumnos;
public Escuela() {
this.alumnos= new ArrayList<Estudiante>();
}
public void agregarAlumno(Estudiante e) {
this.alumnos.add(e);
}
public void mostrarAlumnos() {
for(Estudiante alumnos : this.alumnos) {
System.out.println(alumnos);
}
}
public void ordenarPorLegajo() {
Collections.sort(this.alumnos, new ComparatorEstudianteLegajo());
}
}
<file_sep>package instrumentos;
public class instrumentoCuerda extends Instrumentos implements afinables {
public instrumentoCuerda(String nombre, String descripcion) {
super(nombre,descripcion);
}
public void afinarInstrumento() {
System.out.println(super.getNombreInstrumento() + " ha sido afinada");
}
}
<file_sep>package estudiantes;
public class mainEscuela {
public static void main(String[] args) {
Escuela industrial= new Escuela();
Estudiante lucas = new Estudiante(11,"Lucas");
Estudiante diego = new Estudiante(12,"Diego");
Estudiante marcelo = new Estudiante(11,"Marcelo");
industrial.agregarAlumno(marcelo);
industrial.agregarAlumno(lucas);
industrial.agregarAlumno(diego);
industrial.mostrarAlumnos();
}
}
<file_sep>package instrumentos;
public class vientoMetal extends Instrumentos implements afinables,lustrables{
public vientoMetal(String nombre, String descripcion) {
super(nombre,descripcion);
}
public void lustrarInstrumento() {
System.out.println(super.getNombreInstrumento() + " ha sido lustrado");
}
public void afinarInstrumento() {
System.out.println(super.getNombreInstrumento() + "ha sido afinado automaticamente");
}
}
| af71ffb8bbecb4be632f964ea9def6853afa88d0 | [
"Java"
] | 6 | Java | Nicooliver84/Java | 3968a0a706b8d184648cae0993e84eaa913c172f | 8d6517cf9705cc28573b9cbc06e663410521c4f0 | |
refs/heads/master | <repo_name>alopatindev/scalafmt-server<file_sep>/README.md
HTTP server to format Scala code from text editors (like vim)
[](https://travis-ci.org/alopatindev/scalafmt-server)
# Why
`scalafmt` starts slowly (as any JVM-based app) and [`nailgun`](http://scalameta.org/scalafmt/#Nailgun) is buggy and unmaintaned (?)
<p align="center"><img src="https://raw.githubusercontent.com/alopatindev/assets/master/weird-ng-behavior.png" width="838" height="340"></p>
That's sad
# Usage
Unpack and run the server
```sh
sbt universal:packageZipTarball
tar xzf target/universal/scalafmt-server-*.tgz
scalafmt-server-*/scalafmt-server.sh 8899 &
```
If you're using [vim-autoformat](https://github.com/Chiel92/vim-autoformat):
```viml
let g:formatdef_scalafmt = "'path/to/scalafmt-client.sh 8899'"
let g:formatters_scala = ['scalafmt']
au BufWrite *.scala :Autoformat
```
# License
Licensed under the terms of MIT (read LICENSE.txt for details)
<file_sep>/scripts/scalafmt-server.sh
#!/bin/sh
set -e
PORT=$1
CURRENT_DIR=$(dirname `readlink -f $0`)
if [[ $PORT -eq '' ]]
then
echo 'Port is not specified'
exit 1
fi
"${CURRENT_DIR}/bin/scalafmt-server" -Dhttp.port=${PORT} &
sleep 3s && echo 'object WarmUp { }' | "${CURRENT_DIR}/scalafmt-client.sh" "${PORT}" >> /dev/null
<file_sep>/scripts/scalafmt-client.sh
#!/bin/sh
PORT=$1
HOST='localhost'
INPUT='/dev/stdin'
if [[ $PORT -eq '' ]]
then
echo 'Port is not specified'
exit 1
fi
curl -s --upload-file "${INPUT}" "http://${HOST}:${PORT}/" || cat "${INPUT}"
| 328a9ef404e3335a569f4e89fcd2a9f1f64af9c7 | [
"Markdown",
"Shell"
] | 3 | Markdown | alopatindev/scalafmt-server | 8fae94745d9537fe2af74c5533c810e2cb3aa797 | 11b0ac699aa632423ff4c8455795a49b3e37dc33 | |
refs/heads/master | <repo_name>jessicamindel/fbu-parstagram<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/CameraManager.java
package com.jmindel.fbuparstagram;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class CameraManager {
public static final int CAPTURE_IMAGE_REQUEST_CODE = 1034;
public final static int PICK_PHOTO_REQUEST_CODE = 1046;
public static final int IMG_WIDTH = 600;
private File photoFile;
private String photoFileName;
private Fragment fragment;
public CameraManager(String photoFileName, Fragment fragment) {
this.photoFileName = photoFileName;
this.fragment = fragment;
}
public void takePhoto() {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Create a File reference to access to future access
photoFile = getPhotoFileUri(photoFileName);
// wrap File object into a content provider
// required for API >= 24
// See https://guides.codepath.com/android/Sharing-Content-with-Intents#sharing-files-with-api-24-or-higher
Uri fileProvider = FileProvider.getUriForFile(fragment.getContext(), "com.codepath.fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider);
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(fragment.getContext().getPackageManager()) != null) {
// Start the image capture intent to take photo
fragment.startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_CODE);
}
}
// Returns the File for a photo stored on disk given the fileName
public File getPhotoFileUri(String fileName) {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(fragment.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Parstagram");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d("CameraLauncher", "Failed to create directory");
}
// Return the file target for the photo based on filename
File file = new File(mediaStorageDir.getPath() + File.separator + fileName);
return file;
}
public Bitmap shrinkImage(Bitmap image, int width) throws IOException {
Bitmap resizedBitmap = BitmapScaler.scaleToFitWidth(image, width);
// Configure byte output stream
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// Compress the image further
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// Create a new file for the resized bitmap (`getPhotoFileUri` defined above)
File resizedFile = getPhotoFileUri(photoFileName + "_resized");
resizedFile.createNewFile();
FileOutputStream fos = new FileOutputStream(resizedFile);
// Write the bytes of the bitmap to file
fos.write(bytes.toByteArray());
fos.close();
return resizedBitmap;
}
public Bitmap rotateBitmapOrientation(String photoFilePath) {
// Create and configure BitmapFactory
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoFilePath, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(photoFilePath, opts);
// Read EXIF Data
ExifInterface exif = null;
try {
exif = new ExifInterface(photoFilePath);
} catch (IOException e) {
e.printStackTrace();
}
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
// Rotate Bitmap
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
// Return result
return rotatedBitmap;
}
public Bitmap fixOrientationAndSize() {
Bitmap takenImage = rotateBitmapOrientation(photoFile.getAbsolutePath());
// Resize bitmap
Bitmap scaledImage;
try {
scaledImage = shrinkImage(takenImage, CameraManager.IMG_WIDTH);
} catch (IOException e) {
Log.e("MakePostActivity", "Failed to scale image, using fallback");
e.printStackTrace();
scaledImage = takenImage;
}
return scaledImage;
}
public File getPhotoFile() {
return photoFile;
}
// Trigger gallery selection for a photo
public void pickPhoto() {
// Create intent for picking a photo from the gallery
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(fragment.getContext().getPackageManager()) != null) {
// Bring up gallery to select a photo
fragment.startActivityForResult(intent, PICK_PHOTO_REQUEST_CODE);
}
}
/** @source https://stackoverflow.com/questions/31227547/how-to-upload-image-to-parse-in-android */
public byte[] bitmapToBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
return image;
}
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/Utils.java
package com.jmindel.fbuparstagram;
import android.content.Context;
import android.text.format.DateUtils;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.parse.GetFileCallback;
import com.parse.ParseFile;
import com.parse.ParseUser;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Utils {
// getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014");
public static String getRelativeTimeAgo(String rawJsonDate) {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
Date date = sf.parse(rawJsonDate);
relativeDate = getRelativeTimeAgo(date);
} catch (ParseException e) {
e.printStackTrace();
}
return relativeDate.toUpperCase();
}
public static String getRelativeTimeAgo(Date rawDate) {
String relativeDate = "";
long dateMillis = rawDate.getTime();
long now = (new Date()).getTime();
long between = now - dateMillis;
int hoursBetween = (int) ((between / (1000 * 60 * 60)));
int yearsBetween = (new Date(now)).getYear() - (new Date(dateMillis)).getYear();
if (yearsBetween >= 1) {
SimpleDateFormat moreThanAYear = new SimpleDateFormat("MMM d yyyy", Locale.US);
relativeDate = moreThanAYear.format(dateMillis);
} else if (hoursBetween >= 24) {
SimpleDateFormat moreThanADay = new SimpleDateFormat("MMM d", Locale.US);
relativeDate = moreThanADay.format(dateMillis);
} else {
String rawRelativeDate = DateUtils.getRelativeTimeSpanString(dateMillis, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
String[] parts = rawRelativeDate.split(" ");
relativeDate = parts[0];
switch (parts[1]) {
case "second":
case "seconds":
relativeDate += "s";
break;
case "minute":
case "minutes":
relativeDate += "m";
break;
case "hour":
case "hours":
relativeDate += "h";
break;
case "day":
case "days":
relativeDate += "d";
break;
case "month":
case "months":
relativeDate += "mo";
break;
case "year":
case "years":
relativeDate += "y";
break;
default:
relativeDate = rawRelativeDate;
break;
}
}
return relativeDate.toUpperCase();
}
public static String ellipsize(String str, int maxChars) {
if (str.length() > maxChars) {
String ellipsized = str.substring(0, maxChars - 3);
ellipsized += "...";
return ellipsized;
} else {
return str;
}
}
public static void loadProfileImage(final Context context, final ImageView iv, final ParseUser user) {
ParseFile img = user.getParseFile("profileImage");
if (img != null) {
img.getFileInBackground(new GetFileCallback() {
@Override
public void done(File file, com.parse.ParseException e) {
Glide.with(context).load(file).into(iv);
}
});
}
}
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/activities/ProfileActivity.java
package com.jmindel.fbuparstagram.activities;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.jmindel.fbuparstagram.R;
import com.jmindel.fbuparstagram.fragments.ProfileFragment;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
import butterknife.BindView;
public class ProfileActivity extends AppCompatActivity {
public static final String KEY_USER_ID = "objectId";
FragmentManager fragmentManager;
private ProfileFragment fragment;
@BindView(R.id.flFragmentContainer) FrameLayout fragmentContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
fragmentManager = getSupportFragmentManager();
// Retrieve user passed in from id
String uid = getIntent().getStringExtra(KEY_USER_ID);
ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
userQuery.whereEqualTo(KEY_USER_ID, uid);
userQuery.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> objects, ParseException e) {
if (e != null || objects.size() == 0) {
Log.e("ProfileActivity", "Failed fetching user");
e.printStackTrace();
Toast.makeText(ProfileActivity.this, "Failed fetching user", Toast.LENGTH_LONG).show();
} else {
// Launch fragment specific to fetched user
ParseUser user = objects.get(0);
fragment = new ProfileFragment();
fragment.setUser(user);
fragmentManager.beginTransaction().replace(R.id.flFragmentContainer, fragment).commit();
}
}
});
}
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/activities/DetailActivity.java
package com.jmindel.fbuparstagram.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.jmindel.fbuparstagram.R;
import com.jmindel.fbuparstagram.adapters.PostAdapter;
import com.jmindel.fbuparstagram.model.Comment;
import com.jmindel.fbuparstagram.model.Post;
import com.jmindel.fbuparstagram.scrolling.CommentLayout;
import com.jmindel.fbuparstagram.scrolling.EdgeDecorator;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class DetailActivity extends AppCompatActivity {
public static final String KEY_POST_ID = "postId";
List<Post> posts;
PostAdapter postAdapter;
@BindView(R.id.rvPost) RecyclerView rvPost;
@BindView(R.id.clComments) CommentLayout clComments;
@BindView(R.id.bComment) Button bComment;
@BindView(R.id.etComment) EditText etComment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ButterKnife.bind(this);
posts = new ArrayList<>();
postAdapter = new PostAdapter(this, posts);
postAdapter.setEnablePostDetailClick(false);
LinearLayoutManager postLayoutManager = new LinearLayoutManager(this) {
@Override
public boolean canScrollVertically() {
return false;
}
};
rvPost.setLayoutManager(postLayoutManager);
rvPost.setAdapter(postAdapter);
rvPost.addItemDecoration(new EdgeDecorator(32, true, false));
bComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String body = etComment.getText().toString();
if (!body.equals("")) {
Comment comment = new Comment();
comment.setBody(body);
comment.setPost(posts.get(0));
comment.setUser(ParseUser.getCurrentUser());
comment.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
etComment.setText("");
clComments.load();
// TODO: Clean this up
}
});
} else {
Toast.makeText(DetailActivity.this, "Write a message before commenting!", Toast.LENGTH_LONG).show();
}
}
});
String currPostId = getIntent().getStringExtra(KEY_POST_ID);
Post.Query currPostQuery = new Post.Query().withUser();
currPostQuery.whereEqualTo(Post.KEY_ID, currPostId);
currPostQuery.findInBackground(new FindCallback<Post>() {
@Override
public void done(List<Post> objects, ParseException e) {
posts.add(objects.get(0));
postAdapter.notifyItemInserted(0);
clComments.setPost(posts.get(0));
clComments.load();
}
});
}
}
<file_sep>/README.md
### FBU SEA CodePath
# Parstagram
A simplified Instagram clone built with Parse.

# Assignment Checkpoints
## Required User Stories
- [x] User sees app icon in home screen. (1 point)
- [x] User can sign up to create a new account using Parse authentication (1 point)
- [x] User can log in and log out of his or her account (1 points)
- [x] The current signed in user is persisted across app restarts (1 point)
- [x] User can take a photo, add a caption, and post it to "Instagram" (2 points)
- [x] User can view the last 20 posts submitted to "Instagram" (2 points)
- [x] User can pull to refresh the last 20 posts submitted to "Instagram" (1 points)
- [x] User can tap a post to view post details, including timestamp and caption. (2 points)
## Stretch Stories
- [ ] Style the login page to look like the real Instagram login page. (2 points)
- [ ] Style the feed to look like the real Instagram feed. (2 points)
- [x] I styled it to look somewhat like Instagram, but as a CardView instead.
- [x] The user should switch between different tabs - viewing all posts (feed view), capture (camera and photo gallery view) and profile tabs (posts made) using fragments and a Bottom Navigation View. (2 points)
- [x] User can load more posts once he or she reaches the bottom of the feed using endless scrolling. (2 points)
- [x] Show the username and creation time for each post (1 point)
- [ ] After the user submits a new post, show an indeterminate progress bar while the post is being uploaded to Parse (1 point)
- [x] User Profiles:
- [x] Allow the logged in user to add a profile photo (1 point)
- [x] Display the profile photo with each post (1 points)
- [x] Tapping on a post's username or profile photo goes to that user's profile page and shows a grid view of the user's posts (2 points)
- [x] User can comment on a post and see all comments for each post in the post details screen. (2 points)
- [x] User can like a post and see number of likes for each post in the post details screen. (2 points)
## My Own Stories
- [x] Use Butterknife to reduce boilerplate
- [ ] Use ParseLive to automatically update content on a new post
- [ ] Retain posts in timeline instead of reloading every time (not quite SQL persistence)
- [ ] Add user follow functionality
- [x] Finished the backend, but not the frontend
- [ ] User can choose image filters before posting
- [ ] User can annotate and draw on images...
- [ ] With brushes
- [ ] With stamps
- [ ] User can repost a post
- [ ] ...with their own filters and/or annotations added
- [ ] The repost links back to the original post despite having a potentially different image
- [ ] Add fun scroll animations (e.g. background color fade on scroll, segmented scrolling, etc.)
- [ ] Implement search features
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/fragments/ComposeFragment.java
package com.jmindel.fbuparstagram.fragments;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.jmindel.fbuparstagram.CameraManager;
import com.jmindel.fbuparstagram.R;
import com.jmindel.fbuparstagram.model.Post;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ComposeFragment extends Fragment {
private CameraManager cameraManager;
String photoFileName = "photo.jpg";
private ParseFile imageFile;
public static final String KEY_POST = "post";
@BindView(R.id.ivImage) ImageView ivImage;
@BindView(R.id.etCaption) EditText etCaption;
@BindView(R.id.bFromLibrary) Button bFromLibrary;
@BindView(R.id.bFromCamera) Button bFromCamera;
@BindView(R.id.bPost) Button bPost;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_compose, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
cameraManager = new CameraManager(photoFileName, this);
bFromLibrary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cameraManager.pickPhoto();
}
});
bFromCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cameraManager.takePhoto();
}
});
bPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String caption = etCaption.getText().toString();
if (imageFile != null && !caption.equals("")) {
Post post = new Post();
post.setImage(imageFile);
post.setCaption(caption);
post.setUser(ParseUser.getCurrentUser());
post.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e != null) {
Log.e("ComposeFragment", "Failed to post");
e.printStackTrace();
Toast.makeText(getContext(), "Failed to post", Toast.LENGTH_LONG).show();
} else {
Log.d("ComposeFragment", "Posted successfully!");
Toast.makeText(getContext(), "Posted successfully!", Toast.LENGTH_SHORT).show();
etCaption.setText("");
}
}
});
} else {
Toast.makeText(getContext(), "Add an image and caption before posting.", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == CameraManager.CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Log.d("ComposeFragment", "Successfully took photo");
// by this point we have the camera photo on disk
Bitmap scaledImage = cameraManager.fixOrientationAndSize();
// Load the taken image into a preview
ivImage.setImageBitmap(scaledImage);
imageFile = new ParseFile(cameraManager.getPhotoFile());
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d("ComposeFragment", "Canceled open camera");
}
} else if (requestCode == CameraManager.PICK_PHOTO_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK && data != null) {
Uri photoUri = data.getData();
try {
Bitmap selectedImage = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), photoUri);
ivImage.setImageBitmap(selectedImage);
imageFile = new ParseFile(cameraManager.bitmapToBytes(selectedImage));
} catch (IOException e) {
Log.e("ComposeFragment", "Failed to get image from library");
e.printStackTrace();
Toast.makeText(getContext(), "Failed to get image from library", Toast.LENGTH_LONG).show();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d("ComposeFragment", "Canceled open library");
} else {
Log.e("ComposeFragment", "No data passed from image library");
}
}
}
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/activities/HomeActivity.java
package com.jmindel.fbuparstagram.activities;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.jmindel.fbuparstagram.R;
import com.jmindel.fbuparstagram.fragments.ComposeFragment;
import com.jmindel.fbuparstagram.fragments.ProfileFragment;
import com.jmindel.fbuparstagram.fragments.TimelineFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
public class HomeActivity extends AppCompatActivity {
// ids start with 11
public static final int MAKE_POST_REQUEST_CODE = 11;
@BindView(R.id.bottom_navigation) BottomNavigationView bottomNav;
FragmentManager fragmentManager;
TimelineFragment timelineFragment;
ComposeFragment composeFragment;
ProfileFragment profileFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
timelineFragment = new TimelineFragment();
composeFragment = new ComposeFragment();
profileFragment = new ProfileFragment();
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment fragment;
switch (menuItem.getItemId()) {
case R.id.miCompose:
fragment = composeFragment;
break;
case R.id.miProfile:
fragment = profileFragment;
break;
case R.id.miHome:
default:
fragment = timelineFragment;
break;
}
fragmentManager.beginTransaction().replace(R.id.flFragmentContainer, fragment).commit();
return true;
}
});
fragmentManager.beginTransaction().replace(R.id.flFragmentContainer, timelineFragment).commit();
// Set logged out to false
getIntent().putExtra(LoginActivity.KEY_LOGGED_OUT, false);
}
// public void onMakePost(View view) {
// Intent i = new Intent(this, MakePostActivity.class);
// startActivityForResult(i, MAKE_POST_REQUEST_CODE);
// }
//
// @Override
// protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// if (resultCode == RESULT_OK && requestCode == MAKE_POST_REQUEST_CODE) {
//// final Post post = data.getParcelableExtra(MakePostActivity.KEY_POST);
//// post.saveInBackground(new SaveCallback() {
//// @Override
//// public void done(ParseException e) {
//// if (e != null) {
//// Log.e("HomeActivity", "Posting failed");
//// e.printStackTrace();
//// Toast.makeText(HomeActivity.this, "Posting failed", Toast.LENGTH_LONG).show();
//// } else {
//// Log.d("HomeActivity", "Posting succeeded!");
//// items.add(0, post);
//// adapter.notifyItemInserted(0);
//// rvPosts.scrollToPosition(0);
//// // TODO: Navigate to new post and/or otherwise show it
//// }
//// }
//// });
// }
// }
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/scrolling/EndlessScrollRefreshLayout.java
package com.jmindel.fbuparstagram.scrolling;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.jmindel.fbuparstagram.R;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public abstract class EndlessScrollRefreshLayout<Item, VH extends RecyclerView.ViewHolder> extends FrameLayout {
protected RecyclerView.Adapter<VH> adapter;
protected List<Item> items;
protected EndlessRecyclerViewScrollListener scrollListener;
@BindView(R.id.rvItems) protected RecyclerView rvItems;
@BindView(R.id.swipeContainer) protected SwipeRefreshLayout swipeContainer;
public EndlessScrollRefreshLayout(@NonNull Context context) {
super(context);
init();
}
public EndlessScrollRefreshLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public EndlessScrollRefreshLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
inflate(getContext(), R.layout.layout_endless_scroll_refresh, this);
ButterKnife.bind(this, this);
// Configure RecyclerView
items = new ArrayList<>();
adapter = makeAdapter();
rvItems.setAdapter(adapter);
rvItems.addItemDecoration(new EdgeDecorator(getEdgePadding(), shouldPadTopEdge(), shouldPadBottomEdge()));
// LEARN: There's got to be a better and far more properly polymorphic way to do this...
switch (getLayoutManagerType()) {
case Grid:
GridLayoutManager gLayoutManager = makeGridLayoutManager();
rvItems.setLayoutManager(gLayoutManager);
// Configure infinite scrolling
scrollListener = new EndlessRecyclerViewScrollListener(gLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
loadMore();
}
};
break;
case StaggeredGrid:
StaggeredGridLayoutManager sgLayoutManager = makeStaggeredGridLayoutManager();
rvItems.setLayoutManager(sgLayoutManager);
// Configure infinite scrolling
scrollListener = new EndlessRecyclerViewScrollListener(sgLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
loadMore();
}
};
break;
default:
case Linear:
LinearLayoutManager lLayoutManager = makeLinearLayoutManager();
rvItems.setLayoutManager(lLayoutManager);
// Configure infinite scrolling
scrollListener = new EndlessRecyclerViewScrollListener(lLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
loadMore();
}
};
break;
}
// Add the scroll listener to RecyclerView
rvItems.addOnScrollListener(scrollListener);
// Add swipe to refresh actions
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
items.clear();
adapter.notifyDataSetChanged();
load();
}
});
swipeContainer.setColorSchemeResources(getColorScheme());
}
public abstract void load();
public abstract void loadMore();
public abstract RecyclerView.Adapter<VH> makeAdapter();
public abstract LayoutManagerType getLayoutManagerType();
public abstract LinearLayoutManager makeLinearLayoutManager();
public abstract GridLayoutManager makeGridLayoutManager();
public abstract StaggeredGridLayoutManager makeStaggeredGridLayoutManager();
public abstract int[] getColorScheme();
public abstract int getEdgePadding();
public abstract boolean shouldPadTopEdge();
public abstract boolean shouldPadBottomEdge();
public enum LayoutManagerType {
Linear, Grid, StaggeredGrid
}
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/model/Post.java
package com.jmindel.fbuparstagram.model;
import com.parse.FindCallback;
import com.parse.ParseClassName;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.io.Serializable;
@ParseClassName("Post")
public class Post extends ParseObject implements Serializable {
public static final String KEY_CAPTION = "caption";
public static final String KEY_IMAGE = "image";
public static final String KEY_USER = "user";
public static final String KEY_CREATED_AT = "createdAt";
public static final String KEY_ID = "objectId";
public String getCaption() {
return getString(KEY_CAPTION);
}
public void setCaption(String caption) {
put(KEY_CAPTION, caption);
}
public ParseFile getImage() {
return getParseFile(KEY_IMAGE);
}
public void setImage(ParseFile image) {
put(KEY_IMAGE, image);
}
public ParseUser getUser() {
return getParseUser(KEY_USER);
}
public void setUser(ParseUser user) {
put(KEY_USER, user);
}
public void findLikesInBackground(FindCallback<Like> cb) {
Like.Query query = new Like.Query().withPost().withUser().forPost(this);
query.findInBackground(cb);
}
public void findCommentsInBackground(FindCallback<Comment> cb) {
Comment.Query query = new Comment.Query().withPost().withUser().forPost(this);
query.findInBackground(cb);
}
public static class Query extends ParseQuery<Post> {
public Query() {
super(Post.class);
}
public Query getTop() {
return getTop(20);
}
public Query getTop(int limit) {
setLimit(limit);
return this;
}
public Query withUser() {
include("user");
return this;
}
}
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/ParseApp.java
package com.jmindel.fbuparstagram;
import android.app.Application;
import com.jmindel.fbuparstagram.model.Comment;
import com.jmindel.fbuparstagram.model.Like;
import com.jmindel.fbuparstagram.model.Post;
import com.parse.Parse;
import com.parse.ParseObject;
public class ParseApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ParseObject.registerSubclass(Post.class);
ParseObject.registerSubclass(Like.class);
ParseObject.registerSubclass(Comment.class);
final Parse.Configuration config = new Parse.Configuration.Builder(this)
.applicationId("jmindel-fbu-parstagram")
.clientKey("<KEY>")
.server("https://jmindel-fbu-parstagram.herokuapp.com/parse")
.build();
Parse.initialize(config);
}
}
<file_sep>/FBUParstagram/app/src/main/java/com/jmindel/fbuparstagram/activities/LoginActivity.java
package com.jmindel.fbuparstagram.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.jmindel.fbuparstagram.R;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import butterknife.BindView;
import butterknife.ButterKnife;
public class LoginActivity extends AppCompatActivity {
@BindView(R.id.etUsername) EditText etUsername;
@BindView(R.id.etPassword) EditText etPassword;
@BindView(R.id.etEmail) EditText etEmail;
@BindView(R.id.bLogin) Button bLogin;
@BindView(R.id.bSignUp) Button bSignUp;
// ids start with 1
public static final int HOME_REQUEST_CODE = 1;
public static final String KEY_LOGGED_OUT = "loggedOut";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
// Set up button clicks
bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
if (!username.equals("") && !password.equals("")) {
login(username, password);
}
}
});
bSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
final String email = etEmail.getText().toString();
if (!username.equals("") && !password.equals("") && !email.equals("")) {
signUp(username, password, email);
}
}
});
// Automatically log in cached user
ParseUser currUser = ParseUser.getCurrentUser();
if (currUser != null) {
Log.d("LoginActivity", "Logged-in user persisted successfully.");
launchHome();
}
}
protected void login(final @NonNull String username, final @NonNull String password) {
ParseUser.logInInBackground(username, password, new LogInCallback() {
@Override
public void done(ParseUser user, ParseException e) {
if (e == null) {
Log.d("LoginActivity", "Login successful!");
launchHome();
} else {
Log.e("LoginActivity", "Login failed.");
e.printStackTrace();
}
}
});
}
protected void signUp(final @NonNull String username, final @NonNull String password, final @NonNull String email) {
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(<PASSWORD>);
user.setEmail(email);
user.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
Log.d("LoginActivity", "Sign up succeeded!");
login(username, password);
} else {
Log.d("LoginActivity", "Sign up failed.");
}
}
});
}
protected void launchHome() {
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
startActivityForResult(i, HOME_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == RESULT_OK && requestCode == HOME_REQUEST_CODE) {
boolean loggedOut = data.getBooleanExtra(KEY_LOGGED_OUT, false);
if (loggedOut) finish();
}
}
}
| e088ebaffee96522875fef0ccbaad049dfc915b6 | [
"Markdown",
"Java"
] | 11 | Java | jessicamindel/fbu-parstagram | 16107df7f1e95d0f0c95357c769917746da4629b | e00d68d882a441b520b432d23fd5341fcab2519e | |
refs/heads/master | <file_sep><?php
/*
Código escrito por <NAME>
em caso de dúvidas, mande um email para <EMAIL>
*/
date_default_timezone_set("Brazil/East"); //Define o horário padrão como o de Brazilia.
function linha($semana){
echo "<tr>\n";
for($i=0;$i < 7; $i++){
if(isset($semana[$i])){
if ($semana[$i] == date('d') or $i == 6){
echo "<td><strong>{$semana[$i]}</strong></td>\n";
}elseif($i == 0){
echo "<td class='domingo'>{$semana[$i]}</td>\n";
}else{
echo "<td>{$semana[$i]}</td>\n";
}
}else{
echo "<td></td>\n";
}
}
echo "</tr>\n";
}
function calendario(){
$dia = 1;
$semana = array();
while ($dia <= 31){
array_push($semana,$dia);
if(count($semana) == 7){
linha($semana);
$semana = array();
}
$dia++;
}
linha($semana);
}
function bemVindo(){
if (date('H') >= 6 and date('H')<= 11){
echo "Bom dia.";
}else if(date('H') >= 12 and date('H') <= 17){
echo "Boa tarde.";
}else{
echo "Bom noite";
}
}
<file_sep><?php
include 'functions.php';
?>
<html>
<head>
<title>Dia <?php echo date('d');?>!</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>
<h1>Estamos em <?php echo date('Y');?></h1>
<p><?php bemVindo();?></p>
<p>Agora são <?php echo date('H');?> horas e <?php echo date('i');?> minutos.</p>
<table border="2" class="table-responsive">
<tr>
<th>Dom</th>
<th>Seg</th>
<th>Ter</th>
<th>Qua</th>
<th>Qui</th>
<th>Sex</th>
<th>Sab</th>
</tr>
<?php calendario();?>
</table>
</body>
</html>
| f3fc4ad73cb4561523763f1c28f6383b3b5df076 | [
"PHP"
] | 2 | PHP | jorcelinojunior/calendar | 237703137a8d200d03ecce3164794d5742498b88 | f098a2e5714d055dd26f97dcf133222c2965bda6 | |
refs/heads/master | <repo_name>lukasz-m-b/quick-lookup<file_sep>/ajax.php
<?php
require_once('WordEntry.php');
session_start();
// ini_set('display_errors', 1);
// error_reporting(E_ALL ^ E_STRICT);
list($command, $value) = each(json_decode(file_get_contents('php://input'), true));
$commands_white_list = ['fetch', 'prepare_download'];
if (in_array($command, $commands_white_list)) {
echo json_encode($command($value));
} else {
echo '{"error":"illegal request to server"}';
}
function db() {
return new PDO($_SESSION['pdo_data'][0], $_SESSION['pdo_data'][1], $_SESSION['pdo_data'][2]);
}
function fetch($word) {
$from_db = fetch_word_from_db($word);
if ($from_db !== false) {
return ['response' => $from_db->HTML()];
}
$from_online = fetch_word_online($word);
if ($from_online !== false) {
return ['response' => $from_online->HTML()];
}
return ['error' => 'not found'];
}
function fetch_word_online($word) {
$dom = new DOMDocument();
@$dom->loadHTMLFile("http://pl.bab.la/slownik/angielski-polski/$word");
$sections = $dom->getElementsByTagName('section');
$section = null;
for ($i = 0; $i < $sections->length; $i++) {
if (strpos($sections->item($i)->nodeValue, 'tłumaczenie polskie') !== false) {
$section = $sections->item($i);
break;
}
}
if ($section === null) {
return false;
}
$a_in_section = $section->getElementsByTagName('a');
$a_words = [];
for ($i = 0; $i < $a_in_section->length; $i++) {
$a = $a_in_section->item($i);
if ($a->hasAttribute('href') && strpos($a->getAttribute('href'), 'babSpeakIt') !== false) {
$a_words[] = $a->nextSibling->nextSibling->nodeValue;
}
}
if (empty($a_words)) {
return false;
}
$word_entry = new WordEntry($a_words);
$db = db();
$insert = $db->prepare("INSERT INTO words VALUES (NULL, ?, ?);");
$insert->execute([$word, $word_entry->JSON()]);
return $word_entry;
}
function fetch_word_from_db($word) {
$db = db();
$get = $db->prepare("SELECT word_entry FROM words WHERE queried_word = ? LIMIT 1");
$get->execute([$word]);
$fetched = $get->fetchAll(PDO::FETCH_ASSOC);
if (empty($fetched)) {
return false;
}
return new WordEntry(json_decode($fetched[0]['word_entry']));
}
function prepare_download($html) {
$_SESSION['html'] = $html;
return ['response' => 'ok'];
}
?>
<file_sep>/WordEntry.php
<?php
class WordEntry {
private $meanings;
public function __construct($data) {
if (is_array($data)) { // from html
$this->meanings = [];
for($i = 0; $i < count($data); $i += 2) {
$en = $data[$i];
$pl = $data[$i + 1];
if (array_key_exists($en, $this->meanings)) {
$this->meanings[$en][] = $pl;
} else {
$this->meanings[$en] = [$pl];
}
}
} else { // from json
$this->meanings = (array) $data;
}
}
public function __debugInfo() {
return $this->meanings;
}
public function HTML() {
$html = '';
foreach($this->meanings as $en => $pl) {
$html .= '<p><a href="javascript:;" class="word_en is_selected">' . $en . '</a>: ';
foreach ($pl as $word_pl) {
$html .= '<a href="javascript:;" class="word_pl is_selected">' . $word_pl . '</a> ';
}
$html .= '</p>';
}
return $html;
}
public function JSON() {
return json_encode($this->meanings);
}
}
?>
<file_sep>/README.md
# quick-lookup
##### (this is an early experimental version, take a look version 2.0)
A PHP/jQuery application for speakers of Polish to facilitate reading English texts and learning new vocabulary. It still has some rough edges and there is a lot of functionality to add.
http://lukaszb.byethost15.com/quick_lookup/
<file_sep>/download.php
<?php
header('content-type: text/html');
header('content-disposition: attachment; filename="words_'
. (new DateTime())->format('Y-m-d') . '".html'
);
session_start();
if (!isset($_SESSION['html'])) {
exit();
}
?>
<html>
<meta charset="UTF-8">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
font-size: medium;
}
p.note_sentence {
font-style: italic;
}
span.word_emphasize {
font-weight: bold;
color: navy;
}
</style>
<?php
echo str_replace('<button class="remove_note">usuń notatkę</button>', '<hr>', $_SESSION['html']);
echo '</html>';
exit();
?>
<file_sep>/index.php
<?php
// ini_set('display_errors', 1);
// error_reporting(E_ALL ^ E_STRICT);
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="quick-lookup.css" type="text/css">
<link rel="shortcut icon" href="green.png" type="image/png">
<title>quick lookup</title>
</head>
<body>
<div id="top_title"><h1>quick lookup</h1></div>
<div id="lookup">
<div class="hint" id="lookup_hint"></div>
<table>
<tr>
<td id="lookup_text" style="width: 50%; text-align: justify;">
<textarea id="lookup_text_textarea" cols="100" rows="20">
"He's not coming back out, I tell you!" stated a pimply-faced man, shaking his head with finality. "It's been an hour and a quarter since he went in. He's done for."
The townsfolk, huddled together in the midst of the ruins and rubble, watched the gaping black hole of the entrance to the tunnel in silence. A fat man dressed in a yellow smock shifted slightly from one foot to the other, cleared his throat and pulled his wrinkled cap from his head.
"We have to wait a bit longer," he said as he wiped the sweat from his sparse eyebrows.
"Why wait?" snorted pimply, "There in the caves lurks a basilisk, or have you forgotten, burgrave? Anyone goes down there, that's the end of them. Have you forgotten how many have died down there already? What are we waiting for?"
"This was the agreement, wasn't it?" murmured the fat man uncertainly.
"An agreement you made with a living man, burgrave" said the pimply-faced man's companion, a giant of a man in a leather butcher's apron. "He is now dead, as surely as the sun shines in the sky. It was plain from the beginning that he was headed towards death, like all the others before him. He didn't even take a mirror with him, only a sword - and everybody knows you need a mirror in order to kill a basilisk."
</textarea><br>
<button id="lookup_text_analyze">analizuj</button>
</td>
<td id="lookup_glosses">
</td>
</tr>
</table>
</div>
<hr>
<div id="notes">
</div>
<div style="text-align: center;">
<button id="download">zapisz notatki do pliku</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="quick-lookup.js"></script>
</body>
</html>
<?php
$_SESSION['pdo_data'] = json_decode(file_get_contents('pdo.data'), true);
?>
<file_sep>/quick-lookup.js
var debugging = false;
//debugging = true;
var word_html_cache = {};
var last_sentence_clicked = '';
$('body').on('click', '#lookup_text_analyze', function() {
analyze_text();
}).on('click', '#lookup_new', function() {
$('td#lookup_text').html('<textarea id="lookup_text_textarea" cols="100" rows="15">' +
'</textarea><br>' +
'<button id="lookup_text_analyze">analyze</button>');
$('td#lookup_glosses').empty();
}).on('click', 'a.word', function() {
var searched = $(this).text();
last_sentence_clicked = $(this).parent().text().replace(
new RegExp(' ' + searched + ' ', 'g'),
function(x) {return ' <span class="word_emphasize">' + x + '</span> ';}
).replace(
/\s+([\.\?\,\!])/g,
function(m) {return m[1];}
);
if (searched in word_html_cache) {
$('#lookup_glosses').fadeOut(200, function() {
$('#lookup_glosses').html(word_html_cache[searched]).append(
'<button id="make_note">zapisz notatkę</button>'
);}).fadeIn();
return;
}
ajax(
{fetch: searched},
function(html) {
word_html_cache[searched] = html.response;
$('#lookup_glosses').fadeOut(200, function() {
$('#lookup_glosses').html(html.response).append(
'<button id="make_note">zapisz notatkę</button>'
);}).fadeIn();
},
function(error) {
if (error.error === 'not found') {
last_sentence_clicked = '';
display_error('nieznane słowo');
}
});
}).on('click', 'a.word_pl', function() {
$(this).toggleClass('is_selected');
if ($(this).hasClass('is_selected')) {
$('.word_en', $(this).parent()).first().addClass('is_selected');
}
}).on('click', 'a.word_en', function() {
var word_en_is_selected = $(this).hasClass('is_selected');
$(this).parent().children().each(
word_en_is_selected
? function(_, a) {$(a).removeClass('is_selected');}
: function(_, a) {$(a).addClass('is_selected');}
);
}).on('click', '#make_note', function() {
if (last_sentence_clicked === '') {
return;
}
var note = '<div class="note"><p class="note_sentence">' + last_sentence_clicked + '</p>';
var words_added = false;
$('td#lookup_glosses p').each(function(_, p) {
var glosses = $(p).children();
if (glosses.first().hasClass('is_selected')) {
var note_gloss = '<p><span class="word_emphasize">' + glosses.first().text() + '</span>: ';
glosses.slice(1).each(function(_, a) {
if ($(a).hasClass('is_selected')) {
note_gloss += $(a).text() + ' ';
}
});
note += note_gloss + '</p>';
words_added = true;
}
});
if (words_added) {
$('#notes').append(note + '<button class="remove_note">usuń notatkę</button><br><br></div>');
}
}).on('click', '.remove_note', function() {
$(this).parent().slideUp(200, function() {$(this).remove();});
}).on('click', '#download', function() {
if ($('#notes').children().length > 0) {
ajax({prepare_download: $('#notes').html()}, function() {
window.location = 'download.php';
});
}
});
// ----- //
function ajax(to_send, callback, error_callback) {
$.ajax({
url: 'ajax.php',
method: 'post',
data: JSON.stringify(to_send),
processData: false,
contentType: 'application/json; charset=UTF-8',
success: function(received) {
if (debugging) {
console.log(received);
return;
}
var response = JSON.parse(received);
if ('error' in response) {
if (error_callback) {
error_callback(response);
} else {
display_error('ERROR\n' + response.error);
}
} else if (callback) {
callback(response);
}
},
error: function() {
display_error('błąd połączenia z serwerem');
}
});
}
function display_error(msg) {
alert(msg);
}
// ----- //
$('#lookup_hint').attr('data-hint',
'Ta strona pomoże Ci szybko sprawdzać nieznane słowa w angielskich tekstach. <ul>' +
'<li>wklej dowolny angielski tekst i kliknij <i>analizuj</i></li>'+
'<li>gdy natrafisz na nieznane słowo, kliknij je, by sprawdzić znaczenie w słowniku</li>' +
'<li>klikając <i>zapisz notatkę</i>, możesz zapisać nowe słowo, by go nie zapomnieć</li>' +
'<li>słownik podaje wszystkie znaczenia słowa - jeśli niektóre uważasz za niepotrzebne ' +
'lub niepasujące do zdania, możesz je łatwo usunąć</li></ul>');
function show_hint(div) {
div.html(div.attr('data-hint') + ' ').append(
$(' <a class="got_it" href="javascript:;">jasne</a>').click(function() {
hide_hint($(this).parent());
}));
}
function hide_hint(div) {
div.html($(' <a class="got_it" href="javascript:;">co to jest?</a>').click(function() {
show_hint($(this).parent());
}));
}
$('div.hint').each(function() {
hide_hint($(this));
});
// ----- //
function analyze_text() {
var html = '<span class="sentence">' +
$('#lookup_text_textarea').val().replace(/[\.\?\,\"\'\/\!\&\(\)\[\]\<\>\n\—\”\“\’]/g, function(m) {
return ' ' + m + ' ';
}).split(/[\t ]+/).map(function(x) {
if ('?,"\'/!&()[]<>—”“’'.indexOf(x) !== -1) {
return '<span class="punc">' + $('<div />').text(x).html() + '</span>';
} else if (x === '.') {
return '</span>.<span class="sentence">';
} else if (x === '?') {
return '</span>?<span class="sentence">';
} else if (x === '!') {
return '</span>!<span class="sentence">';
} else if (x === '\n' || x === '\r') {
return '<br>';
} else {
return ' <a class="word">' + $('<div />').text(x).html() + '</a> ';
}
}).join('') + '</span>';
$('td#lookup_text').html(
'<div style="height: 500px; overflow-y: scroll; padding: 10px; margin: 5px">' + html + '</div>'
).append('<br><button id="lookup_new">nowy tekst</button>');
}
| ae6c2eb571e517e02cf71da72e664e30b778918c | [
"Markdown",
"JavaScript",
"PHP"
] | 6 | PHP | lukasz-m-b/quick-lookup | 228cf8669691bc1edd2335f61bc0e56c97215e33 | 69993779c4dcc8de5f0a6235e6e676300b101289 | |
refs/heads/master | <file_sep>package clem.app.jnews.constant
import android.widget.Toast
object Constant {
/**
* baseUrl
*/
const val REQUEST_BASE_URL = "http://172.16.58.3:5000/"
/**
* Toast
*/
@JvmField
var showToast: Toast? = null
/**
* Share preferences name
*/
const val SHARED_NAME = "_preferences"
/**
* Debug
*/
const val INTERCEPTOR_ENABLE = false
}<file_sep>package clem.app.jnews.retrofit
import clem.app.jnews.bean.NewsItem
import kotlinx.coroutines.experimental.Deferred
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Query
/**
* Retrofit请求api
*/
interface RetrofitService {
@Headers("Authorization: ContentType <KEY>")
@GET("news")
fun getNewsList(
@Query("category") category: String
): Deferred<List<NewsItem>>
}<file_sep>package clem.app.jnews.bean
data class NewsItem(
/**
* category : tech_science/list
* desc :
* image : ./photo/AS20180220003821.html
* main_title :
* subcategory :
* time : 2018-02-24
* url : https://www.asahi.com/articles/ASL2B01DPL29PLFA012.html
*/
var title: String,
var category: String,
var desc: String,
var image: String,
var main_title: String,
var subcategory: String,
var time: String,
var url: String
)<file_sep>package clem.app.jnews
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import clem.app.jnews.base.BaseActivity
import clem.app.jnews.bean.NewsItem
import clem.app.jnews.retrofit.RetrofitHelper
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
class MainActivity : BaseActivity() {
private var newsAsync: Deferred<List<NewsItem>>? = null
override fun initImmersionBar() {
super.initImmersionBar()
immersionBar.titleBar(R.id.toolbar).init()
}
override fun setLayoutId(): Int = R.layout.activity_main
override fun cancelRequest() {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
toolbar.run {
title = getString(R.string.app_name)
setSupportActionBar(this)
}
drawerLayout.run {
val toggle = ActionBarDrawerToggle(
this@MainActivity,
this,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
addDrawerListener(toggle)
toggle.syncState()
}
navigationView.run { setNavigationItemSelectedListener(onDrawerNavigationItemSelectedListener) }
fab.run { setOnClickListener(onFabClickListener) }
}
private fun getNews() {
var newsList: List<NewsItem>
async(UI) {
tryCatch({
it.printStackTrace()
}, {
newsAsync?.cancelByActive()
newsAsync = RetrofitHelper.retrofitService.getNewsList("national/list")
val result = newsAsync?.await()
result ?: let {
toast("Failed")
return@async
}
toast(result.size.toString())
})
}
}
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// 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.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
private val onDrawerNavigationItemSelectedListener =
NavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.nav_camera -> {
// Handle the camera action
}
R.id.nav_gallery -> {
}
R.id.nav_slideshow -> {
}
R.id.nav_manage -> {
}
R.id.nav_share -> {
}
R.id.nav_send -> {
}
}
drawerLayout.closeDrawer(GravityCompat.START)
true
}
private val onFabClickListener =
View.OnClickListener {
Snackbar.make(coordinator, "Snack it", Snackbar.LENGTH_LONG).show()
}
}
| 429cf7aafbb0dee9468f487cab4dbd472860dc84 | [
"Kotlin"
] | 4 | Kotlin | narakai/JNews | 1b3a25c3da373856a0c0ac3674c9645dc9d039de | 0c08f8571f67c1f28ded357300e164fd8bf0bba4 | |
refs/heads/master | <repo_name>PuyaAlemirad/TeacherRestService<file_sep>/test/JUnitTest/NewEmptyJUnitTest.java
///*
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
//package JUnitTest;
//
//import dao.TeacherDAOInterface;
//import entity.Teacher;
//import java.util.ArrayList;
//import java.util.List;
//import org.junit.Before;
//import org.junit.Test;
//import service.DaoRest;
//
//public class NewEmptyJUnitTest {
//
// MockPairDAO mock;
// DaoRest daoRest;
// Teacher t;
//
// @Before
// public void setUp() {
// mock = new MockPairDAO();
// daoRest = new DaoRest();
// t = new Teacher();
// }
//
// @Test
// public void createTeacher() {
// mock.addTeacher(t);
//
// }
//
// class MockPairDAO implements TeacherDAOInterface {
//
// @Override
// public void addTeacher(Teacher t) {
//
// }
//
// @Override
// public void editTeacher(Teacher t) {
//
// }
//
// @Override
// public void removeTeacher(Long id) {
//
// }
//
// @Override
// public Teacher findById(Long id) {
//
// if (t.getId().equals(id)) {
// return t;
// } else {
// return null;
// }
//
// }
//
// @Override
// public List<Teacher> getAllTeacher() {
// List<Teacher> list = new ArrayList<>();
// return list;
// }
//
// }
//}
<file_sep>/README.md
# TeacherRestService
Rest service API that has all the features for a CRUD.
Project was done in februari 2019.
<file_sep>/src/java/dao/TeacherDAO.java
package dao;
import entity.Teacher;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class TeacherDAO implements TeacherDAOInterface {
@PersistenceContext
EntityManager em;
@Override
public void addTeacher(Teacher t) {
em.persist(t);
}
@Override
public void editTeacher(Teacher t) {
em.merge(t);
}
@Override
public void removeTeacher(int id) {
em.remove(em.find(Teacher.class, id));
}
@Override
public Teacher findById(int id) {
return em.find(Teacher.class, id);
}
@Override
public List<Teacher> getAllTeacher() {
return em.createQuery("SELECT t FROM Teacher t").getResultList();
}
}
| 123db03defad4e52d4579587d06dd380ab043646 | [
"Markdown",
"Java"
] | 3 | Java | PuyaAlemirad/TeacherRestService | ec8904917acfbce5b2d9539e958e41dff5cd9b68 | 6c5890d418ee4f584016646ff6a1e8fe22cf5b3e | |
refs/heads/master | <file_sep>import Styled, { createGlobalStyle } from 'styled-components'
import { normalize } from 'styled-normalize'
import BG from '../../assets/images/background.jpg'
export const GlobalStyle = createGlobalStyle`
${normalize}
html, body {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Bebas Neue', cursive;
font-family: 'Montserrat', sans-serif;
background: url(${BG}) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width: 100%;
height: 100vh;
overflow-y: hidden;
}
.counterDiv {
margin-top: 2rem;
@media (max-width: 1024px) {
margin: 0;
flex: 2.5 !important;
}
}
.is-loading {
color: ${props => props.theme.isLoadingColor};
font-size: 3.6rem;
@media (min-width: 320px) and (max-width: 1023px) {
font-size: 2rem;
}
}
.is-complete {
font-size: 6rem;
font-weight: bold;
color: ${props => props.theme.primaryTextColor};
}
.has-msg {
margin: 1rem 0 0 0;
font-size: 1rem;
text-align: center;
@media (min-width: 320px) and (max-width: 1023px) {
font-size: 12px;
padding: 0rem 1rem .5rem;
}
}
.notify-text {
text-align: center;
@media (min-width: 320px) and (max-width: 1023px) {
font-size: 12px;
letter-spacing: .1rem !important;
}
}
.top-div {
@media (max-width: 1024px) {
flex: 0 !important;
padding-top: 8%;
}
}
`
export const BGTransparent = Styled.div`
position: absolute;
width: 100%;
height: 100vh;
background: ${props => props.theme.main};
opacity: .8;
`
export const Wrapper = Styled.div`
position: absolute;
width: 100%;
overflow: hidden;
height: 100vh;
`
export const Container = Styled.div`
display: flex;
flex: 1;
justify-content: center;
height: 100vh;
`
export const Grid = Styled.div`
display: flex;
flex: ${props => props.flex || 1};
flex-direction: ${props => props.direction || 'row'};
justify-content: ${props => props.justify || ''};
align-items: ${props => props.align || ''};
`
export const Box = Styled.div`
display: flex;
flex: ${props => props.flex || 1};
justify-content: ${props => props.justify || ''};
flex-direction: ${props => props.direction || ''};
align-items: ${props => props.align || ''};
margin: ${props => props.margin || ''};
& p {
font-family: Montserrat;
font-weight: bold;
letter-spacing: .4rem;
color: ${props => props.theme.primaryTextColor};
text-transform: uppercase;
margin: 0;
}
.input {
background: none;
padding: 0;
width: 35rem;
height: 6rem;
-webkit-border-top-left-radius: .5rem;
-webkit-border-bottom-left-radius: .5rem;
border-top-left-radius: .5rem;
border-bottom-left-radius: .5rem;
border-right: 0 !important;
-webkit-border-right: none;
-moz-border-right: none;
-o-border-right: none;
border: solid .2rem ${props => props.theme.primaryBorderColor};
text-align: center;
font-size: 1.4rem;
color: ${props => props.theme.primaryTextColor};
outline: none;
z-index: 20;
&::placeholder {
color: ${props => props.theme.primaryTextColor};
background: transparent;
line-height: 6.1rem;
@media (min-width: 320px) and (max-width: 1023px) {
font-size: 1rem;
}
}
@media (min-width: 320px) and (max-width: 1023px) {
width: 15rem;
height: 3.5rem;
}
@media (max-width: 320px) {
width: 13rem;
height: 3.5rem;
}
}
`
export const Img = Styled.img`
position: absolute;
left: -1rem;
bottom: -1rem;
opacity: ${props => props.theme.logoOpacity};
z-index: 0;
width: 27.3%;
height: 83%;
@media (min-width: 320px) and (max-width: 460px) {
left: -3.5rem;
bottom: 2rem;
width: 80%;
height: 75%;
}
`
export const Title = Styled.div`
font-family: Montserrat;
font-size: 3.7rem;
font-weight: 500;
letter-spacing: 1rem;
color: ${props => props.theme.primaryTextColor};
text-transform: uppercase;
@media (min-width: 320px) and (max-width: 1023px) {
font-size: 1rem;
margin-top: 1rem;
letter-spacing: .8rem;
}
`
export const CounterTick = Styled.div`
text-align: center;
margin: 0px 3rem;
@media (min-width: 320px) and (max-width: 1023px) {
margin: .8rem;
}
.title {
font-family: 'Montserrat';
font-size: .9rem;
font-weight: bold;
letter-spacing: .2rem;
color: ${props => props.theme.primaryTextColor};
@media (min-width: 320px) and (max-width: 1023px) {
font-size: .5rem;
}
}
.tick {
font-family: 'Bebas Neue';
font-size: 5.5rem;
font-weight: bold;
letter-spacing: .2rem;
color: ${props => props.theme.primaryTextColor};
@media (min-width: 320px) and (max-width: 1023px) {
font-size: 2rem;
}
}
`
export const Button = Styled.button`
background: ${props => props.theme.primaryTextColor};
color: ${props => props.theme.primaryTextColor};
width: 4.8rem;
height: 6.4rem;
border: none;
border-top-right-radius: .5rem;
border-bottom-right-radius: .5rem;
padding: 0;
text-align: center;
cursor: pointer;
outline: none;
display: flex;
flex: 1;
justify-content: center;
align-items: center;
& img {
transition: all .5s;
&:hover {
transform: scale(1.5);
@media (min-width: 320px) and (max-width: 1023px) {
transform: scale(1.3);
}
}
}
@media (min-width: 320px) and (max-width: 1023px) {
width: 2.4rem;
height: 3.9rem;
}
`
export const ToggleBtn = Styled.button`
position: absolute;
right: 2rem;
top: 2rem;
font-size: 3rem;
background: transparent;
border: none;
z-index: 3;
cursor: pointer;
outline: none;
@media (min-width: 320px) and (max-width: 1023px) {
right: 1rem;
top: 0;
}
i {
color: ${props => props.theme.primaryTextColor};
font-size: 3rem;
@media (min-width: 320px) and (max-width: 1023px) {
font-size: 1rem;
}
}
`
export const Form = Styled.form`
display: flex;
margin-top: 1rem;
@media (min-width: 320px) and (max-width: 1023px) {
margin-top: 1rem;
}
`
<file_sep>import React, { Fragment, useState } from 'react'
import { ThemeProvider } from 'styled-components'
import Countdown from 'react-countdown-now'
import Axios from 'axios'
import {
GlobalStyle,
Wrapper,
Container,
Grid,
Img,
Box,
Title,
BGTransparent,
Button,
ToggleBtn,
Form,
} from './style'
import CounterTickComponent from './CounterTickComponent'
import Logo from '../../assets/images/logo.png'
import LogoY from '../../assets/images/logoy.png'
import Check from '../../assets/images/check.png'
import CheckY from '../../assets/images/checky.png'
const theme = {
main: '#d8b153',
primaryTextColor: 'black',
primaryBorderColor: 'black',
logoOpacity: '.2',
isLoadingColor: '#d8b153',
}
const invertedTheme = {
main: 'black',
primaryTextColor: '#d8b153',
primaryBorderColor: '#d8b153',
logoOpacity: '.2',
isLoadingColor: 'black',
}
const ComingSoon = () => {
const [mode, setMode] = useState(true)
const [email, setEmail] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [hasMsg, setHasMsg] = useState('')
const handleSubmit = e => {
setIsLoading(true)
setHasMsg('')
e.preventDefault()
Axios.put(
'https://api.sendgrid.com/v3/marketing/contacts',
{
contacts: [{ email }],
list_ids: [],
},
{
headers: {
'access-control-allow-origin': '*',
},
}
)
.then(res => {
setIsLoading(false)
setHasMsg('Received your notify request ... Thank you!')
})
.catch(err => {
setIsLoading(false)
setHasMsg('Something went wrong please try again ... Thank you!')
})
}
const Completed = () => <span className="is-complete">We are up now!</span>
const renderer = ({ days, hours, minutes, seconds, completed }) => {
if (completed) {
return <Completed />
}
return (
<Fragment>
<CounterTickComponent title="Days" time={days} />
<CounterTickComponent title="Hours" time={hours} />
<CounterTickComponent title="Minutes" time={minutes} />
<CounterTickComponent title="Seconds" time={seconds} />
</Fragment>
)
}
return (
<ThemeProvider theme={mode ? theme : invertedTheme}>
<Fragment>
<GlobalStyle />
<BGTransparent />
<ToggleBtn
onClick={e => {
e.preventDefault()
setMode(mode != true)
}}
>
<i className="fa fa-adjust"></i>
</ToggleBtn>
<Wrapper id="main-wrapper">
<Img src={mode ? Logo : LogoY} />
<Container>
<Grid direction="column">
<Box
className="top-div"
direction="column"
justify="flex-end"
align="center"
flex="1.5"
margin="2rem 0 0 0"
>
<Title>Coming Soon</Title>
</Box>
<Box
flex="1"
justify="center"
className="counterDiv"
margin="1rem 0 0 0"
>
<Countdown
date={new Date('01/20/2020').getTime()}
renderer={renderer}
/>
</Box>
<Box
className="bottom-div"
direction="column"
justify="flex-end"
align="center"
flex="1"
>
<p className="notify-text">Get Notified when it's ready</p>
<Box flex="0" justify="center" align="flex-start">
<Form onSubmit={handleSubmit}>
<input
className="input"
placeholder="Enter your Email"
type="email"
required
onChange={e => setEmail(e.target.value)}
/>
<Button disabled={isLoading}>
{isLoading ? (
<i className="is-loading fa fa-cog fa-spin"></i>
) : (
<img
width="21"
height="21"
src={mode ? Check : CheckY}
alt="Check Icon"
/>
)}
</Button>
</Form>
</Box>
<Box
flex="1"
direction="column"
justify="flex-start"
align="center"
margin="1rem 0 0 0"
>
<p className="has-msg">{hasMsg}</p>
</Box>
</Box>
</Grid>
</Container>
</Wrapper>
</Fragment>
</ThemeProvider>
)
}
export default ComingSoon
<file_sep>import React from 'react'
import { CounterTick } from './style'
const CounterTickComponent = ({ title, time }) => {
return (
<CounterTick>
<div className="title">{title}</div>
<div className="tick">{time}</div>
</CounterTick>
)
}
export default CounterTickComponent
| e95983a1a188b5278ce85e916357772aae70ba00 | [
"JavaScript"
] | 3 | JavaScript | adilsaeed31/react-comingsoon-page | b1c4c0105c8864e123c9ee727c72f2ac70830245 | 868508b8379360c99d0dabdabf80101b86c5d9c0 | |
refs/heads/main | <repo_name>annakristin97/weightlifting-tracker-app<file_sep>/README.md
# weightlifting-tracker-app
Weightlifting Tracker Android App
| 40d505bae2dd698b1acc4ecbc67884c17cdfef02 | [
"Markdown"
] | 1 | Markdown | annakristin97/weightlifting-tracker-app | 958f915acce4924b348acb657125eccedd6446c9 | 5c8f141466140b3f4b84bb74a4ad46e55b08754c | |
refs/heads/master | <file_sep>class MoviesController < ApplicationController
def movie_params
params.require(:movie).permit(:title, :rating, :description, :release_date)
end
def show
id = params[:id] # retrieve movie ID from URI route
@movie = Movie.find(id) # look up movie by unique ID
# will render app/views/movies/show.<extension> by default
end
def index
# getting all movies
@movies = Movie.all
# getting all ratings
@all_ratings = Movie.available_ratings_options
# checking if ratings can be applied
if params[:ratings]
# getting the ratings values from the params
@ratings = params[:ratings].keys
# maintaining session ratings
session[:filtered_rating] = @ratings
if session[:sort] and not params[:sort]
# instatiating new hash
query_hash = Hash.new
# maintaining session fitlered ratings
query_hash['ratings'] = params[:ratings]
# if allowable sortable sort
if params[:sort]
query_hash['sort'] = params[:sort]
else
query_hash['sort'] = session[:sort]
end
redirect_to movies_path(query_hash)
end
elsif session[:filtered_rating] # checking for sessions filtered ratings, if applicable
# instatiating new hash
query_hash = Hash.new
# maintaining session fitlered ratings
query_hash['ratings'] = Hash[session[:filtered_rating].collect { |item| [item, "1"] } ]
# if allowable sortable sort
if params[:sort]
query_hash['sort'] = params[:sort]
else
query_hash['sort'] = session[:sort]
end
# storing empty to session's filtered ratings
session[:filtered_rating] = nil
# maining the flash entries
flash.keep
# redirecting to browser page that issued request
redirect_to movies_path(query_hash)
else
# getting all ratings
@ratings = @all_ratings
end
# getting movies with specified rating
@movies.where!(rating: @ratings)
# when sorted highlight, change reordering in ascending order
case params[:sort]
when 'release_date'
@release_date_class = "hilite"
@movies.order!('release_date')
@release_date_path = "none"
@title_path = "title"
session[:sort] = 'release_date'
when 'title'
@title_class = "hilite"
@movies.order!('title')
@release_date_path = "release_date"
@title_path = "none"
session[:sort] = 'title'
when nil
@release_date_path = "release_date"
@title_path = "title"
session[:sort] = "none"
end
end
def new
# default: render 'new' template
end
def create
@movie = Movie.create!(movie_params)
flash[:notice] = "#{@movie.title} was successfully created."
redirect_to movies_path
end
def edit
@movie = Movie.find params[:id]
end
def update
@movie = Movie.find params[:id]
@movie.update_attributes!(movie_params)
flash[:notice] = "#{@movie.title} was successfully updated."
redirect_to movie_path(@movie)
end
def destroy
@movie = Movie.find(params[:id])
@movie.destroy
flash[:notice] = "Movie '#{@movie.title}' deleted."
redirect_to movies_path
end
end
<file_sep>class Movie < ActiveRecord::Base
# getting distinct ratings and sorting the list
def self.available_ratings_options
pluck('DISTINCT rating').sort!
end
end
| 5e3e7e9595732bcdbd55721dcf7502a28bc0bbd1 | [
"Ruby"
] | 2 | Ruby | AMyscich/rottenpotatoes-rails-intro | 678372e7f8aaa1b738442c14f0db1a70104af552 | 5dae5e1c9f182c871926aef177c2fc19ba5cddc8 | |
refs/heads/master | <repo_name>mschmulen/IsomorphicSwift<file_sep>/Tests/LinuxMain.swift
import XCTest
@testable import IsomorphicSwiftTests
XCTMain([
testCase(IsomorphicSwiftTests.allTests),
])
<file_sep>/Sources/IsomorphicSwift/IsoYacht.swift
import Foundation
public struct IsoYacht : Codable {
public var name:String
public var year:Int
public init(name: String, year: Int) {
self.name = name
self.year = year
}
}<file_sep>/Sources/IsomorphicSwift/IsoPart.swift
import Foundation
public struct IsoPart : Codable {
public var name:String
public var description:String
public init(name: String, description: String) {
self.name = name
self.description = description
}
}<file_sep>/README.md
# IsomorphicSwift
A description of this package.
| 6be926801b73d0e93ace92f1754da1977f0d7175 | [
"Swift",
"Markdown"
] | 4 | Swift | mschmulen/IsomorphicSwift | 443dc0fa48c4280f4ac5000c672897c96e336465 | afdffc7bef0458e4594c05d39d7c13303bcf14ce | |
refs/heads/master | <file_sep># --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>, <NAME> and <NAME>
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
np.set_printoptions(threshold=np.nan)
import numpy.random as npr
from model.config import cfg
from model.bbox_transform import bbox_transform
from utils.cython_bbox import bbox_overlaps
def proposal_target_layer(rpn_rois, rpn_scores, gt_boxes, _num_classes):
"""
Assign object detection proposals to ground-truth targets. Produces proposal
classification labels and bounding-box regression targets.
"""
# Proposal ROIs (0, x1, y1, x2, y2) coming from RPN
# (i.e., rpn.proposal_layer.ProposalLayer), or any other source
all_rois = rpn_rois
all_scores = rpn_scores
# Include ground-truth boxes in the set of candidate rois
if cfg.TRAIN.USE_GT:
zeros = np.zeros((gt_boxes.shape[0], 1), dtype=gt_boxes.dtype)
all_rois = np.vstack(
(all_rois, np.hstack((zeros, gt_boxes[:, :-1])))
)
# not sure if it a wise appending, but anyway i am not using it
all_scores = np.vstack((all_scores, zeros))
num_images = 1
rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images
fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
# Sample rois with classification labels and bounding box regression
# targets
labels, rois, roi_scores, bbox_targets, bbox_inside_weights, choose_box = _sample_rois(
all_rois, all_scores, gt_boxes, fg_rois_per_image,
rois_per_image, _num_classes)
rois = rois.reshape(-1, 5)
roi_scores = roi_scores.reshape(-1)
labels = labels.reshape(-1, 1)
bbox_targets = bbox_targets.reshape(-1, _num_classes * 4)
bbox_inside_weights = bbox_inside_weights.reshape(-1, _num_classes * 4)
bbox_outside_weights = np.array(bbox_inside_weights > 0).astype(np.float32)
return rois, roi_scores, labels, bbox_targets, bbox_inside_weights, bbox_outside_weights, choose_box
def _get_bbox_regression_labels(bbox_target_data, num_classes):
"""Bounding-box regression targets (bbox_target_data) are stored in a
compact form N x (class, tx, ty, tw, th)
This function expands those targets into the 4-of-4*K representation used
by the network (i.e. only one class has non-zero targets).
Returns:
bbox_target (ndarray): N x 4K blob of regression targets
bbox_inside_weights (ndarray): N x 4K blob of loss weights
"""
clss = bbox_target_data[:, 0]
bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)
bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)
inds = np.where(clss > 0)[0]
for ind in inds:
cls = clss[ind]
start = int(4 * cls)
end = start + 4
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
return bbox_targets, bbox_inside_weights
def _compute_targets(ex_rois, gt_rois, labels):
"""Compute bounding-box regression targets for an image."""
assert ex_rois.shape[0] == gt_rois.shape[0]
assert ex_rois.shape[1] == 4
assert gt_rois.shape[1] == 4
targets = bbox_transform(ex_rois, gt_rois)
if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED:
# Optionally normalize targets by a precomputed mean and stdev
targets = ((targets - np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS))
/ np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS))
return np.hstack(
(labels[:, np.newaxis], targets)).astype(np.float32, copy=False)
def _sample_rois(all_rois, all_scores, gt_boxes, fg_rois_per_image, rois_per_image, num_classes):
"""Generate a random sample of RoIs comprising foreground and background
examples.
"""
# overlaps: (rois x gt_boxes)
choose_box = 0
overlaps = bbox_overlaps(
np.ascontiguousarray(all_rois[:, 1:5], dtype=np.float),
np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float)) #计算all_rois和gt_boxes之间的重叠部分 overlaps[n, k] n是all_rois.shape[0],K是gt_boxes.shape[0]
gt_assignment = overlaps.argmax(axis=1) #找到每一个rois 对应的groundtruth位置
max_overlaps = overlaps.max(axis=1) #找到每一个rois 对应的groundtruth其中anchors的score
labels = gt_boxes[gt_assignment, 4]#gt_labels的第五个位置的信息赋给labels class信息
# Select foreground RoIs as those with >= FG_THRESH overlap
fg_inds = np.where(max_overlaps >= cfg.TRAIN.FG_THRESH)[0] #找到前景 max_overlaps>=0.5
# Guard against the case when an image has fewer than fg_rois_per_image #预防找到的前景少于fg_rois_per_image的情况
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where((max_overlaps < cfg.TRAIN.BG_THRESH_HI) &
(max_overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # 找到0.1<overlaps<0.5的位置当作背景
# TODO: 改动de起始点
fg_rois_per_image_temp = fg_rois_per_image
# Small modification to the original version where we ensure a fixed number of regions are sampled
if fg_inds.size > 0 and bg_inds.size > 0: #如果前景与背景都存在
fg_rois_per_image = min(fg_rois_per_image, fg_inds.size) #找到真正的fg_rois_per_image的数量
fg_inds = npr.choice(fg_inds, size=int(fg_rois_per_image), replace=False) #随机生成fg_rois_per_image数量的fg_inds
choose_box = fg_inds.size
# fg_rois = all_rois[fg_inds]
num_temp = np.int((fg_rois_per_image_temp - fg_inds.size) // fg_inds.size) # 每个框增值的数量
res_temp = np.int((fg_rois_per_image_temp - fg_inds.size) % fg_inds.size) # 最后一个框多增值的数量
import copy
cp_fg_inds = copy.deepcopy(fg_inds)
for idx in cp_fg_inds:
box_group_temp = []
for i1 in range(3):
for i2 in range(3):
for i3 in range(3):
for i4 in range(3):
if i1 == 1 and i2 == 1 and i3 == 1 and i4 == 1:
continue
# print("----------------------------------------")
# print(all_rois[idx].copy())
# print(i1,i2,i3,i4)
box_temp = all_rois[idx].copy()
box_add_temp = [0, (i1-1) * 0.1 * (box_temp[3] - box_temp[1]),
(i2-1) * 0.1 * (box_temp[4] - box_temp[2]),
(i3-1) * 0.1 * (box_temp[3] - box_temp[1]),
(i4 - 1) * 0.1 * (box_temp[4] - box_temp[2]),]
box_temp += box_add_temp
box_group_temp.append(box_temp)
# print(box_temp)
# print("----------------------------------------")
box_group_temp = np.array(box_group_temp)
# print("=====================\n",box_group_temp)
# print('88888888888888888888888888888888888888888888888888888888')
# print(np.shape(all_rois))
# print(box_group_temp.shape)
# print("jieguo",res_temp)
# 选框
# overlaps: (rois x gt_boxes)
overlaps1 = bbox_overlaps(
np.ascontiguousarray(box_group_temp[:, 1:5], dtype=np.float),
np.ascontiguousarray(gt_boxes[:, :4],
dtype=np.float)) # 计算all_rois和gt_boxes之间的重叠部分 overlaps[n, k] n是all_rois.shape[0],K是gt_boxes.shape[0]
gt_assignment1 = overlaps1.argmax(axis=1) # 找到每一个rois 对应的groundtruth位置
max_overlaps1 = overlaps1.max(axis=1) # 找到每一个rois 对应的groundtruth其中anchors的score
order_temp = np.argsort(-max_overlaps1) # 降序排序
box_group_temp = box_group_temp[order_temp] # box
gt_assignment1 = gt_assignment1[order_temp] # 对应groundtruth编号
# print('#######',gt_assignment1)
# print(num_temp)
if idx != cp_fg_inds[-1]:
box_group_temp = box_group_temp[:num_temp]
gt_assignment1 = gt_assignment1[:num_temp]
# fg_rois_per_image += num_temp # 根据新增的正样本数量
else:
box_group_temp = box_group_temp[:num_temp + res_temp]
gt_assignment1 = gt_assignment1[:num_temp + res_temp]
# fg_rois_per_image += num_temp + res_temp # 根据新增的正样本数量
# box_group_temp = tf.convert_to_tensor(box_group_temp)
# print(all_rois.shape)
# print(box_group_temp.shape)
for i in range(len(box_group_temp)):
fg_inds = np.append(fg_inds, len(all_rois) + i) # 将新的box的序号添加到fg_inds
labels = np.append(labels, labels[idx])
all_scores = np.append(all_scores, 0.5) # 防止返回值越界
# labels += gt_boxes[gt_assignment1, 4] # gt_labels的第五个位置的信息赋给labels class信息
all_rois = np.concatenate((all_rois, box_group_temp), axis=0) # 新的box添加到原来的rois后面
gt_assignment = np.concatenate((gt_assignment, gt_assignment1), axis=0)
# Select foreground RoIs as those with >= FG_THRESH overlap
# fg_inds1 = np.where(max_overlaps1 >= cfg.TRAIN.FG_THRESH)[0] # 找到前景 max_overlaps>=0.5
if fg_inds.size != fg_rois_per_image_temp:
lack = fg_rois_per_image_temp - fg_inds.size
else:
lack = 0
# print(all_rois.shape)
# print(all_scores.shape)
bg_rois_per_image = rois_per_image - fg_rois_per_image_temp + lack # 每张图片上的rois-fg_rois就是bg_rois_per_image
to_replace = bg_inds.size < bg_rois_per_image # 如果bg_inds.size少于bg_rois_per_image 也就是说出现更多的前景
bg_inds = npr.choice(bg_inds, size=int(bg_rois_per_image), replace=to_replace) #随机选取bg_rois_per_image数量的bg_inds
elif fg_inds.size > 0:
to_replace = fg_inds.size < rois_per_image
fg_inds = npr.choice(fg_inds, size=int(rois_per_image), replace=to_replace)
fg_rois_per_image = rois_per_image
elif bg_inds.size > 0:
to_replace = bg_inds.size < rois_per_image
bg_inds = npr.choice(bg_inds, size=int(rois_per_image), replace=to_replace)
fg_rois_per_image = 0
else:
import pdb
pdb.set_trace()
# The indices that we're selecting (both fg and bg)
# print(len(fg_inds))
keep_inds = np.append(fg_inds, bg_inds)
# print(keep_inds)
# Select sampled values from various arrays:
# print("=====================\n",labels,len(labels))
labels = labels[keep_inds] #去掉<0.1的值
# print("=====================\n",labels,len(labels))
# print(len(labels))
# print(labels)
# Clamp labels for the background RoIs to 0
labels[int(fg_rois_per_image_temp):] = 0 #将background的标签设置为0
# print(labels)
rois = all_rois[keep_inds] #找到在0.1~1之间的rois
roi_scores = all_scores[keep_inds] #找到在0.1~1之间的roi_scores
bbox_target_data = _compute_targets(
rois[:, 1:5], gt_boxes[gt_assignment[keep_inds], :4], labels) #返回pre 与gt 之间的tx值 并经过normalize处理 形式是labels+4tx
# print(gt_assignment[keep_inds])
bbox_targets, bbox_inside_weights = \
_get_bbox_regression_labels(bbox_target_data, num_classes)
rois = np.float32(rois)
roi_scores = np.float32(roi_scores)
# with open("log.txt","a") as f:
# f.write("label_list:\n"+str(labels) +
# "\n" + "fg_inds:\n" + str(fg_inds) + "\n"
# "roi_scores:\n" + str(roi_scores)+"\n" +
# "bbox_targets:\n" + str(bbox_targets) + "\n" +
# "rois:\n" + str(rois))
return labels, rois, roi_scores, bbox_targets, bbox_inside_weights, choose_box #返回每一个anchor对应的类别信息,rois设定为0.1~1之间的roi,bbox_targets的信息是在其对应坐标上的,bbox_inside_weights的也是
| b42540fae5d154914754042e76ecd69fe1689fac | [
"Python"
] | 1 | Python | gqy4166000/tf-faster-rcnn | cd22621411c18f83c98d1cf25e8865f3d4619eb1 | 2715fb5156654188cdb777ab1ec9b4462db5a405 | |
refs/heads/master | <file_sep>import styled from "styled-components";
const Paragraph = styled.p`
font-size: ${props => (props.bold ? "1.5rem" : "1.2rem")};
font-weight: 500;
margin-bottom: 1.5rem;
font-weight: ${props => (props.bold ? "600" : "500")};
`;
export default Paragraph;
<file_sep>import React, { useEffect } from "react"
import {
ModalBackground,
ModalContainer,
ModalHeader,
ModalHeaderTitle,
ModalHeaderClose,
} from "./styles"
import IconCross from "../icons/Cross"
import { useSpring, animated } from "react-spring"
const AnimatedModalContainer = animated(ModalContainer)
export default function Modal({ isOpen, onClose, title, children }) {
const contentProps = useSpring({
opacity: isOpen ? 1 : 0,
config: { duration: 100 },
})
useEffect(() => {
window.addEventListener("keydown", onEscKeyDown, false)
return () => {
window.removeEventListener("keydown", onEscKeyDown, false)
}
}, [isOpen])
const onEscKeyDown = e => {
if (e.key !== "Escape") return
onClose()
}
if (isOpen) {
return (
<ModalBackground
data-testid="modal-background"
open={isOpen}
onClick={onClose}
>
<AnimatedModalContainer
style={contentProps}
onClick={event => event.stopPropagation()}
>
<ModalHeader>
<ModalHeaderTitle>{title || ""}</ModalHeaderTitle>
<ModalHeaderClose
data-testid="modal-header-close"
onClick={onClose}
>
<IconCross />
</ModalHeaderClose>
</ModalHeader>
{children}
</AnimatedModalContainer>
</ModalBackground>
)
} else {
typeof document !== `undefined` &&
document.body.style.removeProperty(`overflow-y`)
return null
}
}
<file_sep>import * as Yup from "yup"
const phoneRegExp = /^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/
export const validationSchema = Yup.object().shape({
name: Yup.string()
.min(2, "Too Short!")
.max(50, "Too Long!")
.required("Required"),
email: Yup.string()
.email("Invalid email")
.required("Required"),
location: Yup.string().required("Required"),
phone: Yup.string()
.matches(phoneRegExp, "Phone number is not valid")
.required("Required"),
subject: Yup.string().required("Required"),
})
export const options = [
{ value: "info", label: "General Info" },
{ value: "workshop", label: "Workshop" },
{ value: "personal-training", label: "Personal Training" },
{ value: "nutrition", label: "Nutrition" },
{ value: "disc", label: "DISC – Personality Test" },
]
export const initialValues = {
email: "",
name: "",
location: "",
phone: "",
subject: "info",
message: "",
}
<file_sep>import styled from "styled-components"
const Title = styled.h1`
width: 100%;
text-align: center;
margin: 0 0 1.5rem 0;
`
export default Title
<file_sep>import React from "react"
import { render } from "@testing-library/react"
import Icon from "../Icon.css.js"
import theme from "../theme"
describe("Button", () => {
it("renders correctly", () => {
const { asFragment } = render(<Icon />)
expect(asFragment()).toMatchSnapshot()
})
it("renders correctly with theme", () => {
const { asFragment, container } = render(<Icon theme={theme} />)
expect(container.firstChild).toHaveStyleRule("fill", theme.textColor)
expect(asFragment()).toMatchSnapshot()
})
})
<file_sep>import React from "react"
import { render } from "@testing-library/react"
import Form from "../index.js"
describe("Form", () => {
it("renders correctly", () => {
const { asFragment } = render(<Form />)
expect(asFragment()).toMatchSnapshot()
})
})
<file_sep>import React from "react";
import styled from "styled-components";
import { ErrorMessage } from "formik";
const StyledErrorMessage = styled(ErrorMessage)`
color: #d8000c;
font-size: 0.75rem;
margin-top: 0.15rem;
`;
const InputGroup = styled.div`
margin-bottom: 0.5rem;
`;
const Label = styled.label`
display: block;
font-size: 0.75rem;
margin: 0.25rem 0;
`;
export default props => (
<InputGroup>
<Label>{props.label}</Label>
{props.children}
<StyledErrorMessage {...props.error} />
</InputGroup>
);
<file_sep>import React from "react"
import { render } from "@testing-library/react"
import ArrowDown from "../ArrowDown.js"
describe("Icon/arrow-down", () => {
it("renders correctly", () => {
const { asFragment } = render(<ArrowDown />)
expect(asFragment()).toMatchSnapshot()
})
})
<file_sep>import styled from "styled-components"
const Icon = styled.svg`
display: block;
fill: ${props => props.theme.textColor};
width: 1rem;
height: 1rem;
`
export default Icon
<file_sep>import React from "react"
import Icon from "../styled/Icon.css.js"
export default props => (
<Icon {...props} viewBox="0 0 32 32">
<path d="M16 31l15-15h-9v-16h-12v16h-9z"></path>
</Icon>
)
<file_sep>import styled from "styled-components"
const Content = styled.div`
@media (min-width: 768px) {
padding: 1rem 2rem;
}
`
export default Content
<file_sep>import React from "react"
import styled from "styled-components"
import { graphql, useStaticQuery } from "gatsby"
import Title from "./styled/Title.css.js"
import Section from "./styled/Section.css.js"
import Content from "./styled/Content.css.js"
const Label = styled.label`
display: block;
margin-bottom: 0.25rem;
`
const Value = styled.div`
display: block;
font-weight: 600;
max-width: 500px;
margin: 0 auto;
`
const Block = styled.div`
margin-bottom: 1rem;
`
const Inner = styled.div`
display: flex;
justify-content: center;
align-items: center;
`
export default () => {
const data = useStaticQuery(graphql`
query ContactInfoQuery {
contactJson {
email
title
phone
address
}
}
`)
const { title, email, phone, address } = data.contactJson
return (
<Section>
<Title>{title}</Title>
<Inner>
<Content style={{ textAlign: "center" }}>
<Block>
<Label>Email:</Label>
<Value>
<a href={`mailto:${email}`}>{email}</a>
</Value>
</Block>
<Block>
<Label>Phone:</Label>
<Value>{phone}</Value>
</Block>
<Block>
<Label>Address:</Label>
<Value>{address}</Value>
</Block>
</Content>
</Inner>
</Section>
)
}
<file_sep>import React from "react"
import { render } from "@testing-library/react"
import Button from "../Button.css.js"
import theme from "../theme"
describe("Button", () => {
it("renders correctly", () => {
const { asFragment, container } = render(<Button>Label</Button>)
expect(container.firstChild).not.toHaveStyleRule("display", "block")
expect(container.firstChild).not.toHaveStyleRule("width", "100%")
expect(asFragment()).toMatchSnapshot()
})
it("renders correctly with block modifier", () => {
const props = { block: true }
const { asFragment, container } = render(<Button {...props}>Label</Button>)
expect(container.firstChild).toHaveStyleRule("display", "block")
expect(container.firstChild).toHaveStyleRule("width", "100%")
expect(asFragment()).toMatchSnapshot()
})
it("renders correctly with theme", () => {
const props = { theme }
const { asFragment } = render(<Button {...props}>Label</Button>)
expect(asFragment()).toMatchSnapshot()
})
})
<file_sep>import React from "react";
import styled from "styled-components";
const UL = styled.ul`
font-size: 1.2rem;
& > li {
margin-bottom: 2rem;
}
`;
export default props => (
<UL>
{props.items.map((item, index) => (
<li key={index}>{item}</li>
))}
</UL>
);
<file_sep>import React from "react"
import { render } from "@testing-library/react"
import Paragraph from "../Paragraph.css.js"
describe("Paragraph", () => {
it("renders correctly", () => {
const { asFragment, container } = render(<Paragraph>Content</Paragraph>)
expect(container.firstChild).toHaveStyleRule("font-weight", "500")
expect(container.firstChild).toHaveStyleRule("font-size", "1.2rem")
expect(asFragment()).toMatchSnapshot()
})
it("renders correctly with bold", () => {
const { asFragment, container } = render(
<Paragraph bold={true}>Content</Paragraph>
)
expect(container.firstChild).toHaveStyleRule("font-weight", "600")
expect(container.firstChild).toHaveStyleRule("font-size", "1.5rem")
expect(asFragment()).toMatchSnapshot()
})
})
<file_sep>import React, { useState } from "react"
import qs from "query-string"
import PresentationContainer from "./PresentationContainer"
export default () => {
const [isModalOpen, setIsModalOpen] = useState(false)
const [successModal, setSuccessModal] = useState(false)
const handleModalOpenClick = () => {
setIsModalOpen(true)
}
const handleModalCloseClick = () => {
setIsModalOpen(false)
}
const handleSuccessModalOpen = () => {
setSuccessModal(true)
}
const handleSuccessModalClose = () => {
setSuccessModal(false)
}
const handleFormSubmit = (values, setSubmitting) => {
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: qs.stringify({ "form-name": "contact", ...values }),
})
.then(() => {
setSubmitting(false)
setIsModalOpen(false)
handleSuccessModalOpen()
})
.catch(error => console.error(error))
}
return (
<PresentationContainer
isModalOpen={isModalOpen}
onModalOpenClick={handleModalOpenClick}
onModalCloseClick={handleModalCloseClick}
onFormSubmit={handleFormSubmit}
successModal={successModal}
onSuccessModalClose={handleSuccessModalClose}
/>
)
}
<file_sep>import React from "react"
import { Formik, Form } from "formik"
import InputGroup from "../common/InputGroup"
import Select from "../common/Select"
import Button from "../styled/Button.css.js"
import Input from "../styled/TextInput.css.js"
import Textarea from "../styled/Textarea.css.js"
import { validationSchema, options, initialValues } from "../../helper/form"
export default ({ onFormSubmit }) => {
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={(values, { setSubmitting }) => {
onFormSubmit(values, setSubmitting)
}}
>
{({ isSubmitting, values, handleChange, handleBlur }) => (
<Form
name="contact"
method="post"
data-netlify="true"
data-netlify-honeypot="bot-field"
>
<input type="hidden" name="form-name" value="contact" />
<InputGroup
label="Full Name"
error={{ name: "name", component: "div" }}
>
<Input
onChange={handleChange}
onBlur={handleBlur}
type="text"
name="name"
value={values.name}
placeholder="<NAME>"
/>
</InputGroup>
<InputGroup label="Email" error={{ name: "email", component: "div" }}>
<Input
onChange={handleChange}
onBlur={handleBlur}
type="email"
name="email"
value={values.email}
placeholder="<EMAIL>"
/>
</InputGroup>
<InputGroup
label="Location"
error={{ name: "location", component: "div" }}
>
<Input
onChange={handleChange}
onBlur={handleBlur}
type="text"
name="location"
value={values.location}
placeholder="Los Angeles, California"
/>
</InputGroup>
<InputGroup
label="Phone Number"
error={{ name: "phone", component: "div" }}
>
<Input
onChange={handleChange}
onBlur={handleBlur}
type="text"
name="phone"
value={values.phone}
placeholder="+x xxx xxx xxxx"
/>
</InputGroup>
<InputGroup
label="Subject"
error={{ name: "subject", component: "div" }}
>
<Select
name="subject"
value={values.subject}
options={options}
onChange={handleChange}
onBlur={handleBlur}
/>
</InputGroup>
<InputGroup
label="Additional Information"
error={{ name: "message", component: "div" }}
>
<Textarea
onChange={handleChange}
onBlur={handleBlur}
name="message"
value={values.message}
placeholder="Message"
/>
</InputGroup>
<Button block type="submit" disabled={isSubmitting}>
{isSubmitting ? "Submitting..." : "Submit Request"}
</Button>
</Form>
)}
</Formik>
)
}
<file_sep>module.exports = {
siteMetadata: {
title: `sportconsulting.ca`,
description: `Sportconsulting.ca provides services for athletes and teams that help improve their performance and achieve goals.`,
keywords: `sport consulting, players, teams, professional, semi-pro, amateur, personal trainer, sport nutrition, DISC, personality test, athlete performance, baseball, basketball, football, hockey, soccer, lacrosse, Frisbee ultimate, tennis, swimming, try-out, college`,
},
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-transformer-json`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `data`,
path: `${__dirname}/src/data`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
{
resolve: `gatsby-plugin-styled-components`,
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images-contentful`,
options: {
maxWidth: 600,
linkImagesToOriginal: false,
withWebp: true,
},
},
],
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `sportconsulting.ca`,
short_name: `sportconsulting`,
start_url: `/`,
background_color: `#1171b7`,
theme_color: `#1171b7`,
display: `minimal-ui`,
icon: `src/images/logo_sq.png`, // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_DELIVERY_ACCESS_TOKEN,
},
},
{
resolve: `gatsby-plugin-google-gtag`,
options: {
trackingIds: [process.env.GA_TRACKING_ID],
gtagConfig: {
anonymize_ip: true,
},
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
`gatsby-plugin-offline`,
],
}
<file_sep>import React from "react"
import { render } from "@testing-library/react"
import UnorderedList from "../UnorderedList.js"
describe("UnorderedList", () => {
it("renders correctly without items", () => {
const { asFragment } = render(<UnorderedList items={[]} />)
expect(asFragment()).toMatchSnapshot()
})
it("renders correctly with items", () => {
const { asFragment } = render(
<UnorderedList items={["item 1", "item 2"]} />
)
expect(asFragment()).toMatchSnapshot()
})
})
<file_sep>import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700&display=swap');
* {
scroll-behavior: smooth;
box-sizing: border-box;
}
body {
font-family: 'Source Sans Pro', sans-serif;
font-size: 16px;
margin: 0 auto;
padding: 0;
max-width: 1200px;
color: ${props => props.theme.textColor};
}
a {
text-decoration: none;
color: ${props => props.theme.primaryColor};
font-weight: bold;
&:hover {
color: ${props => props.theme.primaryColorHover};
}
}
img {
max-width: 100%;
}
`;
export default GlobalStyle;
<file_sep>import { lighten } from "polished";
const primaryColor = "#1171b7";
const theme = {
primaryColor,
primaryColorHover: lighten(0.1, primaryColor),
borderColor: "#ccc",
textColor: "#444444"
};
export default theme;
<file_sep>const Input = `
border: thin solid;
display: block;
padding: 0.5em;
background: #fff;
width: 100%;
`;
export default Input;
<file_sep>import React from "react"
import { render } from "@testing-library/react"
import IconCross from "../Cross.js"
describe("Icon/cross", () => {
it("renders correctly", () => {
const { asFragment } = render(<IconCross />)
expect(asFragment()).toMatchSnapshot()
})
})
| 97ba46da761419145222fcab86de8f6324a2c4aa | [
"JavaScript"
] | 23 | JavaScript | alarivan/sport_consulting | 4e9111f8ad931a0a0a79409495410a0bb03a059c | 8f0b5dcc941eb0e20891c4ee6e285a5fb3b8db28 | |
refs/heads/master | <repo_name>niilante/Ajax-Contact-Form<file_sep>/public/js/contact-form.js
(function (root, factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.ContactForm = factory();
}
}(this, function () {
"use strict";
var ContactForm = function (form, options) {
if (!this || !(this instanceof ContactForm)) {
return new ContactForm(form, options);
}
if (!form || !options) {
return;
}
this.form = form instanceof Node ? form : document.querySelector(form);
this.endpoint = options.endpoint;
this.send();
};
ContactForm.prototype = {
hasClass: function (el, name) {
return new RegExp('(\\s|^)' + name + '(\\s|$)').test(el.className);
},
addClass: function (el, name) {
if (!this.hasClass(el, name)) {
el.className += (el.className ? ' ' : '') + name;
}
},
removeClass: function (el, name) {
if (this.hasClass(el, name)) {
el.className = el.className.replace(new RegExp('(\\s|^)' + name + '(\\s|$)'), ' ').replace(/^\s+|\s+$/g, '');
}
},
each: function (collection, iterator) {
var i, len;
for (i = 0, len = collection.length; i < len; i += 1) {
iterator(collection[i], i, collection);
}
},
template: function (string, data) {
var piece;
for (piece in data) {
if (Object.prototype.hasOwnProperty.call(data, piece)) {
string = string.replace(new RegExp('{' + piece + '}', 'g'), data[piece]);
}
}
return string;
},
empty: function (el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
},
removeElementsByClass: function (className) {
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
},
post: function (path, data, success, fail) {
var xhttp = new XMLHttpRequest();
xhttp.open('POST', path, true);
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhttp.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
var response = '';
try {
response = JSON.parse(this.responseText);
} catch (err) {
response = this.responseText;
}
success.call(this, response);
} else {
fail.call(this, this.responseText);
}
}
};
xhttp.send(data);
xhttp = null;
},
param: function (data) {
var params = typeof data === 'string' ? data : Object.keys(data).map(
function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]); }
).join('&');
return params;
},
send: function () {
this.form.addEventListener('submit', function (e) {
e.preventDefault();
var elements = document.querySelectorAll('.form-control'),
formData;
this.each(elements, function (el, i) {
if (this.hasClass(el.parentNode, 'has-error')) {
this.removeClass(el.parentNode, 'has-error');
this.removeElementsByClass('help-block');
}
}.bind(this));
formData = {
'name' : document.querySelector('input[name="form-name"]').value,
'email' : document.querySelector('input[name="form-email"]').value,
'subject' : document.querySelector('input[name="form-subject"]').value,
'message' : document.querySelector('textarea[name="form-message"]').value
};
this.post(this.endpoint, this.param(formData), this.feedback.bind(this), this.fail.bind(this));
}.bind(this), false);
},
feedback: function (data) {
if (!data.success) {
if (data.errors.name) {
var name = document.querySelector('input[name="form-name"]').parentNode,
error;
this.addClass(name, 'has-error');
error = this.template(
'<span class="help-block">{report}</span>', {
report: data.errors.name
});
name.insertAdjacentHTML('beforeend', error);
}
if (data.errors.email) {
var email = document.querySelector('input[name="form-email"]').parentNode,
error;
this.addClass(email, 'has-error');
error = this.template(
'<span class="help-block">{report}</span>', {
report: data.errors.email
});
email.insertAdjacentHTML('beforeend', error);
}
if (data.errors.subject) {
var subject = document.querySelector('input[name="form-subject"]').parentNode,
error;
this.addClass(subject, 'has-error');
error = this.template(
'<span class="help-block">{report}</span>', {
report: data.errors.subject
});
subject.insertAdjacentHTML('beforeend', error);
}
if (data.errors.message) {
var message = document.querySelector('textarea[name="form-message"]').parentNode,
error;
this.addClass(message, 'has-error');
error = this.template(
'<span class="help-block">{report}</span>', {
report: data.errors.message
});
message.insertAdjacentHTML('beforeend', error);
}
} else {
var success = this.template(
'<div class="alert alert-success">{report}</div>', {
report: data.message
});
this.empty(this.form);
this.form.insertAdjacentHTML('beforeend', success);
}
},
fail: function (data) {
console.log(data);
}
};
return ContactForm;
}));<file_sep>/index.php
<?php
require_once './vendor/autoload.php';
$helperLoader = new SplClassLoader('Helpers', './vendor');
$helperLoader->register();
use Helpers\Config;
$config = new Config;
$config->load('./config/config.php');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ajax contact form</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="jumbotron">
<div class="container">
<h1>Ajax Contact Form</h1>
<p>A simple ajax based contact form using pure JavaScript and PHP.</p>
<p><a class="btn btn-primary btn-lg" href="https://github.com/pinceladasdaweb/Ajax-Contact-Form" role="button">Learn more »</a></p>
</div>
</div>
<div class="col-md-6 col-md-offset-3">
<form enctype="application/x-www-form-urlencoded;" id="contact-form" class="form-horizontal" role="form" method="post">
<div class="form-group" id="name-field">
<label for="form-name" class="col-lg-2 control-label"><?php echo $config->get('fields.name'); ?></label>
<div class="col-lg-10">
<input type="text" class="form-control" id="form-name" name="form-name" placeholder="<?php echo $config->get('fields.name'); ?>" required>
</div>
</div>
<div class="form-group" id="email-field">
<label for="form-email" class="col-lg-2 control-label"><?php echo $config->get('fields.email'); ?></label>
<div class="col-lg-10">
<input type="email" class="form-control" id="form-email" name="form-email" placeholder="<?php echo $config->get('fields.email'); ?>" required>
</div>
</div>
<div class="form-group" id="subject-field">
<label for="form-subject" class="col-lg-2 control-label"><?php echo $config->get('fields.subject'); ?></label>
<div class="col-lg-10">
<input type="text" class="form-control" id="form-subject" name="form-subject" placeholder="<?php echo $config->get('fields.subject'); ?>" required>
</div>
</div>
<div class="form-group" id="message-field">
<label for="form-message" class="col-lg-2 control-label"><?php echo $config->get('fields.message'); ?></label>
<div class="col-lg-10">
<textarea class="form-control" rows="6" id="form-message" name="form-message" placeholder="<?php echo $config->get('fields.message'); ?>" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default"><?php echo $config->get('fields.btn-send'); ?></button>
</div>
</div>
</form>
</div>
<script src="public/js/contact-form.js"></script>
<script type="text/javascript">
new ContactForm('#contact-form', {
endpoint: './process.php'
});
</script>
</body>
</html><file_sep>/process.php
<?php
require_once './vendor/autoload.php';
$helperLoader = new SplClassLoader('Helpers', './vendor');
$mailLoader = new SplClassLoader('SimpleMail', './vendor');
$helperLoader->register();
$mailLoader->register();
use Helpers\Config;
use SimpleMail\SimpleMail;
$config = new Config;
$config->load('./config/config.php');
$errors = array();
$data = array();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['name']));
$email = stripslashes(trim($_POST['email']));
$subject = stripslashes(trim($_POST['subject']));
$message = stripslashes(trim($_POST['message']));
$pattern = '/[\r\n]|Content-Type:|Bcc:|Cc:/i';
if (preg_match($pattern, $name) || preg_match($pattern, $email) || preg_match($pattern, $subject)) {
die("Header injection detected");
}
if (empty($name)) {
$errors['name'] = $config->get('messages.validation.emptyname');
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = $config->get('messages.validation.emptyemail');
}
if (empty($subject)) {
$errors['subject'] = $config->get('messages.validation.emptysubject');
}
if (empty($message)) {
$errors['message'] = $config->get('messages.validation.emptymessage');
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$mail = new SimpleMail();
$mail->setTo($config->get('emails.to'));
$mail->setFrom($config->get('emails.from'));
$mail->setSender($name);
$mail->setSubject($config->get('subject.prefix') . ' ' . $subject);
$body = "
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
</head>
<body>
<h1>{$subject}</h1>
<p><strong>{$config->get('fields.name')}:</strong> {$name}</p>
<p><strong>{$config->get('fields.email')}:</strong> {$email}</p>
<p><strong>{$config->get('fields.message')}:</strong> {$message}</p>
</body>
</html>";
$mail->setHtml($body);
$mail->send();
$data['success'] = true;
$data['message'] = $config->get('messages.success');
}
echo json_encode($data);
} | b26c178a7ca4f01729a695391a1685c01e1f4832 | [
"JavaScript",
"PHP"
] | 3 | JavaScript | niilante/Ajax-Contact-Form | ba9a8b6760a1d1114f2969c7429fff7bc6366fb1 | dc2d1caedb481cfca9077b6d60234c4b3b7adb65 | |
refs/heads/master | <repo_name>gwrdev/revproxy<file_sep>/Web1/Dockerfile
FROM php:7.0-apache
EXPOSE 80
COPY www/ /var/www/html/
CMD ["apache2ctl", "-D", "FOREGROUND"]<file_sep>/README.md
# revproxy
Basic set of files to support testing reverse proxy and Docker
<file_sep>/Web2/www/index.php
<H1>Apache Docker Web Page - Server 2 version 1</H1>
<?php
echo "Server Name: ", $_SERVER['SERVER_NAME'], " <P>";
echo "Server Addr: ", $_SERVER['SERVER_ADDR'], " <P>";
echo "Server Port: ", $_SERVER['SERVER_PORT'], " <P>";
echo "Hostname: ", exec('hostname'), " <P>";
echo "All IPs: ", exec('hostname -I'), " <P>";
echo '<P>';
#echo '<P>';
#phpinfo();
?>
| c53a4cf65f9f339240dd181e9c73675284ea1a6c | [
"Markdown",
"Dockerfile",
"PHP"
] | 3 | Dockerfile | gwrdev/revproxy | 2c58bd083b2f40efced9753ae86ff77567579862 | 264136a166d60abdfd582e5f6e04763f30128e59 | |
refs/heads/master | <repo_name>vaakonecromong/instagram_agaleski<file_sep>/htdocs/includes/functions.php
<?php
// check if we have SSL connection
function fnc_is_ssl() {
// check HTTPS information
if(isset($_SERVER['HTTPS'])) {
if('on' == strtolower($_SERVER['HTTPS'])) {
return true;
}
if('1' == $_SERVER['HTTPS']) {
return true;
}
} else {
// check port
if(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
return true;
}
}
return false;
}
// get url scheme
function fnc_url_scheme() {
$scheme = fnc_is_ssl() ? 'https://' : 'http://';
return $scheme;
}
?><file_sep>/htdocs/callback.php
<?php
session_start();
require_once('includes/functions.php');
require_once('includes/instagram.php');
$instagram = new chc_instagram();
$schame = fnc_url_scheme();
// if no instagram code
if(!isset($_GET['code'])){
// we have some instagram fail
$_SESSION['instagram_authorized'] = false;
// go back to homepage
header('location: '.$schame.$_SERVER['HTTP_HOST']);
}
// in other case we are authorized
$_SESSION['instagram_authorized'] = true;
$_SESSION['instagram_code'] = $_GET['code'];
// go back to homepage
header('location: '.$schame.$_SERVER['HTTP_HOST']);
?><file_sep>/readme.md
# Instagram API Task
- Simple PHP application<file_sep>/htdocs/index.php
<?php
session_start();
ob_start();
require_once('includes/functions.php');
require_once('includes/instagram.php');
$schame = fnc_url_scheme();
$instagram_data = null;
$file_created = false;
$file_name = 'result.csv';
// sort instagram post by likes count, descending order
function sort_data($a, $b) {
return $b->likes->count > $a->likes->count;
}
// convert instagram post data to array for CSV file
function convert_obj_to_array($obj) {
$a = array();
$a['id'] = $obj->id;
$a['type'] = $obj->type;
$a['created_time'] = $obj->created_time;
$a['link'] = $obj->link;
$a['likes'] = $obj->likes->count;
$a['comments'] = $obj->comments->count;
$a['filter'] = $obj->filter;
$a['thumbnail_url'] = $obj->images->thumbnail->url;
return $a;
}
// if user clicks "get instagram results"
if(isset($_POST['get_instagram_results'])) {
// unset trigger, prvent data resubmiting alert
unset($_POST['get_instagram_results']);
// set trigger in session data
$_SESSION['can_authorize'] = true;
// redirect to homepage with clear $_POST table
header('location: '.$schame.$_SERVER['HTTP_HOST']);
}
// if we can start to try authorize
if(isset($_SESSION['can_authorize'])) {
// create Instagram API object
$instagram = new chc_instagram();
// try authorize user
if(!isset($_SESSION['instagram_authorized'])) {
$instagram->authorize();
} else {
// if user authorized
if(true === $_SESSION['instagram_authorized'] and isset($_SESSION['instagram_code'])) {
// get access token
$data = $instagram->get_access_token($_SESSION['instagram_code']);
// if access token granted store it in session data
if(is_object($data) and isset($data->access_token)) {
$_SESSION['instagram_access_token'] = $data->access_token;
}
} else {
// TODO: authorization fail, display some information to user
// now we cam just reset data, to give user next chance for authorization, with next page refresh
session_unset();
session_destroy();
}
}
// do we have access token?
if(isset($_SESSION['instagram_access_token'])) {
// if yes we can get post from instragram.com,
// in sandbox mode there is no possible to get more then 20 posts, or use pagination,
// so even we will get pagination data from instagram, but this data is not complete and
// is just useless for next API call
$data = $instagram->get_tag_media('natural', 100, $_SESSION['instagram_access_token']);
// so if we have some real post data
if(is_object($data) and (isset($data->data) and count($data->data))) {
// sort posts by likes count, descenting
usort($data->data, 'sort_data');
// copy temp data to global variable
$instagram_data = $data;
// ok, open/create CVS file
$file = fopen($file_name, 'w');
// simple counter
$counter = 0;
// for each post from instagram
foreach($instagram_data->data as $obj) {
// cover it to associative array
$a = convert_obj_to_array($obj);
// if first post, before data write, add to file some columns information
if(!$counter) {
fputcsv($file, array_keys($a));
}
// store post data
fputcsv($file, array_values($a));
$counter++;
}
// close file
fclose($file);
$file_created = true;
}
// destroy session data, for next page refresh, test demo
session_unset();
session_destroy();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Instagram API</title>
<meta name="description" content="Tutorial PHP application.">
<meta name="keywords" content="Instagram API, CSV, PHP">
<link rel="icon" href="img/favicon.png">
<link href="https://fonts.googleapis.com/css?family=Barlow+Condensed:300,400,500,600,700" rel="stylesheet">
<link rel="stylesheet" href="css/style.css" type="text/css" media="all">
<script src="js/library/jquery-3.2.1.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<!-- HEADER -->
<header class="ch-header">
<div class="wrap-cnt">
<div class="cnt">
<h1 class="title">Create a small PHP App using the <span class="color">Instagram API</span>,<br class="hidden"> which receives 100 results for the hashtag<br> <span class="color">#natural</span></h1>
<h2 class="subtitle">The application should sort the results by the number of likes<br class="hidden"> and save them to a <span class="color">.CSV</span> file.</h2>
</div>
</div>
</header>
<!-- ACTION FORM -->
<section class="ch-action-form">
<div class="wrap-cnt">
<div class="cnt">
<form class="form" action="" method="post">
<div class="interfce">
<?php if($file_created) { ?>
<div class="wrap-control">
<div class="control">
<div class="file-logo">
<div class="logo csv"></div>
</div>
<a class="btn btn-download" href="<?php echo $file_name; ?>" download="<?php echo $file_name; ?>">Download result as CSV file</a>
</div>
</div>
<?php } else { ?>
<div class="wrap-control">
<div class="control">
<div class="loader-spinner">
<div class="spinner"></div>
</div>
<button type="submit" class="btn btn-get" name="get_instagram_results">Get instagram results</button>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
</div>
</section>
<!-- INSTAGRAM RESULT -->
<?php
// do we have some instagram data?
if(!is_null($instagram_data)) {
?>
<section class="ch-instagram-result">
<div class="wrap-cnt">
<div class="cnt">
<?php
// do we have post data
if(isset($instagram_data->data) and count($instagram_data->data)) {
// store output on the side
$out = '';
$out .= '<div class="list">';
// for each post
foreach($instagram_data->data as $post) {
$out .= '<div class="item">';
$out .= '<div class="item-cnt">';
// show image as link to oryginal instagram.com post
$out .= '<figure class="image">';
$out .= '<a href="'.$post->link.'" target="_blank">';
$out .= '<img src="'.$post->images->low_resolution->url.'">';
$out .= '</a>';
$out .= '</figure>';
// show number of likes
$out .= '<div class="likes">';
$postfix = ($post->likes->count == 1) ? 'like' : 'likes';
$out .= '<h6 class="count">'.$post->likes->count.' '.$postfix.'</h6>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
}
$out .= '</div>';
echo $out;
}
?>
</div>
</div>
</section>
<?php } ?>
<!-- FOOTER -->
<footer class="ch-footer">
<div class="wrap-cnt">
<div class="cnt">
<h6 class="copyright">Demo by <NAME></h1>
</div>
</div>
</footer>
</body>
</html>
<?php
$cnt = ob_get_clean();
echo $cnt;
?><file_sep>/htdocs/includes/instagram.php
<?php
class chc_instagram {
// some private data
private $INSTAGRAM_CLIENT_ID = '4a5f1c7815a444468ed4f019c625594a';
private $INSTAGRAM_CLIENT_SECRET = '08572eeeae424d57951afe4569c668ab';
private $INSTAGRAM_API_URL = 'https://api.instagram.com/v1/';
private $INSTAGRAM_API_OAUTH_URL = 'https://api.instagram.com/oauth/authorize';
private $INSTAGRAM_API_OAUTH_ACCESS_TOKEN_URL = 'https://api.instagram.com/oauth/access_token';
private $INSTAGRAM_REDIRECT_URL = '';
// constructor
public function __construct() {
// create callback URL
$this->INSTAGRAM_REDIRECT_URL = fnc_url_scheme().$_SERVER['HTTP_HOST'].'/callback.php';
}
// authorize user
public function authorize() {
$url = $this->INSTAGRAM_API_OAUTH_URL.'?client_id='.$this->INSTAGRAM_CLIENT_ID.'&redirect_uri='.urlencode($this->INSTAGRAM_REDIRECT_URL).'&scope=public_content'.'&response_type=code';
header('location:'.$url);
}
// get access token
public function get_access_token($code) {
$params = array();
$params['client_id'] = $this->INSTAGRAM_CLIENT_ID;
$params['client_secret'] = $this->INSTAGRAM_CLIENT_SECRET;
$params['grant_type'] = 'authorization_code';
$params['redirect_uri'] = $this->INSTAGRAM_REDIRECT_URL;
$params['code'] = $code;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->INSTAGRAM_API_OAUTH_ACCESS_TOKEN_URL);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($curl, CURLOPT_POST, count($params));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($result);
}
// get recent instagram media by tag name
public function get_tag_media($tag, $count, $access_token) {
$params = array();
$params['access_token'] = $access_token;
$params['count'] = $count;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->INSTAGRAM_API_URL.'tags/'.$tag.'/media/recent?'.http_build_query($params));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($result);
}
} | 2560c0f46aae341371b39b818a4651d9874e4945 | [
"Markdown",
"PHP"
] | 5 | PHP | vaakonecromong/instagram_agaleski | 09670dce1c3eaef33c7a71fd5ca2cb5322c05236 | 88079cfbd2cb539c901601c83dd869aed6e38f1e | |
refs/heads/main | <repo_name>sigflysea/my-burger<file_sep>/src/components/Burger/OrderSummary/OrderSummary.js
import React from 'react';
import Auxi from '../../../hoc/Auxi/Auxi';
import Button from '../../UI/Button/Button';
const orderSummary = (props) => {
const ingredientSum = Object.keys(
props.ingredients
).map((igKey) => {
return (
<li key={igKey}>
<span
style={{ textTransform: 'capitalize' }}
>
{igKey}
</span>
: {props.ingredients[igKey]}
</li>
);
});
return (
<Auxi>
<p>Your order: </p>
<ul>{ingredientSum}</ul>
<p>
<strong>
Your total is: ${props.price}
</strong>
</p>
<Button
btnType='Danger'
clicked={props.cancelOrder}
>
Cancel
</Button>
<Button
btnType='Success'
clicked={props.proceedOrder}
>
Place Order
</Button>
</Auxi>
);
};
export default orderSummary;
| 71b46c8ffde92f3bde156f25b6e51dbeeac94116 | [
"JavaScript"
] | 1 | JavaScript | sigflysea/my-burger | 9eb68579786e5f30f98b55b4fc554720fecc7483 | a80567eb532aaffdac843bf4828d369f202005e1 | |
refs/heads/master | <file_sep>#!/bin/bash
# SROShell - Programa para rastrear objetos correios.
# Autor: <NAME> <<EMAIL>>
# _________________________________________________________________________________________
#
# Versão: 20170726 - Versão inicial.
# Como quase todos os programas, esse não é diferente, poderá apresentar alguns
# erros no resultado final. Não fiz o teste com código do SEDEX - usei o PAC :-(
# foi mais barato :-).
#
# Versão: 20170728 - <NAME> <<EMAIL>>
# - Corrigido bug.
# - Adicionado opção de "novo rastreamento" (O José esqueceu de colocar)
# _________________________________________________________________________________________
#
# ==================================== Início do Script ===================================
SROC="/tmp/srorast.xxxxxx"
ValidSRO='[A-Z]{2}[0-9]{9}[A-Z]{2}'
# Mensagem de ajuda.
Mensagem_Ajuda="
\033[32;1mSROShell - Rastreamento de objetos correios.\033[m
\033[32;1mDigite o códido de rastreamento usando o seguinte exemplo:\033[m
\033[33;1mLetra\033[m + \033[31;1mNúmero\033[m + \033[34;1mLetra\033[m
\033[33;1mAA\033[m \033[31;1m123456789\033[m \033[34;1mAA\033[m
\033[32;1mSe houver mais de um produto a ser rastreado, faça um de cada vez.\033[m
"
SRO_Rastreamento(){
# Pega o código de rastreamento passado pelo usuário.
echo -e "\033[32;1mSRO - Digite o código de Restreamento:\033[m"
read codigo_sro
# Verifica se o usuário digitou o código.
while [ -z $codigo_sro ]; do
sleep 1
echo -e "\033[32;1mPor favor, digite o código de rastreamento:\033[m"
read codigo_sro
echo -e "\033[31;1mVocê não digitou o código de rastreamento.\033[m"
exit 1 # Não digitou, então tchau
done
# Verifica se o código obedece os valores de duas letras, nove números e duas letras.
# Se sim, realiza o rastreamento.
if [[ $codigo_sro =~ $ValidSRO ]]; then
lynx -source http://www.websro.com.br/correios.php?P_COD_UNI=$codigo_sro | tr -d "\t" | egrep "<td|<h[1-2]" | sed 's/<[^>]*>//g' > $SROC
else
# Se o código for inválido exibe uma mensagem de erro.
clear
echo -e "\033[31;1mOPS!!! Código Inválido.\033[m"
echo -e "\033[31;1m***********************\033[m"
echo -e "$Mensagem_Ajuda"
# Chama a função novo rastreamento. Se o usuário não desejar realizar
Novo_Rastreamento
fi
}
SRO_Resultado(){
# Obtém os resultados do rastreamento armazenado no arquivo temporário.
__Objt=$(cat $SROC | grep -i "^OBJETO:" | cut -d':' -f2 | tr -d ' ' )
__Objt_Enc=$(cat $SROC | grep "^Objeto")
__Local_Ent=$(cat $SROC | grep "^Local:" | grep "^Local" | awk '{print $2,$3}')
__Data_Enc=$(cat $SROC | egrep "[0-9]{2}/[0-9]{2}/[0-9]{4}" | awk '{print $1}')
__Hora_Enc=$(cat $SROC | egrep "[0-9]{2}:[0-9]{2}" | awk '{print $2}')
__Origem=$(cat $SROC | egrep "Destino:" | sed 's/Destino:.*//g')
__Destino=$(cat $SROC | egrep "Destino:" | cut -d':' -f3)
# Organizando o resultado na tela.
ResultadoSRO="
\033[37;1mSROShell - Rastreamento de Objetos - WEBSRO Correios\033[m
\033[37;1m____________________________________________________\033[37;1m
\033[32;1mOBJETO:\033[m \033[33;1m$__Objt\033[m
\033[32;1mDATA:\033[m \033[33;1m$__Data_Enc\033[m
\033[32;1mHORA:\033[m \033[33;1m$__Hora_Enc\033[m
\033[32;1m$__Objt_Enc\033[m \033[33;1m$__Local_Ent\033[m
\033[32;1m$__Origem\033[m
\033[32;1mDestino:\033[m \033[33;1m$__Destino\033[m
\033[37;1m____________________________________________________\033[m
"
# Mostra o resultado na saída padrão.
echo -e "$ResultadoSRO"
# Após mostrar o resultado, pergunta se o usuário deseja fazer um novo
# rastreamento.
Novo_Rastreamento
}
Novo_Rastreamento(){
echo -e "\033[33;1mDeseja pesquisar mais algum pedido [S/N]?\033[m"
read resposta
case $resposta in
s|S) SRO_Rastreamento ; SRO_Resultado ;;
n|N) exit 0 ;;
*) exit 1 ;; # Se o usuário der um ENTER sai do mesmo jeito
esac
}
# Chama a função e exibe os resultados.
SRO_Rastreamento
SRO_Resultado
# ==================================== Fim do Script ===================================
<file_sep># SROShell
Rastreamento de Objetos - correios via SHELL
Com esse script (programa) você poderá realizar rastreamento de objetos usando o
SHELL. Para isso será necessário que você instale o "Lynx, é ele que fará o acesso a
net e baixará o conteúdo para ser manipulado pelo script.
O SROShell não foi testado com código do SEDEX - usei o PAC - por ser mais barato :-)
| b6876d88d46f7888460c87ea401be49023dec7bd | [
"Markdown",
"Shell"
] | 2 | Shell | TheHarleySousa/SROShell | 4aee1f4009d289e5cbaa991d6b30c954252e10f5 | bb52c63f48055659ac4c4f84a6bd41b3c963f511 | |
refs/heads/master | <file_sep>//设置事件中心,使用发布订阅模式
var EventCenter = {
on: function(type, handler) {
$(document).on(type, handler)
},
fire: function(type, data) {
$(document).trigger(type, data)
}
//如果需要可以添加 delete 用来删除事件。
}
//使用范例
// EventCenter.on('hello', function(e, data){
// console.log(data)
// })
// EventCenter.fire('hello', '你好')
/*----------初始化Footer-----------*/
var Footer = {
init: function() {
this.$footer = $('footer')
this.$ul = this.$footer.find('ul')
this.$box = this.$footer.find('.box')
this.$leftBtn = this.$footer.find('.icon-left')
this.$rightBtn = this.$footer.find('.icon-right')
this.isToEnd = false
this.isToStart = true
this.isAnimate = false //防止重复点击
this.bind() //绑定事件
this.render() //初始化渲染
},
bind: function() {
var _this = this
//右侧滚动
this.$rightBtn.on('click', function() {
if (_this.isAnimate) return
var itemWidth = _this.$box.find('li').outerWidth(true)
var rowCount = Math.floor(_this.$box.width() / itemWidth)
if (!_this.isToEnd) {
_this.isAnimate = true
_this.$ul.animate({
left: '-=' + rowCount * itemWidth
}, 400, function() {
_this.isAnimate = false
_this.isToStart = false
if (parseFloat(_this.$box.width()) - parseFloat(_this.$ul.css('left')) >= parseFloat(_this.$ul.css('width'))) {
_this.isToEnd = true
}
})
}
})
//左侧滚动
this.$leftBtn.on('click', function() {
if (_this.isAnimate) return
var itemWidth = _this.$box.find('li').outerWidth(true)
var rowCount = Math.floor(_this.$box.width() / itemWidth)
if (!_this.isToStart) {
_this.isAnimate = true
_this.$ul.animate({
left: '+=' + rowCount * itemWidth
}, 400, function() {
_this.isToEnd = false
_this.isAnimate = false
if (parseFloat(_this.$ul.css('left')) >= 0) {
_this.isToStart = true
}
})
}
})
//选取专辑
this.$footer.on('click', 'li', function() {
$(this).addClass('active')
.siblings().removeClass('active')
//触发 select-albumn
EventCenter.fire('select-albumn', {
channelId: $(this).attr('data-channel-id'),
channelName: $(this).attr('data-channel-name')
})
})
},
render: function() {
var _this = this
//获取专辑
$.getJSON('//jirenguapi.applinzi.com/fm/getChannels.php')
.done(function(ret) {
_this.renderFooter(ret.channels)
}).fail(function() {
console.log('error')
})
},
renderFooter: function(channels) {
var html = ''
//把本地 localStorage 的收藏也加上
channels.unshift({
channel_id: 0,
name: '我的最爱',
cover_small: 'http://cloud.hunger-valley.com/17-10-24/1906806.jpg-small',
cover_middle: 'http://cloud.hunger-valley.com/17-10-24/1906806.jpg-middle',
cover_big: 'http://cloud.hunger-valley.com/17-10-24/1906806.jpg-big',
})
//构建DOM
channels.forEach(function(channel) {
html += '<li data-channel-id=' + channel.channel_id + ' data-channel-name=' + channel.name + '>' + ' <div class="cover" style="background-image:url(' + channel.cover_small + ')"></div>' + ' <h3>' + channel.name + '</h3>' + '</li>'
})
this.$ul.html(html)
this.setStyle()
},
setStyle: function() {
var count = this.$footer.find('li').length
var width = this.$footer.find('li').outerWidth(true)
//重置容器宽度
this.$ul.css({
width: count * width + 'px'
})
}
}
/*----------初始化 Fm--------*/
var Fm = {
init: function() {
this.channelId = 'public_shiguang_80hou' //设置初始专辑
this.channelName = '80后'
this.$container = $('#page-music main')
this.audio = new Audio() //初始化 Audio
this.audio.autoplay = true //自动播放
this.currentSong = null //当前音乐
this.clock = null
this.collections = this.loadFromLocal() //本地收藏
this.bind()
this.playInit() //播放初始化
},
playInit: function() {
//本地收藏优先
if (Object.keys(this.collections).length > 0) {
EventCenter.fire('select-albumn', {
channelId: '0',
channelName: '我的最爱'
})
} else {
//没有收藏就按初始专辑播放线上歌曲
this.loadSong()
}
},
bind: function() {
var _this = this
//响应 select-albumn
EventCenter.on('select-albumn', function(e, channel) {
_this.channelId = channel.channelId
_this.channelName = channel.channelName
_this.loadSong()
})
this.$container.find('.btn-play').on('click', function() {
if ($(this).hasClass('icon-pause')) {
$(this).removeClass('icon-pause').addClass('icon-play')
_this.audio.pause()
} else {
$(this).removeClass('icon-play').addClass('icon-pause')
_this.audio.play()
}
})
this.$container.find('.btn-next').on('click', function() {
_this.loadSong()
})
//非JQuery对象绑定事件
this.audio.addEventListener('play', function() {
clearInterval(_this.clock)
_this.clock = setInterval(function() {
_this.updateState()
_this.setLyric()
}, 1000)
})
this.audio.addEventListener('pause', function() {
clearInterval(_this.clock)
})
this.audio.addEventListener('end', function() {
_this.loadSong()
})
//增删我的收藏
this.$container.find('.btn-collect').on('click', function() {
var $btn = $(this)
if ($btn.hasClass('active')) {
$btn.removeClass('active')
//直接删除对象中的元素
delete _this.collections[_this.currentSong.sid]
} else {
$(this).addClass('active')
_this.collections[_this.currentSong.sid] = _this.currentSong
}
//保存到 localStorage 里
_this.saveToLocal()
})
},
loadSong: function() {
var _this = this
//本地读取我的收藏
if (this.channelId === '0') {
_this.loadCollection()
} else {
//线上请求歌曲
$.getJSON('//jirenguapi.applinzi.com/fm/getSong.php', {
channel: this.channelId
})
.done(function(ret) {
_this.play(ret.song[0] || null)
})
}
},
play: function(song) {
this.currentSong = song //重置当前歌曲
this.audio.src = song.url
this.$container.find('.btn-play').removeClass('icon-play').addClass('icon-pause')
this.$container.find('.aside figure').css('background-image', 'url(' + song.picture + ')')
$('.bg').css('background-image', 'url(' + song.picture + ')')
this.$container.find('.detail h1').text(song.title)
this.$container.find('.detail .author').text(song.artist)
this.$container.find('.tag').text(this.channelName)
//判断是否是本地收藏歌曲
if (this.collections[song.sid]) {
this.$container.find('.btn-collect').addClass('active')
} else {
this.$container.find('.btn-collect').removeClass('active')
}
this.loadLyric(song.sid)
},
//更新时间、进度条
updateState: function() {
var timeStr = Math.floor(this.audio.currentTime / 60) + ':' + (Math.floor(this.audio.currentTime) % 60 / 100).toFixed(2).substr(2)
this.$container.find('.current-time').text(timeStr)
this.$container.find('.bar-progress').css('width', this.audio.currentTime / this.audio.duration * 100 + '%')
},
loadLyric: function(sid) {
var _this = this
$.getJSON('//jirenguapi.applinzi.com/fm/getLyric.php', {
sid: sid
})
.done(function(ret) {
var lyricObj = {}
ret.lyric.split('\n').forEach(function(line) {
var timeArr = line.match(/\d{2}:\d{2}/g)
if (timeArr) {
timeArr.forEach(function(time) {
lyricObj[time] = line.replace(/\[.+?\]/g, '')
})
}
})
if(lyricObj['00:00'].indexOf('音乐来自') > -1){
delete lyricObj['00:00']
}
_this.lyricObj = lyricObj
})
},
setLyric: function() {
var timeStr = '0' + Math.floor(this.audio.currentTime / 60) + ':' + (Math.floor(this.audio.currentTime) % 60 / 100).toFixed(2).substr(2)
if (this.lyricObj && this.lyricObj[timeStr]) {
//可以添加更多的样式,用来显示歌词特效
// var styles = ['slideInUp','zoomIn','rollIn', 'rotateIn', 'flipInX','fadeIn', 'bounceIn','swing', 'pulse']
// var style = styles[Math.floor(Math.random()*styles.length)]
this.$container.find('.lyric p').text(this.lyricObj[timeStr])
.boomText()
}
},
loadFromLocal: function() {
return JSON.parse(localStorage['collections'] || '{}')
},
saveToLocal: function() {
localStorage['collections'] = JSON.stringify(this.collections)
},
loadCollection: function() {
var keyArray = Object.keys(this.collections)
if (keyArray.length === 0) return
var randomIndex = Math.floor(Math.random() * keyArray.length)
var randomSid = keyArray[randomIndex]
this.play(this.collections[randomSid])
}
}
//设置 boomText 插件
$.fn.boomText = function(type) {
//确认显示样式
type = type || 'rollIn'
//处理文本
this.html(function() {
var arr = $(this).text()
.split('').map(function(word) {
return '<span class="boomText">' + word + '</span>'
})
return arr.join('')
})
var index = 0
var $boomTexts = $(this).find('span')
var clock = setInterval(function() {
$boomTexts.eq(index).addClass('animated ' + type)
index++
if (index >= $boomTexts.length) {
clearInterval(clock)
}
}, 100)
}
Footer.init()
Fm.init()<file_sep># musicRadio
电台音乐
| f713b8494dd5b4f45a7244d17ec9080b79e74d21 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | zh-yang/musicRadio | da547e028f674da976a5a1773c111381f511e1c6 | 8c46bf8e88ad607eaf431d27542abcb5ce7bb8f4 | |
refs/heads/master | <repo_name>greenty5/waveEqFoam<file_sep>/README.md
# waveEqFoam
Solving a wave equation using OpenFOAM
<file_sep>/createFields.H
Info<< "Reading field phi\n" << endl;
/*
volScalarField T
(
IOobject
(
"T",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
*/
volScalarField phi
(
IOobject
(
"phi",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
Info<< "Reading transportProperties\n" << endl;
IOdictionary transportProperties
(
IOobject
(
"transportProperties",
runTime.constant(),
mesh,
IOobject::MUST_READ_IF_MODIFIED,
IOobject::NO_WRITE
)
);
/*
Info<< "Reading diffusivity DT\n" << endl;
dimensionedScalar DT
(
transportProperties.lookup("DT")
);
*/
/*
dimensionedScalar c0 =
dimensionedScalar
(
"c0",
dimensionSet (0, 1, -1, 0, 0, 0, 0),
1.0
);
*/
dimensionedScalar c0
(
transportProperties.lookup("c0")
);
#include "createFvOptions.H"
| a5fa44bee7ea0c94fedd18c6930fb923b21d4d02 | [
"Markdown",
"C"
] | 2 | Markdown | greenty5/waveEqFoam | 65de5fb7df460d4b1856a1f28235d955b0f68b7b | 48bbd007e0e4fd2b907318e509310eb7e8876570 | |
refs/heads/master | <file_sep>
/**
* Requirements
*/
var chai = require('chai'),
assert = require('chai').assert,
chaiAsPromised = require('chai-as-promised');
resumePdfToJson = require('../index');
chai.use(chaiAsPromised);
/**
* Test Descriptions
*/
describe('resumePdfToJson', function() {
var path = 'test/JasonNode.pdf';
var output = 'test/JasonNode.json';
var p = resumePdfToJson(path, {'output': output})
.then(function(data) {
return data;
});
it('The resumePdfToJson(...) promise is fullfilled.', function() {
return assert.isFulfilled(p);
});
});
<file_sep># resume-pdf-to-json
A Node module that parses a LinkedIn Resume PDF and returns a JSON Object and/or outputs a JSON file.
LinkedIn Resume's are available on your profile under **View Profile As** ▼ **Save to PDF**
## Installation
```shell
npm install resume-pdf-to-json --save-dev
```
## Usage
### Return JSON
```js
var resumePdfToJson = require('resume-pdf-to-json');
var path = 'data/[FirstLast].pdf';
return resumePdfToJson(path)
.then(function(data) {
return {
'resume': data,
};
});
```
### Return JSON + Output JSON File
```js
var resumePdfToJson = require('resume-pdf-to-json');
var path = 'data/[FirstLast].pdf';
var output = 'data/outputname.json';
return resumePdfToJson(path, {'output': output})
.then(function(data) {
return {
'resume': data,
};
});
```
### Support
There are multiple sections of the LinkedIn PDF resume output, however, not all have been tested. The following sections have been accomodated for;
- Summary
- Experience
- Volunteer Experience
- Skills & Expertise
- Education
- [number] person has recommended [name]
- [number] people have recommended [name]
Support for additional sections may be added in the future.
<file_sep>
'use strict';
/**
* Requirements
*/
var Promise = require('promise'),
extend = require('extend'),
pdfText = require('pdf-text');
// jsonfile = require('jsonfile');
// If user wishes to out put json, will be imported
// in p(); documented here for reference.
/**
* Settings
*/
var settings = {
'headers': [
'Summary',
'Experience',
'Volunteer Experience',
'Skills & Expertise',
'Education',
'person has recommended',
'people have recommended'
],
'subsections': [
'Experience',
'Volunteer Experience'
],
'listsections': [
'Skills & Expertise'
],
'onelinesections': [
'Education'
],
'lineLength': 99, // could be 99
'replace': [
[' - ', ' - '],
[' at ', ' at '],
[' ', ' '],
[' , ', ', ']
]
};
/**
* Functions
*/
function resumePdfToJson(cb) {
var service = this;
service = {
'parse': parse,
'index': index,
'isHeader': isHeader,
'isTime': isTime,
'isDateRange': isDateRange,
'isPageNum': isPageNum,
'isRecommendation': isRecommendation,
'skip': skip,
'replace': replace,
'indexHeaders': indexHeaders
};
function isHeader(line) {
if (settings.headers.indexOf(line) > -1) return line;
return false;
}
function isTime(line) {
var i0 = line[0];
var iX = line[line.length - 1];
return (i0 === '(' && iX === ')');
}
function isDateRange(line) {
if (typeof line === 'undefined') return false;
var i0 = line.split(' - ')[0];
var date = i0[i0.length - 1];
return (line.indexOf(' - ') > -1 && isNaN(date) === false);
}
function isPageNum(line) {
return (line === 'Page' || !isNaN(+line));
}
function isRecommendation(line) {
var i0 = line.indexOf('person has recommended');
var i1 = line.indexOf('people have recommended');
return (i0 !== -1 || i1 !== -1);
}
function indexHeaders(chunks) {
var h, headers = [];
for (var sh = settings.headers.length - 1; sh >= 0; sh--) {
h = settings.headers[sh];
if (chunks.indexOf(h) > -1) headers.push(chunks.indexOf(h));
}
// Look for recommendations
for (var ch = chunks.length - 1; ch >= 0; ch--) {
if ( service.isRecommendation(chunks[ch]) ) headers.push(ch);
}
headers.sort(function(a, b){return a - b;});
for (var i = headers.length - 1; i >= 0; i--) {
h = headers[i];
headers[i] = chunks[h];
}
return headers;
}
function index(section) {
return service.headers.indexOf(section);
}
function skip(name, line) {
var skip = false;
skip = (line === 'Contact ' + name + ' on LinkedIn') ? true : skip;
return skip;
}
function replace(line) {
var r;
for (var i = 0; i < settings.replace.length; i++) {
r = settings.replace[i];
line = line.replace(r[0] , r[1]);
}
return line;
}
function parse(chunks) {
var cut, h, r, t, s, is, h1, h2, h3, ti;
var line, next, header, section,
head, time, range, text, prev;
var data = [];
var subsections = [];
var onelinesections = [];
var recommendations = [];
var groups = [];
var subsection = false;
var listsection = false;
var onelinesection = false;
var recommendation = false;
var skip = false;
var cnt = -1;
var dataHeader = {
'head': [
chunks[2],
chunks[3],
chunks[4]
]
};
var firstName = dataHeader.head[0].split(' ')[0];
// clean out the extra headers
for (var x = 0; x < chunks.length; x++) {
cut = dataHeader.head.indexOf(chunks[x]);
if ( cut > -1 ) {
chunks.splice(x, 1);
}
}
// clean out the page numbers
for (var y = 0; y < chunks.length; y++) {
if (service.isPageNum(chunks[y]) && chunks[y] === 'Page') {
chunks.splice(y, 2);
}
}
// create index reference to reflect order of
// headers in the pdf
service.headers = service.indexHeaders(chunks);
for (var i = 0; i < chunks.length; i++) {
line = chunks[i];
if (service.skip(firstName, line)) continue;
h = service.isHeader(line);
r = service.isRecommendation(line);
line = line.trim();
line = service.replace(line);
// create new section if this line is a header
if (h || r) {
header = line;
next = service.headers[service.index(header) + 1];
// if the headline is a recomendation, get the amount of
// people recommended and set next to false.
if (service.isRecommendation(line)) {
header = chunks[i - 1] + ' ' + line;
}
cnt = cnt + 1;
data.push({
'head': [header],
'text': [],
'sections': []
});
}
// if this section has sub-sections and it is
// not a header save it in a different array
// for parsing.
if (subsection && !h && !r) {
if (!subsections[cnt]) subsections[cnt] = {'head': [header], 'text': []};
subsections[cnt].text.push(line);
// if the section is a list section, just add
// to the text as a list.
} else if (listsection && !h && !r) {
data[cnt].text.push(line);
// if this section is a one line section and
// it is not a header save it in a different
// array for parsing.
} else if (onelinesection && !h && !r) {
if (!onelinesections[cnt]) onelinesections[cnt] = {'head': [header], 'text': []};
onelinesections[cnt].text.push(line);
// if this section is a recommendation, not a header,
// and not a recommendation header, parse it for the
// recommendation section
} else if (recommendation && !h && !r) {
// if it's a new recommendation, create a new section
if (line[0] === '"') {
data[cnt].sections.push({'text':[line]});
// else just add line to the last recomendation in the list.
} else {
ti = data[cnt].sections.length - 1;
t = data[cnt].sections[ti].text;
data[cnt].sections[ti].text = (t + ' ' + line).trim();
}
// save the line in this section's text array
// if the line isn't a page number, and the length
// is greater than the base paragraph line length.
} else if (data[cnt] && !service.isPageNum(line) && !h && !r) {
// concantenate the text.
t = data[cnt].text;
data[cnt].text = (t + ' ' + line).trim();
}
// set the subsection flag if the header is subsection
if (settings.subsections.indexOf(header) !== -1) subsection = true;
// set the listsection flag if the header is listsection
if (settings.listsections.indexOf(header) !== -1) listsection = true;
// set the onelinesection flag if the header is a onelinesection
if (settings.onelinesections.indexOf(header) !== -1) onelinesection = true;
// set the recommendation flag if the header is a recommendation
if (typeof header !== 'undefined' && service.isRecommendation(header))
recommendation = true;
// if the next line is the section after the special section
if (chunks[i + 1] === next || !next) {
subsection = false;
listsection = false;
onelinesection = false;
recommendation = false;
}
}
/**
* Parse info for subsections
* Sub-sections are classified by having three head lines
* with the third being enclosed in parentheses, ex. '(...)'
*/
for (var ss = 0; ss < subsections.length; ss++) {
// some indexes are empty, skip them if they are
if (typeof subsections[ss] === 'undefined') continue;
text = subsections[ss].text;
is = service.index(subsections[ss].head[0]);
// reset the count for this section
cnt = -1;
// got through the text of the sub sections
for (var s = 0; s < text.length; s++) {
line = text[s];
prev = text[s - 1];
h1 = line;
h2 = text[s + 1];
h3 = text[s + 2];
// if the time variable fits the time format,
// create a new section and set the headline vars.
// if (h3 && service.isTime(h3)) {
// if (s === 0 || nuw) {
if (service.isDateRange(h2)) {
head = [h1, h2];
cnt = cnt + 1;
if (h3 && service.isTime(h3)) head.push(h3);
data[is].sections.push({
'head': head,
'text': ''
});
// if the time isn't time, and the line isn't
// a page number, and the line isn't one of
// the headline vars, add line to the section text.
} else if (line && !service.isPageNum(line) && head.indexOf(line) === -1) {
// concantentate section text
t = data[is].sections[cnt].text;
data[is].sections[cnt].text = (t + ' ' + line).trim();
}
}
}
/**
* Parse info for one line sections
* Sub-sections are classified by groups of two lines
*/
for (var ol = 0; ol < onelinesections.length; ol++) {
// some indexes are empty, skip them if they are
if (typeof onelinesections[ol] === 'undefined') continue;
text = onelinesections[ol].text;
is = service.index(onelinesections[ol].head[0]);
// group the sections by two
while (text.length > 0) {
groups.push(text.splice(0, 2));
}
// go through the groups and add them as sections.
for (var g = 0; g < groups.length; g++) {
head = [ groups[g][0] ];
text = groups[g][1];
// if they aren't page numbers and they are groups
// of two, create sections for them.
if (groups[g].length === 2 && !service.isPageNum(text) && data[is]) {
data[is].sections.push({
'head': head,
'text': text
});
}
}
}
data.unshift(dataHeader);
return data;
}
pdfText(settings.path, function(err, chunks) {
if (err) {
cb(err, null);
} else {
try {
cb(null, service.parse(chunks));
} catch (e) {
console.log(e);
cb(e, null);
}
}
});
}
function p(resolve, reject) {
resumePdfToJson(function(err, data) {
if (err) {
reject(err);
return;
}
if (settings.output) {
require('jsonfile').writeFile(settings.output, data);
}
resolve(data);
});
}
module.exports = function(path, config) {
settings = extend(true, {}, config, settings);
settings.path = path;
return new Promise(p);
}; | ba3db31102f6d413f501509ceced1ee4d6a87cf9 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | expdesignio/resume-pdf-to-json | 55c90952949efaf6935f239c10846fef93f0bc41 | 2f7bf54123e93c292907872a7344c95138ba2745 | |
refs/heads/master | <repo_name>phuong23401/Demofile<file_sep>/src/view/Client.java
package view;
import controller.StudentManager;
import model.Student;
import storage.FileManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Client {
private static final Scanner SCANNER = new Scanner(System.in);
private static List<Student> c0221i1 = new ArrayList<>();
private static final StudentManager MANAGER = new StudentManager("<NAME>", c0221i1);
private static final Student STUDENT = newStudent();
public static void main(String[] args) {
while (true) {
System.out.println("-----CHƯƠNG TRÌNH QUẢN LÍ SINH VIÊN-----");
System.out.println("1. Hiển thị danh sách sinh viên");
System.out.println("2. Thêm mới sinh viên");
System.out.println("3. Sửa thông tin sinh viên");
System.out.println("4. Xóa sinh viên");
System.out.println("5. Ghi vào file");
System.out.println("6. Đọc từ file");
System.out.println("0. Thoát");
System.out.println("Mời chọn chức năng: ");
int choose = Integer.parseInt(SCANNER.nextLine());
switch (choose) {
case 1:
MANAGER.showAllStudent();
break;
case 2:
addStudent();
break;
case 3:
editStudent();
break;
case 4:
deleteStudent();
break;
case 5:
writeFile();
break;
case 6:
readFile();
break;
case 0:
System.exit(0);
break;
default:
System.out.println("Mời nhập chức năng trong menu!");
break;
}
}
}
private static void addStudent() {
try {
MANAGER.addNewStudent(STUDENT);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void editStudent() {
try {
MANAGER.editStudent(inputId(), STUDENT);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void deleteStudent() {
try {
MANAGER.deleteStudent(inputId());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeFile() {
try {
FileManager.writeFile(c0221i1);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readFile() {
try {
c0221i1 = FileManager.readFile();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Student newStudent() {
int id = inputId();
String name = inputName();
String add = inputAddress();
return new Student(id, name, add);
}
private static String inputAddress() {
System.out.print("Moi ban nhap dia chi: ");
return SCANNER.nextLine();
}
private static String inputName() {
System.out.print("Moi ban nhap ten: ");
return SCANNER.nextLine();
}
private static int inputId() {
System.out.print("Moi ban nhap Id: ");
return Integer.parseInt(SCANNER.nextLine());
}
} | 7ce73c5601a13cda3749bff46617139c347500bc | [
"Java"
] | 1 | Java | phuong23401/Demofile | 89064802487f86239aa996ca44ce498499e2dc30 | dd2c6416d590b6a7dba89e2e2ecceafd7ff1d4f1 | |
refs/heads/master | <file_sep>require "HistoryModel/version"
module HistoryModel
# History Model
require 'elasticsearch/model'
require_relative 'application_record.rb'
require_relative 'application_controller.rb'
module Model
class History < ApplicationRecord
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
mapping do
indexes :email, index: 'not_analyzed'
indexes :url, index: 'not_analyzed'
indexes :origin_url, index: 'not_analyzed'
indexes :target_url, index:'not_analyzed'
indexes :lang, index:'not_analyzed'
indexes :image,index: 'not_analyzed'
end
end
end
module Controller
#class HistoryController < ApplicationController
def show
id = params[:id]
history = History.find_by(id: id)
render json: history
end
def index
histories = History.all
render json: histories
end
def create
enter_date = params[:enter_date]
leave_time = params[:leave_time]
focus_elasped_time = params[:focus_elasped_time]
total_elasped_time = params[:total_elasped_time]
history = History.create(email: params[:email],
url: params[:url],
origin_url: params[:origin_url],
target_url: params[:target_url],
lang: params[:lang],
title: params[:title],
description: params[:description],
image: params[:image],
search: params[:search],
enter_date: enter_date,
leave_time: leave_time,
focus_elasped_time: focus_elasped_time,
total_elasped_time: total_elasped_time)
history.save
render json: history
end
def destroy
id = params[:id]
history = History.find_by(id: id)
if history != nil
history.destroy
end
render json: history
end
#end
end
end
<file_sep>source 'https://rubygems.org'
# Specify your gem's dependencies in HistoryModel.gemspec
gemspec
#Database
gem 'pg'
# Use ElasticSearch models
gem 'elasticsearch-model', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.2'
| 36ca87faef92794be885f52173e2e3957494769c | [
"Ruby"
] | 2 | Ruby | Pumgrana/api-common | 97a447d06586d1de22abc658d21b79b9a717c075 | 64f3eb7693fda6bac06a859bbfea0f0752c70a02 | |
refs/heads/master | <file_sep>---
title: "Home"
menu: "main"
weight: 1
---
<file_sep>---
title: "Contact"
menu: "main"
weight: 5
---
Tel: 415-890-5744
Email: [<EMAIL>](mailto:<EMAIL>)
<file_sep>var Jolie = {};
Jolie.fadeInImages = function() {
var delay = 0;
$('#instafeed img').each(function() {
var image = $(this);
setTimeout(function() { image.addClass('show'); }, delay);
delay += 100;
});
};
Jolie.feed = new Instafeed({
get: 'user',
userId: '1580317725',
clientId: '<KEY>',
accessToken: '<KEY>',
resolution: 'standard_resolution',
sortBy: 'random',
after: Jolie.fadeInImages
});
Jolie.feed.run();
<file_sep>---
title: "About Us"
menu: "main"
weight: 3
---
## About Jolie
Jolie SF was dreamt up with the desire to celebrate people every day.
As dessert consultants we help dream and source products for your business needs. We hope to make this process as sweet as the products we source.
Jolie (Jo-Lee) is a French word meaning “pretty.” While in France, Vanessa’s limited French speaking skills allowed her only a handful of phrases and words and she found herself saying “tres jolie” (very pretty) probably more often than appropriate, but we think her enjoyment made up for it.
{{< figure src="/vanessa_couvrey.jpg">}}
## About Vanessa
Vanessa is a Bay Area local who grew up in Cupertino, CA. After graduating from Cal Poly, San Luis Obispo with a degree in Business Marketing she decided food was her ultimate calling and pursued a degree in Culinary Arts from The Culinary Institute of America at Greystone. An externship brought her to Rennes, France where she worked at the Michelin star restaurant La Fontaine aux Perles performing many duties including making traditional French desserts. She came back and dove into work for Revolution Foods in Oakland, CA, traveling the U.S. training chefs on new menus and helping the R&D chef with new food for kid lunches. With a strong desire to get back into making more delicious and sugary things she landed in the Absinthe pastry kitchen under Chef Bill Corbett. It was here where she honed her pastry skills and began to dream up Jolie SF. Vanessa has always loved making people feel special and baking is one of her favorite ways to do that.
| 8906a765e9635a66b291e78c4dbf993c500dd17f | [
"Markdown",
"JavaScript"
] | 4 | Markdown | jameskerr/joliesf | 0d98451705b5e994531ca32c06e4003fe1122bc7 | 880ce74f7fa1f99dd93c2d836eea686f7315b01a | |
refs/heads/main | <file_sep>package com.example.cureit
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 3507d52d215335da5fd93601a7bcea88ac9f3dc6 | [
"Kotlin"
] | 1 | Kotlin | rohitasture/CureIt | 630c91af54e5fb78f171fbc0e99c9b5806ea23a7 | 866a130a1958607495d3013b2eb8fa5f230c36f9 | |
refs/heads/main | <file_sep>#include <iostream>
#include <math.h>
#include <string>
#include <stdio.h>
#include <sstream>
#include <windows.h>
#include <cstdlib>
//#include <system>
using namespace std;
int board[8][8];
int mStep[5];
int sheep[2];
void clearBoard(int board[8][8]){
for(int j = 7; j > -1; j--){
for(int i = 0; i < 8; i++){
board[i][j] = 0;
}
}
}
void outputBoardTest(int board[8][8]){
cout << endl;
for(int j = 7; j > -1; j--){
for(int i = 0; i < 8; i++){
cout << board[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void outputChessBoard(int board[8][8]){
//cout << endl;
cout << "___________________________________" << endl;
for(int j = 7; j > -1; j--){
cout << "|";
for(int i = 0; i < 8; i++){
if (board[i][j] == 1){
cout << " " << "O" << " ";
}
if (board[i][j] == 2){
cout << " " << "B" << " ";
}
if (board[i][j] == 0){
cout << " ";
}
cout << "|";
}
cout << " " << j + 1;
if (j == 7) {
cout<< "\t\t\t" << "Волки и Овца";
}
if (j == 6) {
cout<< "\t" << "Правила игры:";
}
if (j == 5) {
cout<< "\t" << "2)Волки ходят на одну 1 клетку по диагонали, но только вперёд";
}
if (j == 4) {
cout<< "\t" << "4)Волки побеждаю, когда овца не может никуда ходить";
}
if (j == 3) {
cout<< "\t" << "куда она должна сходить";
}
if (j == 2) {
cout<< "\t" << "откуда волк должен сделать ход и через '-' куда он должен сходить";
}
if (j == 1) {
cout<< "\t\t\t " << "Пример ввода:";
}
if (j == 0) {
cout<< "\t" << "Ob8-c7 Bh1-g2 ";
}
cout << endl;
cout << "|___|___|___|___|___|___|___|___|__";
if (j == 6) {
cout<< "\t" << "1)Овца ходит только на 1 клетку по диагонали";
}
if (j == 5) {
cout<< "\t" << "3)Овца побеждает, когда доходит до 1 линии";
}
if (j == 4) {
cout<< "\t" << "5)Чтобы сделать ход за овцу, необходимо ввести клетку,";
}
if (j == 3) {
cout<< "\t" << "6)Чтобы сделать ход за волка, необходимо ввести клетку,";
}
if (j == 1) {
cout<< "\t" << "Ходит овца: Ходит волк: ";
}
cout << endl;
}
cout << " a b c d e f g h";
cout << endl;
}
void inputStart(int Ostart){
if(Ostart == 1){
board[1][7] = 1;
sheep[0] = 1;
sheep[1] = 7;
}
if(Ostart == 2){
board[3][7] = 1;
sheep[0] = 3;
sheep[1] = 7;
}
if(Ostart == 3){
board[5][7] = 1;
sheep[0] = 5;
sheep[1] = 7;
}
if(Ostart == 4){
board[7][7] = 1;
sheep[0] = 7;
sheep[1] = 7;
}
for(int i = 0; i < 8; i += 2){
board[i][0] = 2;
}
}
int locate(){
int start = -1;
char input[3];
char symbol = getchar();
int number = 0;
while(symbol != '\n'){
for(int i = 0; i < 3; i++){
if (number == i){
input[i] = symbol;
}
}
number++;
symbol = getchar();
}
if((input[0] == 'b') && (input[1] == '8') && (number == 2)){
start = 1;
}
if((input[0] == 'd') && (input[1] == '8') && (number == 2)){
start = 2;
}
if((input[0] == 'f') && (input[1] == '8') && (number == 2)){
start = 3;
}
if((input[0] == 'h') && (input[1] == '8') && (number == 2)){
start = 4;
}
return start;
}
int numb(char number){
int output = -1;
if((number >= '1') && (number <= '8')){
output = number - '1';
}
return output;
}
int let(char letter){
int output = -1;
if((letter >= 'a') && (letter <= 'h')){
output = letter - 'a';
}
return output;
}
void step(int animal){
for (int i = 0; i < 5; i++){
mStep[i] = -1;
}
//cout << "O";
char input[6];//количество введёных символов
if (animal == 1){
cout << 'O';
cout << (char)(sheep[0] + 'a');
cout << (char)(sheep[1] + '1');
cout << '-';
char symbol = getchar();
int number = 4;
while(symbol != '\n'){
for(int i = 4; i < 6; i++){
if (number == i){
input[i] = symbol;
}
}
number++;
symbol = getchar();
}
input[0] = 'O';
input[1] = (char)(sheep[0] + 'a');
input[2] = (char)(sheep[1] + '1');
input[3] = '-';
}
if (animal == 2){
cout << 'B';
char symbol = getchar();
int number = 1;
while(symbol != '\n'){
for(int i = 1; i < 6; i++){
if (number == i){
input[i] = symbol;
}
}
number++;
symbol = getchar();
}
input[0] = 'B';
}
//cout << input[0] << input[1] << input[2] << input[3] << input[4] << input[5] <<endl;
if((input[0] == 'O') && (animal == 1) && (input[3] == '-')){//проверка для овцы
mStep[0] = animal;
mStep[1] = let(input[1]);
mStep[2] = numb(input[2]);
mStep[3] = let(input[4]);
mStep[4] = numb(input[5]);
}
if((input[0] == 'B') && (animal == 2) && (input[3] == '-')){//проверка для волка
mStep[0] = animal;
mStep[1] = let(input[1]);
mStep[2] = numb(input[2]);
mStep[3] = let(input[4]);
mStep[4] = numb(input[5]);
}
//cout << mStep[0] << mStep[1] << mStep[2] << mStep[3] << mStep[4] <<endl;
int erorr = 0;
for (int i = 0; i < 5; i++){
if (mStep[i] == -1){
erorr = -1;
}
}
if (erorr != 0){
for (int i = 0; i < 5; i++){
mStep[i] = -1;
}
}
//cout << erorr << endl;
}
void outputStepTest(){
for (int i = 0; i < 5; i++){
cout << mStep[i] << " ";
}
cout << endl;
}
int whoWin(){
for (int i = 0; i < 8; i++){// если овца дошла до конца, то она победила
if (board[i][0] == 1){
//cout << "win1";
return 1;
}
}
if (sheep[1] < 7){
if (sheep[0] == 0){//если находится слева (не на 8 строке) и зажата, то проигрышь
if ((board[sheep[0] + 1][sheep[1] - 1] == 2) && (board[sheep[0] + 1][sheep[1] + 1] == 2)){
//cout << "win2";
return 2;
}
}
}else{
if (sheep[0] == 0){//если находится слева (на 8 строке) и зажата, то проигрышь
if (board[sheep[0] + 1][sheep[1] - 1] == 2){
//cout << "win3";
return 2;
}
}
}
if (sheep[1] < 7){
if (sheep[0] == 7){//если находится справа (не на 8 строке) и зажата, то проигрышь
if ((board[sheep[0] - 1][sheep[1] - 1] == 2) && (board[sheep[0] - 1][sheep[1] + 1] == 2)){
//cout << "win4";
return 2;
}
}
}else{
if (sheep[0] == 7){//если находится справа (на 8 строке) и зажата, то проигрышь
if (board[sheep[0] - 1][sheep[1] - 1] == 2){
//cout << "win5";
return 2;
}
}
}
if (sheep[1] < 7){
if ((board[sheep[0] + 1][sheep[1] - 1] == 2) && (board[sheep[0] - 1][sheep[1] - 1] == 2) && (board[sheep[0] + 1][sheep[1] + 1] == 2) && (board[sheep[0] - 1][sheep[1] + 1] == 2)){// если зажата по бокам на 8 линии
//cout << "win6";
return 2;
}
}else{
if ((board[sheep[0] + 1][sheep[1] - 1] == 2) && (board[sheep[0] - 1][sheep[1] - 1] == 2)){// если зажата по бокам на 8 линии
//cout << "win7";
return 2;
}
}
return 0;
}
int PVP(int shOrWolf){
int winner = -1;
bool stop = true;
//shOrWolf = 0;//счетчик ходов
while (stop){
system ("cls");
outputChessBoard(board);
if (shOrWolf % 2 == 0){//ход Овцы
cout << "Ходит овца:" << endl;
bool correct = false;
step(1);
int inputError = 0;
while (!correct){
if (mStep[0] != -1){
if((board[mStep[1]][mStep[2]] == 1) && (board[mStep[3]][mStep[4]] == 0) && ((mStep[2] == mStep[4] + 1) || (mStep[2] == mStep[4] - 1)) && ((mStep[1] == mStep[3] - 1) || (mStep[1] == mStep[3] + 1))){
board[mStep[1]][mStep[2]] = 0;
board[mStep[3]][mStep[4]] = 1;
sheep[0] = mStep[3];
sheep[1] = mStep[4];
correct = !correct;
}else{
inputError++;
system ("cls");
outputChessBoard(board);
cout << "Попыток неправельного ввода: " << inputError << endl;
cout << "Повторите ввод" << endl;
cout << "Ходит овца:" << endl;
step(1);
//cout << "erorr1" << endl;
}
}else{
//cout << "erorr2" << endl;
inputError++;
system ("cls");
outputChessBoard(board);
cout << "Попыток неправельного ввода: " << inputError << endl;
cout << "Повторите ввод" << endl;
cout << "Ходит овца:" << endl;
step(1);
}
}
}else{//ход волка
cout << "Ходит волк:" << endl;
bool correct = false;
step(2);
int inputError = 0;
while (!correct){
if (mStep[0] != -1){
if((board[mStep[1]][mStep[2]] == 2) && (board[mStep[3]][mStep[4]] == 0) && (mStep[2] == mStep[4] - 1) && ((mStep[1] == mStep[3] - 1) || (mStep[1] == mStep[3] + 1))){
board[mStep[1]][mStep[2]] = 0;
board[mStep[3]][mStep[4]] = 2;
correct = !correct;
}else{
inputError++;
system ("cls");
outputChessBoard(board);
cout << "Попыток неправельного ввода: " << inputError << endl;
cout << "Повторите ввод" << endl;
cout << "Ходит волк:" << endl;
step(2);
}
}else{
inputError++;
system ("cls");
outputChessBoard(board);
cout << "Попыток неправельного ввода: " << inputError << endl;
cout << "Повторите ввод" << endl;
cout << "Ходит волк:" << endl;
step(2);
}
}
}
winner = whoWin();// проверяем на победу и в случае чего выходим
if ((winner == 1) || (winner == 2) || (winner == -1)){
stop = !stop;
}
shOrWolf++;
}
return winner;
}
bool repeat(){
int inputError = 0;
bool erorr = true;
while(erorr){
//system ("cls");
if (inputError == 0){
cout << "Чтобы начать игру заново введите: '1'" << endl;
cout << "Чтобы закрыть игру введите: '0'" << endl;
}else{
system ("cls");
cout << "Попыток неправельного ввода: " << inputError << endl;
cout << "Повторите попытку" << endl;
cout << "Чтобы начать игру заново введите: '1'" << endl;
cout << "Чтобы закрыть игру введите: '0'" << endl;
}
char input[1];
char symbol = getchar();
int number = 0;
while(symbol != '\n'){
for(int i = 0; i < 1; i++){
if (number == i){
input[i] = symbol;
}
}
number++;
symbol = getchar();
}
if (input[0] == '0'){
system ("cls");
return false;
}
if (input[0] == '1'){
system ("cls");
return true;
}
inputError++;
}
}
int main(){
bool rep = true;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL,"russian");
//rep = repeat();
while (rep){
clearBoard(board);
//Выбор клетки, с которой начинает ходить овца
int OStart = -1;
int inputError = 0;
//OStart = 1; // b8
//OStart = 2; // d8
//OStart = 3; // f8
//OStart = 4; // h8
///*
while(OStart == -1){
if (inputError == 0){
system ("cls");
cout<< "Волки и Овца"<< endl;
cout << endl;
cout << "Введите клетку, с которой овца начнет ходить" << endl;
cout << "Возможные варианты: 'b8', 'd8', 'f8', 'h8'" << endl;
}else{
system ("cls");
cout << "Попыток неправельного ввода: " << inputError << endl;
cout << "Повторите попытку" << endl;
cout << "Введите клетку, с которой овца начнет ходить" << endl;
cout << "Возможные варианты: 'b8', 'd8', 'f8', 'h8'" << endl;
}
OStart = locate();
inputError++;
}
inputError = 0;
inputStart(OStart);
//*/
/*
board[0][6] = 1;
board[1][5] = 2;
board[2][6] = 2;
sheep[0] = 0;
sheep[1] = 6;
//outputBoardTest(board);
//outputChessBoard(board);
*/
int endd = PVP(0);
if (endd == 1){
system ("cls");
outputChessBoard(board);
cout << "Победила овца" << endl;
cout << endl;
rep = repeat();
}
if (endd == 2){
system ("cls");
outputChessBoard(board);
cout << "Победили волки" << endl;
cout << endl;
rep = repeat();
}
if (endd == -1){
system ("cls");
outputChessBoard(board);
cout << "Erorr output" << endl;
cout << endl;
rep = repeat();
}
//step(1);// ход овцы
//outputStepTest();
//step(2);// ход волка
//outputStepTest();
}
return 0;
exit(0);
}
<file_sep>#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
struct DataList{
double Uy, Sy, Ux, Sx, t, a;
DataList* next;
};
void startList(DataList* root){
(*root).Uy = 0;
(*root).Sy = 0;
(*root).Ux = 0;
(*root).Sx = 0;
(*root).t = 0;
(*root).a = 0;
(*root).next = NULL;
}
void writeList(DataList* ls, double Ux, double Sx, double Uy, double Sy, double t, double a){
DataList* lsEnd = ls;
while ((*lsEnd).next != NULL)
lsEnd = (*lsEnd).next;
(*lsEnd).Uy = Uy;
(*lsEnd).Sy = Sy;
(*lsEnd).Ux = Ux;
(*lsEnd).Sx = Sx;
(*lsEnd).t = t;
(*lsEnd).a = a;
(*lsEnd).next = new DataList;
startList((*lsEnd).next);
}
const double g = 9.80665;
/*
double deltaT = 0.01;
double Uy = 20;
double Sy = 0;
double Ux = 20;
double Sx = 0;
double Sx_max = 0;
double Sx_min = 1000;
*/
double percent = 0.75;
int rebound = 1;
DataList* simulate(double Ux, double Sx, double Uy, double Sy, double deltaT){
DataList* output = new DataList;
startList(output);
double t = 0;
for (int i = 0; i <= rebound; i++){
while (Sy >= 0){
Sx += deltaT*Ux;
Sy += Uy*deltaT - (g*deltaT*deltaT)/2;
Uy = Uy - (g*deltaT);
t += deltaT;
writeList(output, Ux, Sx, Uy, Sy, t, g);
//cout << Sx << " " << Ux << endl;
//cout << Sx << endl;
}
Uy = Uy *(-1)*percent;
Sy = Sy*(-1);
}
return output;
}
void print(DataList* ls)
{
cout << "Printing data" << endl;
cout << "Time\tSx\tUx\tSy\tUy\t\tG" << endl;
DataList* outLs = ls;
while ((*outLs).next != NULL){
cout << fixed << showpoint;
cout << setprecision(2);
cout << (double)(*outLs).t << "\t" << (*outLs).Sx << "\t" << (*outLs).Ux << "\t" << (*outLs).Sy << "\t" << (*outLs).Uy << "\t\t" << (*outLs).a << endl;
outLs = (*outLs).next;
}
}
bool testSimulate()
{
double maxSy = 0;
double minSy = 100;
double deltaT = 0.01;
double Uy = 20;
double Sy = 0;
double Ux = 3;
double Sx = 0;
DataList* outLs = simulate(Ux, Sx, Uy, Sy, deltaT);
while ((*outLs).next != NULL){
if ((*outLs).Sy > maxSy){
maxSy = (*outLs).Sy;
}
if ((*outLs).Sy < minSy){
minSy = (*outLs).Sy;
}
if ((*outLs).Ux != Ux){ // горизонтальная состовляющая постоянна
return false;
}
outLs = (*outLs).next;
}
//cout << maxSy << "\t" << Uy*Uy/2/g - 0.02 << "\t" << Uy*Uy/2/g + 0.02<< endl;
//cout << minSy << endl;
if ((maxSy < (Uy*Uy/2/g - 0.2)) || (maxSy > (Uy*Uy/2/g + 0.2))){ // долетел до теоретического максимума
return false;
}
if ((minSy > 0.2) || (minSy < -0.2)){ // удар об землю
return false;
}
if ((*outLs).Sx != (*outLs).t*Ux){ // проверка на дальность полёта
return false;
}
return true;
}
void runTest(bool (*testFunction)(), const string& testName)
{
if (testFunction() == true)
std::cout << "Test " << testName << " - OK" << std::endl;
else
std::cout << "Test " << testName << " - FAIL" << std::endl;
}
int main(){
runTest(testSimulate, "Simulation");
//DataList* dl = simulate(3, 0, 20, 0, 0.01);
//print(dl);
return 0;
}
<file_sep>#include <iostream>
using namespace std;
struct Node
{
int val;
Node* next;
};
void init(Node* node)
{
node->val = 0;
node->next = NULL;
}
void show(Node* root)
{
Node* cur = root;
while (cur->next != NULL)
{
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
void pushNode(Node* root, Node* node)
{
Node* cur = root;
while (cur->next != NULL)
cur = cur->next;
cur->next = new Node;
init(cur->next);
cur->val = node->val;
}
void rShiftList(Node* root,int n)
{
for (int i = 0; i < n; i++)
{
Node* cur = root;
int num = cur->val;
int x[2];
x[0] = cur->next->val;
cur->next->val = cur->val;
cur->val = 0;
int j =0;
while (cur->next->next != NULL)
{
if(j%2 == 0 ){
cur = cur->next;
x[1] = cur->next->val;
cur->next->val = x[0];
}else{
cur = cur->next;
x[0] = cur->next->val;
cur->next->val = x[1];
}
j++;
}
}
}
bool testrShiftList()
{
Node* root = new Node;
init(root);
pushNode(root, new Node{ 1 });
pushNode(root, new Node{ 2 });
pushNode(root, new Node{ 3 });
pushNode(root, new Node{ 4 });
pushNode(root, new Node{ 5 });
//show(root);
rShiftList(root, 3);
//show(root);
return (root->val == 0 && root->next->val == 0 && root->next->next->val == 0 && root->next->next->next->val == 1 && root->next->next->next->next->val == 2);
}
static void runTest(bool (*testFunction)(), const string& testName)
{
if (testFunction() == 1)
std::cout << "Test " << testName << " - OK" << std::endl;
else
std::cout << "Test " << testName << " - FAIL" << std::endl;
}
int main()
{
runTest(testrShiftList, "lRoundShiftTest");
}
<file_sep>#include <iostream>
using namespace std;
int mas[1000];
void input(int* source, int size){
for(int i = 0; i < size; i++){
cin >> source[i];
}
}
void output(int* source, int size){
for(int i = 0; i < size; i++){
cout << source[i];
}
}
void rShiftMas(int* source,int n, int size){
for (int i = size - (n + 1); i != -1; i--)
source[i+n] = source[i];
for (int i = 0; i < n; i++)
source[i] = 0;
}
bool comprasion(int* a, int* b, int size){
for (int i = 0; i < size; i++){
if (a[i] != b[i]){
return false;
}else{
return true;
}
}
}
bool test(int* a, int* b, int n, int size)
{
rShiftMas(a, n, size);
return comprasion(a, b, size);
}
int main(){
int n, size;
n = 3;
size = 8;
int test_1_input[size] = {1, 2, 3, 4, 5, 6, 7, 8};
int test_1_output[size] = {0, 0, 0, 1, 2, 3, 4, 5};
int test_2_input[size] = {5, -4, 3, -2, 1, 0, 0, 0};
int test_2_output[size] = {0, 0, 0, 5, -4, 3, -2, 1};
if (test(test_1_input, test_1_output, n, size)){
cout << "True" << endl;
}else{
cout << "False" << endl;
}
if (test(test_2_input, test_2_output, n, size)){
cout << "True" << endl;
}else{
cout << "False" << endl;
}
/*
cin >> n;
cin >> size;
input(mas, size);
rShiftMas(mas, n, size);
output(mas, size);
*/
//rShiftMas(mas, n size);
return 0;
}<file_sep># Boyarinov_Ivan_Practice_2021_summer
<file_sep>#include <iostream>
using namespace std;
int funct(int number, int variants){
return number % variants + 1;
}
int main(){
int number, variants;
cin >> number;
cin >> variants;
cout << funct(number, variants);
return 0;
}
<file_sep>#include <iostream>
#include <fstream>
#include <Windows.h>
#include <limits>
using namespace std;
const double g = 10;
struct flight
{
int mh = 120;
int mt = 57;
int* points;
double v=0;
double a=0;
double h=0;
double t=0;
double InputFlight(flight n_flight, double v0, double h0, double t0);
void createImage(int t, int h);
void initImage();
void saveToPnmFile(string fileName);
flight* next;
};
class List
{
flight* head;
public:
List() :head(NULL) {};
~List();
void AddFlight(flight n_flight);
void ShowFlight(double t0, double t1);
};
List::~List()
{
while (head != NULL)
{
flight* temp;
temp = head->next;
delete head;
head = temp;
}
}
double flight::InputFlight(flight n_flight, double v0, double h0, double t0)
{
t = t0;
h = h0 + v0 * t0 - g * t0 * t0 / 2;
v = v0 - g * t0;
a = -g;
return h;
}
void List::AddFlight(flight n_flight)
{
flight* temp;
temp = new flight;
temp->next = head;
temp->t = n_flight.t;
temp->h = n_flight.h;
temp->v = n_flight.v;
temp->a = n_flight.a;
head = temp;
}
int TestTime(double t1, double t2)
{
if ((t1 > t2)||(t1<0)||(t2<0))
{
cout << "Ошибка в задании диапазона времени" << endl;
return -1;
}
return 0;
}
int TestHight(double h0)
{
double hMax = 20000;
if ((h0 < 0) || (h0 > hMax))
{
cout << "Ошибка в задании начальной высоты" << endl;
return -1;
}
return 0;
}
void List::ShowFlight(double t1,double t2)
{
flight* temp;
temp = head;
while (temp != NULL)
{
if ((temp->t >= t1) && (temp->t <= t2))
{
cout << "t= " << temp->t << "\t\t";
cout << "h= " << temp->h << "\t\t";
cout << "v= " << temp->v << "\t\t";
cout << "a= " << temp->a << endl;
}
temp = temp->next;
}
cout << endl;
}
void flight::initImage()
{
int n = mt * mh;
points = new int[n];
for (int i = 0; i < n; i++)
points[i] = 0;
}
void flight::createImage(int t, int h)
{
int n;
n = h * mt + t;
points[n] = 1;
}
void flight::saveToPnmFile( string fileName)
{
fstream fout(fileName, ios::out);
int n;
fout << "P1" << endl;
fout << mt << " " << mh << endl;
for (int i = mh-1; i >=0; i--)
{
for (int j = 0; j < mt; j++)
{
n = (i * mt + j);
fout << points[n] << " ";
}
fout << endl;
}
fout << endl;
fout.close();
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
flight n_flight;
List lst;
double v0 = 10;
double g = 10;
double m = 1;
double h0 = 100;
double t0;
double h1=100;
double t1 = 0;
double t2 = 3;
double dt = 0.1;
t0 = t1;
if ((TestTime(t1, t2) == -1)||(TestHight(h0)==-1))
{
return -1;
}
n_flight.initImage();
while (h1 >=0)
{
h1 = n_flight.InputFlight(n_flight, v0, h0, t0);
n_flight.createImage(t0*10, h1);
lst.AddFlight(n_flight);
t0 = t0 + dt;
}
lst.ShowFlight(t1,t2);
n_flight.saveToPnmFile("image.pnm");
}
| 854807beec08253c37045b1ff97d6ca8c39cb491 | [
"Markdown",
"C++"
] | 7 | C++ | Gromozeka-BI/Boyarinov_Ivan_Practice_2021_summer | 6c460955bceb2de752c6dc0ec4f180fdd3736ae4 | 0424ad61ebb7c3a24c2d81e953184c32763a65e0 | |
refs/heads/master | <repo_name>EvolSoft/CustomAlerts<file_sep>/CustomAlerts/src/CustomAlerts/Commands/Commands.php
<?php
namespace CustomAlerts\Commands;
use pocketmine\command\Command;
use CustomAlerts\CustomAlerts;
use pocketmine\command\CommandSender;
use pocketmine\utils\TextFormat;
Class Commands extends Command{
private $plugin;
public function __construct(CustomAlerts $plugin)
{
parent::__construct("customalerts", "CustomAlerts commands.", null, ["calerts"]);
$this->plugin = $plugin;
}
public function execute(CommandSender $sender, string $commandLabel, array $args)
{
if(isset($args[0])){
switch(strtolower($args[0])){
case "help":
if($sender->hasPermission("customalerts.help")){
$sender->sendMessage(TextFormat::colorize("&b-- &aAvailable Commands &b--"));
$sender->sendMessage(TextFormat::colorize("&d/calerts help &b-&a Show help about this plugin"));
$sender->sendMessage(TextFormat::colorize("&d/calerts info &b-&a Show info about this plugin"));
$sender->sendMessage(TextFormat::colorize("&d/calerts reload &b-&a Reload the config"));
}else{
$sender->sendMessage(TextFormat::colorize("&cYou don't have permissions to use this command"));
}
break;
case "info":
if($sender->hasPermission("customalerts.info")){
$sender->sendMessage(TextFormat::colorize(CustomAlerts::PREFIX . "&aCustomAlerts &dv" . $this->plugin->getDescription()->getVersion() . "&a developed by &dEvolSoft §r§aand updated by §dKanekiLeChomeur "));
$sender->sendMessage(TextFormat::colorize(CustomAlerts::PREFIX . "&aWebsite &d" . $this->plugin->getDescription()->getWebsite()));
}else{
$sender->sendMessage(TextFormat::colorize("&cYou don't have permissions to use this command"));
}
break;
case "reload":
if($sender->hasPermission("customalerts.reload")){
$this->plugin->reloadConfig();
$this->plugin->cfg = $this->plugin->getConfig()->getAll();
$sender->sendMessage(TextFormat::colorize(CustomAlerts::PREFIX . "&aConfiguration Reloaded."));
}else{
$sender->sendMessage(TextFormat::colorize("&cYou don't have permissions to use this command"));
}
break;
default:
if($sender->hasPermission("customalerts")){
$sender->sendMessage(TextFormat::colorize(CustomAlerts::PREFIX . "&cSubcommand &a" . $args[0] . " &cnot found. Use &a/calerts help &cto show available commands"));
}else{
$sender->sendMessage(TextFormat::colorize("&cYou don't have permissions to use this command"));
}
break;
}
}else{
if($sender->hasPermission("customalerts")){
$sender->sendMessage(TextFormat::colorize(CustomAlerts::PREFIX . "&cUse &a/calerts help &cto show available commands"));
}else{
$sender->sendMessage(TextFormat::colorize("&cYou don't have permissions to use this command"));
}
}
}
}
<file_sep>/README.md

# CustomAlerts
Customize or hide alerts (join/leave messages, whitelist messages, outdated server/client messages, etc...) plugin for PocketMine-MP
[](http://gestyy.com/er3sEQ)
## Category
PocketMine-MP plugins
## Requirements
PocketMine-MP API 4.0.0
## Overview
**CustomAlerts** lets you customize or hide all PocketMine alerts (join/leave messages, whitelist messages, outdated server/client messages, etc...)
**EvolSoft Website:** *Downed*
***This Plugin uses the New API. You can't install it on old versions of PocketMine.***
With CustomAlerts you can customize or hide whitelist kick messages, outdated server/client messages, join/leave messages, first join messages, death messages, world change messages... (read documentation)
**Features**
- Customize or hide join, quit and death messages
- Add first join and world change messages
- Customize Motd ***(from MCPE 0.11.0)***
- Customize Outdated Server/Client kick messages ***(from MCPE 0.11.0 BUILD 11)***
- Customize Whitelist kick messages ***(from MCPE 0.11.0 BUILD 11)***
- Customize Full Server kick messages ***(from MCPE 0.11.0 BUILD 11) [Please keep in mind that if you have VIP or additional slots on your server you MUST disable this feature from config]***
- Customize Death messages ***(There a problem for the moment due to PocketMine-MP 4)***
**What is included?**
In the ZIP file you will find:<br>
*- CustomAlerts_v2.phar : CustomAlerts Plugin + API*<br>
*- CustomAlertsExample_v1.5.zip : Example Plugin source code*<br>
**Commands:**
***/customalerts*** *- CustomAlerts commands*
## Donate
Please support the development of this plugin with a small donation by clicking [:dollar: here](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=<EMAIL>&lc=US&item_name=KanekiLeChomeur&no_note=0&cn=&curency_code=EUR&bn=PP-DonationsBF:btn_donateCC_LG.gif:NonHosted).
Your small donation will help me paying web hosting, domains, buying programs (such as IDEs, debuggers, etc...) and new hardware to improve software development. Thank you :smile:
## Documentation
**Text format (Available on PocketMine console and on MCPE since v0.11.0):**
**Colors:**
Black ("&0");<br>
Dark Blue ("&1");<br>
Dark Green ("&2");<br>
Dark Aqua ("&3");<br>
Dark Red ("&4");<br>
Dark Purple ("&5");<br>
Gold ("&6");<br>
Gray ("&7");<br>
Dark Gray ("&8");<br>
Blue ("&9");<br>
Green ("&a");<br>
Aqua ("&b");<br>
Red ("&c");<br>
Light Purple ("&d");<br>
Yellow ("&e");<br>
White ("&f");<br>
**Special:**
Obfuscated ("&k");<br>
Bold ("&l");<br>
Strikethrough ("&m");<br>
Underline ("&n");<br>
Italic ("&o");<br>
Reset ("&r");<br>
**Configuration (config.yml):**
```yaml
---
#REMEMBER THAT IF YOU USE CustomAlerts EXTENSIONS, MESSAGES MAY NOT FOLLOW THE DEFAULT CONFIG
#Date/Time format (replaced in {TIME}). For format codes read http://php.net/manual/en/datetime.formats.php
datetime-format: "H:i:s"
#Server Motd message settings (available from MCPE 0.11.0 and later)
Motd:
#Motd update timeout
update-timeout: 1
#Show custom Motd
custom: true
#Motd message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&e[{TIME}] &aWelcome to your server! &n&b[{MAXPLAYERS}/{TOTALPLAYERS}]"
#Outdated Client message (available from MCPE 0.11.0 BUILD 11 and later)
OutdatedClient:
#Show custom Outdated Client message
custom: true
#Outdated Client message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&cYour MCPE client is outdated!"
#Outdated Server message (available from MCPE 0.11.0 BUILD 11 and later)
OutdatedServer:
#Show custom Outdated Server message
custom: true
#Outdated Server message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&cOops! Server outdated!"
#Whitelisted Server message (available from MCPE 0.11.0 BUILD 11 and later)
WhitelistedServer:
#Show custom Whitelisted Server message
custom: true
#Whitelisted Server message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c&oThis Server is whitelisted!"
#Full Server message (available from MCPE 0.11.0 BUILD 11 and later)
FullServer:
#Show custom Full Server message
custom: true
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&e{PLAYER}&b, The Server is full &c[{TOTALPLAYERS}/{MAXPLAYERS}]&b!\n&l&dTry to join later :)"
#First Join message settings
FirstJoin:
#Enable First Join message
enable: true
#First Join message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&2[{TIME}] &a{PLAYER}&d joined the game for the first time."
#Join message settings
Join:
#Hide Join message
hide: false
#Show custom Join message
custom: true
#Join message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&2[{TIME}] &a{PLAYER}&e joined the game."
#Quit message settings
Quit:
#Hide Quit message
hide: true
#Show custom Quit message
custom: false
#Quit message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&4[{TIME}] &c{PLAYER}&e has left the game"
#World Change message settings
WorldChange:
#Enable World Change message
enable: true
#World Change message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {ORIGIN}: Show origin world name
# - {PLAYER}: Show player name
# - {TARGET}: Show target world name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&2[{TIME}] &a{PLAYER}&e moved from &c{ORIGIN}&e to &a{TARGET}"
#Death message settings
Death:
#Hide deafult Death message
hide: false
#Show custom default Death message
custom: true
#Default Death message
#Available Tags:
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} died"
#Death by contact message
death-contact-message:
#Hide Death by contact message
hide: false
#Show custom Death by contact message
custom: true
#Death by contact message
#Available Tags:
# - {BLOCK}: The name of the block which killed the player
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&cOops! {PLAYER} was killed by {BLOCK}"
#Death by entity message (players and mobs)
kill-message:
#Hide Death by entity message
hide: false
#Show custom Death by entity message
custom: true
#Death by entity message
# - {KILLER}: The name of the killer entity
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&9{PLAYER} &ewas killed by &c{KILLER}"
#Death by projectile message
death-projectile-message:
#Hide Death by projectile message
hide: false
#Show custom Death by projectile message
custom: true
#Death by projectile message
# - {KILLER}: The name of the killer entity
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} was killed by {KILLER} by arrow"
#Death by suffocation message
death-suffocation-message:
#Hide Death by suffocation message
hide: false
#Show custom Death by suffocation message
custom: true
#Death by suffocation message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} suffocated"
#Death by fall message
death-fall-message:
#Hide Death by fall message
hide: false
#Show custom Death by fall message
custom: true
#Death by fall message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} fell from a high place"
#Death by fire message
death-fire-message:
#Hide Death by fire message
hide: false
#Show custom Death by fire message
custom: true
#Death by fire message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} went up in flames"
#Death on fire message
death-on-fire-message:
#Hide Death on fire message
hide: false
#Show custom Death on fire message
custom: true
#Death on fire message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} burned"
#Death by lava message
death-lava-message:
#Hide Death by lava message
hide: false
#Show custom Death by lava message
custom: true
#Death by lava message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} tried to swim in lava"
#Death by drowning message
death-drowning-message:
#Hide Death by drowning message
hide: false
#Show custom Death by drowning message
custom: true
#Death by drowning message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} drowned"
#Death by explosion message
death-explosion-message:
#Hide Death by explosion message
hide: false
#Show custom Death by explosion message
custom: true
#Death by explosion message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} exploded"
#Death by void message
death-void-message:
#Hide Death by void message
hide: false
#Show custom Death by void message
custom: true
#Death by void message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} fell into the void"
#Death by suicide message
death-suicide-message:
#Hide Death by suicide message
hide: false
#Show custom Death by suicide message
custom: true
#Death by suicide message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} committed suicide"
#Death magic message
death-magic-message:
#Hide Death magic message
hide: false
#Show custom Death magic message
custom: true
#Death magic message
# - {MAXPLAYERS}: Show the maximum number of players supported by the server
# - {PLAYER}: Show player name
# - {TIME}: Show current time
# - {TOTALPLAYERS}: Show the number of all online players
message: "&c{PLAYER} was killed by a spell"
```
**Commands:**
***/customalerts*** *- CustomAlerts commands* **Not usable for the moment**
<br><br>
**Permissions:**
<br>
- <dd><i><b>customalerts.*</b> - CustomAlerts permissions.</i></dd>
- <dd><i><b>customalerts.help</b> - CustomAlerts command Help permission.</i></dd>
- <dd><i><b>customalerts.info</b> - CustomAlerts command Info permission.</i></dd>
- <dd><i><b>customalerts.reload</b> - CustomAlerts command Reload permission.</i></dd>
## API
Almost all our plugins have API access to widely extend their features.
**Basic Tutorial:**
*1. Define the plugin dependency in plugin.yml (you can check if CustomAlerts is installed in different ways):*
```yaml
depend: [CustomAlerts]
```
*2. Include CustomAlerts API and CustomAlerts Events in your php code:*
```php
//PocketMine Event Listener
use pocketmine\event\Listener;
//CustomAlerts API
use CustomAlerts\CustomAlerts;
//CustomAlerts Events
use CustomAlerts\Events\CustomAlertsJoinEvent;
```
*3. Create the class:*
```php
class Example extends PluginBase implements Listener {
}
```
*4. Check if CustomAlerts API is compatible (insert this code in onEnable():void function)*
```php
if(CustomAlerts::getAPI()->getAPIVersion() == "(used API version)"){
//API compatible
//Register Events
$this->getServer()->getPluginManager()->registerEvents($this, $this);
}else{
//API not compatible
$this->getPluginLoader()->disablePlugin($this);
}
}
```
*5. Handle a CustomAlerts event (in this tutorial we will handle the CustomAlertsJoinEvent):*
```php
public function onCAJoinEvent(CustomAlertsJoinEvent $event){
$event->setMessage("Example Join message: " . $event->getPlayer()->getName());
}
```
*6. Access the API by doing:*
```php
CustomAlerts::getAPI()->api_function();
```
***A full plugin example using CustomAlerts API and CustomAlerts Events is included in the ZIP file.***
**CustomAlerts API Events:**
Each CustomAlerts event has two global functions:
###### Set Message:
```php
setMessage($message);
```
**Description:**<br>
Set event message.<br>
**Parameters:**<br>
*$message*
###### Get Message:
```php
getMessage();
```
**Description:**<br>
Get event message.<br>
**Return:**<br>
*string*
###### CustomAlertsDeathEvent:
This event is handled when a player dies.
Event functions are:
###### Get Player:
```php
Player getPlayer()
```
**Description:**<br>
Get death event player.<br>
**Return:**<br>
The death event player
###### Get Cause:
```php
EntityDamageEvent|null getCause()
```
**Description:**<br>
Get death event cause.<br>
**Return:**<br>
The death event cause
###### CustomAlertsFullServerKickEvent:
This event is handled when a player is kicked due to full server.
Event functions are:
###### Get NetworkSession:
```php
NetworkSession getOrigin()
```
**Description:**<br>
Get event NetworkSession.<br>
**Return:**<br>
The event NetworkSession (instance of pocketmine\Player)
###### CustomAlertsJoinEvent:
This event is handled when a player joins.
Event functions are:
###### Get Player:
```php
Player getPlayer()
```
**Description:**<br>
Get join event player.<br>
**Return:**<br>
The join event player (instance of pocketmine\player\Player)
###### Get default PocketMine join message:
```php
string getPocketMineJoinMessage()
```
**Description:**<br>
Get default PocketMine join message.<br>
**Return:**<br>
The default PocketMine join message
###### CustomAlertsMotdUpdateEvent:
This event is handled when the motd is updated
Event functions are:
###### Get default PocketMine Motd:
```php
string getPocketMineMotd()
```
**Description:**<br>
Get default PocketMine Motd.<br>
**Return:**<br>
The default PocketMine Motd
###### CustomAlertsOutdatedClientKickEvent:
This event is handled when a player is kicked due to outdated client.
Event functions are:
###### Get NetworkSession:
```php
NetworkSession getOrigin()
```
**Description:**<br>
Get event NetworkSession.<br>
**Return:**<br>
The event NetworkSession (instance of pocketmine\network\mcpe\NetworkSession)
###### CustomAlertsOutdatedServerKickEvent:
This event is handled when a player is kicked due to outdated server.
Event functions are:
###### Get NetworkSession:
```php
NetworkSession getOrigin()
```
**Description:**<br>
Get event player.<br>
**Return:**<br>
The event NetworkSession (instance of pocketmine\network\mcpe\NetworkSession)
###### CustomAlertsQuitEvent:
This event is handled when a player quits. It must be declared:
Event functions are:
###### Get Player:
```php
Player getPlayer()
```
**Description:**<br>
Get quit event player.<br>
**Return:**<br>
The quit event player (instance of pocketmine\player\Player)
###### Get default PocketMine quit message:
```php
string getPocketMineQuitMessage()
```
**Description:**<br>
Get default PocketMine quit message.<br>
**Return:**<br>
The default PocketMine quit message
###### CustomAlertsWhitelistKickEvent:
This event is handled when a player is kicked due to whitelisted server.
Event functions are:
###### Get Player:
```php
PlayerInfo getPlayerInfo()
```
**Description:**<br>
Get event player.<br>
**Return:**<br>
The event PlayerInfo (instance of pocketmine\player\PlayerInfo)
###### CustomAlertsWorldChangeEvent:
This event is handled when a player changes world. It must be declared:
Event functions are:
###### Get Player:
```php
Player getPlayer()
```
**Description:**<br>
Get world change event player.<br>
**Return:**<br>
The world change event player (instance of pocketmine\player\Player)
###### Get Origin World:
```php
World getFrom()
```
**Description:**<br>
Get origin world.<br>
**Return:**<br>
The origin world (instance of pocketmine\world\World)
###### Get Target World:
```php
World getTarget()
```
**Description:**<br>
Get target world.<br>
**Return:**<br>
The target world (instance of pocketmine\world\World)
**CustomAlerts API Functions:**
###### Get Version:
```php
string getVersion()
```
**Description:**<br>
Get CustomAlerts plugin version.<br>
**Return:**<br>
plugin version
###### Get API Version:
```php
string getAPIVersion()
```
**Description:**<br>
Get the CustomAlerts API version.<br>
**Return:**<br>
plugin API version
###### Check if motd message is custom:
```php
boolean isMotdCustom()
```
**Description:**<br>
Check if motd message is custom.<br>
**Return:**<br>
*bool*
###### Get default motd message:
```php
string getMotdMessage()
```
**Description:**<br>
Get motd message.<br>
**Return:**<br>
*string*
###### Check if outdated client message is custom:
```php
boolean isOutdatedClientMessageCustom()
```
**Description:**<br>
Check if outdated client message is custom.<br>
**Return:**<br>
*bool*
###### Get outdated client message:
```php
string getOutdatedClientMessage()
```
**Description:**<br>
Get outdated client message.<br>
**Parameters:**<br>
**Return:**<br>
*string*
###### Check if outdated server message is custom:
```php
boolean isOutdatedServerMessageCustom()
```
**Description:**<br>
Check if outdated server message is custom.<br>
**Return:**<br>
*bool*
###### Get outdated server message:
```php
string getOutdatedServerMessage()
```
**Description:**<br>
Get outdated server message.<br>
**Parameters:**<br>
**Return:**<br>
*string*
###### Check if whitelist message is custom:
```php
boolean isWhitelistMessageCustom()
```
**Description:**<br>
Check if whitelist message is custom.<br>
**Return:**<br>
*bool*
###### Get whitelist message:
```php
string getWhitelistMessage()
```
**Description:**<br>
Get whitelist message.<br>
**Parameters:**<br>
**Return:**<br>
*string*
###### Check if full server message is custom:
```php
boolean isFullServerMessageCustom()
```
**Description:**<br>
Check if full server message is custom.<br>
**Return:**<br>
*bool*
###### Get full server message:
```php
string getFullServerMessage()
```
**Description:**<br>
Get full server message.<br>
**Parameters:**<br>
*$player* the current player<br>
**Return:**<br>
*string*
###### Check if first join message is enabled:
```php
boolean isFirstJoinMessageEnabled()
```
**Description:**<br>
Check if first join message is enabled.<br>
**Return:**<br>
*bool*
###### Get first join message:
```php
string getFirstJoinMessage(Player $player)
```
**Description:**<br>
Get first join message.<br>
**Parameters:**<br>
*$player* the current player<br>
**Return:**<br>
*string*
###### Check if join message is custom:
```php
boolean isJoinMessageCustom()
```
**Description:**<br>
Check if join message is custom.<br>
**Return:**<br>
*bool*
###### Check if join message is hidden:
```php
boolean isJoinMessageHidden()
```
**Description:**<br>
Check if join message is hidden.<br>
**Return:**<br>
*bool*
###### Get join message:
```php
string getJoinMessage(Player $player)
```
**Description:**<br>
Get join message.<br>
**Parameters:**<br>
*$player* the current player<br>
**Return:**<br>
*string*
###### Check if quit message is custom:
```php
boolean isQuitMessageCustom()
```
**Description:**<br>
Check if quit message is custom.<br>
**Return:**<br>
*bool*
###### Check if quit message is hidden:
```php
boolean isQuitMessageHidden()
```
**Description:**<br>
Check if quit message is hidden.<br>
**Return:**<br>
*bool*
###### Get quit message:
```php
string getQuitMessage(Player $player)
```
**Description:**<br>
Get quit message.<br>
**Parameters:**<br>
*$player* the current player<br>
**Return:**<br>
*string*
###### Check if world change message is enabled:
```php
boolean isWorldChangeMessageEnabled()
```
**Description:**<br>
Check if world change message is enabled.<br>
**Return:**<br>
*bool*
###### Get world change message:
```php
string getWorldChangeMessage(Player $player, World $origin, World $target)
```
**Description:**<br>
Get default world change message.<br>
**Parameters:**<br>
*$player* the current player<br>
*$origin* the origin level<br>
*$target* the target level<br>
**Return:**<br>
*string*
###### Check if death messages are custom:
```php
boolean isDeathMessageCustom($cause = null)
```
**Description:**<br>
Check if death messages are custom.<br>
**Parameters:**<br>
*$cause* Check message by cause<br>
**Return:**<br>
*boolean*
###### Check if death messages are hidden:
```php
boolean isDeathMessageHidden($cause = null)
```
**Description:**<br>
Check if death messages are hidden.<br>
**Parameters:**<br>
*$cause* Check message by cause<br>
**Return:**<br>
*bool*
###### Get death message for the specified cause:
```php
string getDeathMessage(Player $player, $cause = null)
```
**Description:**<br>
Get default death message related to the specified cause.<br>
**Parameters:**<br>
*$player* the current player<br>
*$cause* the cause of death (instanceof EntityDamageEvent). If it's null, the function will return the default death message
**Return:**<br>
*string*
<file_sep>/CustomAlerts/src/CustomAlerts/Events/CustomAlertsWhitelistKickEvent.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts\Events;
use pocketmine\player\PlayerInfo;
class CustomAlertsWhitelistKickEvent extends CustomAlertsEvent {
public static $handlerList = null;
/** @var PlayerInfo $player */
private $player;
/**
* @param PlayerInfo $player
*/
public function __construct(?PlayerInfo $player){
$this->player = $player;
}
/**
* Get whitelist kick event player
*
* @return PlayerInfo
*/
public function getPlayerInfo() : ?PlayerInfo {
return $this->player;
}
}
<file_sep>/CustomAlerts/src/CustomAlerts/Events/CustomAlertsMotdUpdateEvent.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts\Events;
class CustomAlertsMotdUpdateEvent extends CustomAlertsEvent {
public static $handlerList = null;
public function __construct(){}
}<file_sep>/CustomAlertsExample/src/CustomAlertsExample/CustomAlertsExample.php
<?php
/*
* This is an Example Plugin with CustomAlerts API implementation
* This plugin will show an example join message using CustomAlerts API and Events
*/
namespace CustomAlertsExample;
use pocketmine\event\Listener;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\TextFormat;
//CustomAlerts API Call
use CustomAlerts\CustomAlerts;
use CustomAlerts\Events\CustomAlertsJoinEvent;
class CustomAlertsExample extends PluginBase implements Listener {
public function onEnable(){
if(CustomAlerts::getAPI()->getAPIVersion() == "2.0"){ //Checking API version. Important for API Functions Calls
$this->getLogger()->info(TextFormat::GREEN . "Example Plugin using CustomAlerts (API v2.0)");
$this->getServer()->getPluginManager()->registerEvents($this, $this);
}else{
$this->getLogger()->alert(TextFormat::RED . "Plugin disabled. Please use CustomAlerts (API v2.0)");
$this->getPluginLoader()->disablePlugin($this);
}
}
public function onCAJoinEvent(CustomAlertsJoinEvent $event){
$event->setMessage("Example Join Message: " . $event->getPlayer()->getName());
}
}<file_sep>/CustomAlerts/src/CustomAlerts/Events/CustomAlertsEvent.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts\Events;
use pocketmine\event\plugin\PluginEvent;
abstract class CustomAlertsEvent extends PluginEvent {
/** @var string */
private $message;
/**
* Get event message
*
* @return string
*/
public function getMessage(){
return $this->message;
}
/**
* Set event message
*
* @param string $message
*/
public function setMessage($message){
$this->message = $message;
}
}<file_sep>/CustomAlerts/src/CustomAlerts/EventListener.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts;
use pocketmine\event\Listener;
use pocketmine\event\player\PlayerDeathEvent;
use pocketmine\event\player\PlayerJoinEvent;
use pocketmine\event\player\PlayerPreLoginEvent;
use pocketmine\event\player\PlayerQuitEvent;
use pocketmine\event\server\DataPacketReceiveEvent;
use pocketmine\network\mcpe\protocol\LoginPacket;
use pocketmine\network\mcpe\protocol\ProtocolInfo;
use pocketmine\player\Player;
use pocketmine\event\server\QueryRegenerateEvent;
use pocketmine\Server;
use pocketmine\network\mcpe\NetworkSession;
use CustomAlerts\Events\CustomAlertsDeathEvent;
use CustomAlerts\Events\CustomAlertsFullServerKickEvent;
use CustomAlerts\Events\CustomAlertsJoinEvent;
use CustomAlerts\Events\CustomAlertsOutdatedClientKickEvent;
use CustomAlerts\Events\CustomAlertsOutdatedServerKickEvent;
use CustomAlerts\Events\CustomAlertsQuitEvent;
use CustomAlerts\Events\CustomAlertsWhitelistKickEvent;
use CustomAlerts\Events\CustomAlertsWorldChangeEvent;
use pocketmine\event\entity\EntityTeleportEvent;
class EventListener implements Listener {
private $plugin;
public function __construct(CustomAlerts $plugin){
$this->plugin = $plugin;
}
/**
* @param DataPacketReceiveEvent $event
*
* @priority HIGHEST
*/
public function onReceivePacket(DataPacketReceiveEvent $event){
$origin = $event->getOrigin();
$packet = $event->getPacket();
if($packet instanceof LoginPacket){
if($packet->protocol < ProtocolInfo::CURRENT_PROTOCOL){
//Outdated Client message
$cevent = new CustomAlertsOutdatedClientKickEvent($origin);
if($this->plugin->isOutdatedClientMessageCustom()){
$cevent->setMessage($this->plugin->getOutdatedClientMessage());
}
$cevent->call();
if($cevent->getMessage() != ""){
$origin->disconnect($cevent->getMessage());
$event->cancel();
return;
}
}else if($packet->protocol > ProtocolInfo::CURRENT_PROTOCOL){
//Outdated Server message
$cevent = new CustomAlertsOutdatedServerKickEvent($origin);
if($this->plugin->isOutdatedServerMessageCustom()){
$cevent->setMessage($this->plugin->getOutdatedServerMessage());
}
$cevent->call();
if($cevent->getMessage() != ""){
$origin->disconnect($cevent->getMessage());
$event->cancel();
return;
}
}
if(count($this->plugin->getServer()->getOnlinePlayers()) >= $this->plugin->getServer()->getMaxPlayers() || count($this->plugin->getServer()->getOnlinePlayers()) - 1 > $this->plugin->getServer()->getMaxPlayers()){
$ev = new CustomAlertsFullServerKickEvent($origin);
if($this->plugin->isFullServerMessageCustom()){
$ev->setMessage($this->plugin->getFullServerMessage());
}
$ev->call();
if($ev->getMessage() != ""){
$origin->disconnect($ev->getMessage());
return;
}
}
}
}
/**
* @param PlayerPreLoginEvent $event
*
* @priority HIGHEST
*/
public function onPlayerPreLogin(PlayerPreLoginEvent $event){
$player = $event->getPlayerInfo();
if(count($this->plugin->getServer()->getOnlinePlayers()) - 1 < $this->plugin->getServer()->getMaxPlayers()){
//Whitelist Message
if(!$this->plugin->getServer()->isWhitelisted($player->getUsername())){
$cevent = new CustomAlertsWhitelistKickEvent($player);
if($this->plugin->isWhitelistMessageCustom()){
$cevent->setMessage($this->plugin->getWhitelistMessage($player));
}
$cevent->call();
if($cevent->getMessage() != ""){
$event->setKickReason(PlayerPreLoginEvent::KICK_REASON_SERVER_WHITELISTED, $cevent->getMessage());
return;
}
}
}else{
}
}
/**
* @param PlayerJoinEvent $event
*
* @priority HIGHEST
*/
public function onPlayerJoin(PlayerJoinEvent $event){
$player = $event->getPlayer();
//Motd Update
$this->plugin->updateMotd();
//Join Message
$cevent = new CustomAlertsJoinEvent($player);
if(!$player->hasPlayedBefore() && $this->plugin->isFirstJoinMessageEnabled()){
$cevent->setMessage($this->plugin->getFirstJoinMessage($player));
}else if($this->plugin->isJoinMessageHidden()){
$cevent->setMessage("");
}else if($this->plugin->isJoinMessageCustom()){
$cevent->setMessage($this->plugin->getJoinMessage($player));
}else{
$cevent->setMessage($event->getJoinMessage());
}
$cevent->call();
$event->setJoinMessage($cevent->getMessage());
}
/**
* @param PlayerQuitEvent $event
*
* @priority HIGHEST
*/
public function onPlayerQuit(PlayerQuitEvent $event){
$player = $event->getPlayer();
//Motd Update
$this->plugin->updateMotd();
//Quit Message
$cevent = new CustomAlertsQuitEvent($player);
if($this->plugin->isQuitMessageHidden()){
$cevent->setMessage("");
}else if($this->plugin->isQuitMessageCustom()){
$cevent->setMessage($this->plugin->getQuitMessage($player));
}else{
$cevent->setMessage($event->getQuitMessage());
}
$cevent->call();
$event->setQuitMessage($cevent->getMessage());
}
/**
* @param EntityTeleportEvent $event
*
* @priority HIGHEST
*/
public function onWorldChange(EntityTeleportEvent $event){
$from = $event->getFrom()->getWorld();
$to = $event->getTo()->getWorld();
$player = $event->getEntity();
if($from->getDisplayName() !== $to->getDisplayName()){
$cevent = new CustomAlertsWorldChangeEvent($player, $from, $to);
if($this->plugin->isWorldChangeMessageEnabled()){
$cevent->setMessage($this->plugin->getWorldChangeMessage($player, $from, $to));
}else{
$cevent->setMessage("");
}
$cevent->call();
if($cevent->getMessage() != ""){
Server::getInstance()->broadcastMessage($cevent->getMessage());
}
}
}
/**
* @param PlayerDeathEvent $event
*
* @priority HIGHEST
*/
public function onPlayerDeath(PlayerDeathEvent $event){
$player = $event->getEntity();
if($player instanceof Player){
$cause = $player->getLastDamageCause();
$cevent = new CustomAlertsDeathEvent($player, $cause);
if($this->plugin->isDeathMessageHidden($cause)){
$cevent->setMessage("");
}else if($this->plugin->isDeathMessageCustom($cause)){
$cevent->setMessage($this->plugin->getDeathMessage($player, $cause));
}else{
$cevent->setMessage($event->getDeathMessage());
}
$cevent->call();
$event->setDeathMessage($cevent->getMessage());
}
}
}
<file_sep>/CustomAlerts/src/CustomAlerts/Events/CustomAlertsWorldChangeEvent.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts\Events;
use pocketmine\player\Player;
use pocketmine\world\World;
class CustomAlertsWorldChangeEvent extends CustomAlertsEvent {
public static $handlerList = null;
/** @var Player $player */
private $player;
/** @var World $origin */
private $origin;
/** @var World $target */
private $target;
/**
* @param Player $player
* @param World $origin
* @param World $target
*/
public function __construct(Player $player, World $origin, World $target){
$this->player = $player;
$this->origin = $origin;
$this->target = $target;
}
/**
* Get world change event player
*
* @return Player
*/
public function getPlayer() : Player {
return $this->player;
}
/**
* Get origin level
*
* @return World
*/
public function getOrigin() : World {
return $this->origin;
}
/**
* Get target level
*
* @return World
*/
public function getTarget() : World {
return $this->target;
}
}
<file_sep>/CustomAlerts/src/CustomAlerts/CustomAlerts.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts;
use pocketmine\player\Player;
use pocketmine\entity\Living;
use pocketmine\event\entity\EntityDamageByBlockEvent;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\level\Level;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\TextFormat;
use CustomAlerts\Commands\Commands;
use CustomAlerts\Events\CustomAlertsMotdUpdateEvent;
use pocketmine\command\PluginCommand;
use pocketmine\entity\projectile\Projectile;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\event\entity\ProjectileHitEntityEvent;
use pocketmine\player\Player as PlayerPlayer;
use pocketmine\player\PlayerInfo;
use pocketmine\world\World;
class CustomAlerts extends PluginBase {
/** @var string */
const PREFIX = "&b[&aCustom&cAlerts&b] ";
/** @var string */
const API_VERSION = "2.0";
private $cfg;
/** @var CustomAlerts $instance */
private static $instance = null;
public function onLoad():void{
if(!self::$instance instanceof CustomAlerts){
self::$instance = $this;
}
}
public function onEnable():void{
@mkdir($this->getDataFolder());
$this->saveDefaultConfig();
$this->cfg = $this->getConfig()->getAll();
$this->getServer()->getCommandMap()->register("customalerts", new Commands($this));
$this->getServer()->getPluginManager()->registerEvents(new EventListener($this), $this);
$this->getScheduler()->scheduleRepeatingTask(new MotdTask($this), 20);
}
/**
* Replace variables inside a string
*
* @param string $str
* @param array $vars
*
* @return string
*/
public function replaceVars($str, array $vars){
foreach($vars as $key => $value){
$str = str_replace("{" . $key . "}", $value, $str);
}
return $str;
}
//API Functions
/**
* Get CustomAlerts API
*
* @return CustomAlerts
*/
public static function getAPI(){
return self::$instance;
}
/**
* Get CustomAlerts version
*
* @return string
*/
public function getVersion(){
return $this->getVersion();
}
/**
* Get CustomAlerts API version
*
* @return string
*/
public function getAPIVersion(){
return self::API_VERSION;
}
/**
* Check if motd is custom
*
* @return bool
*/
public function isMotdCustom() : bool {
return $this->cfg["Motd"]["custom"];
}
/**
* Get motd message
*
* @return string
*/
public function getMotdMessage(){
return TextFormat::colorize($this->replaceVars($this->cfg["Motd"]["message"], array(
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
public function updateMotd(){
$cevent = new CustomAlertsMotdUpdateEvent();
if($this->isMotdCustom()){
$cevent->setMessage($this->getMotdMessage());
}else{
$cevent->setMessage($this->getServer()->getMotd());
}
$cevent->call();
$this->getServer()->getNetwork()->setName($cevent->getMessage());
}
/**
* Check if outdated client message is custom
*
* @return bool
*/
public function isOutdatedClientMessageCustom() : bool {
return $this->cfg["OutdatedClient"]["custom"];
}
/**
* Get outdated client message
*
* @return string
*/
public function getOutdatedClientMessage(){
return TextFormat::colorize($this->replaceVars($this->cfg["OutdatedClient"]["message"], array(
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if outdated server message is custom
*
* @return bool
*/
public function isOutdatedServerMessageCustom() : bool {
return $this->cfg["OutdatedServer"]["custom"];
}
/**
* Get outdated server message
*
*
* @return string
*/
public function getOutdatedServerMessage(){
return TextFormat::colorize($this->replaceVars($this->cfg["OutdatedServer"]["message"], array(
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if whitelist message is custom
*
* @return bool
*/
public function isWhitelistMessageCustom() : bool {
return $this->cfg["WhitelistedServer"]["custom"];
}
/**
* Get whitelist message
*
* @return string
*/
public function getWhitelistMessage(){
return TextFormat::colorize($this->replaceVars($this->cfg["WhitelistedServer"]["message"], array(
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if full server message is custom
*
* @return bool
*/
public function isFullServerMessageCustom() : bool {
$cfg = $this->getConfig()->getAll();
return $cfg["FullServer"]["custom"];
}
/**
* Get full server message
*
*
* @return string
*/
public function getFullServerMessage(){
return TextFormat::colorize($this->replaceVars($this->cfg["FullServer"]["message"], array(
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if first join message is enabled
*
* @return bool
*/
public function isFirstJoinMessageEnabled() : bool {
return $this->cfg["FirstJoin"]["enable"];
}
/**
* Get first join message
*
* @param Player $player
*
* @return string
*/
public function getFirstJoinMessage(Player $player){
return TextFormat::colorize($this->replaceVars($this->cfg["FirstJoin"]["message"], array(
"PLAYER" => $player->getName(),
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if join message is custom
*
* @return bool
*/
public function isJoinMessageCustom() : bool {
return $this->cfg["Join"]["custom"];
}
/**
* Check if join message is hidden
*
* @return bool
*/
public function isJoinMessageHidden() : bool {
return $this->cfg["Join"]["hide"];
}
/**
* Get join message
*
* @param Player $player
*
* @return string
*/
public function getJoinMessage(Player $player){
return TextFormat::colorize($this->replaceVars($this->cfg["Join"]["message"], array(
"PLAYER" => $player->getName(),
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if quit message is custom
*
* @return bool
*/
public function isQuitMessageCustom(){
return $this->cfg["Quit"]["custom"];
}
/**
* Check if quit message is hidden
*
* @return bool
*/
public function isQuitMessageHidden(){
return $this->cfg["Quit"]["hide"];
}
/**
* Get default quit message
*
* @param Player $player
*
* @return string
*/
public function getQuitMessage(Player $player){
return TextFormat::colorize($this->replaceVars($this->cfg["Quit"]["message"], array(
"PLAYER" => $player->getName(),
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if world change message is enabled
*
* @return bool
*/
public function isWorldChangeMessageEnabled(){
return $this->cfg["WorldChange"]["enable"];
}
/**
* Get world change message
*
* @param Player $player
* @param World $origin
* @param World $target
*
* @return string
*/
public function getWorldChangeMessage(Player $player, World $origin, World $target){
return TextFormat::colorize($this->replaceVars($this->cfg["WorldChange"]["message"], array(
"ORIGIN" => $origin->getDisplayName(),
"TARGET" => $target->getDisplayName(),
"PLAYER" => $player->getName(),
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]))));
}
/**
* Check if death messages are custom
*
*
* @return bool
*/
public function isDeathMessageCustom(?EntityDamageEvent $cause = null){
if(!$cause){
return $this->cfg["Death"]["custom"];
}
switch($cause->getCause()){
case EntityDamageEvent::CAUSE_CONTACT:
return $this->cfg["Death"]["death-contact-message"]["custom"];
case EntityDamageEvent::CAUSE_ENTITY_ATTACK:
return $this->cfg["Death"]["kill-message"]["custom"];
case EntityDamageEvent::CAUSE_PROJECTILE:
return $this->cfg["Death"]["death-projectile-message"]["custom"];
case EntityDamageEvent::CAUSE_SUFFOCATION:
return $this->cfg["Death"]["death-suffocation-message"]["custom"];
case EntityDamageEvent::CAUSE_FALL:
return $this->cfg["Death"]["death-fall-message"]["custom"];
case EntityDamageEvent::CAUSE_FIRE:
return $this->cfg["Death"]["death-fire-message"]["custom"];
case EntityDamageEvent::CAUSE_FIRE_TICK:
return $this->cfg["Death"]["death-on-fire-message"]["custom"];
case EntityDamageEvent::CAUSE_LAVA:
return $this->cfg["Death"]["death-lava-message"]["custom"];
case EntityDamageEvent::CAUSE_DROWNING:
return $this->cfg["Death"]["death-drowning-message"]["custom"];
case EntityDamageEvent::CAUSE_ENTITY_EXPLOSION:
case EntityDamageEvent::CAUSE_BLOCK_EXPLOSION:
return $this->cfg["Death"]["death-explosion-message"]["custom"];
case EntityDamageEvent::CAUSE_VOID:
return $this->cfg["Death"]["death-void-message"]["custom"];
case EntityDamageEvent::CAUSE_SUICIDE:
return $this->cfg["Death"]["death-suicide-message"]["custom"];
case EntityDamageEvent::CAUSE_MAGIC:
return $this->cfg["Death"]["death-magic-message"]["custom"];
default:
return $this->cfg["Death"]["custom"];
}
}
/**
* Check if death messages are hidden
*
* @param EntityDamageEvent $cause
*
* @return bool
*/
public function isDeathMessageHidden(EntityDamageEvent $cause = null){
if(!$cause){
return $this->cfg["Death"]["hide"];
}
switch($cause->getCause()){
case EntityDamageEvent::CAUSE_CONTACT:
return $this->cfg["Death"]["death-contact-message"]["hide"];
case EntityDamageEvent::CAUSE_ENTITY_ATTACK:
return $this->cfg["Death"]["kill-message"]["hide"];
case EntityDamageEvent::CAUSE_PROJECTILE:
return $this->cfg["Death"]["death-projectile-message"]["hide"];
case EntityDamageEvent::CAUSE_SUFFOCATION:
return $this->cfg["Death"]["death-suffocation-message"]["hide"];
case EntityDamageEvent::CAUSE_FALL:
return $this->cfg["Death"]["death-fall-message"]["hide"];
case EntityDamageEvent::CAUSE_FIRE:
return $this->cfg["Death"]["death-fire-message"]["hide"];
case EntityDamageEvent::CAUSE_FIRE_TICK:
return $this->cfg["Death"]["death-on-fire-message"]["hide"];
case EntityDamageEvent::CAUSE_LAVA:
return $this->cfg["Death"]["death-lava-message"]["hide"];
case EntityDamageEvent::CAUSE_DROWNING:
return $this->cfg["Death"]["death-drowning-message"]["hide"];
case EntityDamageEvent::CAUSE_ENTITY_EXPLOSION:
case EntityDamageEvent::CAUSE_BLOCK_EXPLOSION:
return $this->cfg["Death"]["death-explosion-message"]["hide"];
case EntityDamageEvent::CAUSE_VOID:
return $this->cfg["Death"]["death-void-message"]["hide"];
case EntityDamageEvent::CAUSE_SUICIDE:
return $this->cfg["Death"]["death-suicide-message"]["hide"];
case EntityDamageEvent::CAUSE_MAGIC:
return $this->cfg["Death"]["death-magic-message"]["hide"];
default:
return $this->cfg["Death"]["hide"];
}
}
/**
* Get death message related to the specified cause
*
* @param Player $player
* @param EntityDamageEvent $cause
*
* @return string
*/
public function getDeathMessage(Player $player, EntityDamageEvent $cause = null){
$array = array(
"PLAYER" => $player->getName(),
"MAXPLAYERS" => $this->getServer()->getMaxPlayers(),
"TOTALPLAYERS" => count($this->getServer()->getOnlinePlayers()),
"TIME" => date($this->cfg["datetime-format"]));
if(!$cause){
$message = $this->cfg["Death"]["message"];
}else{
switch($cause->getCause()){
case EntityDamageEvent::CAUSE_CONTACT:
$message = $this->cfg["Death"]["death-contact-message"]["message"];
if($cause instanceof EntityDamageByBlockEvent){
$array["BLOCK"] = $cause->getDamager()->getName();
break;
}
$array["BLOCK"] = "Unknown";
break;
case EntityDamageEvent::CAUSE_ENTITY_ATTACK:
$message = $this->cfg["Death"]["kill-message"]["message"];
if($cause instanceof EntityDamageByEntityEvent){
$killer = $cause->getDamager();
if($killer instanceof Living){
$array["KILLER"] = $killer->getName();
break;
}
}
$array["KILLER"] = "Unknown";
break;
case EntityDamageEvent::CAUSE_PROJECTILE:
$message = $this->cfg["Death"]["death-projectile-message"]["message"];
if($cause instanceof ProjectileHitEntityEvent){
$projectile = $cause->getEntity();
if($projectile instanceof Projectile){
$killer = $projectile->getOwningEntity();
if($killer instanceof Living){
$array["KILLER"] = $killer->getName();
break;
}
}
}
$array["KILLER"] = "Unknown";
break;
case EntityDamageEvent::CAUSE_SUFFOCATION:
$message = $this->cfg["Death"]["death-suffocation-message"]["message"];
break;
case EntityDamageEvent::CAUSE_FALL:
$message = $this->cfg["Death"]["death-fall-message"]["message"];
break;
case EntityDamageEvent::CAUSE_FIRE:
$message = $this->cfg["Death"]["death-fire-message"]["message"];
break;
case EntityDamageEvent::CAUSE_FIRE_TICK:
$message = $this->cfg["Death"]["death-on-fire-message"]["message"];
break;
case EntityDamageEvent::CAUSE_LAVA:
$message = $this->cfg["Death"]["death-lava-message"]["message"];
break;
case EntityDamageEvent::CAUSE_DROWNING:
$message = $this->cfg["Death"]["death-drowning-message"]["message"];
break;
case EntityDamageEvent::CAUSE_ENTITY_EXPLOSION:
case EntityDamageEvent::CAUSE_BLOCK_EXPLOSION:
$message = $this->cfg["Death"]["death-explosion-message"]["message"];
break;
case EntityDamageEvent::CAUSE_VOID:
$message = $this->cfg["Death"]["death-void-message"]["message"];
break;
case EntityDamageEvent::CAUSE_SUICIDE:
$message = $this->cfg["Death"]["death-suicide-message"]["message"];
break;
case EntityDamageEvent::CAUSE_MAGIC:
$message = $this->cfg["Death"]["death-magic-message"]["message"];
break;
default:
$message = $this->cfg["Death"]["message"];
break;
}
}
return TextFormat::colorize($this->replaceVars($message, $array));
}
}
<file_sep>/CustomAlerts/src/CustomAlerts/MotdTask.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts;
use pocketmine\scheduler\Task;
class MotdTask extends Task {
/** @var CustomAlerts */
private $plugin;
public function __construct(CustomAlerts $plugin){
$this->plugin = $plugin;
}
public function onRun() : void{
CustomAlerts::getAPI()->updateMotd();
}
public function getPlugin(){
return $this->plugin;
}
}
<file_sep>/CustomAlerts/src/CustomAlerts/Events/CustomAlertsFullServerKickEvent.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts\Events;
use pocketmine\network\mcpe\NetworkSession;
class CustomAlertsFullServerKickEvent extends CustomAlertsEvent{
public static $handlerList = null;
/** @var NetworkSession $origin */
private $origin;
/**
* @param NetworkSession $origin
*/
public function __construct(NetworkSession $origin){
$this->origin = $origin;
}
/**
* Get full server kick event player
*
* @return NetworkSession
*/
public function getPlayerInfo() : NetworkSession {
return $this->origin;
}
}
<file_sep>/CustomAlerts/src/CustomAlerts/Events/CustomAlertsOutdatedClientKickEvent.php
<?php
/*
* CustomAlerts v2.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2014-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/CustomAlerts/blob/master/LICENSE)
*/
namespace CustomAlerts\Events;
use pocketmine\network\mcpe\NetworkSession;
use pocketmine\player\Player;
class CustomAlertsOutdatedClientKickEvent extends CustomAlertsEvent {
public static $handlerList = null;
/** @var NetworkSession $origin */
private $origin;
/**
* @param NetworkSession $origin
*/
public function __construct(?NetworkSession $origin){
$this->origin = $origin;
}
/**
* Get outdated client kick event player
*
* @return NetworkSession
*/
public function getOrigin() : ?NetworkSession {
return $this->origin;
}
}
| 3ffcc60361c23bd88fead7a709f3ac56657592a5 | [
"Markdown",
"PHP"
] | 12 | PHP | EvolSoft/CustomAlerts | 86bbdb269410620c8fa835b8b419b2e31a84ae10 | 0c860897051a489fb3bfdb6228c7343348f81472 | |
refs/heads/master | <file_sep>#include <iostream>
#include <cassert>
#include <vector>
using namespace std;
int fibonacci_naive(int n) {
if (n <= 1)
return n;
return fibonacci_naive(n - 1) + fibonacci_naive(n - 2);
}
long long fibonacci_fast(int n) {
vector<long long> f;
f.push_back(0);
f.push_back(1);
for (int i = 2; i <= n; i++){
f.push_back(f[i-1] + f[i-2]);
}
return f[n];
}
void test_solution() {
assert(fibonacci_fast(3) == 2);
assert(fibonacci_fast(10) == 55);
for (int n = 0; n < 20; ++n)
assert(fibonacci_fast(n) == fibonacci_naive(n));
}
int main() {
int n;
cin >> n;
// cout << fibonacci_naive(n) << '\n';
// test_solution();
if (n <= 1){
cout << n;
}
else
{
cout << fibonacci_fast(n) << '\n';
}
return 0;
}
<file_sep># Quiz
### Que 1
How are Managed Services useful?
### Answer
Managed Services may be an alternative to creating and managing infrastructure solutions.
### Que 2
Which of the following is a feature of Cloud Dataproc?
### Answer
It typically takes less than 90 seconds to start a cluster.
<file_sep># Week 2 Quiz
### Question
Curiosity is an analytical skill that involves which of the following?
### Answer
Seeking out new challenges and experiences
### Question
Understanding context is an analytical skill best described by which of the following? Select all that apply.
### Answer
Gathering additional information about data to understand the broader picture
Identifying the motivation behind the collection of a dataset
Adding descriptive headers to columns of data in a spreadsheet
### Question
A data analyst works for an appliance manufacturer. Last year, the company’s profits were down. Lower profits can be a result of fewer people buying appliances, higher costs to make appliances, or a combination of both. The analyst recognizes that those are big issues to solve, so they break down the problems into smaller pieces to analyze them in an orderly way. Which analytical skill are they using?
### Answer
A technical mindset
### Question
Which analytical skill involves managing the people, processes, and tools used in data analysis?
### Answer
Data strategy
### Question
Correlation is the aspect of analytical thinking that involves figuring out the specifics that help you execute a plan.
### Answer
False
### Question
What method involves asking numerous questions in order to get to the root cause of a problem?
### Answer
The five whys
### Question
Gap analysis is a method for examining and evaluating how a process works currently in order to get where you want to be in the future.
### Answer
True
### Question
A company is receiving negative comments on social media about their products. To solve this problem, a data analyst uses each of their five analytical skills: curiosity, understanding context, having a technical mindset, data design, and data strategy. This makes it possible for the analyst to use facts to guide business strategy and figure out how to improve customer satisfaction. What is this an example of?
### Answer
Data-driven decision-making
### Question
Adding descriptive headers to columns of data in a spreadsheet is an example of which analytical skill?
### Answer
Understanding context
### Question
Fill in the blank: **\_** involves the ability to break things down into smaller steps or pieces and work with them in an orderly and logical way.
### Answer
A technical mindset
### Question
Data design is how you organize information; data strategy is the management of the people, processes, and tools used in data analysis.
### Answer
True
### Question
The manager at a music shop notices that more trombones are repaired on the days when Alex and Jasmine work the same shift. After some investigation, the manager discovers that Alex is excellent at fixing slides, and Jasmine is great at shaping mouthpieces. Working together, Alex and Jasmine repair trombones faster. The manager is happy to have discovered this relationship and decides to always schedule Alex and Jasmine for the same shifts. In this scenario, the manager used which quality of analytical thinking?
### Answer
Correlation
### Question
Data analysts ask, “Why?” five times in order to get to the root cause of a problem.
### Answer
True
### Question
An airport wants to make its luggage-handling process faster and simpler for travelers. A data analyst examines and evaluates how the process works currently in order to achieve the goal of a more efficient process. What methodology do they use?
### Answer
Gap analysis
### Question
Fill in the blank: Data analysts use the five analytical skills of curiosity, understanding context, having a technical mindset, data design, and data strategy to make **\_** decisions.
### Answer
data-driven
### Question
Having a technical mindset is an analytical skill involving what?
### Answer
Breaking things down into smaller steps or pieces
### Question
Fill in the blank: Data strategy involves **\_** the people, processes, and tools used in data analysis.
### Answer
managing
### Question
Fill in the blank: Being able to identify a relationship between two or more pieces of data describes **\_**.
### Answer
correlation
### Question
A junior data analyst is seeking out new experiences in order to gain knowledge. They watch videos and read articles about data analytics. They ask experts questions. Which analytical skill are they using?
### Answer
Curiosity
### Question
Data-driven decision-making involves the five analytical skills: curiosity, understanding context, having a technical mindset, data design, and data strategy. Each plays a role in data-driven decision-making.
### Answer
True
<file_sep># Quiz
### Que 1
Why might a GCP customer choose to use Cloud Source Repositories?
### Answer
They don't want to host their own git instance, and they want to integrate with IAM permissions.
### Que 2
Why might a GCP customer choose to use Cloud Functions?
### Answer
Their application contains event-driven code that they don't want to have to provision compute resources for.
### Que 3
Why might a GCP customer choose to use Deployment Manager?
### Answer
Deployment Manager is an infrastructure management system for GCP resources.
### Que 4
You want to define alerts on your GCP resources, such as when health checks fail. Which is the best GCP product to use?
### Answer
Stackdriver Monitoring
### Que 5
Which statements are true about Stackdriver Logging? Choose all that are true (2 statements)
### Answer
Stackdriver Logging lets you define metrics based on your logs.
Stackdriver Logging lets you view logs from your applications, and filter and search on them.
<file_sep>## Quiz
### Question 1
Assume that we have typed the following in the Python shell:
```
>>> x = ‘chemistry’
>>> x[3]
```
### Answer
m
### Question 2
Assume that we have typed the following in the Python shell:
```
>>> x = ‘chemistry’
>>> ‘i’ in x
```
### Answer
True
### Question 3
Assume that we have typed the following in the Python shell:
```
>>> x = ‘3’
>>> y = ‘4’
>>> x + y * 2
```
### Answer
344
### Question 4
Assume that we have typed the following in the Python shell:
```
>>> x = [1, 2]
>>> y = [3, 4]
>>> x.append(y)
>>> x
```
What will be printed on the screen as a result?
### Answer
[1, 2, [3, 4]]
### Question 5
Assume that the following Python program is executed:

What will be printed on the screen as a result?
### Answer
2
### Question 6
Assume that the following Python program is executed:

What will be printed on the screen as a result?
### Answer
[4, 5, 5, 6]
### Question 7
Correct indentation is essential for your Python program to work.
### Answer
True
### Question 8
Raspberry Pi can execute Python 3 code, but not Python 2.
### Answer
False
<file_sep># Week 2 Quiz
### Question 1
Suppose I define the following function in R
```
cube <- function(x, n) {
x^3
}
```
What is the result of running
`cube(3)`
### Answer
The number 27 is returned
### Question 2
The following code will produce a warning in R.
```
x <- 1:10
if(x > 5) {
x <- 0
}
```
Why?
### Answer
'x' is a vector of length 10 and 'if' can only test a single logical statement.
### Question 3
Consider the following function
```
f <- function(x) {
g <- function(y) {
y + z
}
z <- 4
x + g(x)
}
```
If I then run in R
```
z <- 10
f(3)
```
### Answer
10
### Question 4
Consider the following expression:
```
x <- 5
y <- if(x < 3) {
NA
} else {
10
}
```
What is the value of 'y' after evaluating this expression?
### Answer
10
### Question 5
Consider the following R function
```
h <- function(x, y = NULL, d = 3L) {
z <- cbind(x, d)
if(!is.null(y))
z <- z + y
else
z <- z + f
g <- x + y / z
if(d == 3L)
return(g)
g <- g + 10
g
}
```
Which symbol in the above function is a free variable?
### Answer
f
### Question 6
What is an environment in R?
### Answer
a collection of symbol/value pairs
### Question 7
The R language uses what type of scoping rule for resolving free variables?
### Answer
Lexical scoping
### Question 8
How are free variables in R functions resolved?
### Answer
The values of free variables are searched for in the environment in which the function was defined
### Question 9
What is one of the consequences of the scoping rules used in R?
### Answer
All objects must be stored in memory
### Question 10
In R, what is the parent frame?
### Answer
It is the environment in which a function was called
<file_sep>## Python 3 Programming Specialization offered by University of Michigan
### This module contains the solutions from the courses that I have completed in the above mentioned Specialization.<file_sep># IMPORTANT
Please perform the operations provided on the Qwiklabs page. Those operations are performed directly on the terminal in python interpreter and are essential for the grading rubric to mark you. One file has been added i.e. user_emails.csv which is compulsory to create in your linux instance.
<file_sep>## Replace
firstname,surname,,job title
## with
firstname,surname,company,job title
## in data.csv
<file_sep>## Assignment
### Project Title
Smart TV's and Smart Watches
### Identify two embedded systems that are sold on the market today and analyze their interfaces.
Smart TV's - Large Screen, Better Clarity
Smart Watches - Small Screen, Better Portability
### Describe all inputs to each system and outputs from each system.
1. Smart TV
Inputs: Touch, Voice, Remote, Smartphone, Computer, Wi-Fi, power
Outputs: Video, Audio, Apps, Games, Chats, Audio and Video calls
2. Smart Watches
Inputs: Touch, Bluetooth, Voice, charge, Smartphone
Outputs: Audio, Video, Info on screen, Health data like heartrate, Distance travelled, Audio and Video Calls
### Classify the inputs and outputs based on their mode of interaction:
### -Visual - describing data carried by visible light
### -Audio - describing data carried by sound
### -Tactile - describing data carried by touch
### -Electronic - describing data encoded in electrical signals
Visual - Info or data provided, Video
Audio - Calls or movie or a video's sound
Tactile - Touch
Electronic - Charge and Power
<file_sep>## This module contains the quiz answers to the course 'Crash course on Python' provided by Google, part of IT Automation Specialization.
### There is no week 5 folder because there's no quiz in week 5<file_sep>#include <bits/stdc++.h>
#include <vector>
using namespace std;
int fun1(int destination, int d_tank, vector<int> stops)
{
int position = 0;
int count = 0;
while (position < destination)
{
position += d_tank;
if (position > destination)
{
return count;
}
vector<int> temp;
for (int i = 0; i < stops.size(); i++)
{
if (stops[i] <= position)
{
temp.push_back(stops[i]);
}
}
if (temp.size() != stops.size() && stops[temp.size()] - temp[temp.size() - 1] > d_tank)
{
return -1;
}
position = temp[temp.size() - 1];
count += 1;
}
return count;
}
int main()
{
int destination, d_tank, num, temp;
cin >> destination;
cin >> d_tank;
cin >> num;
vector<int> stops;
for (int i = 0; i < num; i++)
{
cin >> temp;
stops.push_back(temp);
}
cout << fun1(destination, d_tank, stops);
return 0;
}<file_sep># Quiz
### Que 1
What data storage service might you select if you just needed to migrate a standard relational database running on a single machine in a datacenter to the cloud?
### Answer
Cloud SQL
### Que 2
Which GCP data storage service offers ACID transactions and can scale globally?
### Answer
Cloud Spanner
### Que 3
Which data storage service provides data warehouse services for storing data but also offers an interactive SQL interface for querying the data?
### Answer
BigQuery
<file_sep># noinspection PyShadowingNames
def signatures(lst, n):
index = 0
coordinates = []
while index < n:
curr = lst[index]
while index < n - 1 and curr[1] >= lst[index + 1][0]:
index += 1
coordinates.append(curr[1])
index += 1
print(len(coordinates))
return ' '.join([str(i) for i in coordinates])
if __name__ == "__main__":
num = int(input())
coordinates = []
for temp in range(num):
x, y = input().split()
coordinates.append((x, y))
coordinates.sort(key=lambda x: x[1])
print(signatures(coordinates, num))
<file_sep>def min_stops(destination, d_tank, stops):
position = 0
count = 0
while position < destination:
position += d_tank
if position > destination:
return count
temp = [i for i in stops if i <= position]
if len(temp) != len(stops) and stops[len(temp)] - temp[-1] > d_tank:
return -1
position = temp[-1]
count += 1
return count
if __name__ == "__main__":
destination = int(input())
d_tank = int(input())
num = int(input())
stops = [int(i) for i in input().split()]
print(min_stops(destination, d_tank, stops))
<file_sep>#! /usr/bin/env python3
import os
import requests
dir = "/data/feedback/"
for file in os.listdir("/data/feedback/"):
format = ["title", "name", "date", "feedback"]
content = {}
with open('{}/{}'.format(dir, file), 'r') as file:
counter = 0
for line in file:
line = line.replace("\n", "")
content[format[counter]] = line.strip('\n')
counter += 1
response = requests.post("http://172.16.58.3/feedback/", json=content)
if not response.ok:
raise Exception("POST failed! | Status code: {} | File: {}".format(
response.status_code, file))
print("Feedback Uploaded")
<file_sep># Week 1 Quiz
### Question 1
Select the option that correctly completes the sentence:
Training a model using labeled data and using this model to predict
the labels for new data is known as ____________.
### Answer
Supervised Learning
### Question 2
Select the option that correctly completes the sentence:
Modeling the features of an unlabeled dataset to find hidden
structure is known as ____________.
### Answer
Unsupervised Learning
### Question 3
Select the option that correctly completes the sentence:
Training a model using categorically labelled data to predict labels
for new data is known as __________.
### Answer
Classification
### Question 4
Select the option that correctly completes the sentence:
Training a model using labelled data where the labels are
continuous quantities to predict labels for new data is known as
__________.
### Answer
Regression
### Question 5
Using the data for classes 0, 1, and 2 plotted below, what class
would a KNeighborsClassifier classify the new point as for k = 1 and
k = 3?

### Answer
k = 1: Class 1
k = 3: Class 2
### Question 6
Which of the following is true for the nearest neighbor classifier
(Select all that apply):
### Answer
Memorizes the entire training set
### Question 7
Why is it important to examine your dataset as a first step in
applying machine learning? (Select all that apply):
### Answer
See what type of cleaning or preprocessing still needs to be done
You might notice missing data
Gain insight on what machine learning model might be
appropriate, if any
Get a sense for how difficult the problem might be
### Question 8
The key purpose of splitting the dataset into training and test sets
is:
### Answer
To estimate how well the learned model will generalize
to new data
### Question 9
The purpose of setting the random_state parameter in
train_test_split is: (Select all that apply)
### Answer
To make experiments easily reproducible by always
using the same partitioning of the data
### Question 10
Given a dataset with 10,000 observations and 50 features plus one
label, what would be the dimensions of X_train, y_train, X_test, and
y_test? Assume a train/test split of 75%/25%.
### Answer
X_train: (7500, 50)
y_train: (7500, )
X_test: (2500, 50)
y_test: (2500, )<file_sep># Week 2 Assignment Quiz
## The functions that will be needed to complete this quiz are in the folder Programming Assignment
### Question 1
What value is returned by the following call to pollutantmean()? You should round your output to 3 digits.
```
pollutantmean("specdata", "sulfate", 1:10)
```
### Answer
4.064
### Question 2
What value is returned by the following call to pollutantmean()? You should round your output to 3 digits.
```
pollutantmean("specdata", "nitrate", 70:72)
```
### Answer
1.706
### Question 3
What value is returned by the following call to pollutantmean()? You should round your output to 3 digits.
```
pollutantmean("specdata", "sulfate", 34)
```
### Answer
1.477
### Question 4
What value is returned by the following call to pollutantmean()? You should round your output to 3 digits.
```
pollutantmean("specdata", "nitrate")
```
### Answer
1.703
## Question 5
What value is printed at end of the following code?
```
cc <- complete("specdata", c(6, 10, 20, 34, 100, 200, 310))
print(cc$nobs)
```
### Answer
228 148 124 165 104 460 232
### Question 6
What value is printed at end of the following code?
```
cc <- complete("specdata", 54)
print(cc$nobs)
```
### Answer
219
### Question 7
What value is printed at end of the following code?
```
RNGversion("3.5.1")
set.seed(42)
cc <- complete("specdata", 332:1)
use <- sample(332, 10)
print(cc[use, "nobs"])
```
### Answer
711 135 74 445 178 73 49 0 687 237
### Question 8
What value is printed at end of the following code?
```
cr <- corr("specdata")
cr <- sort(cr)
RNGversion("3.5.1")
set.seed(868)
out <- round(cr[sample(length(cr), 5)], 4)
print(out)
```
### Answer
0.2688 0.1127 -0.0085 0.4586 0.0447
### Question 9
What value is printed at end of the following code?
```
cr <- corr("specdata", 129)
cr <- sort(cr)
n <- length(cr)
RNGversion("3.5.1")
set.seed(197)
out <- c(n, round(cr[sample(n, 5)], 4))
print(out)
```
### Answer
243.0000 0.2540 0.0504 -0.1462 -0.1680 0.5969
### Question 10
Question 10
What value is printed at end of the following code?
```
cr <- corr("specdata", 2000)
n <- length(cr)
cr <- corr("specdata", 1000)
cr <- sort(cr)
print(c(n, round(cr, 4)))
```
### Answer
0.0000 -0.0190 0.0419 0.1901<file_sep>### Question
Write about the design of a system that you might build for your home which uses an Arduino with a wifi shield. The system must use the wifi connection for a useful purpose in the system. The Arduino should be wired to sensors and/or actuators which help it to perform some useful task in your home.
Be sure to clearly describe the need for the wifi connection in your system.
### Answer
I would use Arduino with a Wi-Fi shield to create a Network Attached Storage by connecting the Arduino with a SSD, that can act as the personal cloud storage for my family. Now since cloud storage needs internet access, the arduino will need constant access to internet and that is where the Wi-Fi shield comes in. The shield will enable the arduino to get constant internet access, which will in turn provide instant and fast upload and download speeds for the user.
<file_sep>### Quiz
### Question 1
A light sensor (photoresistor) is an analog sensor.
### Answer
True
### Question 2
A microphone is a digital sensor.
### Answer
False
### Question 3
A push button is an analog sensor.
### Answer
False
### Question 4
A keyboard is a digital sensor.
### Answer
True
### Question 5
Which of the following components are actuators? Select all that apply.
### Answer
a servo motor
an LED
a heating element
### Question 6
The component of an embedded system that executes a program is:
### Answer
A microcontroller
### Question 7
An analog-to-digital converter is common in embedded systems because
### Answer
many sensors are analog while the microcontroller is digital.
### Question 8
Consider the anti-lock braking system in a car. What are the main sensors and actuators of this system from the perspective of the driver?
### Answer
brake pedal and brake calipers and pads
<file_sep># Quiz
### Que 1
What do you have to do to enable encryption when using Cloud Storage?
### Answer
Nothing as encryption is enabled by default.
### Que 2
Which Google Cloud features could help prevent DDoS attacks?
### Answer
All of the these
### Que 3
You don't want programmers to have access to production resources. What's the easiest way to do this in Google Cloud?
### Answer
Create development and production projects, and don't give developers access to production.
### Que 4
What Google Cloud service can you use to enforce the principle of least privilege when using Google Cloud?
### Answer
IAM members and roles
<file_sep># Quiz
### Que 1
In GCP, what is the minimum number of IP addresses that a VM instance needs?
### Answer
One: Only an internal IP address
### Que 2
What are the three types of networks offered in the Google Cloud Platform?
### Answer
Default network, auto network, and custom network.
### Que 3
What is one benefit of applying firewall rules by tag rather than by address?
### Answer
When a VM is created with a matching tag, the firewall rules apply irrespective of the IP address it is assigned.
<file_sep># Quiz
### Que 1
You're creating a service and you want to protect it from being overloaded by too many client retries in the event of a partial outage. Which design pattern would you implement
### Answer
Circuit breaker
### Que 2
You need a relational database for a system that requires extremely high availability (99.999%). The system must run uninterrupted even in the event of a regional outage. Which database would you choose?
### Answer
Spanner
<file_sep>#!/usr/bin/env python3
from PIL import Image
from glob import glob
import os
for file in glob('ic_*'):
image = Image.open(file).convert('RGB')
path, filename = os.path.split(file)
filename = os.path.splitext(filename)[0] # get filename without extension
image.rotate(270).resize((128, 128)).save('/opt/icons/{}.jpeg'.format(filena$
print('DONE!!')
<file_sep>## Introduction to Git and Github
### Most of this course is executed directly on the command line like the push or pull requests. Still a few files that were created or required, I have added them to this repo.<file_sep># Converting a wired Canon printer into wireless using a Raspberry Pi


## 1. Raspberry Pi + CUPS:
CUPS (Common UNIX Printing System) is a modular printing system for Unix-like computer operating systems which allows a computer to act as a print server.
This option is the easiest one, since we just have to download the CUPS software into the Raspberry Pi, get its IP address and type it with “:631” in the bar address in the browser of another computer.
## 2. Raspberry Pi + Sockets:
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.
This option is more difficult than the first one, since we have to write our own server code and client code using sockets in order to send the file to be printed, print it, and tell both the server and the client that everything is okay.
We already have an idea about sockets thanks to one of the specialization courses, thus it is a chance for us to implement what we have learned. In contrast, we are not much sure about the security of the system, but we are willing to work more on it
## 3. Arduino:
Since we did not learn how Arduino communicates with the world, we do not know much about the feasibility of this option. (We googled this but it was not much of help). Also, Arduino doesn’t have a USB port, unlike Raspberry Pi, so things will be more complicated.
## We are going for option 2 for various reasons:
1. More difficult than option 1 and less difficult than option 3.
2. We already have the necessary knowledge needed.
3. Although security seems like a problem, but it is faster than the other two options

<file_sep>## Install Wireshark and start capture

<file_sep>## Assignment
### Identify and analyze a device that is an IoT device now, but in the past was a non-IoT device. Describe and list the features of the device. Compare the functions of the device in the past to the functions of the device now.
A very common example is a television. It just used to be a screen for people to stare at, but now it can be a screen for people to talk to and interact with.
### Compare the functions of the device in the past to the functions of the device now.
Past functions or the functions of a Digital TV:
1. Could not access internet
2. Could not install applications
3. Limited watching or viewing content
4. Never had a touch screen
5. Limited resources to access like channels or stations
6. Could not multitask
7. Didn't have as good display
But a smart TV can do all the above mentioned things and those are the differences between a TV of the past and a TV of the present.
### For your chosen IoT device, list any improvements or any diminishments if they exist, over the non-IOT device. Describe any limitations that are present in the new IoT version of the device.
Improvements or new features:
1. Can access the internet
2. Can install and run applications
3. Way higher watching content e.g. Netflix, Amazon Prime etc.
4. Can have a touch screen
5. Much higher access to resources like channels or stations
6. Can easily multitask
7. Can have a 4k or an 8k display
### Describe any privacy issues with the IoT device that never existed in the original version of the device. Compare the price of the original device to the price of the new IoT version of the device. When performing a price comparison, attempt to normalize for the changing value of currency over time by using an online inflation calculator.
A major privacy issue is that since the smart IoT tv is connected to the internet, it is vulnerable to hacking attempts and other various attacks. Once hacked, the hacker can access all your data through the network that your IoT device is connected to.
Smart TV's emerged around 2010, and $1 according to that time is $1.19 in 2020. And the price at that time used to be about or under $500 whereas now a smart tv can cost well above $1000. But, it can easily be justified based on the added features and newer advancements.
<file_sep>## Replace
print("hello " + name + ", your random number is " + number)
## with
print("hello " + name + ", your random number is " + str(number))
## in greetings.py
<file_sep># Week 2 Assignment Quiz
## The functions that will be needed to complete this quiz are in the folder Programming Assignment
### Question 1
What result is returned by the following code?
```
best("SC", "heart attack")
```
### Answer
MUSC MEDICAL CENTER
### Question 2
What result is returned by the following code?
```
best("NY", "pneumonia")
```
### Answer
MAIMONIDES MEDICAL CENTER
### Question 3
What result is returned by the following code?
```
best("AK", "pneumonia")
```
### Answer
YUKON KUSKOKWIM DELTA REG HOSPITAL
### Question 4
What result is returned by the following code?
```
rankhospital("NC", "heart attack", "worst")
```
### Answer
WAYNE MEMORIAL HOSPITAL
### Question 5
What result is returned by the following code?
```
rankhospital("WA", "heart attack", 7)
```
### Answer
YAKIMA VALLEY MEMORIAL HOSPITAL
### Question 6
What result is returned by the following code?
```
rankhospital("TX", "pneumonia", 10)
```
### Answer
SETON SMITHVILLE REGIONAL HOSPITAL
### Question 7
What result is returned by the following code?
```
rankhospital("NY", "heart attack", 7)
```
### Answer
BELLEVUE HOSPITAL CENTER
### Question 8
What result is returned by the following code?
```
r <- rankall("heart attack", 4)
as.character(subset(r, state == "HI")$hospital)
```
### Answer
CASTLE MEDICAL CENTER
### Question 9
What result is returned by the following code?
```
r <- rankall("pneumonia", "worst")
as.character(subset(r, state == "NJ")$hospital)
```
### Answer
BERGEN REGIONAL MEDICAL CENTER
### Question 10
What result is returned by the following code?
```
r <- rankall("heart failure", 10)
as.character(subset(r, state == "NV")$hospital)
```
### Answer
RENOWN SOUTH MEADOWS MEDICAL CENTER<file_sep>def largest_num(num, nums):
greatest = ''
nums.sort()
for i in nums:
start = greatest + str(i)
end = str(i) + greatest
if int(start) > int(end):
greatest = start
else:
greatest = end
return int(greatest)
if __name__ == '__main__':
num = int(input())
nums = [int(i) for i in input().split()]
print(largest_num(num, nums))
<file_sep>complete <- function(directory, id = 1:332) {
filenames <- list.files(path=directory, pattern="*.csv")
ids <-vector()
counts = vector()
for(i in id) {
filename <- sprintf("%03d.csv", i)
filepath <- paste(directory, filename, sep="/")
data <- read.csv(filepath)
ids <- c(ids, i)
completeCases <- data[complete.cases(data),]
counts <- c(counts, nrow(completeCases))
}
data.frame(id=ids, nobs=counts)
}
<file_sep>## Quiz
### Question 1
What protocols are required for Internet communication?
### Answer
@TCP or UDP/IP
### Question 2
Which network device copies packets onto all ports?
### Answer
hub
### Question 3
What is the protocol associated with the world wide web?
### Answer
HTTP
### Question 4
A MANET protocol is likely to differ from a typical LAN protocol because a MANET protocol will
### Answer
consume less power than a typical LAN protocol.
### Question 5
The function of a packet header is to
### Answer
contain packet information generated by a protocol layer.
### Question 6
A packet sniffer is a tool that can be used to record local traffic on a network.
### Answer
True
### Question 7
A hub can be used to communicate between two LANs with different protocols.
### Answer
False
### Question 8
In the HTTP protocol, a request message is sent by a web client to a web server.
### Answer
True
<file_sep>def calc_fib(n):
f = [0, 1]
for i in range(2, 61):
f.insert(i, (f[i-1] + f[i-2]) % 10)
rem = n % 60
quotient = (n - rem) / 60
return int((sum(f) * quotient + sum(f[0: rem+1])) % 10)
n = int(input())
print(calc_fib(n))
<file_sep>## Quiz
### Question 1
Which component is not contained on the Raspberry Pi B+ board?
### Answer
Analog-to-Digital converter
### Question 2
An ARM-based processor is
### Answer
A processor which contains a core designed by ARM Ltd.
### Question 3
Which of the following is not a task of an operating system?
### Answer
Improve performance by increasing clock frequency of the processor
### Question 4
Which feature of the Raspberry Pi tends to make it seem like it is not an IoT device?
### Answer
It provides a graphic interface using a keyboard, monitor and mouse
### Question 5
Once the Raspberry Pi has been configured, what must be contained on the micro SD card?
### Answer
The operating system
### Question 6
Which of the following is not an impact of overclocking?
### Answer
Improved temperature profile
### Question 7
raspi-config can only be used during the initial setup.
### Answer
False
### Question 8
The Raspberry Pi can be configured to boot directly to the desktop
### Answer
True
<file_sep>## Quiz
### Question 1
Which Arduino function can be used to read information from a sensor?
### Answer
digitalRead()
### Question 2
A photoresistor:
### Answer
changes resistance according to light level
### Question 3
A voltage divider is:
### Answer
a circuit that contains resistors connected in series
### Question 4
True or False: A voltage-controlling sensor can be read by an Arduino using the analogRead() function.
### Answer
True
### Question 5
In order to perform On-Off actuation, the following Arduino command might be used:
### Answer
digitalWrite()
### Question 6
The function of a Digital to Analog Converter is:
### Answer
to generate an analog voltage from digital signals
### Question 7
Which Arduino command is used to generate a pulse width modulated signal?
### Answer
analogWrite()
### Question 8
The duty cycle of a signal describes:
### Answer
the fraction of time it is high
<file_sep># Converting a wired Canon printer into wireless using a Raspberry Pi

## Requirement specification document:
At my house, I have the Canon PIXMA MG2470 All-in-One Inkjet Printer and it annoys me a lot when I have to print something, I have to carry my laptop to the living room to plug it into the printer and keep standing there until it is done printing, sometimes it takes a long time if there are a lot of pages and the printer is not very fast, especially if I have to print a coloured image or printout.
And then I got an idea after completing this specialization, I can turn it into a wireless printer using a Raspberry Pi instead of buying a new Wireless printer which will most probably cost around $200 - $300, whereas buying a Raspberry Pi with required equipment will be around \$50.
What I used was a $35 Raspberry Pi 4, and a $5 packet containing resistors and LED’s because I had already had a SD card on which I loaded Raspbian and some solder and other electrical stuff that I already had lying around at the house.
## What the user has to do:
• Download the software required for the printer.

• Choose the document to print.
• And select the printer. It will be available wirelessly if the user is connected to the same Wi-Fi.
## What I, as a developer have to do:
• Raspberry Pi should receive the file using Sockets and forward it to the printer.
• Order should be maintained i.e. Image that is received first should be printed first.
• File transfer speed should be fast so as to make the printing feasible and actually helpful. The file transfer speed should not depend on the internet speed.
<file_sep>This is my first repository.
A repository is a location where all the files of a particular project are stored
This is basically the only file that is to be created in the linux instance.
But there are few basic git commands to be performed in the terminal.<file_sep># Quiz
### Que 1
You are developing an application that transcodes large video files. Which storage option is the best choice for your application?
### Answer
Cloud Storage
### Que 2
You manufacture devices with sensors and need to stream huge amounts of data from these devices to a storage option in the cloud. Which Google Cloud Platform storage option is the best choice for your application?
### Answer
Cloud Bigtable
### Que 3
Which statement is true about objects in Cloud Storage?
### Answer
They are immutable, and new versions overwrite old unless you turn on versioning.
### Que 4
You are building a small application. If possible, you'd like this application's data storage to be at no additional charge. Which service has a free daily quota, separate from any free trials?
### Answer
Cloud Datastore
### Que 5
How do the Nearline and Coldline storage classes differ from Multi-regional and Regional? Choose all that are correct (2 responses).
### Answer
Nearline and Coldline assess additional retrieval fees.
Nearline and Coldline assess lower storage fees.
### Que 6
Your application needs a relational database, and it expects to talk to MySQL. Which storage option is the best choice for your application?
### Answer
Cloud SQL
### Que 7
Your application needs to store data with strong transactional consistency, and you want seamless scaling up. Which storage option is the best choice for your application?
### Answer
Cloud Spanner
### Que 8
Which GCP storage service is often the ingestion point for data being moved into the cloud, and is frequently the long-term storage location for data?
### Answer
Cloud Storage
<file_sep># Quiz
### Que 1
Identify two reasons for deploying applications using containers. (Choose 2 responses.)
### Answer
Consistency across development, testing, production environments
Simpler to migrate workloads
### Que 2
True or False: Kubernetes allows you to manage container clusters in multiple cloud providers.
### Answer
True
### Que 3
True or False: Google Cloud Platform provides a secure, high-speed container image storage service for use with Kubernetes Engine.
### Answer
True
### Que 4
In Kubernetes, what does "pod" refer to?
### Answer
A group of containers that work together
### Que 5
Does Google Cloud Platform offer its own tool for building containers (other than the ordinary docker command)?
### Answer
Yes; the GCP-provided tool is an option, but customers may choose not use it.
### Que 6
Where do your Kubernetes Engine workloads run?
### Answer
In clusters built from Compute Engine virtual machines
<file_sep>## Quiz
### Question 1
What is the name of the Python package used to control the Raspberry Pi camera module?
### Answer
picamera
### Question 2
What function in the camera library is used to take a picture?
### Answer
capture()
### Question 3
What is a “duty cycle”?
### Answer
The fraction of time a square wave is high
### Question 4
Why is pulse width modulation useful?
### Answer
It can be used to mimic an analog signal
### Question 5
How many input wires does a servo have?
### Answer
3
### Question 6
Why is it common to use an external power supply to drive a servo?
### Answer
A servo needs more current than a microcontroller can provide
### Question 7
The CSI camera interface of the Raspberry Pi needs to be activated before using the camera module.
### Answer
True
### Question 8
The speed of a servo motor is easily controlled.
### Answer
False
<file_sep># Quiz
### Que 1
Which compute service lets customers run virtual machines that run on Google's infrastructure?
### Answer
Compute Engine
### Que 2
Which compute service lets customers deploy their applications in containers that run in clusters on Google's infrastructure?
### Answer
Kubernetes Engine
### Que 3
Which compute service lets customers focus on their applications, leaving most infrastructure and provisioning to Google, while still offering various choices of runtime?
### Answer
App Engine
### Que 4
Which compute service lets customers supply chunks of code, which get run on-demand in response to events, on infrastructure wholly managed by Google?
### Answer
Cloud Functions
### Que 5
For what kind of traffic would the regional load balancer be the first choice? Choose all that are correct (2 answers).
### Answer
UDP traffic
TCP traffic on arbitrary port numbers
### Que 6
Choose a simple way to let a VPN into your Google VPC continue to work in spite of routing changes,
### Answer
Cloud Router
### Que 7
Which of these storage needs is best addressed by Cloud Datastore?
### Answer
Structured objects, with transactions and SQL-like queries
### Que 8
Which of these storage needs is best addressed by Cloud Spanner?
### Answer
A relational database with SQL queries and horizontal scalability
### Que 9
Which of these storage needs is best addressed by Cloud Bigtable?
### Answer
Structured objects, with lookups based on a single key
### Que 10
Which of these storage needs is best addressed by Cloud Storage?
### Answer
Immutable binary objects
<file_sep># Quiz
### Que 1
You want a secure, private connection between your network and a Google Cloud network. There is not a lot of volume, but the connection needs to be extremely reliable. Which configuration below would you choose?
### Answer
VPN with high availability and Cloud Router.
### Que 2
You have a contract with a service provider to manage your Google VPC networks. You want to connect a network they own to your VPC. Both networks are in Google Cloud. Which Connection option should you choose?
### Answer
VPC peering
### Que 3
You are a large bank deploying an online banking service to Google Cloud. The service needs high volume access to mainframe data on-premises. Which connectivity option would likely be best?
### Answer
Cloud Interconnect
### Que 4
You are deploying a large-scale web application with users all over the world and a lot of static content. Which load balancer configuration would likely be the best?
### Answer
HTTP load balancer with SSL configured and the CDN enabled.
<file_sep>## Quiz
### Question 1
How many pins does the Raspberry Pi B+ have?
### Answer
40
### Question 2
How many GPIO pins are dedicated to the SPI protocol?
### Answer
5
### Question 3
What voltage level is associated with HIGH on the GPIO of the Raspberry Pi?
### Answer
3.3
### Question 4
What function determines the numbering of the pins used?
### Answer
GPIO.setmode()
### Question 5
What function determines whether a pin will be used as an input or an output?
### Answer
GPIO.setup()
### Question 6
What function is used to set a pin to a value?
### Answer
GPIO.output()
### Question 7
What function is used to read a digital value on a pin?
### Answer
GPIO.input()
### Question 8
What function is used to read an analog value on a pin?
### Answer
None of the above
<file_sep>## Quiz
### Question 1
Pressure in a water pump system is analogous to what concept in an electrical circuit?
### Answer
voltage
### Question 2
A narrow pipe in a water system is analogous to what concept in an electrical circuit?
### Answer
resistance
### Question 3
Electrical current is measured in:
### Answer
Amperes
### Question 4
Electrical resistance is measured in:
### Answer
Ohms
### Question 5
An LED is reverse-biased when:
### Answer
the anode is negative with respect to the cathode
### Question 6
The function of a potentiometer is to:
### Answer
vary the resistance between points in the circuit
### Question 7
True or False: All of the holes in a column on the side of a breadboard are electrically connected.
### Answer
True
### Question 8
True or False: When resistance increases and current is held constant, voltage also increases.
### Answer
True
<file_sep># Week 4 Quiz
### Question
In row 1 of the following spreadsheet, the words rank, name, population, and county are called what?

### Answer
Attributes
### Question
In the following spreadsheet, the observation of Greensboro describes all of the data in row 4.

### Answer
True
### Question
If a data analyst wants to list the cities in this spreadsheet alphabetically, instead of numerically, what feature can they use in column B?

### Answer
Sort range
### Question
A data analyst types =POPULATION(C2:C11) to find the average population of the cities in this spreadsheet. However, they realize that have used the wrong formula. What syntax will correct this function?

### Answer
=AVERAGE(C2:C11)
### Question
In the following query, FROM is telling the database to filter out data from the Orders table.

### Answer
False
### Question
You are writing a query that asks a database to retrieve data about the customer with identification number 244. The column name for customer identification numbers is customer_id. What is the correct SQL clause?
### Answer
WHERE customer_id = 244
### Question
A data analyst creates the following visualization to clearly demonstrate how much more populous Charlotte is than the next-largest North Carolina city, Raleigh. It’s called a line chart.

### Answer
False
### Question
A data analyst wants to demonstrate a trend of how something has changed over time. What type of chart is best for this task?
### Answer
Line
### Question
Fill in the blank: In row 8 of the following spreadsheet, you can find the **\_** of Cary.

### Answer
observation
### Question
In the following query, what does FROM tell the database?

### Answer
From which table to select data
### Question
Fill in the blank: A data analyst creates a table, but they realize this isn’t the best visualization for their data. To fix the problem, they decide to use the **\_** feature to change it to a column chart.
### Answer
chart editor
### Question
A data analyst wants to demonstrate how the population in Charlotte has increased over time. They create the chart below. What is this type of chart called?

### Answer
Line chart
### Question
A data analyst wants to demonstrate how the population in Charlotte has increased over time. They create this data visualization. This is an example of an area chart.

### Answer
False
<file_sep># Quiz
### Que 1
Your service has an availability SLO of 99%. What could you use to monitor whether you are meeting it?
### Answer
Uptime check
### Que 2
You're deploying test environments using Compute Engine VMs. Some downtime is acceptable, and it is very important to deploy them as inexpensively as possible. What single thing below could save you the most money?
### Answer
Preemptible machines
### Que 3
You made a minor update to a service and would like to test it in production by sending a small portion of requests to the new version. Which would you choose?
### Answer
Canary deployment
### Que 4
You've made a minor fix to one of your services. You want to deploy the new version with no downtime. Which would you choose?
### Answer
Rolling update
<file_sep># Quiz
### Que 1
Which best describes an SLO?
### Answer
It is a target reliability you want your service to achieve.
### Que 2
Using SMART criteria, which below would be the least effective KPI?
### Answer
User experience design
### Que 3
Which best describes a user story?
### Answer
It is a short description of a feature written from the user's point of view.
<file_sep># Week 3 Quiz
### Question 1
Fill in the blanks of this code to print out the numbers 1 through 7
### Answer
```
number = 1
while number <= 7:
print(number, end=" ")
number+=1
```
### Question 2
The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen.
### Answer
```
def show_letters(word):
for i in word:
print(i)
show_letters("Hello")
# Should print one line per letter
```
### Question 3
Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits. Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
### Answer
```
def digits(n):
count=len(str(n))
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
```
### Question 4
This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). Fill in the blanks so that calling multiplication_table(1, 3) will print out:
1 2 3
2 4 6
3 6 9
### Answer
```
def multiplication_table(start, stop):
for x in range(stop):
for y in range(stop):
print(str((x+1)*(y+1)), end=" ")
print()
multiplication_table(1, 3)
# Should print the multiplication table shown above
```
### Question 5
The counter function counts down from start to stop when start is bigger than stop, and counts up from start to stop otherwise. Fill in the blanks to make this work correctly.
### Answer
```
def counter(start, stop):
x=start
if start<=stop:
string="Counting up: "
while x <=stop:
string+=str(x)
if x!=stop:
string+=","
x+=1
else:
string="Counting down: "
while x >=stop:
string+=str(x)
if x!=stop:
string+=","
x-=1
return string
print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"
```
### Question 6
The even_numbers function returns a space-separated string of all positive numbers that are divisible by 2, up to and including the maximum that's passed into the function. For example, even_numbers(6) returns “2 4 6”. Fill in the blank to make this work.
### Answer
```
def even_numbers(maximum):
return_string = ""
for x in range(2,maximum+1,2):
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # Should be 2 4 6
print(even_numbers(10)) # Should be 2 4 6 8 10
print(even_numbers(1)) # No numbers displayed
print(even_numbers(3)) # Should be 2
print(even_numbers(0)) # No numbers displayed
```
### Question 7
The following code raises an error when executed. What's the reason for the error?
```
def decade_counter():
while year < 50:
year += 10
return year
```
### Answer
Failure to initialize variables
### Question 8
What is the value of x at the end of the following code?
```
for x in range(1, 10, 3):
print(x)
```
### Answer
7
### Question 9
What is the value of y at the end of the following code?
```
for x in range(10):
for y in range(x):
print(y)
```
### Answer
8
### Question 10
How does this function need to be called to print yes, no, and maybe as possible options to vote for?
```
def votes(params):
for vote in params:
print("Possible option:" + vote)
```
### Answer
`votes(['yes', 'no', 'maybe'])`
<file_sep>## Quiz
### Question 1
What is a difference between clients and servers on the Internet?
### Answer
Clients initiate requests for service
### Question 2
What Python function is used to perform a DNS lookup?
### Answer
gethostbyname()
### Question 3
What Python function is used by the client to establish a connection between sockets?
### Answer
connect()
### Question 4
The recv() function performs a non-blocking wait, by default.
### Answer
False
### Question 5
When is the code inside an except clause executed?
### Answer
When code inside the associated try clause causes an appropriate exception
### Question 6
Binding a socket on the server-side requires what information?
### Answer
The port number for communication
### Question 7
What is a “live” server?
### Answer
A server that serves many requests over a long time
### Question 8
Sockets can be used to communicate between two Raspberry Pis.
### Answer
True
<file_sep>## This repo contains the solutions to all the courses that I have completed on Coursera.
### Some folders are individual courses while others are Specializations.
## NOTE:
### This repo does not contain the notes or documents provided during the course, only the solutions.<file_sep>## Quiz
### Question 1
What is the name of the library which contains the printf() function?
### Answer
stdio.h
### Question 2
What does the '\n' character mean?
### Answer
newline
### Question 3
What type of data is surrounded by double quotes in a program?
### Answer
A string
### Question 4
What C type is one byte long?
### Answer
char
### Question 5
Does the following statement evaluate to True or False?
`(10 || (5-2)) && ((6 / 2) - (1 + 2))`
### Answer
False
### Question 6
What does the following program print to the screen?
```
int main (){
int x = 0, y = 1;
if (x || !y)
printf("1");
else if (y && x)
printf("2");
else
printf("3");
}
```
### Answer
3
### Question 7
What does the following program print to the screen?
```
int main (){
int x = 0, z = 2;
while (x < 3) {
printf ("%i ", x);
x = x + z;
}
}
```
### Answer
0 2
### Question 8
What does the following program print to the screen?
```
int foo (int q) {
int x = 1;
return (q + x);
}
int main (){
int x = 0;
while (x < 3) {
printf ("%i ", x);
x = x + foo(x);
}
}
```
### Answer
0 1
<file_sep># This function creates a special object of type matrix that can cache its inverse
makeCacheMatrix <- function(x = numeric()) {
inv <- NULL
get <- function() x
getInverse <- function() {
if(length(x)%%sqrt(length(x))==0) {
# making sure that matrix is n x n
inv <<- solve(x)
}
}
list(get = get, getInverse = getInverse)
}
if (FALSE){
'This function takes the matrix object created by the function written above
and calculates its inverse. If the matrix and its inverse are equal then this
function retrieves the inverse stored in the cache!!'
}
cacheSolve <- function(x, ...) {
if(!is.atomic(x)){
# checks if the given parameter is atomic
inv <- x$getInverse()
if(!is.null(inv)) {
message('getting cached data')
return(inv)
}
} else {
# Converts it to atomic if it's not already
message('getting the inverse-- no cached data found')
return(makeCacheMatrix(x)$getInverse())
}
}
# non-atomic example
f <- makeCacheMatrix(matrix(1:4, 2, 2))
print(cacheSolve(f))
# atomic examples
print(cacheSolve(matrix(1:4, 2, 2)))<file_sep># Quiz
### Que 1
What is the purpose of Virtual Private Networking (VPN)?
### Answer
To enable a secure communication method (a tunnel) to connect two trusted environments through an untrusted environment, such as the Internet.
### Que 2
Which GCP Interconnect service requires a connection in a GCP colocation facility and provides 10 Gbps per link?
### Answer
Dedicated Interconnect
### Que 3
If you cannot meet Google’s peering requirements, which network connection service should you choose to connect to Google Workspace and YouTube?
### Answer
Carrier Peering
### Que 4
Which of the following approaches to multi-project networking, uses a centralized network administration model?
### Answer
Shared VPC
<file_sep>## Applied Data Science with Python Specialization offered by Univeristy of Michigan
### This module contains the solutions from the courses that I have completed in the above mentioned Specialization.<file_sep># Week 1 Quiz
### Question 1
What is a computer program?
### Answer
A step-by-step recipe of what needs to be done to complete a task, that gets executed by the computer.
### Question 2
What’s automation?
### Answer
The process of replacing a manual step with one that happens automatically.
### Question 3
Which of the following tasks are good candidates for automation? Check all that apply.
### Answer
Creating a report of how much each sales person has sold in the last month.
Setting the home directory and access permissions for new employees joining your company.
Populating your company's e-commerce site with the latest products in the catalog.
### Question 4
What are some characteristics of the Python programming language? Check all that apply
### Answer
Python programs are easy to write and understand.
The Python interpreter reads our code and transforms it into computer instructions.
We can practice Python using web interpreters or codepads as well as executing it locally.
### Question 5
How does Python compare to other programming languages?
### Answer
Each programming language has its advantages and disadvantages
### Question 6
Write a Python script that outputs "Automating with Python is fun!" to the screen.
### Answer
`print("Automating with Python is fun!")`
### Question 7
Fill in the blanks so that the code prints "Yellow is the color of sunshine".
### Answer
```
color = 'Yellow'
thing = 'sunshine'
print(color + " is the color of " + thing)
```
### Question 8
Keeping in mind there are 86400 seconds per day, write a program that calculates how many seconds there are in a week, if a week is 7 days. Print the result on the screen.
Note: Your result should be in the format of just a number, not a sentence.
### Answer
`print(86400*7)`
### Question 9
Use Python to calculate how many different passwords can be formed with 6 lower case English letters. For a 1 letter password, there would be 26 possibilities. For a 2 letter password, each letter is independent of the other, so there would be 26 times 26 possibilities. Using this information, print the amount of possible passwords that can be formed with 6 letters.
### Answer
`print(26**6)`
### Question 10
Most hard drives are divided into sectors of 512 bytes each. Our disk has a size of 16 GB. Fill in the blank to calculate how many sectors the disk has.
Note: Your result should be in the format of just a number, not a sentence.
### Answer
```
disk_size = 16*1024*1024*1024
sector_size = 512
sector_amount = disk_size/sector_size
print(sector_amount)
```
<file_sep>#include <stdio.h>
void main()
{
int arr[6];
arr[0] = 0;
arr[1] = 1;
for (int i = 2; i < 6; i++)
{
arr[i] = arr[i - 1] + arr[i - 2];
}
for (int i = 0; i < 6; i++)
{
printf("%d ", arr[i]);
}
}<file_sep>import math
def change(amount):
denominations_10 = math.floor(amount / 10)
denominations_5 = math.floor((amount - denominations_10 * 10) / 5)
denominations_1 = amount - (denominations_10 * 10 + denominations_5 * 5)
return denominations_1 + denominations_5 + denominations_10
if __name__ == '__main__':
amount = int(input())
print(change(amount))
<file_sep># Quiz
### Que 1
What’s the benefit of writing templates for your Deployment Manager configuration?
### Answer
Allows you to abstract part of your configuration into individual building blocks that you can reuse
### Que 2
What does Google Cloud Platform Marketplace offer?
### Answer
Production-grade solutions from third-party vendors who have already created their own deployment configurations based on Deployment Manager
<file_sep>import http.client
conn = http.client.HTTPSConnection("www.uci.edu")
conn.request("GET", "/")
resp = conn.getresponse()
content = resp.read(1000)
print(content)
conn.close()
<file_sep># Guided Projects
## Guided projects are projects on Coursera that take only hours to complete. So there are no weeks just one quiz or assignment in each project.<file_sep># Quiz
### Que 1
Name two use cases for Google Cloud Dataproc (Select 2 answers).
### Answer
Data mining and analysis in datasets of known size
Migrate on-premises Hadoop jobs to the cloud
### Que 2
Name two use cases for Google Cloud Dataflow (Select 2 answers).
### Answer
Orchestration
Extract, Transform, and Load (ETL)
### Que 3
Name three use cases for the Google Cloud Machine Learning Platform (Select 3 answers).
### Answer
Content personalization
Sentiment analysis
Fraud detection
### Que 4
Which statements are true about BigQuery? Choose all that are true (2 statements).
### Answer
BigQuery is a good choice for data analytics warehousing.
BigQuery lets you run fast SQL queries against large databases.
### Que 5
Name three use cases for Cloud Pub/Sub (Select 3 answers).
### Answer
Analyzing streaming data
Decoupling systems
Internet of Things applications
### Que 6
What is TensorFlow?
### Answer
An open-source software library that’s useful for building machine learning applications
### Que 7
What does the Cloud Natural Language API do?
### Answer
It analyzes text to reveal its structure and meaning.
<file_sep># Quiz
### Question 1
Selenium library files are included in the java project as ?
### Answer
External Jar File
### Question 2
Which method can navigate you to a particular URL?
### Answer
driver.get(url); where driver is a browser instance
### Question 3
What is the difference between driver.close() and driver.quit() methods in Selenium?
### Answer
driver.close() method closes the currently active window and driver.quit() method closes all the opened windows
### Question 4
Which of the following is not a valid locator in Selenium?
### Answer
Id, textbox, value
### Question 5
To verify the actual results with expected results, TestNG has?
### Answer
Assert Statement
### Question 6
To click a radio button or a normal button, which of the following is a valid action in Selenium?
### Answer
element.click(); where element is WebElement
### Question 7
Which of the following is possibly a correct Xpath?
### Answer
//table[@id='customer']/tbody/td
<file_sep># Quiz
### Que 1
What Google Cloud feature would be easiest to use to automate a build in response to code being checked into your source code repository?
### Answer
Build triggers
### Que 2
Which Google Cloud tools can be used to build a continuous integration pipeline?
### Answer
All of the these
<file_sep># Week 3 Quiz
### Question 1
Take a look at the 'iris' dataset that comes with R. The data can be loaded with the code:
```
library(datasets)
data(iris)
```
A description of the dataset can be found by running
```?iris```
There will be an object called 'iris' in your workspace. In this dataset, what is the mean of 'Sepal.Length' for the species virginica? Please round your answer to the nearest whole number.
### Code
```
library(datasets)
data(iris)
?iris
mean(iris[iris$Species == "virginica",]$Sepal.Length)
[1] 6.588
```
### Answer
6.588 rounded off becomes 7
### Question 2
Continuing with the 'iris' dataset from the previous Question, what R code returns a vector of the means of the variables 'Sepal.Length', 'Sepal.Width', 'Petal.Length', and 'Petal.Width'?
### Code
```
library(datasets)
data(iris)
apply(iris[, 1:4], 2, mean)
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.843333 3.057333 3.758000 1.199333
```
### Answer
apply(iris[, 1:4], 2, mean)
### Question 3
Load the 'mtcars' dataset in R with the following code
```
library(datasets)
data(mtcars)
```
There will be an object names 'mtcars' in your workspace. You can find some information about the dataset by running
```?mtcars```
### Answer
sapply(split(mtcars$mpg, mtcars$cyl), mean)
with(mtcars, tapply(mpg, cyl, mean))
tapply(mtcars$mpg,mtcars$cyl, mean)
### Question 4
Continuing with the 'mtcars' dataset from the previous Question, what is the absolute difference between the average horsepower of 4-cylinder cars and the average horsepower of 8-cylinder cars?
(Please round your final answer to the nearest whole number. Only enter the numeric result and nothing else.)
### Code
```
library(datasets)
data(mtcars)
mean(mtcars[mtcars$cyl == "8",]$hp) - mean(mtcars[mtcars$cyl == "4",]$hp)
[1] 126.5779
```
### Answer
126.5779 rounded off becomes 127
### Question 5
If you run
```
debug(ls)
```
what happens when you next call the 'ls' function?
### Answer
Execution of 'ls' will suspend at the beginning of the function and you will be in the browser.<file_sep>## There's no code to be shared for week 3.
## The only hint I have is that when you are asked to create the instances using instance template and the steps tell you to run the code on your local machine that means that you have to run those lines of code in the cloud shell, which can be accessed using the terminal resembling icon near the bell icon on top right corner.
<file_sep>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int ad_revenue(int num, vector<int> &profit, vector<int> &clicks)
{
int revenue = 0;
sort(profit.begin(), profit.end());
sort(clicks.begin(), clicks.end());
for (int i = 0; i < num; i++)
{
revenue += profit[i] * clicks[i];
}
return revenue;
}
int main()
{
int num, temp;
cin >> num;
vector<int> profit;
vector<int> clicks;
for (int i = 0; i < num; i++)
{
cin >> temp;
profit.push_back(temp);
}
for (int i = 0; i < num; i++)
{
cin >> temp;
clicks.push_back(temp);
}
cout << ad_revenue(num, profit, clicks) << "\n";
return 0;
}
<file_sep>#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
long long fibonacci_sum_last_digit(long long m, long long n) {
vector<int> f;
f.push_back(0);
f.push_back(1);
for (int i = 2; i <= 60; i++){
f.push_back((f[i-1] + f[i-2]) % 10);
}
long long rem1 = m % 60;
long long quotient1 = (m - rem1) / 60;
long long rem2 = n % 60;
long long quotient2 = (n - rem2) / 60;
long long sum1 = accumulate(f.begin() + rem1, f.end(), 0);
long long sum2 = accumulate(f.begin(), f.begin() + rem2 + 1, 0);
long long sum3 = accumulate(f.begin(), f.end(), 0) * (quotient2 - (quotient1 + 1));
return (sum1 + sum2 +sum3) % 10;
}
int main() {
long long m, n;
cin >> m >> n;
cout << fibonacci_sum_last_digit(m, n) << '\n';
return 0;
}
<file_sep>#!/usr/bin/env python3
import os
from PIL import Image
# path = os.path.expanduser('~') + '/supplier-data/images/'
path = 'supplier-data/images/'
for file in os.listdir(path):
if '.tiff' in file:
img = Image.open(path + file).convert("RGB")
dir, filename = os.path.split(file)
# get filename without extension
filename = os.path.splitext(filename)[0]
img.resize((600, 400)).save(path + filename + '.jpeg', 'jpeg')
<file_sep># Week 1 Quiz
### Question 1
Python is an example of an
### Answer
Interpreted Language
### Question 2
Data Science is a
### Answer
Interdisciplinary, made up of all of the above
### Question 3
Data visualization is not a part of data science.
### Answer
False
### Question 4
Which bracketing style does Python use for tuples?
### Answer
( )
### Question 5
In Python, strings are considered Mutable, and can be changed.
### Answer
False
### Question 6
What is the result of the following code: `['a', 'b', 'c'] + [1, 2, 3]`
### Answer
`['a', 'b', 'c', 1, 2, 3]`
### Question 7
String slicing is
### Answer
A way to make a substring of a string in python
### Question 8
When you create a lambda, what type is returned? E.g. `type(lambda x: x+1)` returns
### Answer
`<class 'function'>`
### Question 9
The epoch refers to
### Answer
January 1, year 1970
### Question 10
This code, `[x**2 for x in range(10)]` , is an example of a
### Answer
List Comprehension
### Question 11
Given a 6x6 NumPy array r, which of the following options would slice the shaded elements?

### Answer
`r.reshape(36)[::7]`
### Question 12
Given a 6x6 NumPy array r, which of the following options would slice the shaded elements?

### Answer
`r[2:4,2:4]`
<file_sep># Week 1 Quiz
### Question
Which of the following options describes data analysis?
### Answer
The collection, transformation, and organization of data in order to draw conclusions, make predictions, and drive informed decision-making.
### Question
In data analytics, a model is a group of elements that interact with one another.
### Answer
False
### Question
What tactics can a data analyst use to effectively blend gut instinct with facts? Select all that apply.
### Answer
Use their knowledge of how their company works to better understand a business need.
Apply their unique past experiences to their current work, while keeping in mind the story the data is telling.
### Question
A furniture manufacturer wants to find a more environmentally friendly way to make its products. A data analyst helps solve this problem by gathering relevant data, analyzing it, and using it to draw conclusions. The analyst then shares their analysis with subject-matter experts from the manufacturing team, who validate the findings. Finally, a plan is put into action. This scenario describes data science.
### Answer
False
### Question
To get the most out of data-driven decision-making, it’s important to include insights from people very familiar with the business problem. Identify what these people are called.
### Answer
Subject-matter experts
### Question
You have just finished analyzing data for a marketing project. Before moving forward, you share your results with members of the marketing team to see if they might have additional insights into the business problem. What practice does this support?
### Answer
Data-driven decision-making
### Question
You have recently subscribed to an online data analytics magazine. You really enjoyed an article and want to share it in the discussion forum. Which of the following would be appropriate in a post? Select all that apply.
### Answer
Checking your post for typos or grammatical errors
Giving credit to the original author
Including your own thoughts about the article
### Question
Data analysis is the various elements that interact with one another in order to provide, manage, store, organize, analyze, and share data.
### Answer
False
### Question
Fill in the blank: Data ecosystems are made up of elements that **\_** with each other. This makes it possible for them to produce, manage, store, organize, analyze, and share data.
### Answer
interact
### Question
Select the best description of gut instinct.
### Answer
An intuitive understanding of something with little or no explanation
### Question
You read an interesting article about data analytics in a magazine and want to share some ideas from the article in the discussion forum. In your post, you include the author and a link to the original article. This would be an inappropriate use of the forum.
### Answer
False
### Question
A company defines a problem it wants to solve. Then, a data analyst gathers relevant data, analyzes it, and uses it to draw conclusions. The analyst shares their analysis with subject-matter experts, who validate the findings. Finally, a plan is put into action. What does this scenario describe?
### Answer
Data-driven decision-making
### Question
What do subject-matter experts do to support data-driven decision-making? Select all that apply.
### Answer
Validate the choices made as a result of the data insights
Review the results of data analysis and identify any inconsistencies
Offer insights into the business problem
### Question
Sharing the results of your analysis with colleagues who are very familiar with the business problem supports what practice?
### Answer
Data-driven decision-making
### Question
Fill in the blank: The term **\_** is defined as an intuitive understanding of something with little or no explanation.
### Answer
gut instinct
### Question
Fill in the blank: The people very familiar with a business problem are called **\_**. They are an important part of data-driven decision-making.
### Answer
subject-matter experts
### Question
The collection, transformation, and organization of data in order to draw conclusions, make predictions, and drive informed decision-making describes what?
### Answer
Data analysis
### Question
In data analytics, what term describes a collection of elements that interact with one another?
### Answer
A data ecosystem
### Question
Fill in the blank: Data **\_** involves creating new ways of modeling and understanding the unknown by using raw data.
### Answer
science
<file_sep># Quiz
### Question 1
The libraries that we need to import are:
numpy as bp
matplotlib.pyplot as plt
cv2
### Answer
False
### Question 2
The main points that we must remember when we work with OpenCV are:
### Answer
Three
### Question 3
If we want to draw a shape and fill it inside we must write:
### Answer
-1
### Question 4
We can draw shapes by coding the coordinates of the shape we want to draw and we can draw shapes with the mouse.
### Answer
True
### Question 5
We have opend an image with Matplotlib.pyplot and we want to remove only the Blue channel. Our code will be:
### Answer
[:, :, 2] = -1
### Question 6
We can only draw on specific points on an image. We cannot draw shapes by moving our mouse.
### Answer
False
### Question 7
We are working with OpenCV and we want to draw a straight line on our image. How many points do we need to use?
### Answer
2
### Question 8
We have opened an image with OpenCV. We want to flip it on both Vertical and Horizontal axis. Which is correct the code ?
### Answer
cv2.flip(img, -1)
### Question 9
We can draw with a mouse but we cannot give functionallity to both buttons of the mouse.
### Answer
False
<file_sep>## Quiz
### Question 1
What does the ‘sudo’ command do?
### Answer
Allows a command to execute with root permission
### Question 2
What command shows a list of running processes?
### Answer
ps
### Question 3
What command prints out the contents of a directory?
### Answer
ls
### Question 4
What command creates a new directory?
### Answer
mkdir
### Question 5
What command should be used before powering off the machine?
### Answer
shutdown
### Question 6
What is the username of the non-root account created when Raspian is installed?
### Answer
pi
### Question 7
What command starts the graphic user interface from the shell after booting the Raspberry Pi?
### Answer
startx
### Question 8
The Raspberry Pi comes with Linux pre-installed?
### Answer
False
<file_sep># Quiz
### Que 1
You've been asked to write a program that uses Vision API to check for inappropriate content in photos that are uploaded to a Cloud Storage bucket. Any photos that are inappropriate should be deleted. What might be the simplest, cheapest way to deploy in this program?
### Answer
Cloud Functions
### Que 2
You have containerized multiple applications using Docker and have deployed them using Compute Engine VMs. You want to save cost and simplify container management. What might you do.
### Answer
Migrate the containers to GKE.
### Que 3
You need to deploy an existing application that was written in .NET version 4. The application requires Windows servers, and you don't want to change it. Which should you use?
### Answer
Compute Engine
<file_sep>def ad_revenue(num, profit, clicks):
profit.sort()
clicks.sort()
revenue = 0
for i in range(num):
revenue += profit[i] * clicks[i]
return revenue
if __name__ == '__main__':
num = int(input())
profit = [int(x) for x in input().split()]
clicks = [int(x) for x in input().split()]
print(ad_revenue(num, profit, clicks))
<file_sep># Week 1 Quiz
### Question
Organizing available information and revealing gaps and opportunities are part of what process?
### Answer
Using structured thinking
### Question
While creating data visualizations for a slideshow, a data analyst considers, “What would help a stakeholder understand this data better?” The analyst is in the analyze step of the data analysis process.
### Answer
False
### Question
A garden center wants to attract more customers. A data analyst in the marketing department suggests advertising in popular landscaping magazines. This is an example of what practice?
### Answer
Reaching your target audience
### Question
A company wants to make more informed decisions regarding next year’s business strategy. An analyst uses data to help identify how things will likely work out in the future. This is an example of which problem type?
### Answer
Making predictions
### Question
Describe the key difference between the problem types of categorizing things and identifying themes.
### Answer
Categorizing things involves assigning items to categories. Identifying themes takes those categories a step further, grouping them into broader themes.
### Question
Which of the following examples are leading questions? Select all that apply.
### Answer
How satisfied were you with our customer representative
In what ways did our product meet your needs?
What do you enjoy most about our service?
### Question
The question, “How could we improve our website to simplify the returns process for our online customers?” is action-oriented.
### Answer
True
### Question
On a customer service questionnaire, a data analyst asks, “If you could contact our customer service department via chat, how much valuable time would that save you?” Why is this question unfair?
### Answer
It makes assumptions
<file_sep># Week 4 Quiz
### Question
Fill in the blank: A data analytics team is working on a project to measure the success of a company’s new financial strategy. The vice president of finance is most likely to be the **\_**.
### Answer
primary stakeholder
### Question
At an online marketplace, the **\_** includes anyone in an organization who interacts with current or potential shoppers.
### Answer
customer-facing team
### Question
There are four key questions data analysts ask themselves: Who is my audience? What do they already know? What do they need to know? And how can I communicate effectively with them? These questions enable data analysts to identify the person in charge of managing the data.
### Answer
False
### Question
You receive an angry email from a colleague on the marketing team. The marketing colleague believes you have taken credit for their work. You do not believe this is true. Select the best course of action.
### Answer
Reply to the email, asking if they can schedule a time to talk about this in person in order to allow both of you to share your perspectives.
### Question
Data analysts focus on statistical significance to make sure they have enough data so that a few unusual responses don’t skew results.
### Answer
False
### Question
A data analyst has been invited to a meeting. They review the agenda and notice that their data analysis project is one of the topics that will be discussed. How can they prepare for an effective meeting? Select all that apply.
### Answer
Bring materials for taking notes.
Think about what project updates they should share.
Plan to arrive on time.
### Question
Which of the following steps are key to leading a professional online meeting? Select all that apply.
### Answer
Making sure your technology is working properly before starting the meeting
Sitting in a quiet area that’s free of distractions
### Question
Your data analytics team has been working on a project for a few weeks. You’re almost done, when your supervisor suddenly changes the business task. Everyone has to start all over again. You announce to the team that you’re going to say something to the supervisor about how unreasonable this is. What’s the best next step?
### Answer
Take a few minutes to calm down, then ask your colleagues to share their perspectives so you can work together to determine the best next step.
<file_sep># Final Quiz
### Question
Scenario 1, questions 1-5
You’ve just started a job as a data analyst at a small software company that provides data analytics and business intelligence solutions. Your supervisor asks you to kick off a project with a new client, Athena’s Story, a feminist bookstore. They have four existing locations, and the fifth shop has just opened in your community.
Athena’s Story wants to produce a campaign to generate excitement for an upcoming celebration and introduce the bookstore to the community. They share some data with your team to help make the event as successful as possible.
Your task is to review the assignment and the available data, then present your approach to your supervisor. Click the link below to access the email from your supervisor:
Then, review the email, and the Customer Survey and Historical Sales datasets.
After reading the email, you notice that the acronym WHM appears in multiple places. You look it up online, and the most common result is web host manager. That doesn’t seem right to you, as it doesn’t fit the context of a feminist bookstore. You email your supervisor to ask. When writing your email, what do you do to ensure it sounds professional? Select all that apply.
### Answer
Use a polite greeting and closing.
Read your email aloud before sending to catch any typos or grammatical errors and to ensure the communication is clear.
Respect your supervisor’s time by writing an email that’s short and to the point.
### Question
Scenario 1 continued
Now that you know WHM stands for Women’s History Month, you review the Customer Survey dataset which contains both qualitative and quantitative data.
The data in column F (Survey Q6: What types of books would you like to see more of at Athena's Story?) is quantitative.
### Answer
False
### Question
Scenario 1 continued
Next, you review the customer feedback in column F of the Customer Survey dataset.
The attribute of column F is, “Survey Q6: What types of books would you like to see more of at Athena's Story?” In order to verify that children’s literature and feminist zines are among the most popular genres, you create a visualization. This will help you clearly identify which genres are most likely to sell well during the Women’s History Month campaign.
Your visualization looks like this:

The chart you create demonstrates the percentages of each book genre that make up the whole. It’s called an area chart.
### Answer
False
### Question
Now that you’ve confirmed that children’s literature and feminist zines are among the most requested book genres, you review the Historical Sales dataset.
You’re pleased to see that the dataset contains data that’s specific to children’s literature and feminist zines. This will provide you with the information you need to make data-inspired decisions. In addition, the children’s literature and feminist zines metrics will help you organize and analyze the data about each genre in order to determine if they’re likely to be profitable.
Next, you calculate the total sales over 52 weeks for feminist zines. What is the correct syntax?
### Answer
=SUM(E2:E53)
### Question
Scenario 1 continued
After familiarizing yourself with the project and available data, you present your approach to your supervisor. You provide a scope of work, which includes important details, a schedule, and information on how you plan to prepare and validate the data. You also share some of your initial results and the pie chart you created.
In addition, you identify the problem type, or domain, for the data analysis project. You decide that the historical sales data can be used to provide insights into the types of books that will sell best during Women’s History Month this coming year. This will also enable you to determine if Athena’s Story should begin selling more children’s literature and feminist zines.
Using historical data to make informed decisions about how things may be in the future is an example of identifying themes.
### Answer
False
### Question
Scenario 2, questions 6-10
You’ve completed this program and are now interviewing for your first junior data analyst position. You’re hoping to be hired by an event planning company, Patel Events Plus. Access the job description below:
So far, you’ve successfully completed the first round of interviews with the human resources manager and director of data and strategy. Now, the vice president of data and strategy wants to learn more about your approach to managing projects and clients. Access the email you receive from the human resources director below:
You arrive Thursday at 1:45 PM for your 2 PM interview. Soon, you’re taken into the office of <NAME>, vice president of data and strategy. After welcoming you, she begins the behavioral interview.
First, she hands you a copy of Patel Events Plus’s organizational chart. Access the chart below:
As you’ve learned in this course, stakeholders are people who invest time, interest, and resources into the projects you’ll be working on as a data analyst. Let’s say you’re working on a project involving data and strategy. Based on what you find in the organizational chart, if you need information from the primary stakeholder, who can you ask?
### Answer
Vice president, data and strategy
### Question
Scenario 2 continued
Next, the vice president wants to understand your knowledge about asking effective questions. Consider and respond to the following question. Select all that apply.
Let’s say we just completed a big event for a client and wanted to find out if they were satisfied with their experience. Provide some examples of measurable questions that you could include in the customer feedback survey.
### Answer
Would you recommend Patel Events Plus to a colleague or friend? Yes or no?
On a scale from 1 to 5, with 1 being not at all likely and 5 being very likely, how likely are you to recommend Patel Events Plus?
### Question
Scenario 2 continued
Now, the vice president presents a situation having to do with resolving challenges and meeting stakeholder expectations. Consider and respond to the following question.
You’re working on a rush project, and you discover your dataset is not clean. Even though it has numerous nulls, redundant data, and other issues, the primary stakeholder insists that you move ahead and use it anyway. The project timeline is so tight that there simply isn’t enough time for cleaning. How would you handle that situation?
### Answer
Communicate the situation to your supervisor and ask for advice on how to handle the situation with the stakeholder.
### Question
Scenario 2 continued
Your next interview question deals with sharing information with stakeholders. Consider and respond to the following question. Select all that apply.
Let’s say you’ve designed a dashboard to give stakeholders easy, automatic access to data about an upcoming event. Describe the benefits of using a dashboard.
### Answer
Dashboards offer live monitoring of incoming data.
Dashboards enable stakeholders to interact with the data.
### Question
Scenario 2 continued
Your final behavioral interview question involves using metrics to answer business questions. Your interviewer hands you a copy of the Patel Events dataset.
Then, she asks: Recently, Patel Events Plus purchased a new venue for our events. If we asked you to compare the purchase price (cost) and net profit, what would you be calculating?
### Answer
Return on investment
<file_sep># Quiz
### Que 1
True or False: Google Cloud Load Balancing allows you to balance HTTP-based traffic across multiple Compute Engine regions.
### Answer
True
### Que 2
Which statement is true about Google VPC networks and subnets?
### Answer
Networks are global; subnets are regional
### Que 3
An application running in a Compute Engine virtual machine needs high-performance scratch space. Which type of storage meets this need?
### Answer
Local SSD
### Que 4
Choose an application that would be suitable for running in a Preemptible VM.
### Answer
A batch job that can be checkpointed and restarted
### Que 5
How do Compute Engine customers choose between big VMs and many VMs?
### Answer
Use big VMs for in-memory databases and CPU-intensive analytics; use many VMs for fault tolerance and elasticity
### Que 6
How do VPC routers and firewalls work?
### Answer
They are managed by Google as a built-in feature.
### Que 7
A GCP customer wants to load-balance traffic among the back-end VMs that form part of a multi-tier application. Which load-balancing option should this customer choose?
### Answer
The regional internal load balancer
### Que 8
For which of these interconnect options is a Service Level Agreement available?
### Answer
Dedicated Interconnect
<file_sep># Course Quiz
Scenario 1, question 1-5
You’ve just started a new job as a data analyst. You’re working for a midsized pharmacy chain with 38 stores in the American Southwest. Your supervisor shares a new data analysis project with you.
She explains that the pharmacy is considering discontinuing a bubble bath product called Splashtastic. Your supervisor wants you to analyze sales data and determine what percentage of each store’s total daily sales come from that product. Then, you’ll present your findings to leadership.
You know that it's important to follow each step of the data analysis process: ask, prepare, process, analyze, share, and act. So, you begin by defining the problem and making sure you fully understand stakeholder expectations.
One of the questions you ask is where to find the dataset you’ll be working with. Your supervisor explains that the company database has all the information you need.
Next, you continue to the prepare step. You access the database and write a query to retrieve data about Splashtastic. You notice that there are only 38 rows of data, representing the company’s 38 stores. In addition, your dataset contains five columns: Store Number, Average Daily Customers, Average Daily Splashtastic Sales (Units), Average Daily Splashtastic Sales (Dollars), and Average Total Daily Sales (All Products).
### Question 1
You know that spreadsheets work well for processing and analyzing a small dataset, like the one you’re using. To get the data from the database into a spreadsheet, what should you do?
### Answer
Download the data as a .CSV file, then import it into a spreadsheet.
### Question 2
You’ve downloaded the data from your company database and imported it into a spreadsheet. To use the dataset for this scenario, click the link below and select “Use Template.”
Now, it’s time to process the data. As you know, this step involves finding and eliminating errors and inaccuracies that can get in the way of your results. While cleaning the data, you notice that information about Splashtastic is missing in row 16. The best course of action is to delete row 16 from your dataset so the missing data doesn’t get in the way of your results.
### Answer
False
### Question 3
Once you’ve found the missing information, you analyze your dataset.
During analysis, you create a new column F. At the top of the column, you add: Average Percentage of Total Sales - Splashtastic. What is this column label called?
### Answer
An attribute
### Question 4
Next, you determine the average store sales of Splashtastic over the past 12 months at all stores, The range that contains these sales is E2:E39. To do this, you use a function. Fill in the blank to complete the function correctly: =**\_** (E2:E39).
### Answer
AVERAGE
### Question 5
You’ve reached the share phase of the data analysis process. It involves which of the following? Select all that apply.
### Answer
Create a data visualization to highlight the Splashtastic sales insights you've discovered.
Prepare a slideshow about Splashtastic’s sales and practice your presentation.
Present your findings about Splashtastic to stakeholders.
Scenario 2, questions 6-10
You’ve been working for the nonprofit National Dental Society (NDS) as a junior data analyst for about two months. The mission of the NDS is to help its members advance the oral health of their patients. NDS members include dentists, hygienists, and dental office support staff.
The NDS is passionate about patient health. Part of this involves automatically scheduling follow-up appointments after crown replacement, emergency dental surgery, and extraction procedures. NDS believes the follow-up is an important step to ensure patient recovery and minimize infection.
Unfortunately, many patients don’t show up for these appointments, so the NDS wants to create a campaign to help its members learn how to encourage their patients to take follow-up appointments seriously. If successful, this will help the NDS achieve its mission of advancing the oral health of all patients.
Your supervisor has just sent you an email saying that you’re doing very well on the team, and he wants to give you some additional responsibility. He describes the issue of many missed follow-up appointments. You are tasked with analyzing data about this problem and presenting your findings using data visualizations.
An NDS member with three dental offices in Colorado offers to share its data on missed appointments. So, your supervisor uses a database query to access the dataset from the dental group. The query instructs the database to retrieve all patient information from the member’s three dental offices, located in zip code 81137.
### Question 6
The table is dental_data_table, and the column name is zip_code. You write the following query, but get an error. What statement will correct the problem?

### Answer
WHERE zip_code = 81137
### Question 7
The dataset your supervisor retrieved and imported into a spreadsheet includes a list of patients, their demographic information, dental procedure types, and whether they attended their follow-up appointment. To use the dataset for this scenario, click the link below and select “Use Template.”
The patient demographic information includes data such as age and gender. As you’re learning, it’s your responsibility as a data analyst to make sure your analysis is fair. The fact that the dataset includes people who all live in the same zip code might get in the way of fairness.
### Answer
True
### Question 8
As you’re reviewing the dataset, you notice that there are a disproportionate number of senior citizens. So, you investigate further and find out that this zip code represents a rural community in Colorado with about 800 residents. In addition, there’s a large assisted-living facility in the area. Nearly 300 of the residents in the 81137 zip code live in the facility.
You recognize that’s a sizable number, so you want to find out if age has an effect on a patient’s likelihood to attend a follow-up dental appointment. You analyze the data, and your analysis reveals that older people tend to miss follow-ups more than younger people.
So, you do some research online and discover that people over the age 60 are 50% more likely to miss dentist appointments. Sometimes this is because they’re on a fixed income. Also, many senior citizens lack transportation to get to and from appointments.
With this new knowledge, you write an email to your supervisor expressing your concerns about the dataset. He agrees with your concerns, but he’s also impressed with what you’ve learned and thinks your findings could be very important to the project. He asks you to change the business task. Now, the NDS campaign will be about educating dental offices on the challenges faced by senior citizens and finding ways to help them access quality dental care.
Fill in the blank: Changing the business task involves defining a new **\_**.
### Answer
question or problem to be solved
### Question 9
You continue with your analysis. In the end, your findings support what you discovered during your online research: As people get older, they’re less likely to attend follow-up dental visits.
But you’re not done yet. You know that data should be combined with human insights in order to lead to true data-driven decision-making. So, your next step is to share this information with people who are familiar with the problem. They’ll help verify the results of your data analysis.
Fill in the blank: The people who are familiar with a problem and help verify the results of data analysis are **\_**.
### Answer
subject-matter experts
### Question 10
The subject-matter experts are impressed by your analysis. The team agrees to move to the next step: data visualization. You know it’s important that stakeholders at NDS can quickly and easily understand that older people are less likely to attend important follow-up dental appointments. This will help them create an effective campaign for members.
It’s time to create your presentation to stakeholders. It will include a data visualization that depicts the relationship between age and follow-up dental appointment attendance rates. For this, a doughnut chart will be most effective.
### Answer
False
<file_sep>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
pwm = GPIO.PWM(12, 50)
pwm.start(0)
while True:
for i in range(100):
pwm.ChangeDutyCycle(i)
time.sleep(0.01)
for i in range(100, 0, -1):
pwm.ChangeDutyCycle(i)
time.sleep(0.01)
<file_sep>## Google-IT-Automation-with-Python Specialization
### This module contains the code snippets and files that will help you in completing the courses.
<file_sep># Week 3 Quiz
### Question
In which stage of the data life cycle does a business decide what kind of data it needs, how the data will be managed, and who will be responsible for it?
### Answer
Plan
### Question
The destroy stage of the data life cycle might involve which of the following actions? Select all that apply.
### Answer
Shredding paper files
Using data-erasure software
### Question
A data analyst uses a spreadsheet function to aggregate data. Then, they add a pivot table to show totals from least to greatest. This would happen during which stage of the data life cycle?
### Answer
Analyze
### Question
The data life cycle deals with the stages that data goes through; data analysis involves following a process to analyze data.
### Answer
True
### Question
A company takes insights provided by its data analytics team, validates them, and finalizes a strategy. They then implement a plan to solve the original business problem. This describes the share step of the data analysis process.
### Answer
False
### Question
Fill in the blank: A function is a predefined operation, whereas a formula is **\_**.
### Answer
a set of instructions used to perform a specified calculation.
### Question
Data analysts use queries to request, retrieve, and update information within a database.
### Answer
True
### Question
Structured query language (SQL) enables data analysts to communicate with a database.
### Answer
True
### Question
Fill in the blank: A business decides what kind of data it needs, how the data will be managed, and who will be responsible for it during the **\_** stage of the data life cycle.
### Answer
Plan
### Question
A data analyst is working at a small tech startup. They’ve just completed an analysis project, which involved private company information about a new product launch. In order to keep the information safe, the analyst uses secure data-erasure software for the digital files and a shredder for the paper files. Which stage of the data life cycle does this describe?
### Answer
Destroy
### Question
Fill in the blank: The data life cycle has six stages, whereas data analysis has six **\_**.
### Answer
Process steps
### Question
A company takes insights provided by its data analytics team, validates them, and finalizes a strategy. They then implement a plan to solve the original business problem. This describes which step of the data analysis process?
### Answer
Act
### Question
Fill in the blank: A formula is a set of instructions used to perform a specified calculation; whereas a function is **\_**.
### Answer
A predefined operation
### Question
Fill in the blank: A query is used to **\_** information from a database. Select all that apply.
### Answer
Retrieve
Request
Update
<file_sep># Quiz
### Question 1
True or False: The number of examples specified in the model config file (as num_examples, under eval_config) must exactly match the number of sample images in the images/test folder.
### Answer
True. It is necessary.
### Question 2
In our project, which software library is responsible for detecting/recognizing the Region of Interest or ROI, which in our case is segments of an image that contain text, and requires training to be able to do so?
### Answer
Tensorflow
### Question 3
True or false: Tensorflow requires us to convert annotation data from XML, CSV or other formats into TFRecord format .
### Answer
True
### Question 4
Which of the following needs to be changed to match our setup within the config file?
### Answer
path to labelmap
num_classes
path to checkpoint
### Question 5
In order to capture a webcam feed, what parameter do we pass to cv2.VideoCapture()?
### Answer
0+cv2.CAP_DSHOW
### Question 6
What command begins the Tensorflow detection session?
### Answer
sess.run()
### Question 7
We can extract the box coordinates to extract our ROI using the vis_util.return_coordinates(). Before doing this, how do we check that the detected object is the one we want?
### Answer
Check category_index[i]['name]
<file_sep>### If you do not have access to a real Arduino, you can visit tinkedcad.com to simulate an Arduino
### Then open Arduino IDE, load the required example, and paste the code from Arduino IDE to your tinkercad circuit or create your own code and paste it onto the code section at tinkedcad.com in your circuit.
<file_sep># This is the file that was created on Github and then imported via a pull request
def hello():
print('Greetings')
<file_sep>## Assignment


<file_sep># Quiz
### Que 1
Which of the following does not allow you to interact with GCP?
### Answer
Cloud Explorer
### Que 2
What is the difference between GCP Console and Cloud Shell?
### Answer
Cloud Shell is a command-line tool, while GCP Console is a graphical user interface
<file_sep>## Quiz
### Question 1
In a communication over the Internet, how is the “port” number used?
### Answer
to identify the application protocol being used
### Question 2
The Domain Name Service is:
### Answer
a service to map domain names to IP addresses
### Question 3
Which of the following is NOT an argument to the Ethernet.begin() function?
### Answer
Local processor
### Question 4
DHCP is:
### Answer
a protocol to assign IP addresses to network nodes
### Question 5
What is NOT a type of encryption used in WiFi today?
### Answer
WPC
### Question 6
True or False: The SSID of a WiFi network is the name of the network.
### Answer
True
### Question 7
True or False: An Ethernet client does not send data to an Ethernet server.
### Answer
False
### Question 8
True or False: A MAC address is unique for each network adapter.
### Answer
True
<file_sep>## Python Project Pillow, Tesseract and OpenCV
### There is no week 3 folder because there is no quiz or assignment in week 2<file_sep>## Using Python to interact with the Operating System
### In this repo, you will find only the answers for the Qwiklabs Graded External Tool. There are no answers for practice quizzes.<file_sep>## Assignment
### Code
```
void setup()
{
pinMode(13, OUTPUT);
pinMode(2, INPUT);
pinMode(5, INPUT);
}
void loop()
{
if (digitalRead(2) == HIGH || digitalRead(5) == HIGH)
digitalWrite(13, HIGH);
else
digitalWrite(13, LOW);
}
```

<file_sep>## Data Structures and Algorithms Specialization offered by University of California San Diego & National Research University Higher School of Economics
### This module contains the solutions from the courses that I have completed in the above mentioned Specialization.<file_sep>## Quiz
### Question 1
An EEPROM is:
### Answer
non-volatile
### Question 2
A mask is:
### Answer
a sequence of bits used to identify bits of interest
### Question 3
Assume that you have a byte but you are interested in only the 2 least significant bits of the byte. Which hexadecimal number represents the mask that you would use to help you?
### Answer
0x03
### Question 4
How many wires are used for communication in the I2C protocol?
### Answer
2
### Question 5
Which role describes a node that places data on the bus?
### Answer
Transmitter
### Question 6
When is an Acknowledge bit sent?
### Answer
after each byte is sent
### Question 7
True or False: The Wire.write() function buffers data before sending it.
### Answer
True
### Question 8
True or False: During normal operation, the SDA line should not change while the SCL line is high.
### Answer
True
<file_sep>#include <iostream>
#include <vector>
using namespace std;
int fibonacci_fast(int n) {
vector<int> f;
f.push_back(0);
f.push_back(1);
for (int i = 2; i <= 60; i++){
f.push_back((f[i-1] + f[i-2]) % 10);
}
int temp = n % 60;
return f[temp];
}
int main() {
int n;
cin >> n;
if (n <= 1){
cout << n;
}
else
{
cout << fibonacci_fast(n) << '\n';
}
return 0;
}
<file_sep># Quiz
### Que 1
What is the foundational process at the base of Google's Site Reliability Engineering (SRE) ?
### Answer
Monitoring
### Que 2
What is the purpose of the Stackdriver Trace service?
### Answer
Reporting on latency as part of managing performance.
### Que 3
Stackdriver integrates several technologies, including monitoring, logging, error reporting, and debugging that are commonly implemented in other environments as separate solutions using separate products. What are key benefits of integration of these services?
### Answer
Reduces overhead, reduces noise, streamlines use, and fixes problems faster
<file_sep>## Quiz
### Question 1
What is the function of the linking process after compilation?
### Answer
It merges the libraries with the application code into a single executable
### Question 2
What is the role of avrdude?
### Answer
It writes the executable into the memory of the Arduino
### Question 3
Why are classes (in C++) useful?
### Answer
They improve the organization and understandability of the code
### Question 4
What is one way that a sketch can invoke a function contained inside a class?
### Answer
The name of the class can be concatenated with the name of the function, with a period in between.
### Question 5
Which of the following statements is true?
### Answer
The setup() function is executed once and the loop() function is executed iteratively, as long as the Arduino is powered on.
### Question 6
True or False: An analog pin can accept analog inputs and drive analog outputs.
### Answer
False
### Question 7
If a sketch running on an Arduino UNO executes the following statements, what voltage would be expected on pin 1 afterwards?
```
pinMode(1, OUTPUT);
digitalWrite(1, HIGH);
```
### Answer
5
### Question 8
True or False: The delay() function causes program execution to pause for a number of milliseconds.
### Answer
True
<file_sep># This is the file that was created in the linux instance
def git_operation():
print("I am adding example.py file to the remote repository.")
git_operation()
<file_sep>#include <iostream>
#include <cmath>
using namespace std;
int change(int amount)
{
int denominations_10 = floor(amount / 10);
int denominations_5 = floor((amount - denominations_10 * 10) / 5);
int denominations_1 = amount - (denominations_10 * 10 + denominations_5 * 5);
return denominations_1 + denominations_5 + denominations_10;
}
int main()
{
int amount;
cin >> amount;
cout << change(amount);
}<file_sep># Week 4 Quiz
## Questions with same question number are the ones that vary from one quiz to another!!
### Question 1
What is produced at the end of this snippet of R code?
```
set.seed(1)
rpois(5, 2)
```
### Answer
A vector with the numbers 1, 1, 2, 4, 1
### Question 2
What R function can be used to generate standard Normal random variables?
### Answer
rnorm
### Question 3
When simulating data, why is using the set.seed() function important? Select all that apply.
### Answer
It ensures that the sequence of random numbers starts in a specific place and is therefore reproducible.
### Question 4
Which function can be used to evaluate the inverse cumulative distribution function for the Poisson distribution?
### Answer
qpois
### Question 5
What does the following code do?
```
set.seed(10)
x <- rep(0:1, each = 5)
e <- rnorm(10, 0, 20)
y <- 0.5 + 2 * x + e
```
### Answer
Generate data from a Normal linear model
### Question 5
What does the following code do?
```
set.seed(10)
x <- rbinom(10, 10, 0.5)
e <- rnorm(10, 0, 20)
y <- 0.5 + 2 * x + e
```
### Answer
Generate data from a Normal linear model
### Question 6
What R function can be used to generate Binomial random variables?
### Answer
rbinom
### Question 7
What aspect of the R runtime does the profiler keep track of when an R expression is evaluated?
### Answer
the function call stack
### Question 8
Consider the following R code
```
library(datasets)
Rprof()
fit <- lm(y ~ x1 + x2)
Rprof(NULL)
```
(Assume that y, x1, and x2 are present in the workspace.) Without running the code, what percentage of the run time is spent in the 'lm' function, based on the 'by.total' method of normalization shown in 'summaryRprof()'?
### Answer
100%
### Question 9
When using 'system.time()', what is the user time?
### Answer
It is the time spent by the CPU evaluating an expression
### Question 10
f a computer has more than one available processor and R is able to take advantage of that, then which of the following is true when using 'system.time()'?
### Answer
Elapsed time may be smaller than user time<file_sep>#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
long long fibonacci_sum_last_digit(long long n) {
vector<int> f;
f.push_back(0);
f.push_back(1);
for (int i = 2; i <= 60; i++){
f.push_back((f[i-1] + f[i-2]) % 10);
}
long long rem = n % 60;
long long quotient = (n - rem) / 60;
return (accumulate(f.begin(), f.end(), 0) * quotient + accumulate(f.begin(), f.begin() + rem + 1, 0)) % 10;
}
int main() {
long long n;
cin >> n;
if (n <= 1)
cout << n;
else
cout << fibonacci_sum_last_digit(n) << '\n';
return 0;
}
<file_sep># Week 5 Quiz
### Question
An online gardening magazine wants to understand why its subscriber numbers have been increasing. A data analyst discovers that significantly more people subscribe when the magazine has its annual 50%-off sale. This is an example of what?
### Answer
Analyzing customer buying behaviors
### Question
A doctor’s office has discovered that patients are waiting 20 minutes longer for their appointments than in past years. A data analyst could help solve this problem by analyzing how many doctors and nurses are on staff at a given time compared to the number of patients with appointments.
### Answer
True
### Question
Describe the difference between a question and a problem in data analytics.
### Answer
A question is designed to discover information, whereas a problem is an obstacle or complication that needs to be solved.
### Question
Fill in the blank: A business task is described as the problem or **\_** a data analyst answers for a business.
### Answer
question
### Question
What is the process of using facts to guide business strategy?
### Answer
Data-driven decision-making
### Question
Data analysts ensure their analysis is fair for what reason?
### Answer
Fairness helps them avoid biased conclusions.
### Question
Fill in the blank: Fairness is achieved when data analysis doesn't create or **\_** bias.
### Answer
reinforce
### Question
A magazine wants to understand why its subscribers have been increasing. A data analyst could help answer that question with a report that predicts the result of a half-price sale on future subscription rates.
### Answer
False
### Question
Fill in the blank: A problem is an obstacle to be solved, an issue is a topic to investigate, and a **\_** is designed to discover information.
### Answer
Question
### Question
A large hotel chain sees about 500 customers per week. A data analyst working there is gathering data through customer satisfaction surveys. They are anxious to begin analysis, so they start analyzing the data as soon as they receive 50 survey responses. This is an example of what? Select all that apply.
### Answer
Failing to have a large enough sample size
Failing to include diverse perspectives in data collection
<file_sep># Week 2 Quiz
### Question
In data analytics, a pattern is defined as a process or set of rules to be followed for a specific task.
### Answer
False
### Question
In data analytics, quantitative data measures qualities and characteristics.
### Answer
False
### Question
In data analytics, reports use data that doesn’t change once it’s been recorded. Which of the following terms describes this type of data?
### Answer
Static
### Question
A pivot table is a data-summarization tool used in data processing. Which of the following tasks can pivot tables perform? Select all that apply.
### Answer
Calculate totals from data
Group data
Reorganize data
### Question
What is an example of using a metric? Select all that apply.
### Answer
Using annual profit targets to set and evaluate goals
Using key performance indicators, such as click-through rates, to measure revenue
### Question
Which of the following options describes a metric goal? Select all that apply.
### Answer
Evaluated using metrics
Measurable
### Question
Fill in the blank: Return on investment compares the cost of an investment to the **\_** of that investment.
### Answer
net profit
### Question
A data analyst is using data from a short time period to solve a problem related to someone’s day-to-day decisions. They are most likely working with small data.
### Answer
True
<file_sep># temp-linux
Hello this is the README file for this repository that was created on Github platform and then imported
<file_sep># Quiz
### Question 1
How do we display an image in Python using OpenCV?
### Answer
imshow()
### Question 2
How is the width and length of an image retrieved with Python OpenCV using indexing: org_height, org_width = _____ ?
### Answer
image.shape[0:2]
### Question 3
How does increasing the kernel size effect the blur?
### Answer
increases the blur
### Question 4
What generally happens to a given pixel's neighboring pixels when an image is sharpened?
### Answer
Different from the given pixel
### Question 5
What python library is used to check for the existence of a directory?
### Answer
os
<file_sep># Quiz
### Que 1
Which of the following is not a GCP load balancing service?
### Answer
Hardware-defined load balancing
### Que 2
Which three GCP load balancing services support IPv6 clients?
### Answer
HTTP(S) load balancing
TCP proxy load balancing
SSL proxy load balancing
### Que 3
Which of the following are applicable autoscaling policies for managed instance groups?
### Answer
Queue-based workload
Monitoring metrics
Load balancing capacity
CPU utilization
<file_sep>def knapsack(dict, capacity):
amount = 0
temp = []
for i, j in dict:
temp_value, temp_weight = j
if temp_weight <= capacity != 0 and i not in temp:
amount += temp_value
capacity -= temp_weight
elif temp_weight > capacity != 0 and i not in temp:
amount += temp_value / (temp_weight / capacity)
else:
pass
temp.append(i)
return format(amount, '.4f')
if __name__ == '__main__':
items, capacity = map(int, input().split())
dict = {}
for i in range(items):
value, weight = map(int, input().split())
dict[int(value/weight)] = (value, weight)
dict = sorted(dict.items(), reverse=True)
print(knapsack(dict, capacity))
<file_sep>def pisano_period(m):
previous, current = 0, 1
for i in range(0, m * m):
previous, current = current, (previous + current) % m
if previous == 0 and current == 1:
return i + 1
def fibonacci_huge(n, m):
pp_index = pisano_period(m)
n = n % pp_index
previous, current = 0, 1
if n <= 1:
return n
for i in range(n - 1):
previous, current = current, previous + current
return current % m
if __name__ == '__main__':
n, m = map(int, input().split())
print(fibonacci_huge(n, m))
<file_sep># Quiz
### Que 1
Choose fundamental characteristics of cloud computing. Mark all that are correct (4 correct responses).
### Answer
Customers can scale their resource use up and down
Resources are available from anywhere over the network
Computing resources available on-demand and self-service
Customers pay only for what they use or reserve
### Que 2
Choose a fundamental characteristic of devices in a virtualized data center.
### Answer
They are manageable separately from the underlying hardware.
### Que 3
What type of cloud computing service lets you bind your application code to libraries that give access to the infrastructure your application needs?
### Answer
Platform as a Service
### Que 4
What type of cloud computing service provides raw compute, storage, and network, organized in ways that are familiar from physical data centers?
### Answer
Infrastructure as a Service
### Que 5
Which statement is true about the zones within a region?
### Answer
The zones within a region have fast network connectivity among them.
### Que 6
What kind of customer benefits most from billing by the second for cloud resources such as virtual machines?
### Answer
Customers who create and run many virtual machines
<file_sep>import itertools
def prizes(lst, num):
final = []
length = 0
for i in range(1, num):
temp = list(itertools.permutations(lst, i))
temp2 = [i for i in temp if sum(i) == num]
final.append(temp2)
if len(temp2) > length:
length = len(temp2)
final = [i for i in final if len(i) == length]
print(len(final[0][0]))
return ' '.join([str(i) for i in final[0][0]])
if __name__ == "__main__":
num = int(input())
nums = [int(i) for i in range(1, num + 1)]
print(prizes(nums, num))
<file_sep># Quiz
### Que 1
Which statement is true of Virtual Machine Instances in Compute Engine?
### Answer
In Compute Engine, a VM is a networked service that simulates the features of a computer.
### Que 2
What are sustained use discounts?
### Answer
Automatic discounts that you get for running specific Compute Engine resources for a significant portion of the billing month
### Que 3
Which statement is true of persistent disks?
### Answer
Persistent disks are encrypted by default.
<file_sep># Quiz
### Que 1
What abstraction is primarily used to administer user access in Cloud IAM ?
### Answer
Roles, an abstraction of job roles.
### Que 2
Question 2
Which of the following is not a type of IAM role?
### Answer
Advanced
### Que 3
Which of the following is not a type of IAM member?
### Answer
Organization Account
<file_sep>## Quiz
### Question 1
What is a fair definition of an API?
### Answer
A protocol for communicating between programs
### Question 2
What is a good reason to use an SDK rather than directly using an API?
### Answer
An SDK is usually easier to use than an API
### Question 3
What is Pip?
### Answer
A tool to install Python packages
### Question 4
In the Twython library, what function sends a tweet?
### Answer
update_status()
### Question 5
In the Twython library, what function is used to detect tweets in a stream that contain a given string?
### Answer
stream.statuses.filter()
### Question 6
What is the name of the callback function that is invoked when a tweet that contains a selected string is found in a stream?
### Answer
on_success()
### Question 7
The TwythonStreamer class defines the callback function which is invoked when a tweet containing a given string is found in a stream.
### Answer
True
<file_sep>#include <EEPROM.h>
void setup()
{
Serial.begin(9600);
}
void loop()
{
String buffer = "";
buffer = Serial.readString();
int address, data;
if (buffer.startsWith("read"))
{
address = buffer.substring(buffer.indexOf(' ') + 1).toInt();
Serial.print("Data:");
Serial.print(address);
Serial.println();
Serial.println(EEPROM.read(address));
}
else if (buffer.startsWith("write"))
{
address = buffer.substring(6, 7).toInt();
data = buffer.substring(8).toInt();
Serial.print("Address:");
Serial.print(data);
Serial.println();
Serial.print(address);
Serial.println();
EEPROM.write(address, data);
}
}<file_sep>## R Programming by John Hopkins University
### This course contains the quiz and programming solutions to the coursera course R programming offered by John Hopkins University.
### While running programming code files, make sure that the data or the csv files are in the same directory you are working in. <file_sep># Week 3 Quiz
### Question
In spreadsheets, formulas and functions end with an equal sign (=).
### Answer
False
### Question
Fill in the blank: The labels that describe the type of data contained in each column of a spreadsheet are called **\_**.
### Answer
attributes
### Question
To determine an organization’s annual budget, a data analyst might use a slideshow.
### Answer
False
### Question
Which of the following statements accurately describe formulas and functions? Select all that apply.
### Answer
Functions are preset commands that perform calculations.
Formulas are instructions that perform specific calculations.
Formulas and functions assist data analysts in calculations, both simple and complex.
### Question
In the function =MAX(G3:G13), what does G3:G13 represent?
### Answer
The range
### Question
What is the correct spreadsheet formula for multiplying cell D5 times cell D7?
### Answer
=D5\*D7
### Question
Fill in the blank: By negatively influencing data collection, \_\_\_\_ can have a detrimental effect on analysis.
### Answer
bias
### Question
Fill in the blank: A data analyst considers which organization created, collected, or funded a dataset in order to understand its **\_**.
### Answer
context
<file_sep># Quiz
### Question 1
What of these libraries are associated with web scraping?
### Answer
BeautifulSoup
requests
### Question 2
What are valid methods for getting an div element through BeautifulSoup?
### Answer
soup.find_all('div')
soup['div']
soup.find('div')
### Question 3
How can you search for elements of any type that has a given class?
### Answer
Through soup.find_all(None, {'class':'given_class'})
### Question 4
What are some of the key functionalities of the browser developer tools?
### Answer
A JavaScript console that allows you to run code on the web page
A interactive inspection of the web page soure code
An analyzer for all the traffic that happens when you interact with a web page
### Question 5
Why would you use a selector on BeautifulSoup?
### Answer
Because you don't have to do a lot of source code exploration in order to use it
Because you can have it easily through the inspect element functionality of the DevTools
Because it allows you to navigate on complex patterns
### Question 6
What of those are valid ways of performing a POST request?
### Answer
r = req.post(LINK)
params = json.dumps({'username': 'admin'})
headers = {'Content-Type': 'application/json'}
r = req.post(LINK, params, headers=headers)
### Question 7
Why would you use a Session object for performing GET and POST requests?
### Answer
In order to store cookies and mantain the connection state
<file_sep># Week 2 Quiz
### Question 1
Complete the function by filling in the missing parts. The color_translator function receives the name of a color, then prints its hexadecimal value. Currently, it only supports the three additive primary colors (red, green, blue), so it returns "unknown" for all other colors.
### Answer
```
def color_translator(color):
if color == "red":
hex_color = "#ff0000"
elif color == "green":
hex_color = "#00ff00"
elif color == "blue":
hex_color = "#0000ff"
else:
hex_color = "unknown"
return hex_color
print(color_translator("blue")) # Should be #0000ff
print(color_translator("yellow")) # Should be unknown
print(color_translator("red")) # Should be #ff0000
print(color_translator("black")) # Should be unknown
print(color_translator("green")) # Should be #00ff00
print(color_translator("")) # Should be unknown
```
### Question 2
What's the value of this Python expression: "big" > "small"
### Answer
False
### Question 3
What is the elif keyword used for?
### Answer
To handle more than two comparison cases.
### Question 4
Students in a class receive their grades as Pass/Fail. Scores of 60 or more (out of 100) mean that the grade is "Pass". For lower scores, the grade is "Fail". In addition, scores above 95 (not included) are graded as "Top Score". Fill in this function so that it returns the proper grade.
### Answer
```
def exam_grade(score):
if score>95:
grade = "Top Score"
elif score>=60:
grade = "Pass"
else:
grade = "Fail"
return grade
print(exam_grade(65)) # Should be Pass
print(exam_grade(55)) # Should be Fail
print(exam_grade(60)) # Should be Pass
print(exam_grade(95)) # Should be Pass
print(exam_grade(100)) # Should be Top Score
print(exam_grade(0)) # Should be Fail
```
### Question 5
What's the value of this Python expression: 11 % 5?
### Answer
1
### Question 6
Complete the body of the format_name function. This function receives the first_name and last_name parameters and then returns a properly formatted string.
Specifically:
If both the last_name and the first_name parameters are supplied, the function should return like so:
```
print(format_name("Ella", "Fitzgerald"))
Name: <NAME>
```
If only one name parameter is supplied (either the first name or the last name) , the function should return like so:
```
print(format_name("Adele", ""))
Name: Adele
```
or
```
print(format_name("", "Einstein"))
Name: Einstein
```
Finally, if both names are blank, the function should return the empty string:
```
print(format_name("", ""))
```
### Answer
```
def format_name(first_name, last_name):
if first_name!="" and last_name!="":
string="Name: "+last_name+", "+first_name
elif first_name=="" and last_name=="":
string=""
elif first_name=="" or last_name=="":
if first_name=="":
string="Name: "+last_name
else:
string="Name: "+first_name
return string
print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"
print(format_name("", ""))
# Should return an empty string
```
### Question 7
The longest_word function is used to compare 3 words. It should return the word with the most number of characters (and the first in the list when they have the same length). Fill in the blank to make this happen.
### Answer
```
def longest_word(word1, word2, word3):
if len(word1) >= len(word2) and len(word1) >= len(word3):
word = word1
elif len(word2) >= len(word1) and len(word2) >= len(word3):
word = word2
else:
word = word3
return(word)
print(longest_word("chair", "couch", "table"))
print(longest_word("bed", "bath", "beyond"))
print(longest_word("laptop", "notebook", "desktop"))
```
### Question 8
What’s the output of this code?
```
def sum(x, y):
return(x+y)
print(sum(sum(1,2), sum(3,4)))
```
### Answer
10
### Question 9
What's the value of this Python expression
`((10 >= 5*2) and (10 <= 5*2))`
### Answer
True
### Question 10
The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1). Complete the body of the function so that it returns the right number. Note: Since division by 0 produces an error, if the denominator is 0, the function should return 0 instead of attempting the division.
### Answer
```
def fractional_part(numerator, denominator):
if denominator!=0:
x=float(numerator/denominator)
l=[i for i in str(x).split(".")]
y=l[0]
num=x-int(y)
else:
num=0
return num
print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0
```<file_sep>def calc_fib(n):
f = [0, 1]
for i in range(2, 61):
f.insert(i, (f[i-1] + f[i-2]) % 10)
temp = n % 60
return f[temp]
n = int(input())
print(calc_fib(n))
<file_sep>## This module contains the assignment and quiz answers to the course 'Applied Machine Learning in Python' provided by University of Michigan, part of Applied Data Science with Python Specialization.
<file_sep>## Quiz
### Question 1
Which of the following does NOT provide observability in a system?
### Answer
A switch connected to an Arduino input pin
### Question 2
What is meant by the expression “run control of the target”?
### Answer
The ability to stop and start the execution of the target microcontroller
### Question 3
What is NOT an advantage of using a remote debugger?
### Answer
Remote debugging requires an extra communication channel for debugging
### Question 4
What is NOT a feature of an embedded debug interface?
### Answer
Automatic test generation is commonly supported
### Question 5
Which of the following is NOT an advantage of the UART protocol?
### Answer
Higher data transfer rates are typically achieved compared to a parallel protocol
### Question 6
Which of the following statements is NOT true about the UART protocol?
### Answer
The data transmission rate is equal to the baud rate
### Question 7
Synchronization is performed in the UART protocol based on the timing of the Start bit.
### Answer
True
### Question 8
An error in bit transmission (perhaps due to noise) may not be detected, even if a parity bit is used.
### Answer
True
<file_sep>def calc_fib(m, n):
f = [0, 1]
for i in range(2, 61):
f.insert(i, (f[i-1] + f[i-2]) % 10)
rem1 = m % 60
quotient1 = (m - rem1) / 60
rem2 = n % 60
quotient2 = (n - rem2) / 60
sum1, sum2, sum3 = sum(f[rem1:]), sum(f[:rem2+1]), sum(f) * (quotient2 - (quotient1 + 1))
return int((sum1 + sum2 +sum3) % 10)
if __name__ == '__main__':
m, n = map(int, input().split())
print(calc_fib(m, n))
<file_sep># Quiz
### Que 1
You’re building a RESTful microservice. Which would be a valid data format for returning data to the client?
### Answer
All of the above.
### Que 2
You’re writing a service, and you need to handle a client sending you invalid data in the request. What should you return from the service?
### Answer
A 400 error code
### Que 3
Which below would violate 12-factor app best practices?
### Answer
Store configuration information in your source repository for easy versioning.
### Que 4
You’ve re-architected a monolithic web application so state is not stored in memory on the web servers, but in a database instead. This has caused slow performance when retrieving user sessions though. What might be the best way to fix this?
### Answer
Use a caching service like Redis or Memorystore.
<file_sep># Quiz
### Que 1
Currently, you are using Firestore to store information about products, reviews, and user sessions. You'd like to speed up data access in a simple, cost-effective way. What would you recommend?
### Answer
Cache the data using Memorystore.
### Que 2
You want to analyze sales trends. To help achieve this, you want to combine data from your on-premises Oracle database with Google Analytics data and your web server logs. Where might you store the data so it is both easy to query and cost-effective?
### Answer
BigQuery
### Que 3
You are a global financial services company with users all over the world. You need a database service that can provide low latency worldwide with strong consistency. Which service might you choose?
### Answer
Spanner
### Que 4
You need to store user preferences, product information, and reviews for a website you are building. There won't be a huge amount of data. What would be a simple, cost-effective, managed solution?
### Answer
Firestore
<file_sep>#include <iostream>
using namespace std;
int pisano_period(int m) {
int previous = 0;
int current = 1;
for (int i = 0; i < m * m; i++){
previous = current;
current = (previous + current) % m;
if (previous == 0 && current == 1)
return i + 1;
}
return 1;
}
int fibonacci_huge(int n, int m) {
int pp_index = pisano_period(m);
n = n % pp_index;
int previous = 0;
int current = 1;
for (int i = 0; i < n-1; i++){
previous = current;
current = previous + current;
}
return current % m;
}
int main(){
int m, n;
cin >> n, m;
cout << fibonacci_huge(n, m);
return 0;
}
<file_sep>## This module contains the assignment answers to the course 'Algorithmic Toolbox' provided by University of California San Diego & National Research University Higher School of Economics, part of IT Automation Specialization.
### Both the cpp and py scripts give the correct answer.
### I uploaded both because I practiced in both.
### The Dummy Scripts folder in each week contains the blank scripts provided by the course to complete for yourself.
### Only Week 1 and 2 are complete beacuse this course in ongoing.
### I'll keep updating as I go through
<file_sep># Week 4 Quiz
### Question 1
The format_address function separates out parts of the address string into new strings: house_number and street_name, and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the street name which may contain numbers, but never by themselves, and could be several words long. For example, "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function.
### Answer
```
def format_address(address_string):
list1 = address_string.split()
hno = list1[0]
sno = " ".join(list1[1:])
return f"house number {hno} on street named {sno}"
print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"
print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"
print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"
```
### Question 2
The highlight_word function changes the given word in a sentence to its upper-case version. For example, highlight_word("Have a nice day", "nice") returns "Have a NICE day". Can you write this function in just one line?
### Answer
```
def highlight_word(sentence, word):
return(sentence.replace(word,word.upper()))
print(highlight_word("Have a nice day", "nice"))
print(highlight_word("Shhh, don't be so loud!", "loud"))
print(highlight_word("Automating with Python is fun", "fun"))
```
### Question 3
A professor with two assistants, Jamie and Drew, wants an attendance list of the students, in the order that they arrived in the classroom. Drew was the first one to note which students arrived, and then Jamie took over. After the class, they each entered their lists into the computer and emailed them to the professor, who needs to combine them into one, in the order of each student's arrival. Jamie emailed a follow-up, saying that her list is in reverse order. Complete the steps to combine them into one list as follows: the contents of Drew's list, followed by Jamie's list in reverse order, to get an accurate list of the students as they arrived.
### Answer
```
def combine_lists(list1, list2):
new_list = list2
list1.reverse()
for i in list1:
new_list.append(i)
return new_list
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]
print(combine_lists(Jamies_list, Drews_list))
```
### Question 4
Use a list comprehension to create a list of squared numbers (n*n). The function receives the variables start and end, and returns a list of squares of consecutive numbers between start and end inclusively. For example, squares(2, 3) should return [4, 9].
### Answer
```
def squares(start, end):
return [int(n*n) for n in range(start,end+1)]
print(squares(2, 3)) # Should be [4, 9]
print(squares(1, 5)) # Should be [1, 4, 9, 16, 25]
print(squares(0, 10)) # Should be [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
```
### Question 5
Complete the code to iterate through the keys and values of the car_prices dictionary, printing out some information about each one.
### Answer
```
def car_listing(car_prices):
result = ""
for i in car_prices:
result += f"{i} costs {car_prices[i]} dollars" + "\n"
return result
print(car_listing({"<NAME>":19000, "<NAME>":55000, "<NAME>":13000, "<NAME>":24000}))
```
### Question 6
Taylor and Rory are hosting a party. They sent out invitations, and each one collected responses into dictionaries, with names of their friends and how many guests each friend is bringing. Each dictionary is a partial list, but Rory's list has more current information about the number of guests. Fill in the blanks to combine both dictionaries into one, with each friend listed only once, and the number of guests from Rory's dictionary taking precedence, if a name is included in both dictionaries. Then print the resulting dictionary.
### Answer
```
def combine_guests(guests1, guests2):
new_dict = {}
for i in guests1:
if i in guests2:
new_dict[i] = guests1[i]
else:
new_dict[i] = guests1[i]
for i in guests2:
if i not in new_dict:
new_dict[i] = guests2[i]
return new_dict
Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2, "Terry": 1, "Robert": 4}
Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha": 3, "Chris": 5}
print(combine_guests(Rorys_guests, Taylors_guests))
```
### Question 7
Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}.
### Answer
```
def count_letters(text):
list1 = []
for word in text:
if len(word) > 1:
for letter in word:
if letter.isalpha():
if letter.isupper():
list1.append(letter.lower())
else:
list1.append(letter)
else:
if word.isalpha():
if word.isupper():
list1.append(word.lower())
else:
list1.append(word)
list2 = list(dict.fromkeys(list1))
string = ""
temp = 0
for i in list2:
if temp > 0:
string += ", "
temp += 1
string += f"'{i}': {list1.count(i)}"
return "{" + string + "}"
print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}
print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
```
### Question 8
What do the following commands return when animal = "Hippopotamus"?
```
>>> print(animal[3:6])
>>> print(animal[-5])
>>> print(animal[10:])
```
### Answer
pop, t, us
### Question 9
What does the list "colors" contain after these commands are executed?
```
colors = ["red", "white", "blue"]
colors.insert(2, "yellow")
```
### Answer
['red', 'white', 'yellow', 'blue']
### Question 10
What do the following commands return?
```
host_addresses = {"router": "192.168.1.1", "localhost": "127.0.0.1", "google": "8.8.8.8"}
host_addresses.keys()
```
### Answer
['router', 'localhost', 'google']
<file_sep>TCP and IP are two separate computer network protocols.
IP is the part that obtains the address to which data is sent. TCP is responsible for data delivery once that IP address has been found.
It's possible to separate them, but there isn’t really a point in making a difference between TCP and IP. Because they're so often used together, “TCP/IP” and the “TCP/IP model” are now recognized terminology.
Think of it this way: The IP address is like the phone number assigned to your smartphone. TCP is all the technology that makes the phone ring, and that enables you to talk to someone on another phone. They are different from one another, but they are also meaningless without one another.
<file_sep># Quiz
### Que 1
Which statements are true about App Engine? Choose all that are true (2 correct answers).
### Answer
App Engine manages the hardware and networking infrastructure required to run your code.
It is possible for an App Engine application's daily billing to drop to zero.
### Que 2
Name 3 advantages of using the App Engine Flexible Environment over App Engine Standard. Choose all that are true (3 correct answers).
### Answer
You can install third-party binaries
Your application can write to local disk
You can SSH in to your application
### Que 3
Name 3 advantages of using the App Engine Standard Environment over App Engine Flexible. Choose all that are true (3 correct answers).
### Answer
Google provides and maintains runtime binaries
Billing can drop to zero if your application is idle
Scaling is finer-grained
### Que 4
You want to do business analytics and billing on a customer-facing API. Which GCP service should you choose?
### Answer
Apigee Edge
### Que 5
You want to support developers who are building services in GCP through API logging and monitoring. Which GCP service should you choose?
### Answer
Cloud Endpoints
### Que 6
You want to gradually decompose a pre-existing monolithic application, not implemented in GCP, into microservices. Which GCP service should you choose?
### Answer
Apigee Edge
<file_sep>## Assignment
### Code
```
void setup()
{
pinMode(9, OUTPUT);
pinMode(A5, INPUT);
}
void loop()
{
digitalWrite(9, LOW);
if (analogRead(A5)<300)
digitalWrite(9, HIGH);
else
digitalWrite(9, LOW);
}
```
### Circuit

<file_sep># Week 1 Quiz
## Questions with same question number are the ones that vary from one quiz to another!!
### Question 1
The R language is a dialect of which of the following programming languages?
### Answer
S
### Question 1
R was developed by statisticians working at
### Answer
The University of Auckland
### Question 2
The definition of free software consists of four freedoms (freedoms 0 through 3). Which of the following is NOT one of the freedoms that are part of the definition? Select all that apply.
### Answer
The freedom to sell the software for any price.
The freedom to restrict access to the source code for the software.
The freedom to prevent users from using the software for undesirable purposes.
### Question 3
In R the following are all atomic data types EXCEPT: (Select all that apply)
### Answer
`data frame, list, matrix, array, table`
### Question 4
If I execute the expression `x <- 4` in R, what is the class of the object x' as determined by the class()' function?
### Answer
numeric
### Question 5
What is the class of the object defined by `x <- c(4, TRUE)`?
### Answer
character
### Question 6
If I have two vectors `x <- c(1,3, 5)` and `y <- c(3, 2, 10)`, what is produced by the expression `rbind(x, y)`?
### Answer
a matrix with two rows and three columns
### Question 7
A key property of vectors in R is that
### Answer
elements of a vector all must be of the same class
### Question 8
Suppose I have a list defined as `x <- list(2, "a", "b", TRUE)`. What does `x[[2]]` give me? Select all that apply.
### Answer
a character vector containing the letter "a".
a character vector of length 1
### Question 9
Suppose I have a vector `x <- 1:4`and `y <- 2:3`. What is produced by the expression `x + y`?
### Answer
an integer vector with the values 3, 5, 5, 7.
### Question 9
Suppose I have a vector `x <- 1:4`and a vector `y <- 2`. What is produced by the expression `x + y`?
### Answer
a numeric vector with elements 3, 4, 5, 6.
### Question 10
Suppose I have a vector `x <- c(17, 14, 4, 5, 13, 12, 10)` and I want to set all elements of this vector that are greater than 10 to be equal to 4. What R code achieves this? Select all that apply.
### Answer
x[x > 10] <- 4
x[x >= 11] <- 4
### Question 11
Use the Week 1 Quiz Data Set to answer questions 11-20.
In the dataset provided for this Quiz, what are the column names of the dataset?
### Answer
`names(hw1_data)`
`Ozone, Solar.R, Wind, Temp, Month, Day`
### Question 12
Extract the first 2 rows of the data frame and print them to the console. What does the output look like?
### Answer
`hw1_data[c(1:2),]`
```
Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
```
### Question 13
How many observations (i.e. rows) are in this data frame?
### Answer
`nrow(hw1_data)` i.e. 153
### Question 14
Extract the last 2 rows of the data frame and print them to the console. What does the output look like?
### Answer
`hw1_data[c(nrow(hw1_data)-1, nrow(hw1_data)),]`
```
Ozone Solar.R Wind Temp Month Day
152 18 131 8.0 76 9 29
153 20 223 11.5 68 9 30
```
### Question 15
What is the value of Ozone in the 47th row?
### Answer
`hw1_data[47, c('Ozone')]` i.e.21
### Question 16
How many missing values are in the Ozone column of this data frame?
### Answer
`table(factor(is.na(c(hw1_data$Ozone))))[2]` i.e.37
### Question 17
What is the mean of the Ozone column in this dataset? Exclude missing values (coded as NA) from this calculation.
### Answer
`mean(hw1_data$Ozone[!is.na(hw1_data$Ozone)])` i.e. 42.12931
### Question 18
Extract the subset of rows of the data frame where Ozone values are above 31 and Temp values are above 90. What is the mean of Solar.R in this subset?
### Answer
`temp <- complete.cases(hw1_data$Ozone, hw1_data$Solar.R, hw1_data$Temp)
mean(hw1_data$Solar.R[temp & hw1_data$Ozone > 31 & hw1_data$Temp > 90])`
i.e. 212.8
### Question 19
What is the mean of "Temp" when "Month" is equal to 6?
### Answer
`temp <- complete.cases(hw1_data$Month, hw1_data$Temp)
mean(hw1_data$Temp[temp & hw1_data$Month == 6])`
i.e. 79.1
### Question 20
What was the maximum ozone value in the month of May (i.e. Month is equal to 5)?
### Answer
`max(hw1_data$Ozone[hw1_data$Month==5 & !is.na(hw1_data$Ozone)])` i.e. 115
<file_sep>temp = []
for i in range(3):
temp.append(int(input('Enter number:')))
print(sorted(temp))
<file_sep>## Quiz
### Question 1
My watch displays the current weather downloaded from the Internet. My watch is an IoT device.
### Answer
True
### Question 2
Which of the following could be an IoT device?
### Answer
a lamp
a couch
a pen
all of the above (Corect)
### Question 3
An IoT device can most easily be differentiated from a standard computer based on
### Answer
interface with the user and the world
### Question 4
The following trend is NOT related to the growth in IoT technology:
### Answer
Increase in computer monitor size over time.
### Question 5
IoT devices are likely to be more vulnerable to cyberattacks than standard computers.
### Answer
True
### Question 6
Which of these security approaches is feasible for most IoT devices?
### Answer
Regular installation of product firmware updates.
### Question 7
IoT devices gather private information about users. Which statement is most true about the security of that data?
### Answer
Users must rely on data-collecting agencies to securely store and transmit their data.
### Question 8
Although people are aware of the dangers of cyberattacks, they often do not understand the risks to IoT devices.
### Answer
True
<file_sep>## Assignment
### Project Title
S32K1 and MAC57D5xx
### Research two microcontrollers and provide information about them from their datasheets. There are several microcontroller manufacturers that you can investigate including Atmel, Microchip, Freescale, TI, etc. For each microcontroller, report the following information. (Be sure to include a link to an online reference where you found this information.)
### Clock frequency
### Bitwidth of the datapath
### Size of Flash memory
### Number of pins
### Does the microcontroller contain an Analog-to-Digital Converter? If so, how many bits of precision does it have?
1. S32K1
Clock Frequency: 112 MHz
Bit width: 32 bit
Flash Size: 2 MB
Number of pins: Up to 156
Analog to Digital Convertor: LQFP 144
https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/s32k-automotive-mcus/s32k1-microcontrollers-for-general-purpose:S32K
2. MAC57D5xx:
Clock Frequency: 4-40 MHz
Bit width: 32 Bit
Flash Size: 4 MB
Number of pins: 32
Analog to Digital Convertor: MBIST
https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/mac57d5xx-mcus/ultra-reliable-multi-core-arm-based-mcu-for-clusters-and-display-management:MAC57D5xx
### Research the Arduino and Raspberry Pi platforms.
### Indicate if there are operating systems which can be used on each platform. If there are, list those operating systems
### State whether the operating systems are open source or not.
1. Arduino:
No operating system
2. Raspberry Pi
Raspbian based on Linux kernel
Open Source
<file_sep>## Quiz
### Question 1
What is DHCP used for?
### Answer
It is a network protocol used to assign IP addresses.
### Question 2
What is an SSH server?
### Answer
A program which responds to incoming ssh requests
### Question 3
When an ssh client is invoked at the command-line with the “ssh” command, what other argument must be provided on the command line?
### Answer
A domain name or IP address to connect to
### Question 4
What command will reveal the IP address of your Raspberry Pi?
### Answer
ifconfig
### Question 5
What is a fair definition of the term "protocol"?
### Answer
A set of rules for communication
### Question 6
What does an IP address uniquely identify?
### Answer
A host communicating on the Internet
### Question 7
How big is a port TCP/UDP number?
### Answer
16 bits
### Question 8
The nslookup command will show the IP address corresponding to a given domain name.
### Answer
True
<file_sep># Quiz
### Que 1
True or False: In Google Cloud IAM: if a policy applied at the project level gives you Owner permissions, your access to an individual resource in that project might be restricted to View permission if someone applies a more restrictive policy directly to that resource.
### Answer
False
### Que 2
True or False: All Google Cloud Platform resources are associated with a project.
### Answer
True
### Que 3
Service accounts are used to provide which of the following? (Choose all that are correct. Choose 3 responses.)
### Answer
A way to restrict the actions a resource (such as a VM) can perform
Authentication between Google Cloud Platform services
A way to allow users to act with service account permissions
### Que 4
How do GCP customers and Google Cloud Platform divide responsibility for security?
### Answer
Google takes care of the lower parts of the stack, and customers are responsible for the higher parts.
### Que 5
Which of these values is globally unique, permanent, and unchangeable, but chosen by the customer?
### Answer
The project ID
### Que 6
Consider a single hierarchy of GCP resources. Which of these situations is possible? (Choose all that are correct. Choose 3 responses.)
### Answer
There is an organization node, and there is at least one folder.
There is no organization node, and there are no folders.
There is an organization node, and there are no folders.
### Que 7
What is the difference between IAM primitive roles and IAM predefined roles?
### Answer
Primitive roles affect all resources in a GCP project. Predefined roles apply to a particular service in a project.
### Que 8
Which statement is true about billing for solutions deployed using Cloud Marketplace (formerly known as Cloud Launcher)?
### Answer
You pay only for the underlying GCP resources you use, with the possible addition of extra fees for commercially licensed software.
<file_sep># Converting a wired Canon printer into wireless using a Raspberry Pi

## 1. Component Testing:
### The printer:
Test the printer with a normal computer that has Windows on it
Test the printer with a normal computer that has Linux on it
Test the printer on Raspberry Pi using CUPS software
Test the printer on Raspberry Pi using a shell command
### The server code:
Test the server code by receiving a simple message
Test the server code by receiving a file
### The client code:
Test the client code by sending a simple message
Test the client code by sending a file
### The LEDs:
Test each LED individually
Test LEDs together
## 2. Integration Testing:
### The printer & The server code:
Test the server code by receiving a file and printing it
### The server code & The client code:
Send a simple message from the client to the server
Send a file from the client to the server
### The LEDs & The server code:
Test LEDs on the server code
### The whole system:
Send a file from the client to the server, print the file, and turn LEDs into high and low
<file_sep>def EuclidGCD(a, b):
if b == 0:
return a
rem = a % b
return EuclidGCD(b, rem)
def lcm(a, b):
gcd = EuclidGCD(a, b)
num = a / gcd
return int(num*b)
if __name__ == '__main__':
a, b = map(int, input().split())
print(lcm(a, b))
<file_sep>#! /usr/bin/env python3
import os
import requests
import re
desc_path = os.path.expanduser('~') + '/supplier-data/descriptions/'
image_path = os.path.expanduser('~') + '/supplier-data/images/'
text_files = sorted(os.listdir(desc_path))
jpeg_images = sorted([image_name for image_name in os.listdir(
image_path) if '.jpeg' in image_name])
list_content = []
image_counter = 0
for file in text_files:
format = ['name', 'weight', 'description']
with open(desc_path + file, 'r') as f:
data = {}
contents = f.read().split("\n")[0:3]
contents[1] = int((re.search(r'\d+', contents[1])).group())
counter = 0
for content in contents:
data[format[counter]] = content
counter += 1
data['image_name'] = jpeg_images[image_counter]
list_content.append(data)
image_counter += 1
for item in list_content:
resp = requests.post('http://35.202.223.143/fruits/', json=item)
if resp.status_code != 201:
raise Exception('POST error status={}'.format(resp.status_code))
print('Created feedback ID: {}'.format(resp.json()["id"]))
<file_sep># Quiz
### Que 1
No resources in GCP can be used without being associated with...
### Answer
A project
### Que 2
A budget is set at $500 and an alert is set at 100%. What happens when the full amount is used?
### Answer
A notification email is sent to the Billing Administrator.
### Que 3
How do quotas protect GCP customers?
### Answer
By preventing uncontrolled consumption of resources.
<file_sep>## Quiz
### Question 1
What type of connector does an Arduino UNO not contain?
### Answer
HDMI Connector
### Question 2
How many microcontrollers are available for user programming on the Arduino UNO?
### Answer
1
### Question 3
The Arduino UNO contains a user-controllable LED connected to which pin?
### Answer
Digital pin 13
### Question 4
True or False: Analog pin A0 can be used as an analog output.
### Answer
False
### Question 5
Through what interface is the bootloader typically reprogrammed?
### Answer
ICSP
### Question 6
True or False: The schematic shows the connections between components and their placement on the board.
### Answer
False
### Question 7
What operation in the IDE triggers code to be written into the memory of the Arduino?
### Answer
Upload
### Question 8
Which statement about the serial monitor is NOT true?
### Answer
The serial monitor is a program that executes on the Arduino.
| bc77b4119832adf303644d8d0a6b92aa752b5f8e | [
"Markdown",
"Python",
"C",
"R",
"C++"
] | 141 | C++ | dhankhar313/Coursera-Courses | 1f5324d57172b7a1d0798d3c7b6f8cb4cf5e91ce | e20f3b57d115cb870b451e8f4d8914c2272cb2a2 | |
refs/heads/master | <file_sep>package com.miguan.otk.module.user;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.dsk.chain.bijection.Presenter;
import com.jude.exgridview.PieceViewGroup;
import com.jude.library.imageprovider.ImageProvider;
import com.jude.library.imageprovider.OnImageSelectListener;
import com.miguan.otk.model.ImageModel;
import com.miguan.otk.model.UserModel;
import com.miguan.otk.model.bean.Feedback;
import com.miguan.otk.model.services.ServicesResponse;
import com.miguan.otk.utils.LUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.functions.Func1;
/**
* Copyright (c) 2016/11/29. LiaoPeiKun Inc. All rights reserved.
*/
public class FeedbackPresenter extends Presenter<FeedbackActivity> implements OnImageSelectListener, PieceViewGroup.OnViewDeleteListener {
private List<Uri> mUris;
private ImageProvider mImageProvider;
@Override
protected void onCreate(FeedbackActivity view, Bundle saveState) {
super.onCreate(view, saveState);
mUris = new ArrayList<>();
mImageProvider = new ImageProvider(getView());
}
public void pickImage(int type) {
switch (type) {
case 0:
mImageProvider.getImageFromAlbum(this, 3 - mUris.size());
break;
case 1:
mImageProvider.getImageFromCamera(this);
}
}
public void save(int type, String contact, String content) {
if (mUris.size() > 0) {
Observable.from(mUris)
.map(uri -> new File(uri.getPath()))
.flatMap(new Func1<File, Observable<String>>() {
@Override
public Observable<String> call(File file) {
return ImageModel.getInstance().uploadImageAsync(file);
}
})
.toList()
.flatMap(new Func1<List<String>, Observable<Feedback>>() {
@Override
public Observable<Feedback> call(List<String> list) {
return UserModel.getInstance().saveFeedback(type, contact, content, getImages(list));
}
})
.unsafeSubscribe(new ServicesResponse<Feedback>() {
@Override
public void onNext(Feedback feedback) {
getView().finish();
LUtils.toast("谢谢反馈");
}
});
} else {
UserModel.getInstance().saveFeedback(type, contact, content, "")
.unsafeSubscribe(new ServicesResponse<Feedback>() {
@Override
public void onNext(Feedback feedback) {
getView().finish();
LUtils.toast("谢谢反馈");
}
});
}
}
@Override
public void onImageSelect() {
}
@Override
public void onImageLoaded(Uri uri) {
getView().dismissDialog();
getView().addImage(ImageProvider.readImageWithSize(uri, 200, 200));
mUris.add(uri);
}
@Override
public void onError() {
}
@Override
protected void onResult(int requestCode, int resultCode, Intent data) {
mImageProvider.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onViewDelete(int index) {
mUris.remove(index);
}
private String getImages(List<String> list) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
String image = list.get(i);
builder.append(image);
if (i != list.size() - 1) builder.append("|");
}
return builder.toString();
}
}
<file_sep>package com.miguan.otk.module.match;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataFragment;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Match;
import com.miguan.otk.module.news.NewsDetailPresenter;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/11/25. LiaoPeiKun Inc. All rights reserved.
*/
@RequiresPresenter(MatchRulesPresenter.class)
public class MatchRulesFragment extends BaseDataFragment<MatchRulesPresenter, Match> {
@Bind(R.id.tv_rule_mode_final)
TextView mTvFinal;
@Bind(R.id.tv_rule_mode_semifinal)
TextView mTvSemifinal;
@Bind(R.id.tv_rule_mode_battle)
TextView mTvBattle;
@Bind(R.id.tv_rule_mode)
TextView mTvMode;
@Bind(R.id.tv_rule_content)
TextView mTvContent;
@Bind(R.id.tv_rule_general)
TextView mTvGeneral;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.match_fragment_rules, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void setData(Match match) {
mTvFinal.setText(match.getFinal_battle_mode());
mTvSemifinal.setText(match.getSemifinal_battle_mode());
mTvBattle.setText(match.getBattle_mode());
mTvMode.setText(match.getPattern());
mTvContent.setText(match.getRule());
mTvGeneral.setOnClickListener(v -> NewsDetailPresenter.start(getActivity(), match.getArticle_id()));
}
}<file_sep>package com.miguan.otk.adapter.viewholder;
import android.app.Activity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.model.MatchModel;
import com.miguan.otk.model.bean.Mission;
import com.miguan.otk.model.services.ServicesResponse;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/23. LiaoPeiKun Inc. All rights reserved.
*/
public class MissionViewHolder extends BaseViewHolder<Mission> {
private static final int[] ICONS = new int[] {R.mipmap.ic_mission_enroll, R.mipmap.ic_mission_against, R.mipmap.ic_mission_winner};
@Bind(R.id.iv_mission_image)
ImageView mIvIcon;
@Bind(R.id.tv_mission_name)
TextView mTvName;
@Bind(R.id.tv_mission_desc)
TextView mTvDesc;
@Bind(R.id.btn_mission_dole)
Button mBtnDole;
public MissionViewHolder(ViewGroup parent) {
super(parent, R.layout.item_list_mission);
ButterKnife.bind(this, itemView);
}
@Override
public void setData(Mission data) {
mIvIcon.setImageResource(ICONS[getLayoutPosition() % ICONS.length]);
mTvName.setText(data.getTitle());
mTvDesc.setText(data.getComment() + " +" + data.getScore() + "撒币");
if (data.getStatus() == 0) {
mBtnDole.setText("领取奖励");
mBtnDole.setEnabled(true);
mBtnDole.setOnClickListener(v -> {
MatchModel.getInstance().doleMission(data.getMission_id()).unsafeSubscribe(new ServicesResponse<Mission>() {
@Override
public void onNext(Mission mission) {
mBtnDole.setEnabled(false);
mBtnDole.setText("已完成");
}
});
});
} else if (data.getStatus() == 1) {
mBtnDole.setText("已完成");
mBtnDole.setEnabled(false);
} else {
mBtnDole.setText("去完成");
mBtnDole.setEnabled(true);
mBtnDole.setOnClickListener(v -> ((Activity) getContext()).finish());
}
}
}
<file_sep>package com.miguan.otk.module.settings;
import com.dsk.chain.bijection.Presenter;
/**
* Copyright (c) 2016/12/21. LiaoPeiKun Inc. All rights reserved.
*/
public class AboutPresenter extends Presenter<AboutActivity> {
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Copyright (c) 2017/2/14. LiaoPeiKun Inc. All rights reserved.
*/
public class Screenshot implements Parcelable {
private String cpic1;
private String cpic2;
private String pic1;
private String pic2;
private String pic3;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.cpic1);
dest.writeString(this.cpic2);
dest.writeString(this.pic1);
dest.writeString(this.pic2);
dest.writeString(this.pic3);
}
public Screenshot() {
}
protected Screenshot(Parcel in) {
this.cpic1 = in.readString();
this.cpic2 = in.readString();
this.pic1 = in.readString();
this.pic2 = in.readString();
this.pic3 = in.readString();
}
public static final Creator<Screenshot> CREATOR = new Creator<Screenshot>() {
@Override
public Screenshot createFromParcel(Parcel source) {
return new Screenshot(source);
}
@Override
public Screenshot[] newArray(int size) {
return new Screenshot[size];
}
};
public String getCpic1() {
return cpic1;
}
public void setCpic1(String cpic1) {
this.cpic1 = cpic1;
}
public String getCpic2() {
return cpic2;
}
public void setCpic2(String cpic2) {
this.cpic2 = cpic2;
}
public String getPic1() {
return pic1;
}
public void setPic1(String pic1) {
this.pic1 = pic1;
}
public String getPic2() {
return pic2;
}
public void setPic2(String pic2) {
this.pic2 = pic2;
}
public String getPic3() {
return pic3;
}
public void setPic3(String pic3) {
this.pic3 = pic3;
}
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Copyright (c) 2017/1/11. LiaoPeiKun Inc. All rights reserved.
*/
public class Sign implements Parcelable {
private String[] cause;
private String score;
private String money;
private String currency;
private int istoday;
private int isqiandao;
private int baoxiangscore;
private String visits;
private String description;
public String[] getCause() {
return cause;
}
public void setCause(String[] cause) {
this.cause = cause;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public int getIstoday() {
return istoday;
}
public void setIstoday(int istoday) {
this.istoday = istoday;
}
public int getIsqiandao() {
return isqiandao;
}
public void setIsqiandao(int isqiandao) {
this.isqiandao = isqiandao;
}
public int getBaoxiangscore() {
return baoxiangscore;
}
public void setBaoxiangscore(int baoxiangscore) {
this.baoxiangscore = baoxiangscore;
}
public String getVisits() {
return visits;
}
public void setVisits(String visits) {
this.visits = visits;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(this.cause);
dest.writeString(this.score);
dest.writeString(this.money);
dest.writeString(this.currency);
dest.writeInt(this.istoday);
dest.writeInt(this.isqiandao);
dest.writeInt(this.baoxiangscore);
dest.writeString(this.visits);
dest.writeString(this.description);
}
public Sign() {
}
protected Sign(Parcel in) {
this.cause = in.createStringArray();
this.score = in.readString();
this.money = in.readString();
this.currency = in.readString();
this.istoday = in.readInt();
this.isqiandao = in.readInt();
this.baoxiangscore = in.readInt();
this.visits = in.readString();
this.description = in.readString();
}
public static final Creator<Sign> CREATOR = new Creator<Sign>() {
@Override
public Sign createFromParcel(Parcel source) {
return new Sign(source);
}
@Override
public Sign[] newArray(int size) {
return new Sign[size];
}
};
}
<file_sep>package com.miguan.otk.module.settings;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(SettingsPresenter.class)
public class SettingsActivity extends ChainBaseActivity<SettingsPresenter> {
@Bind(R.id.ly_setting_clear)
FrameLayout mLyClear;
@Bind(R.id.tv_setting_clear_cache)
TextView mTvCache;
@Bind(R.id.tv_setting_about_us)
TextView mTvAbout;
@Bind(R.id.btn_setting_logout)
Button mBtnLogout;
@Bind(R.id.ly_setting_update)
FrameLayout mLyUpdate;
@Bind(R.id.tv_setting_version)
TextView mTvVersion;
@Bind(R.id.tv_setting_push)
TextView mTvPush;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
setToolbarTitle(R.string.title_activity_settings);
ButterKnife.bind(this);
mLyClear.setOnClickListener(v -> showDialog());
mTvAbout.setOnClickListener(v -> startActivity(new Intent(this, AboutActivity.class)));
mLyUpdate.setOnClickListener(v -> getPresenter().checkUpdate());
mBtnLogout.setOnClickListener(v -> getPresenter().logout());
mTvPush.setOnClickListener(v -> startActivity(new Intent(this, SettingPushActivity.class)));
}
public void setData(String cache, String version) {
mTvCache.setText(cache);
mTvVersion.setText(String.format(getString(R.string.label_current_version), version));
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_clear_cache)
.setNegativeButton(R.string.btn_cancel, null)
.setPositiveButton(R.string.btn_ok, (dialog, which) -> getPresenter().clearCache())
.show();
}
}
<file_sep>package com.miguan.otk.module.match;
import android.os.Bundle;
import com.dsk.chain.expansion.list.BaseListActivityPresenter;
import com.miguan.otk.R;
import com.miguan.otk.model.MatchModel;
import com.miguan.otk.model.bean.User;
/**
* Copyright (c) 2016/12/22. LiaoPeiKun Inc. All rights reserved.
*/
public class CompetitorListPresenter extends BaseListActivityPresenter<CompetitorListActivity, User> {
private int mCompetitionID;
private int mType;
@Override
protected void onCreate(CompetitorListActivity view, Bundle saveState) {
super.onCreate(view, saveState);
mCompetitionID = getView().getIntent().getIntExtra("match_id", 0);
mType = getView().getIntent().getIntExtra("type", 1);
}
@Override
protected void onCreateView(CompetitorListActivity view) {
super.onCreateView(view);
if (mType == 1) getView().setToolbarTitle(R.string.title_activity_enroll);
else getView().setToolbarTitle(R.string.title_activity_bench);
onRefresh();
}
@Override
public void onRefresh() {
MatchModel.getInstance().getCompetitors(mCompetitionID, mType).unsafeSubscribe(getRefreshSubscriber());
}
}
<file_sep>package com.miguan.otk.module.user;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import com.miguan.otk.adapter.TitlePagerAdapter;
import com.miguan.otk.module.store.OrderListFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(MyOrderPresenter.class)
public class MyOrderActivity extends ChainBaseActivity<MyOrderPresenter> {
@Bind(R.id.tab_my_order)
TabLayout mTabLayout;
@Bind(R.id.pager_my_order)
ViewPager mPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_my_order);
setToolbarTitle(R.string.title_activity_my_order);
ButterKnife.bind(this);
mPager.setAdapter(new TitlePagerAdapter(this, R.array.tab_my_order, getList(), getSupportFragmentManager()));
mTabLayout.setupWithViewPager(mPager);
}
private List<Fragment> getList() {
List<Fragment> list = new ArrayList<>();
for (int i=0; i<2; i++) {
OrderListFragment fragment = new OrderListFragment();
list.add(fragment);
}
return list;
}
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Copyright (c) 2017/1/23. LiaoPeiKun Inc. All rights reserved.
*/
public class Hero implements Parcelable {
private String name;
private int index;
private boolean isCheck;
private boolean isBan;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeInt(this.index);
dest.writeByte(this.isCheck ? (byte) 1 : (byte) 0);
dest.writeByte(this.isBan ? (byte) 1 : (byte) 0);
}
public Hero() {
}
protected Hero(Parcel in) {
this.name = in.readString();
this.index = in.readInt();
this.isCheck = in.readByte() != 0;
this.isBan = in.readByte() != 0;
}
public static final Creator<Hero> CREATOR = new Creator<Hero>() {
@Override
public Hero createFromParcel(Parcel source) {
return new Hero(source);
}
@Override
public Hero[] newArray(int size) {
return new Hero[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean check) {
isCheck = check;
}
public boolean isBan() {
return isBan;
}
public void setBan(boolean ban) {
isBan = ban;
}
}
<file_sep>package com.miguan.otk.adapter.viewholder;
import android.net.Uri;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Comment;
import com.miguan.otk.utils.LUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/11/25. LiaoPeiKun Inc. All rights reserved.
*/
public class CommentViewHolder extends BaseViewHolder<Comment> {
@Bind(R.id.dv_comment_avatar)
SimpleDraweeView mDvAvatar;
@Bind(R.id.tv_comment_name)
TextView mTvName;
@Bind(R.id.tv_comment_content)
TextView mTvContent;
@Bind(R.id.tv_comment_date)
TextView mTvDate;
@Bind(R.id.tv_comment_like)
TextView mTvLike;
public CommentViewHolder(ViewGroup parent) {
super(parent, R.layout.item_list_comment);
ButterKnife.bind(this, itemView);
}
@Override
public void setData(Comment comment) {
mDvAvatar.setImageURI(Uri.parse(comment.getAvatar()));
mTvName.setText(comment.getUsername());
mTvContent.setText(comment.getContent());
mTvDate.setText(comment.getDate());
mTvLike.setText(comment.getLike_num());
mTvLike.setOnClickListener(v -> LUtils.toast("点赞"));
}
}
<file_sep>package com.miguan.otk.module.user;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.dsk.chain.expansion.list.BaseListActivityPresenter;
import com.miguan.otk.model.AddressModel;
import com.miguan.otk.model.bean.Area;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import rx.Observable;
/**
* Copyright (c) 2017/1/19. LiaoPeiKun Inc. All rights reserved.
*/
public class AreaPresenter extends BaseListActivityPresenter<AreaActivity, Area> {
private StringBuilder mName = new StringBuilder();
@Override
protected void onCreate(AreaActivity view, Bundle saveState) {
super.onCreate(view, saveState);
}
@Override
protected void onCreateView(AreaActivity view) {
super.onCreateView(view);
onRefresh();
getAdapter().setOnItemClickListener(position -> {
Area data = getAdapter().getItem(position);
mName.append(data.getName() + " ");
Intent intent = new Intent(getView(), AreaActivity.class);
if (data.getCity() != null) {
intent.putExtra("area_list", data.getCity());
getView().setIntent(intent);
onRefresh();
} else if (data.getArea() != null) {
intent.putExtra("area_list", data.getArea());
getView().setIntent(intent);
onRefresh();
} else {
getView().setResult(Activity.RESULT_OK, intent);
EventBus.getDefault().post(mName);
getView().finish();
}
});
}
@Override
public void onRefresh() {
List<Area> areaList = getView().getIntent().getParcelableArrayListExtra("area_list");
if (areaList != null) {
Observable.just(areaList).unsafeSubscribe(getRefreshSubscriber());
} else {
AddressModel.getInstance().getAreaList().unsafeSubscribe(getRefreshSubscriber());
}
}
}
<file_sep>package com.miguan.otk.module.main;
import com.dsk.chain.expansion.data.BaseDataFragmentPresenter;
import com.miguan.otk.model.bean.League;
/**
* Created by LPK on 2016/11/22.
*/
public class MainLeaguePresenter extends BaseDataFragmentPresenter<MainLeagueFragment, League> {
}
<file_sep>package com.miguan.otk.module.user;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataActivity;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Sign;
import com.miguan.otk.widget.SignedDateDecorator;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import java.util.Calendar;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(SignPresenter.class)
public class SignActivity extends BaseDataActivity<SignPresenter, Sign> {
@Bind(R.id.tv_sign_series_desc)
TextView mTvSeriesDesc;
@Bind(R.id.calendarView)
MaterialCalendarView mCalendarView;
@Bind(R.id.btn_sign_now)
Button mBtnSign;
@Bind(R.id.wv_sign_rules)
WebView mWvRules;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_sign_in);
setToolbarTitle(R.string.title_activity_sign_in);
ButterKnife.bind(this);
showSuccessDialog(null);
Calendar cal = Calendar.getInstance(); //获取当前日期
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
mCalendarView.setOnMonthChangedListener(getPresenter());
mCalendarView.state().edit()
.setMinimumDate(cal)
.setMaximumDate(Calendar.getInstance())
.commit();
}
@Override
public void setData(Sign sign) {
if (sign.getIsqiandao() == 1) {
mBtnSign.setEnabled(false);
mBtnSign.setText("已签到");
} else {
mBtnSign.setOnClickListener(v -> getPresenter().sign());
}
SpannableString span = new SpannableString(String.format(getString(R.string.text_sign_series_desc), 7 - sign.getIstoday()));
span.setSpan(new ForegroundColorSpan(Color.parseColor("#fab02e")), 13, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
mTvSeriesDesc.setText(span);
mWvRules.loadData(sign.getDescription(), "text/html; charset=utf-8", null);
setCalendar(sign);
}
public void setCalendar(Sign sign) {
if (sign.getCause() != null && sign.getCause().length > 0) {
mCalendarView.addDecorator(new SignedDateDecorator(this, sign.getCause()));
}
}
public void setBtnDisable() {
mBtnSign.setEnabled(false);
mBtnSign.setText("已签到");
}
public void showSuccessDialog(Sign sign) {
// String result = sign.getBaoxiangscore() != 0 ?
// String.format(getString(R.string.text_sign_series_bonus), sign.getBaoxiangscore()) : "";
View view = getLayoutInflater().inflate(R.layout.dialog_sign_success,
(ViewGroup) getWindow().getDecorView(), false);
new AlertDialog.Builder(this)
.setView(view)
.create()
.show();
}
}
<file_sep>package com.miguan.otk.wxapi;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
/**
* Copyright (c) 2017/3/2. LiaoPeiKun Inc. All rights reserved.
*/
public class ShareCallback implements UMShareListener {
@Override
public void onStart(SHARE_MEDIA share_media) {
}
@Override
public void onResult(SHARE_MEDIA share_media) {
}
@Override
public void onError(SHARE_MEDIA share_media, Throwable throwable) {
}
@Override
public void onCancel(SHARE_MEDIA share_media) {
}
}
<file_sep>package com.miguan.otk.model.services;
import com.miguan.otk.model.bean.Balance;
import com.miguan.otk.model.bean.Chatroom;
import com.miguan.otk.model.bean.Feedback;
import com.miguan.otk.model.bean.Game;
import com.miguan.otk.model.bean.Home;
import com.miguan.otk.model.bean.Match;
import com.miguan.otk.model.bean.Message;
import com.miguan.otk.model.bean.Mission;
import com.miguan.otk.model.bean.News;
import com.miguan.otk.model.bean.Battle;
import com.miguan.otk.model.bean.Schedule;
import com.miguan.otk.model.bean.Screenshot;
import com.miguan.otk.model.bean.Sign;
import com.miguan.otk.model.bean.Splash;
import com.miguan.otk.model.bean.User;
import com.miguan.otk.model.bean.Version;
import com.miguan.otk.model.bean.Withdraw;
import java.util.List;
import java.util.Map;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
public interface Services {
String BASE_URL = "http://api.beta.otkpk.com/v1/";
//////////////////用户相关/////////////////////
/**
* 用户登录
* @param username 用户名
* @param password 密码
* @return 是否成功
*/
@FormUrlEncoded
@POST("user/user/login")
Observable<User> login(
@Field("username") CharSequence username,
@Field("password") CharSequence password
);
/**
* 用户注册
*
* @param username 用户名
* @param password 密码
* @param mobile 手机
* @param captcha 验证码
* @return 结果
*/
@FormUrlEncoded
@POST("user/user/sign-up")
Observable<User> register(
@Field("username") CharSequence username,
@Field("mobile") CharSequence mobile,
@Field("captcha") CharSequence captcha,
@Field("password") CharSequence password
);
/**
* 发送注册验证码
* @param mobile 手机号
* @return 是否成功
*/
@FormUrlEncoded
@POST("user/user/captcha-register")
Observable<Boolean> sendCaptchaRegister(
@Field("mobile") CharSequence mobile
);
/**
* 发送重置密码验证码
* @param mobile 手机号
* @return 是否成功
*/
@FormUrlEncoded
@POST("user/user/captcha-reset")
Observable<Boolean> sendCaptchaReset(
@Field("mobile") CharSequence mobile
);
/**
* 其他验证码
* @param mobile 手机号
* @return 是否成功
*/
@FormUrlEncoded
@POST("user/user/captcha-update")
Observable<Boolean> sendCaptchaUpdate(
@Field("mobile") CharSequence mobile,
@Field("token") CharSequence token
);
/**
* 忘记密码
*
* @param newPwd 新密码
* @param mobile 手机
* @param captcha 验证码
* @return
*/
@FormUrlEncoded
@POST("user/user/reset-password")
Observable<Boolean> modifyPwd(
@Field("mobile") CharSequence mobile,
@Field("captcha") CharSequence captcha,
@Field("password") CharSequence newPwd
);
/**
* 个人中心
*
* @param token 登录令牌
* @return
*/
@FormUrlEncoded
@POST("user/center/index")
Observable<User> userInfo(
@Field("token") CharSequence token
);
/**
* 个人资料
*
* @param token 登录令牌
* @return
*/
@FormUrlEncoded
@POST("user/message/index")
Observable<User> userProfile(
@Field("token") CharSequence token
);
/**
* 个人资料修改
* token
* photo
* qq
* email
* actuality
* birthday
* province
* city
* sign
* @return
*/
@FormUrlEncoded
@POST("user/message/edit")
Observable<Boolean> modifyProfile(
@FieldMap Map<String, String> request
);
/**
* 立即签到
*
* @param token 登录令牌
* @return
*/
@FormUrlEncoded
@POST("user/sign/index")
Observable<Sign> sign(
@Field("token") CharSequence token
);
/**
* 签到信息
*
* @param token 登录令牌
* @return
*/
@FormUrlEncoded
@POST("user/sign/signdata")
Observable<Sign> signDetail(
@Field("token") CharSequence token,
@Field("month") String month,
@Field("year") Integer year
);
/**
* 参赛记录
*
* @param token 登录令牌
* @return
*/
@GET("user/banner/index")
Observable<List<Match>> myMatchList(
@Query("token") CharSequence token,
@Query("page") Integer page
);
/**
* 对战记录
*
* @param token 登录令牌
* @return
*/
@GET("user/banner/record")
Observable<List<Battle>> againstList(
@Query("token") CharSequence token,
@Query("page") Integer page
);
/**
* 余额明细
* @param type 余额类型 money-元宝 score-撒币
* @param token 登录令牌
* @param page 页数
* @return
*/
@GET("user/balance/{type}")
Observable<List<Balance>> balanceList(
@Path("type") String type,
@Query("token") CharSequence token,
@Query("page") Integer page
);
/**
* 提现记录首页
* @param token 登录令牌
* @return
*/
@GET("user/record/getcashrecord")
Observable<Withdraw> withdrawRecord(
@Query("token") CharSequence token
);
/**
* 提现记录列表
* @param token 登录令牌
* @param page 页数
* @return
*/
@GET("user/record/getcashrecord2")
Observable<List<Withdraw>> withdrawRecord(
@Query("token") CharSequence token,
@Query("page") Integer page
);
/**
* 提现记录列表
* @param token 登录令牌
* @param money 提现金额
* @return
*/
@GET("user/record/deposit")
Observable<Boolean> withdraw(
@Query("token") CharSequence token,
@Query("money") Integer money
);
/**
* 绑定支付宝
*/
@FormUrlEncoded
@POST("user/record/alipaybind")
Observable<Boolean> bindAlipay(
@Field("token") String token,
@Field("mobile") String mobile,
@Field("alipay_account") String account,
@Field("captcha") String captcha
);
/**
* 游戏账号列表
* @param token 登录令牌
* @return
*/
@FormUrlEncoded
@POST("user/gameaccount/gameinfo")
Observable<List<Game>> gameAccounts(
@Field("token") String token
);
/**
* 添加游戏账号
*/
@FormUrlEncoded
@POST("user/gameaccount/accountadd")
Observable<Boolean> addGameAccount(
@Field("token") String token,
@Field("game_name") String game_name,
@Field("game_account") String game_account
);
/**
* 编辑游戏账号
*/
@FormUrlEncoded
@POST("user/gameaccount/accountupdate")
Observable<Boolean> updateGameAccount(
@Field("token") String token,
@Field("id") int id,
@Field("game_account") String game_account
);
/**
* 消息分类最新一条
*/
@FormUrlEncoded
@POST("user/systemmessage/message")
Observable<List<Message>> getMessageDesc(
@Field("token") String token
);
/**
* 消息列表
*/
@FormUrlEncoded
@POST("user/systemmessage/system-message")
Observable<List<Message>> getMessageList(
@Field("token") String token,
@Field("type") Integer type,
@Field("page") Integer page
);
/**
* 吐槽一下
* @param token 登录令牌
* @param type 类型(0:产品建议、1:发现BUG、2:举报作弊、3:其他)
* @param contact 联系方式
* @param content 吐槽内容
* @param img 上传照片
* @param source 信息来源(来源 0:安卓 1:IOS)
* @return
*/
@FormUrlEncoded
@POST("user/feedback/feedback")
Observable<Feedback> feedback(
@Field("token") String token,
@Field("type") Integer type,
@Field("contact") String contact,
@Field("content") String content,
@Field("img") String img,
@Field("source") int source
);
////////////////////比赛相关//////////////////////
/**
* 比赛首页
*
* @param token 登录令牌 可选
* @return
*/
@GET("home/home/index")
Observable<Home> homeMatch(
@Query("token") String token
);
/**
* 赛事详情
*
* @param matchID 赛事ID
* @param token 登录令牌
* @return
*/
@FormUrlEncoded
@POST("competition/competition/index")
Observable<Match> matchDetail(
@Field("token") String token,
@Field("competition_id") int matchID
);
/**
* 赛事参与用户列表
*
* @param matchID 赛事ID
* @param type 参赛人员类型(1:正常,2:替补)
* @return
*/
@GET("competition/competition/competitors")
Observable<List<User>> competitors(
@Query("competition_id") int matchID,
@Query("type") int type
);
/**
* 赛事规则
*
* @param matchID 赛事ID
* @return
*/
@GET("competition/competition/rule")
Observable<Match> competitionRule(
@Query("competition_id") int matchID
);
/**
* 对战表
*
* @param matchID 赛事ID
* @param round 比赛第几轮(从0开始)
* @return
*/
@FormUrlEncoded
@POST("competition/competition/table")
Observable<Schedule> competitionSchedule(
@Field("competition_id") int matchID,
@Field("round") int round
);
/**
* 赛事报名
*
* @param matchID 赛事ID
* @param password 密码(选填)
* @param code 邀请码(选填)
* @return
*/
@FormUrlEncoded
@POST("competition/competition/join")
Observable<Battle> competitionEnter(
@Field("token") String token,
@Field("competition_id") int matchID,
@Field("password") String password,
@Field("invitation_code") String code
);
/**
* 对战页面
*
* @param battleID 赛事ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/index")
Observable<Battle> battleDetail(
@Field("token") String token,
@Field("battle_id") int battleID
);
/**
* 对战准备
*
* @param matchID 赛事ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/ready")
Observable<Battle> ready(
@Field("token") String token,
@Field("battle_id") int matchID
);
/**
* 对战pick
*
* @param battle_id 对战ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/pick")
Observable<Battle> pick(
@Field("token") String token,
@Field("battle_id") int battle_id,
@FieldMap() Map<String, Integer> carPics
);
/**
* 对战ban
*
* @param battleID 赛事ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/ban")
Observable<Battle> ban(
@Field("token") String token,
@Field("battle_id") int battleID,
@Field("ban") Integer ban
);
/**
* 对战提交结果
*
* @param battleID 赛事ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/record")
Observable<Battle> submitResult(
@Field("token") String token,
@Field("battle_id") Integer battleID,
@Field("role") Integer role
);
/**
* 重置对战结果
*
* @param battleID 赛事ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/unrecord")
Observable<Battle> resubmitResult(
@Field("token") String token,
@Field("battle_id") Integer battleID
);
/**
* 赛事签到
*
* @param matchID 赛事ID
* @return
*/
@FormUrlEncoded
@POST("competition/competition/joinsign")
Observable<Boolean> competitionSign(
@Field("token") String token,
@Field("competition_id") int matchID
);
/**
* 获取对战信息
*
* @param competitionID 赛事ID
* @return
*/
@FormUrlEncoded
@POST("competition/competition/battle")
Observable<Battle> battleID(
@Field("token") String token,
@Field("competition_id") int competitionID
);
/**
* 对战截图列表
*
* @param battleID 对战ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/uploadinfo")
Observable<Screenshot> battleUploadInfo(
@Field("token") String token,
@Field("battle_id") int battleID,
@Field("role") String role
);
/**
* 对战提交截图
*
* @param battleID 对战ID
* @return
*/
@FormUrlEncoded
@POST("competition/battle/upload")
Observable<Battle> battleUpload(
@Field("token") String token,
@Field("battle_id") int battleID,
@Field("kind") String kind,
@Field("photo") String photo
);
/**
* 获取聊天室ID
*
* @param room_type 房间类型(c:比赛房间,b:对战房间)
* @param id 对战ID或者比赛ID
* @return
*/
@FormUrlEncoded
@POST("competition/chat/room")
Observable<Chatroom> chatRoomID(
@Field("token") String token,
@Field("room_type") String room_type,
@Field("id") int id
);
////////////////////其他//////////////////////
/**
* 资讯列表
*
* @param type 文章类型 '1'=>'新闻','2'=>'行业','3'=>'攻略','4'=>'评测','5'=>'活动',
* @param page 当前页数
* @return
*/
@GET("article/article/article-list")
Observable<List<News>> newsList(
@Query("type") int type,
@Query("page") int page
);
/**
* 广告图
*
* @param type 广告图位置 read-splash-闪屏; read-opening-首页弹窗
* @param mobile 手机系统类型(1:android, 2:ios)
* @return
*/
@GET("system/system/{type}")
Observable<Splash> splash(
@Path("type") String type,
@Query("mobile") Integer mobile
);
/**
* 每日任务
*
* @param token 登录
* @return
*/
@FormUrlEncoded
@POST("user/task/task")
Observable<List<Mission>> missionList(
@Field("token") String token
);
/**
* 每日任务领取奖励
*
* @param token 登录
* @return
*/
@FormUrlEncoded
@POST("user/task/taskscore")
Observable<Mission> missionDole(
@Field("token") String token,
@Field("id") int missionID
);
/**
* 检测更新
*
* @param version 当前版本号
* @return
*/
@GET("system/system/version-upgrade")
Observable<Version> checkUpdate(
@Query("version") String version
);
}
<file_sep>KEYSTORE_FILE = keystore
KEYSTORE_PASSWORD = <PASSWORD>
KEY_ALIAS = otk
KEY_PASSWORD = <PASSWORD><file_sep>package com.miguan.otk.module.account;
import android.os.Bundle;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import butterknife.ButterKnife;
@RequiresPresenter(ModifyPwdPresenter.class)
public class ModifyPwdActivity extends ChainBaseActivity<ModifyPwdPresenter> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_modify_pwd);
setToolbarTitle(R.string.title_activity_modify_pwd);
ButterKnife.bind(this);
}
}
<file_sep>package com.miguan.otk.adapter.viewholder;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Message;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/26. LiaoPeiKun Inc. All rights reserved.
*/
public class MessageViewHolder extends BaseViewHolder<Message> {
@Bind(R.id.tv_message_date)
TextView mTvDate;
@Bind(R.id.tv_message_content)
TextView mTvContent;
public MessageViewHolder(ViewGroup parent) {
super(parent, R.layout.item_list_message);
ButterKnife.bind(this, itemView);
}
@Override
public void setData(Message data) {
mTvDate.setText(data.getCreate_time());
mTvContent.setText(data.getContent());
}
}
<file_sep>package com.miguan.otk.module.league;
import com.dsk.chain.bijection.Presenter;
/**
* Copyright (c) 2016/11/28. LiaoPeiKun Inc. All rights reserved.
*/
public class AddLeaguePresenter extends Presenter {
}
<file_sep>package com.miguan.otk.module.news;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.list.BaseListFragment;
import com.dsk.chain.expansion.list.ListConfig;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.miguan.otk.model.bean.News;
import com.miguan.otk.utils.LUtils;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
@RequiresPresenter(NewsListPresenter.class)
public class NewsListFragment extends BaseListFragment<NewsListPresenter, News> {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
getListView().setRecyclerPadding(0, LUtils.dp2px(5), 0, 0);
getListView().setClipToPadding(false);
getListView().setClipChildren(false);
return view;
}
@Override
public BaseViewHolder<News> createViewHolder(ViewGroup parent, int viewType) {
return viewType == 1 ? new NewsViewHolder(parent) : new NewsMultiViewHolder(parent);
}
@Override
public int getViewType(int position) {
News news = getPresenter().getAdapter().getItem(position);
return news.getImg().length == 1 ? 1 : 0;
}
@Override
public ListConfig getListConfig() {
SpaceDecoration itemDecoration = new SpaceDecoration(LUtils.dp2px(1));
itemDecoration.setPaddingStart(true);
return super.getListConfig().setItemDecoration(itemDecoration);
}
}
<file_sep>package com.miguan.otk.module.match;
import com.dsk.chain.expansion.list.BaseListActivityPresenter;
import com.miguan.otk.model.MatchModel;
import com.miguan.otk.model.bean.Mission;
/**
* Copyright (c) 2016/12/23. LiaoPeiKun Inc. All rights reserved.
*/
public class MissionListPresenter extends BaseListActivityPresenter<MissionListActivity, Mission> {
@Override
protected void onCreateView(MissionListActivity view) {
super.onCreateView(view);
onRefresh();
}
@Override
public void onRefresh() {
MatchModel.getInstance().getMissionList().unsafeSubscribe(getRefreshSubscriber());
}
}
<file_sep>package com.miguan.otk.module.user;
import android.app.Activity;
import android.os.Bundle;
import com.dsk.chain.bijection.Presenter;
import com.miguan.otk.model.UserModel;
import com.miguan.otk.model.bean.User;
import com.miguan.otk.model.services.ServicesResponse;
/**
* Copyright (c) 2017/1/10. LiaoPeiKun Inc. All rights reserved.
*/
public class ProfileModifyPresenter extends Presenter<ProfileModifyActivity> {
private User mUser;
@Override
protected void onCreate(ProfileModifyActivity view, Bundle saveState) {
super.onCreate(view, saveState);
mUser = getView().getIntent().getParcelableExtra("user");
}
public void submit(String key, String value) {
UserModel.getInstance().setProfile(key, value)
.unsafeSubscribe(new ServicesResponse<Boolean>() {
@Override
public void onNext(Boolean aBoolean) {
if (aBoolean) {
getView().setResult(Activity.RESULT_OK);
getView().finish();
}
}
});
}
}
<file_sep>package com.miguan.otk.module.battle;
import android.os.Bundle;
import com.dsk.chain.expansion.data.BaseDataActivityPresenter;
import com.miguan.otk.model.bean.Battle;
/**
* Copyright (c) 2017/1/3. LiaoPeiKun Inc. All rights reserved.
*/
public class ShotDetailPresenter extends BaseDataActivityPresenter<ShotDetailActivity, Battle> {
private Battle mBattle;
@Override
protected void onCreate(ShotDetailActivity view, Bundle saveState) {
super.onCreate(view, saveState);
mBattle = getView().getIntent().getParcelableExtra("battle");
}
@Override
protected void onCreateView(ShotDetailActivity view) {
super.onCreateView(view);
publishObject(mBattle);
}
}
<file_sep>package com.miguan.otk.module.battle;
import android.graphics.Color;
import android.view.ViewGroup;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.list.BaseListFragment;
import com.dsk.chain.expansion.list.ListConfig;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.miguan.otk.adapter.viewholder.BattleRecordViewHolder;
import com.miguan.otk.model.bean.Battle;
import com.miguan.otk.utils.LUtils;
/**
* Copyright (c) 2016/12/20. LiaoPeiKun Inc. All rights reserved.
*/
@RequiresPresenter(BattleRecordPresenter.class)
public class BattleRecordFragment extends BaseListFragment<BattleRecordPresenter, Battle> {
@Override
public BaseViewHolder<Battle> createViewHolder(ViewGroup parent, int viewType) {
return new BattleRecordViewHolder(parent);
}
@Override
public ListConfig getListConfig() {
DividerDecoration decoration = new DividerDecoration(Color.TRANSPARENT, LUtils.dp2px(8));
return super.getListConfig().setItemDecoration(decoration);
}
}
<file_sep>package com.miguan.otk.base;
import android.app.Application;
import com.dsk.chain.Chain;
import com.dsk.chain.model.ModelManager;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.miguan.otk.utils.LUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
/**
* Created by LPK on 2016/11/21.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
LUtils.initialize(this);
Fresco.initialize(this);
ModelManager.init(this);
Chain.setLifeCycleDelegateProvide(ActivityDelegate::new);
initShare();
PushAgent pushAgent = PushAgent.getInstance(this);
pushAgent.register(new IUmengRegisterCallback() {
@Override
public void onSuccess(String deviceToken) {
// 注册成功会返回device token
LUtils.log("token: " + deviceToken);
}
@Override
public void onFailure(String s, String s1) {
LUtils.log("failure: " + s + ", " + s1);
}
});
}
public void initShare() {
UMShareAPI.get(this);
Config.DEBUG = true;
PlatformConfig.setSinaWeibo("3724165953", "6c218cd5b1938037096aa8886409ba6a", "http://sns.whalecloud.com/sina2/callback");
PlatformConfig.setWeixin("wxfe7723ef510fe37f", "d13d6bdc14d5fe5ac6ffd2a9927a3adf");
PlatformConfig.setQQZone("1105939765", "EYDkf1MlqGDw0RPn");
}
}
<file_sep>package com.miguan.otk.model.local;
import com.miguan.otk.utils.LUtils;
/**
* Copyright (c) 2017/2/23. LiaoPeiKun Inc. All rights reserved.
*/
public class UserPreferences {
private static final String KEY_USER_ID = "user_id";
private static final String KEY_TOKEN ="token";
private static final String KEY_USER_NIM_TOKEN = "auth_key";
public static String getUserID() {
return getString(KEY_USER_ID);
}
public static String getToken() {
return getString(KEY_TOKEN);
}
public static String getNIMToken() {
return getString(KEY_USER_NIM_TOKEN);
}
public static void setUserID(String value) {
setString(KEY_USER_ID, value);
}
public static void setToken(String value) {
setString(KEY_TOKEN, value);
}
public static void setNIMToken(String value) {
setString(KEY_USER_NIM_TOKEN, value);
}
private static String getString(String key) {
return LUtils.getPreferences().getString(key, "").trim();
}
private static void setString(String key, String value) {
LUtils.getPreferences().edit().putString(key, value).apply();
}
}
<file_sep>package com.miguan.otk.module.account;
import com.dsk.chain.bijection.Presenter;
import com.miguan.otk.model.UserModel;
import com.miguan.otk.model.services.ServicesResponse;
import com.miguan.otk.utils.LUtils;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
public class ForgotPresenter extends Presenter<ForgotActivity> {
public void sendCaptcha(String mobile) {
UserModel.getInstance().forgotCaptcha(mobile).subscribe(new ServicesResponse<Boolean>());
}
public void changePwd(String mobile, String captcha, String newPwd) {
UserModel.getInstance().modifyPwd(mobile, captcha, newPwd).subscribe(new ServicesResponse<Boolean>() {
@Override
public void onNext(Boolean aBoolean) {
LUtils.getPreferences().edit().putString("token", "").apply();
getView().finish();
}
});
}
}
<file_sep>package com.miguan.otk.module.league;
import com.dsk.chain.expansion.data.BaseDataActivityPresenter;
/**
* Copyright (c) 2016/11/25. LiaoPeiKun Inc. All rights reserved.
*/
public class LeagueDetailPresenter extends BaseDataActivityPresenter {
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Copyright (c) 2017/2/22. LiaoPeiKun Inc. All rights reserved.
*/
public class Chatroom implements Parcelable {
private String room_id;
public String getRoom_id() {
return room_id;
}
public void setRoom_id(String room_id) {
this.room_id = room_id;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.room_id);
}
public Chatroom() {
}
protected Chatroom(Parcel in) {
this.room_id = in.readString();
}
public static final Creator<Chatroom> CREATOR = new Creator<Chatroom>() {
@Override
public Chatroom createFromParcel(Parcel source) {
return new Chatroom(source);
}
@Override
public Chatroom[] newArray(int size) {
return new Chatroom[size];
}
};
}
<file_sep>package com.miguan.otk.model.constant;
/**
* Copyright (c) 2017/3/6. LiaoPeiKun Inc. All rights reserved.
*/
public interface QQAction {
// 客服QQ(安娜)
String Service = "mqqwpa://im/chat?chat_type=wpa&uin=1655647371";
// 官方QQ群
String Group = "mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + "YTT9mPgKCC-LR_48OUvlQWF3dBpRSJ0j";
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by LPK on 2016/11/22.
*/
public class Match implements Parcelable {
private int competition_id;
private String title;
private String content;
private String start_time;
private String game_name;
private String game_img;
private String game_desc;
private String game_status;
private String game_time;
private int game_type;
private String game_all;
private int rank;
private int status;
/**
* 可参与人数
*/
private String competitors;
/**
* 已经参与人数
*/
private String count_competitor;
/**
* 可参与替补数
*/
private String substitute_competitors;
/**
* 已经参与替补数
*/
private String count_sub_competitor;
private int cost;
private String qq_group_url;
private String share_url;
/**
* 规则内容
*/
private String rule;
/**
* 半决赛前比赛模式
*/
private String battle_mode;
/**
* 决赛比赛模式
*/
private String final_battle_mode;
/**
* 半决赛比赛模式
*/
private String semifinal_battle_mode;
/**
* 通用赛事文章id
*/
private String article_id;
/**
* 游戏模式
*/
private String pattern;
private long reward_money;
private int reward_1;
private int reward_2;
private int reward_3_4;
private int reward_5_8;
private int reward_9_16;
private int reward_17_32;
private int reward_33_64;
private long reward_sb;
private int sb_reward_1;
private int sb_reward_2;
private int sb_reward_3_4;
private int sb_reward_5_8;
private int sb_reward_9_16;
private int sb_reward_17_32;
private int sb_reward_33_64;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.competition_id);
dest.writeString(this.title);
dest.writeString(this.content);
dest.writeString(this.start_time);
dest.writeString(this.game_name);
dest.writeString(this.game_img);
dest.writeString(this.game_desc);
dest.writeString(this.game_status);
dest.writeString(this.game_time);
dest.writeInt(this.game_type);
dest.writeString(this.game_all);
dest.writeInt(this.rank);
dest.writeInt(this.status);
dest.writeString(this.competitors);
dest.writeString(this.count_competitor);
dest.writeString(this.substitute_competitors);
dest.writeString(this.count_sub_competitor);
dest.writeInt(this.cost);
dest.writeString(this.qq_group_url);
dest.writeString(this.share_url);
dest.writeString(this.rule);
dest.writeString(this.battle_mode);
dest.writeString(this.final_battle_mode);
dest.writeString(this.semifinal_battle_mode);
dest.writeString(this.article_id);
dest.writeString(this.pattern);
dest.writeLong(this.reward_money);
dest.writeInt(this.reward_1);
dest.writeInt(this.reward_2);
dest.writeInt(this.reward_3_4);
dest.writeInt(this.reward_5_8);
dest.writeInt(this.reward_9_16);
dest.writeInt(this.reward_17_32);
dest.writeInt(this.reward_33_64);
dest.writeLong(this.reward_sb);
dest.writeInt(this.sb_reward_1);
dest.writeInt(this.sb_reward_2);
dest.writeInt(this.sb_reward_3_4);
dest.writeInt(this.sb_reward_5_8);
dest.writeInt(this.sb_reward_9_16);
dest.writeInt(this.sb_reward_17_32);
dest.writeInt(this.sb_reward_33_64);
}
public Match() {
}
protected Match(Parcel in) {
this.competition_id = in.readInt();
this.title = in.readString();
this.content = in.readString();
this.start_time = in.readString();
this.game_name = in.readString();
this.game_img = in.readString();
this.game_desc = in.readString();
this.game_status = in.readString();
this.game_time = in.readString();
this.game_type = in.readInt();
this.game_all = in.readString();
this.rank = in.readInt();
this.status = in.readInt();
this.competitors = in.readString();
this.count_competitor = in.readString();
this.substitute_competitors = in.readString();
this.count_sub_competitor = in.readString();
this.cost = in.readInt();
this.qq_group_url = in.readString();
this.share_url = in.readString();
this.rule = in.readString();
this.battle_mode = in.readString();
this.final_battle_mode = in.readString();
this.semifinal_battle_mode = in.readString();
this.article_id = in.readString();
this.pattern = in.readString();
this.reward_money = in.readLong();
this.reward_1 = in.readInt();
this.reward_2 = in.readInt();
this.reward_3_4 = in.readInt();
this.reward_5_8 = in.readInt();
this.reward_9_16 = in.readInt();
this.reward_17_32 = in.readInt();
this.reward_33_64 = in.readInt();
this.reward_sb = in.readLong();
this.sb_reward_1 = in.readInt();
this.sb_reward_2 = in.readInt();
this.sb_reward_3_4 = in.readInt();
this.sb_reward_5_8 = in.readInt();
this.sb_reward_9_16 = in.readInt();
this.sb_reward_17_32 = in.readInt();
this.sb_reward_33_64 = in.readInt();
}
public static final Creator<Match> CREATOR = new Creator<Match>() {
@Override
public Match createFromParcel(Parcel source) {
return new Match(source);
}
@Override
public Match[] newArray(int size) {
return new Match[size];
}
};
public int getCompetition_id() {
return competition_id;
}
public void setCompetition_id(int competition_id) {
this.competition_id = competition_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getStart_time() {
return start_time;
}
public void setStart_time(String start_time) {
this.start_time = start_time;
}
public String getGame_name() {
return game_name;
}
public void setGame_name(String game_name) {
this.game_name = game_name;
}
public String getGame_img() {
return game_img;
}
public void setGame_img(String game_img) {
this.game_img = game_img;
}
public String getGame_desc() {
return game_desc;
}
public void setGame_desc(String game_desc) {
this.game_desc = game_desc;
}
public String getGame_status() {
return game_status;
}
public void setGame_status(String game_status) {
this.game_status = game_status;
}
public String getGame_time() {
return game_time;
}
public void setGame_time(String game_time) {
this.game_time = game_time;
}
public int getGame_type() {
return game_type;
}
public void setGame_type(int game_type) {
this.game_type = game_type;
}
public String getGame_all() {
return game_all;
}
public void setGame_all(String game_all) {
this.game_all = game_all;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getCompetitors() {
return competitors;
}
public void setCompetitors(String competitors) {
this.competitors = competitors;
}
public String getCount_competitor() {
return count_competitor;
}
public void setCount_competitor(String count_competitor) {
this.count_competitor = count_competitor;
}
public String getSubstitute_competitors() {
return substitute_competitors;
}
public void setSubstitute_competitors(String substitute_competitors) {
this.substitute_competitors = substitute_competitors;
}
public String getCount_sub_competitor() {
return count_sub_competitor;
}
public void setCount_sub_competitor(String count_sub_competitor) {
this.count_sub_competitor = count_sub_competitor;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public String getQq_group_url() {
return qq_group_url;
}
public void setQq_group_url(String qq_group_url) {
this.qq_group_url = qq_group_url;
}
public String getShare_url() {
return share_url;
}
public void setShare_url(String share_url) {
this.share_url = share_url;
}
public String getRule() {
return rule;
}
public void setRule(String rule) {
this.rule = rule;
}
public String getBattle_mode() {
return battle_mode;
}
public void setBattle_mode(String battle_mode) {
this.battle_mode = battle_mode;
}
public String getFinal_battle_mode() {
return final_battle_mode;
}
public void setFinal_battle_mode(String final_battle_mode) {
this.final_battle_mode = final_battle_mode;
}
public String getSemifinal_battle_mode() {
return semifinal_battle_mode;
}
public void setSemifinal_battle_mode(String semifinal_battle_mode) {
this.semifinal_battle_mode = semifinal_battle_mode;
}
public String getArticle_id() {
return article_id;
}
public void setArticle_id(String article_id) {
this.article_id = article_id;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public long getReward_money() {
return reward_money;
}
public void setReward_money(long reward_money) {
this.reward_money = reward_money;
}
public int getReward_1() {
return reward_1;
}
public void setReward_1(int reward_1) {
this.reward_1 = reward_1;
}
public int getReward_2() {
return reward_2;
}
public void setReward_2(int reward_2) {
this.reward_2 = reward_2;
}
public int getReward_3_4() {
return reward_3_4;
}
public void setReward_3_4(int reward_3_4) {
this.reward_3_4 = reward_3_4;
}
public int getReward_5_8() {
return reward_5_8;
}
public void setReward_5_8(int reward_5_8) {
this.reward_5_8 = reward_5_8;
}
public int getReward_9_16() {
return reward_9_16;
}
public void setReward_9_16(int reward_9_16) {
this.reward_9_16 = reward_9_16;
}
public int getReward_17_32() {
return reward_17_32;
}
public void setReward_17_32(int reward_17_32) {
this.reward_17_32 = reward_17_32;
}
public int getReward_33_64() {
return reward_33_64;
}
public void setReward_33_64(int reward_33_64) {
this.reward_33_64 = reward_33_64;
}
public long getReward_sb() {
return reward_sb;
}
public void setReward_sb(long reward_sb) {
this.reward_sb = reward_sb;
}
public int getSb_reward_1() {
return sb_reward_1;
}
public void setSb_reward_1(int sb_reward_1) {
this.sb_reward_1 = sb_reward_1;
}
public int getSb_reward_2() {
return sb_reward_2;
}
public void setSb_reward_2(int sb_reward_2) {
this.sb_reward_2 = sb_reward_2;
}
public int getSb_reward_3_4() {
return sb_reward_3_4;
}
public void setSb_reward_3_4(int sb_reward_3_4) {
this.sb_reward_3_4 = sb_reward_3_4;
}
public int getSb_reward_5_8() {
return sb_reward_5_8;
}
public void setSb_reward_5_8(int sb_reward_5_8) {
this.sb_reward_5_8 = sb_reward_5_8;
}
public int getSb_reward_9_16() {
return sb_reward_9_16;
}
public void setSb_reward_9_16(int sb_reward_9_16) {
this.sb_reward_9_16 = sb_reward_9_16;
}
public int getSb_reward_17_32() {
return sb_reward_17_32;
}
public void setSb_reward_17_32(int sb_reward_17_32) {
this.sb_reward_17_32 = sb_reward_17_32;
}
public int getSb_reward_33_64() {
return sb_reward_33_64;
}
public void setSb_reward_33_64(int sb_reward_33_64) {
this.sb_reward_33_64 = sb_reward_33_64;
}
}
<file_sep>package com.miguan.otk.module.battle;
import android.os.Bundle;
import android.widget.Button;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataActivity;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Battle;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(BattlePresenter.class)
public class BattleActivity extends BaseDataActivity<BattlePresenter, Battle> {
private BattleHeaderPanel mHeaderPanel;
private BattleBodyPanel mBodyPanel;
@Bind(R.id.btn_battle_status_save)
Button mBtnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.match_activity_battle);
ButterKnife.bind(this);
}
@Override
public void setData(Battle battle) {
// if (battle.getBattle_status_user() == mCurrentStatus) return;
// mCurrentStatus = battle.getBattle_status_user();
setToolbarTitle(String.format(getString(R.string.label_battle_id), battle.getBattle_id()));
if (mHeaderPanel == null) {
mHeaderPanel = new BattleHeaderPanel(this, getContent(), battle);
} else {
mHeaderPanel.load(battle);
}
if (mBodyPanel == null) {
mBodyPanel = new BattleBodyPanel(this, getContent(), battle, getPresenter());
} else {
mBodyPanel.load(battle);
}
}
// public void setStatus(Battle battle) {
//
// mBtnCopy.setOnClickListener(v -> getPresenter().copyName(mTvOpponent.getText().toString().trim()));
// mTvContact.setOnClickListener(v -> startActivity(new Intent(this, ContactJudgeActivity.class)));
// mTvScreenshot.setOnClickListener(v -> getPresenter().toShot(battle));
// mTvChatroom.setOnClickListener(v -> ChatRoomActivityPresenter.start(this, battle.getBattle_id()));
//
// // 观战模式 用户类型为游客或未参赛
// if (battle.getUser_type() == 0 || battle.getUser_type() == 3) {
// setSimpleDesc();
// mBtnSave.setVisibility(View.GONE);
// mSection.setTitle("比赛阶段")
// .setDesc(String.format("%s阶段比赛正在进行中", battle.getBattle_times()));
// return;
// }
//
// // 等待对手生成
// if (battle.getBattle_status() == 0) {
// setSimpleDesc();
// mSection.setTitle("等待对手生成")
// .setDesc("您的对手还没有结束当前比赛,请耐心等待");
// mBtnSave.setVisibility(View.GONE);
// return;
// }
//
// // 准备阶段
// if (battle.getBattle_status() == 1) {
// setSimpleDesc();
// mSection.setTitle(R.string.text_prepare_phase)
// .setDesc(R.string.text_ready_desc);
// if ((battle.getUser_type() == 1 && battle.getBattle_status_user() == 2) || (battle.getUser_type() == 2 && battle.getBattle_status_user() == 3)) {
// mBtnSave.setText("已准备");
// mBtnSave.setEnabled(false);
// } else {
// mBtnSave.setText("准备");
// mBtnSave.setOnClickListener(v -> getPresenter().ready());
// }
// return;
// }
//
// // 结束
// if (battle.getBattle_status() == 5) {
// setSimpleDesc();
// mSection.setTitle(R.string.text_battle_ended)
// .setDesc(String.format(getString(R.string.text_battle_ended_desc), battle.getWinner_id() == battle.getA_user_id() ? battle.getA_username() : (battle.getWinner_id() == battle.getB_user_id() ? battle.getB_username() : "无结果")));
//
// if (battle.getWinner_id() == 1 && battle.getNext_battle_id() > 0) {
// mBtnSave.setText("进入下一轮");
// mBtnSave.setOnClickListener(v -> EventBus.getDefault().post(battle));
// } else if (battle.getIs_end()) {
// mBtnSave.setVisibility(View.GONE);
// } else {
// mBtnSave.setText("结束");
// mBtnSave.setOnClickListener(v -> {
// Intent intent = new Intent(this, BattleActivity.class);
// intent.putExtra("battle_id", battle.getBattle_id());
// startActivity(intent);
// });
// }
// return;
// }
//
// mLyOperation.setVisibility(View.VISIBLE);
// mTvOpponent.setText(battle.getUser_type() == 1 ? battle.getB_gameaccount() : battle.getA_gameaccount());
//
// // 比赛处于pick阶段
// if (battle.getBattle_status() == 2) {
// mSection.setVisibility(View.VISIBLE);
// mBtnSave.setVisibility(View.VISIBLE);
// if (battle.getBattle_status_user() == 5 && battle.getUser_type() == 1
// || battle.getBattle_status_user() == 6 && battle.getUser_type() == 2) {
// mSection.setTitle(R.string.text_pick_title)
// .setDesc(R.string.text_picked_desc)
// .setNotice("");
// mGridHeros.setVisibility(View.GONE);
// mBtnSave.setText("已提交");
// mBtnSave.setEnabled(false);
// } else {
// mGridHeros.setVisibility(View.VISIBLE);
//
// mSection.setTitle(R.string.text_pick_title)
// .setNotice(R.string.text_pick_notice)
// .setDesc(R.string.text_pick_desc);
//
// BanPickAdapter adapter = new BanPickAdapter(this, BanPickAdapter.MODE_PICK);
// adapter.setOnItemClickListener(hero -> {
// if (mSelected.contains(hero)) {
// mSelected.remove(hero);
// adapter.select(hero);
// } else {
// if ((battle.getBattle_mode().equals("BO3") && mSelected.size() >= 3)
// || (battle.getBattle_mode().equals("BO5") && mSelected.size() >= 4)) {
// LUtils.toast("已达最大数量");
// } else {
// mSelected.add(hero);
// adapter.select(hero);
// }
// }
// });
// mGridHeros.setAdapter(adapter);
//
// mBtnSave.setText("提交");
// mBtnSave.setEnabled(true);
// mBtnSave.setOnClickListener(v -> {
// if (mSelected.size() != 3) LUtils.toast("必须选择3个");
// else getPresenter().pick(mSelected);
// });
// }
// }
//
// // 比赛处于ban阶段
// if (battle.getBattle_status() == 3) {
//
// if (battle.getBattle_status_user() == 8 && battle.getUser_type() == 1 || battle.getBattle_status_user() == 9 && battle.getUser_type() == 2) {
// mSection.setTitle(R.string.text_ban_title)
// .setDesc(R.string.text_baned_desc);
// mGridHeros.setVisibility(View.GONE);
// mBtnSave.setText("已提交");
// mBtnSave.setEnabled(false);
// } else {
// mGridHeros.setVisibility(View.VISIBLE);
// mSection.setTitle(R.string.text_ban_title)
// .setNotice(R.string.text_ban_notice)
// .setDesc(R.string.text_ban_desc);
//
// List<Hero> list = new ArrayList<>();
// for (int i=1; i<(battle.getBattle_mode().equals("BO4") ? 5 : 4); i++) {
// Hero hero = new Hero();
// try {
// Method method = battle.getClass().getMethod("get" + (battle.getUser_type() == 2 ? "A" : "B") + "_car" + i);
// hero.setIndex(Integer.valueOf((String) method.invoke(battle)));
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// list.add(hero);
// }
//
// BanPickAdapter adapter = new BanPickAdapter(this, list, BanPickAdapter.MODE_BAN);
// adapter.setOnItemClickListener(index -> {
// if (mSelected.contains(index)) {
// mSelected.remove(index);
// adapter.select(index);
// } else {
// if (mSelected.size() >= 1) {
// LUtils.toast("只能Ban一个");
// } else {
// mSelected.add(index);
// adapter.select(index);
// }
// }
// });
//
// mGridHeros.removeAllViews();
// mGridHeros.setAdapter(adapter);
// mBtnSave.setText("提交");
// mBtnSave.setEnabled(true);
// mBtnSave.setOnClickListener(v -> {
// if (mSelected.size() != 1) LUtils.toast("必须Ban一个英雄");
// else getPresenter().ban(mSelected.get(0).getIndex());
// });
// }
// }
//
// // 进行中
// if (battle.getBattle_status() == 4) {
// if (battle.getBattle_status_user() == 11 && battle.getUser_type() == 1 || battle.getBattle_status_user() == 12 && battle.getUser_type() == 2) {
// mBtnSave.setText("已提交");
// mBtnSave.setEnabled(false);
// mGridHeros.setVisibility(View.GONE);
// mSection.setTitle("提交比赛结果")
// .setDesc(String.format(getString(R.string.text_submit_result_desc), battle.getBattle_times(), battle.getWinner_id() == battle.getA_user_id() ? battle.getA_username() : (battle.getWinner_id() == battle.getB_user_id() ? battle.getB_username() : "无结果")));
// } else {
// mSection.setVisibility(View.GONE);
// mGridHeros.setVisibility(View.GONE);
// mBtnSave.setVisibility(View.GONE);
// mLyResult.setVisibility(View.VISIBLE);
// mBtnImWin.setOnClickListener(v -> getPresenter().submit(battle.getUser_type() == 1 ? battle.getA_user_id() : battle.getB_user_id()));
// mBtnImLost.setOnClickListener(v -> getPresenter().submit(battle.getUser_type() == 2 ? battle.getA_user_id() : battle.getB_user_id()));
//
// if (!battle.getBattle_mode().equals("BO1")) {
// mLyOngoing.setVisibility(View.VISIBLE);
// mTvAAccount.setText(battle.getA_gameaccount());
// mTvBAccount.setText(battle.getB_gameaccount());
//
// List<Hero> listA = new ArrayList<>();
// List<Hero> listB = new ArrayList<>();
// for (int i=1; i<(battle.getBattle_mode().equals("BO4") ? 5 : 4); i++) {
// Hero heroA = new Hero();
// Hero heroB = new Hero();
// try {
// String carA = (String) battle.getClass().getMethod("getA_" + "car" + i).invoke(battle);
// heroA.setIndex(Integer.valueOf(carA));
// heroA.setBan(carA.equals(battle.getA_ban()));
//
// String carB = (String) battle.getClass().getMethod("getB_" + "car" + i).invoke(battle);
// heroB.setIndex(Integer.valueOf(carB));
// heroB.setBan(carB.equals(battle.getB_ban()));
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// listA.add(heroA);
// listB.add(heroB);
// }
//
// BanPickAdapter adapterA = new BanPickAdapter(this, listA, BanPickAdapter.MODE_SHOW);
// mGridABans.setAdapter(adapterA);
//
// BanPickAdapter adapterB = new BanPickAdapter(this, listB, BanPickAdapter.MODE_SHOW);
// mGridBBans.setAdapter(adapterB);
// }
//
// }
// }
//
// // 争议
// if (battle.getBattle_status() == 6) {
// mSection.setVisibility(View.VISIBLE);
// mGridHeros.setVisibility(View.GONE);
// mSection.setTitle("提交比赛结果").setDesc(R.string.text_controversial_desc);
// mBtnSave.setText("重新提交");
// mBtnSave.setOnClickListener(v -> getPresenter().resubmit());
// }
//
// }
}
<file_sep>package com.miguan.otk.model.constant;
import com.miguan.otk.R;
/**
* Copyright (c) 2017/3/7. LiaoPeiKun Inc. All rights reserved.
*/
public enum Hero {
WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false),
MAGE(R.mipmap.ic_mage, 2, "法师", false, false);
// WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false);
// WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false);
// WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false);
// WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false);
// WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false);
// WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false);
// WARRIOR(R.mipmap.ic_warrior, 1, "战士", false, false);
public final int mResID;
public final int mType;
public final String name;
public boolean mIsCheck;
public boolean mIsBan;
Hero(int resID, int type, String name, boolean isCheck, boolean isBan) {
mResID = resID;
mType = type;
this.name = name;
mIsCheck = isCheck;
mIsBan = isBan;
}
public int getType() {
return mType;
}
public boolean isBan() {
return mIsBan;
}
public void setBan(boolean isBan) {
this.mIsBan = isBan;
}
public boolean isCheck() {
return mIsCheck;
}
public void setCheck(boolean isCheck) {
this.mIsCheck = isCheck;
}
public static Hero getHeroFromType(int type) {
for (Hero hero : Hero.values()) {
if (type == hero.mType) return hero;
}
return WARRIOR;
}
}
<file_sep>package com.miguan.otk.module.account;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import com.miguan.otk.utils.LUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
@RequiresPresenter(LoginPresenter.class)
public class LoginActivity extends ChainBaseActivity<LoginPresenter> {
@Bind(R.id.iv_login_back)
ImageView mIvBack;
@Bind(R.id.et_login_username)
EditText mEtMobile;
@Bind(R.id.et_login_password)
EditText mEtPassword;
@Bind(R.id.tv_login_forgot)
TextView mTvForgot;
@Bind(R.id.tv_login_register)
TextView mTvRegister;
@Bind(R.id.btn_login_submit)
Button mBtnLogin;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_login);
setToolbarTitle(R.string.title_activity_login);
ButterKnife.bind(this);
mIvBack.setOnClickListener(v -> finish());
mTvForgot.setOnClickListener(v -> startActivity(new Intent(this, ForgotActivity.class)));
mTvRegister.setOnClickListener(v -> startActivity(new Intent(this, RegisterActivity.class)));
mBtnLogin.setOnClickListener(v -> checkInput());
// mTvQQ.setOnClickListener(v -> getPresenter().doOauthVerify(SHARE_MEDIA.QQ));
// mTvWx.setOnClickListener(v -> getPresenter().doOauthVerify(SHARE_MEDIA.WEIXIN));
}
private void checkInput() {
if (TextUtils.isEmpty(mEtMobile.getText())) {
LUtils.toast("用户名不能为空");
return;
}
if (TextUtils.isEmpty(mEtPassword.getText())) {
LUtils.toast("请输入密码");
return;
}
getPresenter().login(mEtMobile.getText().toString().trim(), mEtPassword.getText().toString().trim());
}
}
<file_sep>package com.miguan.otk.module.news;
import android.content.Intent;
import android.os.Bundle;
import com.dsk.chain.expansion.list.BaseListFragmentPresenter;
import com.miguan.otk.model.NewsModel;
import com.miguan.otk.model.bean.News;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
public class NewsListPresenter extends BaseListFragmentPresenter<NewsListFragment, News> {
private int mType = 1;
@Override
protected void onCreate(NewsListFragment view, Bundle saveState) {
super.onCreate(view, saveState);
if (view.getArguments() != null) {
mType = view.getArguments().getInt("type");
}
}
@Override
protected void onCreateView(NewsListFragment view) {
super.onCreateView(view);
onRefresh();
getAdapter().setOnItemClickListener(position -> {
News news = getAdapter().getItem(position);
Intent intent = new Intent(getView().getActivity(), NewsDetailActivity.class);
intent.putExtra("news", news);
getView().startActivity(intent);
});
}
@Override
public void onRefresh() {
NewsModel.getInstance().getNewsList(mType, 1).unsafeSubscribe(getRefreshSubscriber());
}
@Override
public void onLoadMore() {
NewsModel.getInstance().getNewsList(mType, getCurPage()).unsafeSubscribe(getMoreSubscriber());
}
}
<file_sep>package com.miguan.otk.module.match;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataActivity;
import com.miguan.otk.R;
import com.miguan.otk.adapter.TitlePagerAdapter;
import com.miguan.otk.model.bean.Match;
import com.miguan.otk.model.local.UserPreferences;
import com.miguan.otk.module.account.LoginActivity;
import com.miguan.otk.utils.DateUtils;
import com.miguan.otk.widget.StickyNavLayout;
import org.greenrobot.eventbus.EventBus;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(MatchDetailPresenter.class)
public class MatchDetailActivity extends BaseDataActivity<MatchDetailPresenter, Match> {
@Bind(R.id.sticky_match_detail)
StickyNavLayout mSticky;
@Bind(R.id.refresh_match_detail)
SwipeRefreshLayout mRefresh;
@Bind(R.id.tv_match_detail_title)
TextView mTvTitle;
@Bind(R.id.tv_match_detail_cost)
TextView mTvCost;
@Bind(R.id.tv_match_detail_status)
TextView mTvStatus;
@Bind(R.id.btn_match_detail_status)
Button mBtnStatus;
@Bind(R.id.id_stickynavlayout_tab)
TabLayout mTabLayout;
@Bind(R.id.id_stickynavlayout_viewpager)
ViewPager mPager;
private CountDownTimer mCountDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.match_activity_detail);
setToolbarTitle(R.string.title_activity_match_detail);
ButterKnife.bind(this);
mRefresh.setOnRefreshListener(getPresenter());
mSticky.setOnHeaderScrollListener((scrollY, isHidden) -> {
if (scrollY == 0) mRefresh.setEnabled(true);
else mRefresh.setEnabled(false);
});
mPager.setAdapter(new TitlePagerAdapter(this, R.array.tab_match_detail, getPresenter().getFragments(), getSupportFragmentManager()));
mTabLayout.setupWithViewPager(mPager);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() > 1) mBtnStatus.setVisibility(View.GONE);
else mBtnStatus.setVisibility(View.VISIBLE);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public void setData(Match match) {
if (mRefresh.isRefreshing()) mRefresh.setRefreshing(false);
EventBus.getDefault().post(match); // 更新底下四个fragment
mTvCost.setText(String.format(getString(R.string.label_match_id_cost), match.getCompetition_id(), match.getCost()));
SpannableString spanString = new SpannableString(match.getTitle());
if (match.getGame_type() > 0) {
spanString = new SpannableString(match.getTitle() + " img");
ImageSpan imageSpan = new ImageSpan(this, match.getGame_type() == 1 ? R.mipmap.ic_match_type_private : R.mipmap.ic_match_type_invite);
spanString.setSpan(imageSpan, (match.getTitle() + " ").length(), (match.getTitle() + " img").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mTvTitle.setText(spanString);
long time = Long.valueOf(match.getGame_time());
if (time > 0) {
mCountDownTimer = new CountDownTimer(time * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
String time = DateUtils.getFormatDay(millisUntilFinished);
String status = String.format(getString(R.string.label_match_state), match.getGame_desc(), time);
SpannableString spannableString = new SpannableString(status);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.colorAccent));
spannableString.setSpan(colorSpan, status.length() - time.length(), status.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
mTvStatus.setText(spannableString);
}
@Override
public void onFinish() {
getPresenter().onRefresh();
}
}.start();
} else {
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mTvStatus.setText("赛事状态:" + match.getGame_status());
}
mBtnStatus.setText(match.getGame_status());
switch (match.getStatus()) {
case 2 & 3: // 报名
mBtnStatus.setEnabled(true);
mBtnStatus.setOnClickListener(status -> checkEnroll(match.getCost(), match.getGame_type()));
break;
case 5: // 已报名
setEnrolled();
break;
case 6: // 签到
mBtnStatus.setEnabled(true);
mBtnStatus.setOnClickListener(v -> getPresenter().sign());
break;
case 7: // 已签到
setSigned();
break;
case 8 & 9: // 准备 & 正在进行
mBtnStatus.setEnabled(true);
mBtnStatus.setOnClickListener(v -> getPresenter().getBattleID());
break;
default:
mBtnStatus.setEnabled(false);
// mBtnStatus.setOnClickListener(v -> getPresenter().getBattleID());
break;
}
}
public void checkEnroll(int cost, int type) {
// TODO 检测是否有绑定游戏账号
if (TextUtils.isEmpty(UserPreferences.getToken())) {
startActivity(new Intent(this, LoginActivity.class));
} else if (cost > 0) {
new AlertDialog.Builder(this)
.setMessage(String.format("是否消耗%d撒币报名比赛", cost))
.setPositiveButton(getString(R.string.btn_ok), (dialog, which) -> checkType(type))
.setNegativeButton(getString(R.string.btn_cancel), null)
.show();
} else {
checkType(type);
}
}
public void checkType(int type) {
if (type == 0) {
getPresenter().enter(null, null);
} else {
View view = LayoutInflater.from(this).inflate(R.layout.dialog_enter_password, null);
AlertDialog dialog = new AlertDialog.Builder(MatchDetailActivity.this).setView(view).show();
TextView tvTitle = (TextView) view.findViewById(R.id.tv_dialog_enter_title);
EditText etPwd = (EditText) view.findViewById(R.id.et_dialog_enter_password);
Button btnOk = (Button) view.findViewById(R.id.btn_dialog_ok);
Button btnCancel = (Button) view.findViewById(R.id.btn_dialog_cancel);
tvTitle.setText(type == 1 ? R.string.text_match_input_password : R.string.text_match_input_invite);
etPwd.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
btnOk.setOnClickListener(v -> {
dialog.dismiss();
String pwd = etPwd.getText().toString().trim();
getPresenter().enter(type == 1 ? pwd : null, type == 2 ? pwd : null);
});
btnCancel.setOnClickListener(v -> dialog.dismiss());
}
}
public void setEnrolled() {
mBtnStatus.setText("已报名");
mBtnStatus.setEnabled(false);
}
public void setSigned() {
mBtnStatus.setText("已签到");
mBtnStatus.setEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_share, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
getPresenter().share();
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.miguan.otk.adapter.viewholder;
import android.content.Intent;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Schedule;
import com.miguan.otk.module.battle.BattleActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/23. LiaoPeiKun Inc. All rights reserved.
*/
public class ScheduleViewHolder extends BaseViewHolder<Schedule> {
@Bind(R.id.tv_schedule_a_score)
TextView mTvAScore;
@Bind(R.id.tv_schedule_a_username)
TextView mTvAUsername;
@Bind(R.id.tv_schedule_b_score)
TextView mTvBScore;
@Bind(R.id.tv_schedule_b_username)
TextView mTvBUsername;
public ScheduleViewHolder(ViewGroup parent) {
super(parent, R.layout.item_list_schedule);
ButterKnife.bind(this, itemView);
}
@Override
public void setData(Schedule schedule) {
int colorPrimary = getContext().getResources().getColor(R.color.colorPrimaryDark);
int colorWhite = getContext().getResources().getColor(R.color.white);
int textBody = getContext().getResources().getColor(R.color.textBody);
mTvAScore.setBackgroundColor(schedule.getA_score() > schedule.getB_score() ? colorPrimary : colorWhite);
mTvAScore.setTextColor(schedule.getA_score() > schedule.getB_score() ? colorWhite : textBody);
mTvBScore.setBackgroundColor(schedule.getB_score() > schedule.getA_score() ? colorPrimary : colorWhite);
mTvBScore.setTextColor(schedule.getB_score() > schedule.getA_score() ? colorWhite : textBody);
mTvAScore.setText(schedule.getA_score() + "");
mTvAUsername.setText(schedule.getA_name());
mTvBScore.setText(schedule.getB_score() + "");
mTvBUsername.setText(schedule.getB_name());
itemView.setOnClickListener(v -> {
Intent intent = new Intent(getContext(), BattleActivity.class);
intent.putExtra("battle_id", schedule.getBattle_id());
getContext().startActivity(intent);
});
}
}
<file_sep>package com.miguan.otk.module.account;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import com.miguan.otk.utils.LUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(ForgotPresenter.class)
public class ForgotActivity extends ChainBaseActivity<ForgotPresenter> {
@Bind(R.id.iv_forgot_back)
ImageView mIvBack;
@Bind(R.id.et_forgot_mobile)
EditText mEtMobile;
@Bind(R.id.et_forgot_new)
EditText mEtNewPwd;
@Bind(R.id.et_forgot_confirm)
EditText mEtConfirm;
@Bind(R.id.et_forgot_captcha)
EditText mEtCaptcha;
@Bind(R.id.btn_forgot_captcha)
Button mBtnCaptcha;
@Bind(R.id.btn_forgot_save)
Button mBtnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_forgot);
setToolbarTitle(R.string.title_activity_forgot);
ButterKnife.bind(this);
mIvBack.setOnClickListener(v -> finish());
mBtnCaptcha.setOnClickListener(v -> checkCaptcha());
mBtnSave.setOnClickListener(v -> checkInput());
}
private void checkCaptcha() {
if (mEtMobile.length() != 11) {
LUtils.toast("请输入正确的手机号码");
return;
}
getPresenter().sendCaptcha(mEtMobile.getText().toString().trim());
}
private void checkInput() {
if (mEtMobile.length() != 11) {
LUtils.toast("请输入正确的手机号码");
return;
}
if (TextUtils.isEmpty(mEtConfirm.getText())) {
LUtils.toast("请再次输入密码");
return;
}
if (!mEtConfirm.getText().toString().equals(mEtNewPwd.getText().toString())) {
LUtils.toast("再次密码输入不一致");
return;
}
getPresenter().changePwd(
mEtMobile.getText().toString().trim(),
mEtNewPwd.getText().toString().trim(),
mEtCaptcha.getText().toString().trim()
);
}
}
<file_sep>package com.miguan.otk.module.battle;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jude.exgridview.ExGridView;
import com.miguan.otk.R;
import com.miguan.otk.adapter.BPAdapter;
import com.miguan.otk.adapter.BanPickAdapter;
import com.miguan.otk.model.bean.Battle;
import com.miguan.otk.model.bean.Hero;
import com.miguan.otk.utils.LUtils;
import org.greenrobot.eventbus.EventBus;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2017/2/28. LiaoPeiKun Inc. All rights reserved.
*/
public class BattleBodyPanel {
@Bind(R.id.layout_battle_status)
LinearLayout mLyStatus;
@Bind(R.id.tv_battle_a_status)
TextView mTvAStatus;
@Bind(R.id.tv_battle_b_status)
TextView mTvBStatus;
@Bind(R.id.include_battle_operation)
View mLyOperation;
@Bind(R.id.tv_battling_opponent)
TextView mTvOpponent;
@Bind(R.id.btn_pick_copy)
Button mBtnCopy;
@Bind(R.id.tv_battling_judge)
TextView mTvContact;
@Bind(R.id.tv_battling_screenshot)
TextView mTvScreenshot;
@Bind(R.id.tv_battling_chatroom)
TextView mTvChatroom;
@Bind(R.id.layout_battle_desc)
LinearLayout mLyDesc;
@Bind(R.id.tv_battle_status_title)
TextView mTvTitle;
@Bind(R.id.tv_battle_status_notice)
TextView mTvNotice;
@Bind(R.id.tv_battle_status_desc)
TextView mTvDesc;
@Bind(R.id.grid_battling_list)
ExGridView mGridHeros;
@Bind(R.id.layout_battling_ongoing)
LinearLayout mLyOngoing;
@Bind(R.id.tv_battling_a_account)
TextView mTvAAccount;
@Bind(R.id.grid_battling_a_bans)
ExGridView mGridABans;
@Bind(R.id.tv_battling_b_account)
TextView mTvBAccount;
@Bind(R.id.grid_battling_b_bans)
ExGridView mGridBBans;
@Bind(R.id.btn_battle_status_save)
Button mBtnSave;
@Bind(R.id.ly_battling_submit_result)
LinearLayout mLyResult;
@Bind(R.id.btn_battling_im_win)
Button mBtnImWin;
@Bind(R.id.btn_battling_im_lost)
Button mBtnImLost;
private List<Hero> mSelected = new ArrayList<>();
private Activity mActivity;
private Battle mBattle;
private BattleProxy mProxy;
public BattleBodyPanel(Activity activity, View view, Battle battle, BattleProxy proxy) {
mActivity = activity;
mProxy = proxy;
ButterKnife.bind(this, view);
load(battle);
}
public void load(Battle battle) {
if (mBattle != null && mBattle.getBattle_status_user() == battle.getBattle_status_user()) {
return;
}
mBattle = battle;
hideAllLayout();
if (battle.getUser_type() == 0 || battle.getUser_type() == 3) { // 观战模式 用户类型为游客或未参赛
setDescText("比赛阶段", String.format("%s阶段比赛正在进行中", battle.getBattle_times()), "");
} else if (battle.getBattle_status() == 0) { // 等待对手生成
setDescText("等待对手生成", "您的对手还没有结束当前比赛,请耐心等待", "");
} else if (battle.getBattle_status() == 1) { // 准备阶段
setUserStatus();
setDescText("准备阶段", "点击“准备”按钮进入比赛,准备截断结束之后必须互相添加对手,同事在网页聊天室、游戏里说明是否进行卡组选择界面的截图", "");
mBtnSave.setVisibility(View.VISIBLE);
if ((battle.getUser_type() == 1 && battle.getBattle_status_user() == 2) || (battle.getUser_type() == 2 && battle.getBattle_status_user() == 3)) {
mBtnSave.setText("已准备");
mBtnSave.setEnabled(false);
} else {
mBtnSave.setText("准备");
mBtnSave.setOnClickListener(v -> mProxy.ready());
}
} else if (battle.getBattle_status() == 2) { // 比赛处于pick阶段
setOperation();
mSelected.clear();
if (battle.getBattle_status_user() == 5 && battle.getUser_type() == 1
|| battle.getBattle_status_user() == 6 && battle.getUser_type() == 2) {
setDescText(R.string.text_battle_pick_title, R.string.text_battle_picked_desc, 0);
setButtonDisable();
} else {
setDescText(
R.string.text_battle_pick_title,
R.string.text_battle_pick_desc,
R.string.text_battle_pick_notice
);
setPick();
}
} else if (battle.getBattle_status() == 3) { // 比赛处于ban阶段
setOperation();
mSelected.clear();
if (battle.getBattle_status_user() == 8 && battle.getUser_type() == 1 || battle.getBattle_status_user() == 9 && battle.getUser_type() == 2) {
setDescText(R.string.text_battle_ban_title, R.string.text_battle_baned_desc, 0);
setButtonDisable();
} else {
setDescText(
R.string.text_battle_ban_title,
R.string.text_battle_ban_desc,
R.string.text_battle_ban_notice
);
setBan();
}
} else if (battle.getBattle_status() == 4) { // 进行中
setOperation();
mSelected.clear();
if (battle.getBattle_status_user() == 11 && battle.getUser_type() == 1 || battle.getBattle_status_user() == 12 && battle.getUser_type() == 2) {
mLyDesc.setVisibility(View.VISIBLE);
mTvTitle.setText(R.string.text_battle_submit_result);
mTvDesc.setText(getSubmitResult());
setButtonDisable();
} else {
setBPList();
setSubmitButton();
}
} else if (battle.getBattle_status() == 5) { // 结束
setUserStatus();
setDescText("比赛结束", getResult(), "");
if (battle.getWinner_id() == 1 && battle.getNext_battle_id() > 0) {
mBtnSave.setText("进入下一轮");
mBtnSave.setOnClickListener(v -> EventBus.getDefault().post(battle));
} else if (battle.getIs_end()) {
mBtnSave.setVisibility(View.GONE);
} else {
mBtnSave.setText("结束");
mBtnSave.setOnClickListener(v -> {
Intent intent = new Intent(mActivity, BattleActivity.class);
intent.putExtra("battle_id", battle.getBattle_id());
mActivity.startActivity(intent);
});
}
} else if (battle.getBattle_status() == 6) { // 争议
setOperation();
setDescText(R.string.text_battle_submit_result, R.string.text_battle_controversial_desc, 0);
mBtnSave.setVisibility(View.VISIBLE);
mBtnSave.setEnabled(true);
mBtnSave.setText("重新提交");
mBtnSave.setOnClickListener(v -> mProxy.cancelResult());
}
}
// 设置用户状态
private void setUserStatus() {
mLyStatus.setVisibility(View.VISIBLE);
mTvAStatus.setText(getUserStatusText(mBattle.getA_status()));
mTvBStatus.setText(getUserStatusText(mBattle.getB_status()));
}
private void setOperation() {
mLyOperation.setVisibility(View.VISIBLE);
mTvOpponent.setText(mBattle.getUser_type() == 1 ? mBattle.getB_gameaccount() : mBattle.getA_gameaccount());
mBtnCopy.setOnClickListener(v -> copyName(mTvOpponent.getText().toString().trim()));
mTvContact.setOnClickListener(v -> mActivity.startActivity(new Intent(mActivity, ContactJudgeActivity.class)));
mTvScreenshot.setOnClickListener(v -> toShot(mBattle));
mTvChatroom.setOnClickListener(v -> {
String qq = mBattle.getUser_type() == 1 ? mBattle.getB_qq() : mBattle.getA_qq();
if (TextUtils.isEmpty(qq)) {
LUtils.toast("对方未设置QQ");
} else {
Intent intent = new Intent();
intent.setData(Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + qq));
try {
mActivity.startActivity(intent);
} catch (Exception e) {
LUtils.toast("未安装手Q或安装的版本不支持");
}
}
});
}
// 显示Pick界面
private void setPick() {
mGridHeros.setVisibility(View.VISIBLE);
mBtnSave.setVisibility(View.VISIBLE);
BanPickAdapter adapter = new BanPickAdapter(mActivity);
adapter.setOnItemClickListener(hero -> {
if (mSelected.contains(hero)) {
mSelected.remove(hero);
adapter.select(hero);
} else {
if ((mBattle.getBattle_mode().equals("BO3") && mSelected.size() >= 3)
|| (mBattle.getBattle_mode().equals("BO5") && mSelected.size() >= 4)) {
LUtils.toast("已达最大数量");
} else {
mSelected.add(hero);
adapter.select(hero);
}
}
});
BPAdapter bpAdapter = new BPAdapter(mActivity);
mGridHeros.setAdapter(adapter);
mBtnSave.setText("提交");
mBtnSave.setEnabled(true);
mBtnSave.setOnClickListener(v -> {
int count = mBattle.getBattle_mode().equals("BO5") ? 4 : 3;
if (mSelected.size() != count) LUtils.toast("必须选择" + count + "个");
else mProxy.pick(mSelected);
});
}
// 设置Ban界面
private void setBan() {
mGridHeros.setVisibility(View.VISIBLE);
mBtnSave.setVisibility(View.VISIBLE);
List<Hero> list = new ArrayList<>();
for (int i = 1; i < (mBattle.getBattle_mode().equals("BO5") ? 5 : 4); i++) {
Hero hero = new Hero();
try {
Method method = mBattle.getClass().getMethod("get" + (mBattle.getUser_type() == 2 ? "A" : "B") + "_car" + i);
int type = Integer.valueOf((String) method.invoke(mBattle));
hero.setIndex(type);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
list.add(hero);
}
BanPickAdapter adapter = new BanPickAdapter(mActivity, list, BanPickAdapter.MODE_BAN);
adapter.setOnItemClickListener(hero -> {
if (mSelected.contains(hero)) {
mSelected.remove(hero);
adapter.select(hero);
} else {
if (mSelected.size() >= 1) {
LUtils.toast("只能Ban一个");
} else {
mSelected.add(hero);
adapter.select(hero);
}
}
});
mGridHeros.removeAllViews();
mGridHeros.setAdapter(adapter);
mBtnSave.setText("提交");
mBtnSave.setEnabled(true);
mBtnSave.setOnClickListener(v -> {
if (mSelected.size() != 1) LUtils.toast("必须Ban一个英雄");
else mProxy.ban(mSelected.get(0).getIndex());
});
}
// 设置按钮不可用
private void setButtonDisable() {
mBtnSave.setVisibility(View.VISIBLE);
mBtnSave.setText("已提交");
mBtnSave.setEnabled(false);
}
// 设置提交结果按钮
private void setSubmitButton() {
mBtnSave.setVisibility(View.GONE);
mLyResult.setVisibility(View.VISIBLE);
mBtnImWin.setOnClickListener(v -> showSubmitResultDialog(mBtnImWin.getText().toString().trim(), mBattle.getUser_type() == 1 ? mBattle.getA_user_id() : mBattle.getB_user_id()));
mBtnImLost.setOnClickListener(v -> showSubmitResultDialog(mBtnImLost.getText().toString().trim(), mBattle.getUser_type() == 2 ? mBattle.getA_user_id() : mBattle.getB_user_id()));
}
// 显示两个用户BP列表
private void setBPList() {
mLyOngoing.setVisibility(View.VISIBLE);
if (!mBattle.getBattle_mode().equals("BO1")) {
mTvAAccount.setText(mBattle.getA_gameaccount());
mTvBAccount.setText(mBattle.getB_gameaccount());
List<Hero> listA = new ArrayList<>();
List<Hero> listB = new ArrayList<>();
for (int i = 1; i < (mBattle.getBattle_mode().equals("BO5") ? 5 : 4); i++) {
Hero heroA = new Hero();
Hero heroB = new Hero();
try {
String carA = (String) mBattle.getClass().getMethod("getA_" + "car" + i).invoke(mBattle);
heroA.setIndex(Integer.valueOf(carA));
heroA.setBan(carA.equals(mBattle.getA_ban()));
String carB = (String) mBattle.getClass().getMethod("getB_" + "car" + i).invoke(mBattle);
heroB.setIndex(Integer.valueOf(carB));
heroB.setBan(carB.equals(mBattle.getB_ban()));
// com.miguan.otk.model.constant.Hero hero = com.miguan.otk.model.constant.Hero.getHeroFromType(Integer.valueOf(carA));
// hero.setIsCheck(carA.equals(mBattle.getA_ban()));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
listA.add(heroA);
listB.add(heroB);
}
BanPickAdapter adapterA = new BanPickAdapter(mActivity, listA, BanPickAdapter.MODE_SHOW);
mGridABans.removeAllViews();
mGridABans.setAdapter(adapterA);
BanPickAdapter adapterB = new BanPickAdapter(mActivity, listB, BanPickAdapter.MODE_SHOW);
mGridBBans.removeAllViews();
mGridBBans.setAdapter(adapterB);
}
}
// 设置描述文本
private void setDescText(int titleRes, int descRes, int noticeRes) {
mLyDesc.setVisibility(View.VISIBLE);
mTvTitle.setText(mActivity.getString(titleRes));
mTvDesc.setText(mActivity.getString(descRes));
if (noticeRes > 0) {
mTvNotice.setVisibility(View.VISIBLE);
mTvNotice.setText(mActivity.getString(noticeRes));
} else {
mTvNotice.setVisibility(View.GONE);
}
}
// 设置描述文本
private void setDescText(String title, String desc, String notice) {
mLyDesc.setVisibility(View.VISIBLE);
mTvTitle.setText(title);
mTvDesc.setText(desc);
if (TextUtils.isEmpty(notice)) {
mTvNotice.setVisibility(View.GONE);
} else {
mTvNotice.setVisibility(View.VISIBLE);
mTvNotice.setText(notice);
}
}
// 隐藏所有布局
private void hideAllLayout() {
mLyStatus.setVisibility(View.GONE);
mLyOperation.setVisibility(View.GONE);
mLyDesc.setVisibility(View.GONE);
mGridHeros.setVisibility(View.GONE);
mLyOngoing.setVisibility(View.GONE);
mLyResult.setVisibility(View.GONE);
mBtnSave.setVisibility(View.GONE);
}
// 获取用户状态
private String getUserStatusText(String userStatus) {
if (TextUtils.isEmpty(userStatus)) return mBattle.getBattle_status() == 1 ? "未准备" : "失败";
if (userStatus.equals("准备")) return "已准备";
return userStatus;
}
// 获取提交结果
private String getSubmitResult() {
String result = mBattle.getUser_type() == 1 ? mBattle.getA_battle_record() : mBattle.getB_battle_record();
String username = result.equals("a") ? mBattle.getA_username() : mBattle.getB_username();
return String.format(mActivity.getString(R.string.text_battle_submit_result_desc), mBattle.getBattle_times(), username);
}
// 获取比赛结果
private String getResult() {
if (mBattle.getWinner_id() <= 0) return "双方比赛超时没有人获得胜利";
return String.format(mActivity.getString(R.string.text_battle_ended_desc), mBattle.getWinner_id() == mBattle.getA_user_id() ? mBattle.getA_username() : mBattle.getB_username());
}
// 显示提交结果确认窗口
private void showSubmitResultDialog(String msg, int winnerID) {
new AlertDialog.Builder(mActivity)
.setTitle("是否提交比赛结果")
.setMessage(msg)
.setNegativeButton(R.string.btn_cancel, null)
.setPositiveButton(R.string.btn_ok, (dialog, which) -> mProxy.submitResult(winnerID))
.show();
}
public void copyName(String name) {
ClipboardManager cm = (ClipboardManager) (mActivity).getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText(null, name));
LUtils.toast("复制成功");
}
public void toShot(Battle battle) {
Intent intent = new Intent(mActivity, ShotDetailActivity.class);
intent.putExtra("battle", battle);
mActivity.startActivity(intent);
}
}
<file_sep>package com.miguan.otk.module.battle;
import android.content.Intent;
import android.net.Uri;
import com.dsk.chain.bijection.Presenter;
import com.miguan.otk.model.constant.QQAction;
import com.miguan.otk.utils.LUtils;
/**
* Copyright (c) 2017/1/6. LiaoPeiKun Inc. All rights reserved.
*/
public class ContactJudgePresenter extends Presenter<ContactJudgeActivity> {
public void startQQ() {
Intent intent = new Intent();
intent.setData(Uri.parse(QQAction.Service));
try {
getView().startActivity(intent);
} catch (Exception e) {
LUtils.toast("未安装手Q或安装的版本不支持");
}
}
public void joinQQGroup() {
Intent intent = new Intent();
intent.setData(Uri.parse(QQAction.Group));
// 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
getView().startActivity(intent);
} catch (Exception e) {
LUtils.toast("未安装手Q或安装的版本不支持");
}
}
}
<file_sep>package com.miguan.otk.module.store;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataActivity;
import com.facebook.drawee.view.SimpleDraweeView;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Address;
import com.miguan.otk.model.bean.Order;
import com.miguan.otk.module.user.AddressListActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(PayPresenter.class)
public class PayActivity extends BaseDataActivity<PayPresenter, Order> {
@Bind(R.id.layout_order_address)
LinearLayout mLayoutAddress;
@Bind(R.id.tv_address_consignee)
TextView mTvConsignee;
@Bind(R.id.tv_address_mobile)
TextView mTvMobile;
@Bind(R.id.tv_address_info)
TextView mTvAddress;
@Bind(R.id.dv_goods_thumb)
SimpleDraweeView mDvThumb;
@Bind(R.id.tv_goods_name)
TextView mTvName;
@Bind(R.id.tv_goods_spec)
TextView mTvSpec;
@Bind(R.id.tv_goods_price)
TextView mTvPrice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_activity_pay);
setToolbarTitle(R.string.title_activity_pay);
ButterKnife.bind(this);
}
@Override
public void setData(Order order) {
mLayoutAddress.setOnClickListener(v -> startActivityForResult(new Intent(this, AddressListActivity.class), 0));
setAddress(order.getAddress());
mTvSpec.setText(order.getSpec());
mTvPrice.setText(order.getGoods().getGoods_price());
mTvName.setText(order.getGoods().getGoods_name());
mDvThumb.setImageURI(Uri.parse(order.getGoods().getGoods_image_url()));
}
public void setAddress(Address address) {
mTvConsignee.setText(String.format(getResources().getString(R.string.label_consignee), address.getTrue_name()));
mTvMobile.setText(address.getMob_phone());
mTvAddress.setText(String.format(getString(R.string.label_consignee_address), address.getAddress()));
}
}
<file_sep>package com.miguan.otk.module.battle;
import android.os.Bundle;
import android.widget.TextView;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(ContactJudgePresenter.class)
public class ContactJudgeActivity extends ChainBaseActivity<ContactJudgePresenter> {
@Bind(R.id.tv_judge_qq)
TextView mTvQQ;
@Bind(R.id.tv_judge_qq_group)
TextView mTvQQGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.against_activity_contact_judge);
setToolbarTitle(R.string.title_activity_contact_judge);
ButterKnife.bind(this);
mTvQQ.setOnClickListener(v -> getPresenter().startQQ());
mTvQQGroup.setOnClickListener(v -> getPresenter().joinQQGroup());
}
}
<file_sep>package com.miguan.otk.module.league;
import android.os.Bundle;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import butterknife.ButterKnife;
@RequiresPresenter(AddLeaguePresenter.class)
public class AddLeagueActivity extends ChainBaseActivity<AddLeaguePresenter> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.league_activity_add);
setToolbarTitle(R.string.title_activity_league_add);
ButterKnife.bind(this);
}
}
<file_sep>package com.miguan.otk.module.battle;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.miguan.otk.R;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(ShotBrowsePresenter.class)
public class ShotBrowseActivity extends ChainBaseActivity<ShotBrowsePresenter> {
@Bind(R.id.dv_image_browse)
SimpleDraweeView mDvImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.common_activity_image_browse);
ButterKnife.bind(this);
Uri uri = getIntent().getParcelableExtra("uri");
mDvImage.setImageURI(uri);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int battleID = getIntent().getIntExtra("battle_id", 0);
if (battleID > 0) getMenuInflater().inflate(R.menu.menu_save, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
getPresenter().upload();
return super.onOptionsItemSelected(item);
}
}
<file_sep>include ':app', ':chain', ':PushSDK', ':umshare'
<file_sep>package com.miguan.otk.module.match;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.list.BaseListFragment;
import com.dsk.chain.expansion.list.ListConfig;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.adapter.viewholder.ScheduleViewHolder;
import com.miguan.otk.model.bean.Schedule;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/22. LiaoPeiKun Inc. All rights reserved.
*/
@RequiresPresenter(ScheduleListPresenter.class)
public class ScheduleListFragment extends BaseListFragment<ScheduleListPresenter, Schedule> {
@Bind(R.id.tv_schedule_round)
TextView mTvRound;
@Bind(R.id.iv_schedule_left)
ImageView mIvLeft;
@Bind(R.id.iv_schedule_right)
ImageView mIvRight;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
ButterKnife.bind(this, view);
return view;
}
public void setData(Schedule schedule) {
mTvRound.setText(String.format(getString(R.string.text_which_rounds), schedule.getRound() + 1));
if (schedule.getRound() >= schedule.getRound_count()) {
mIvRight.setVisibility(View.INVISIBLE);
} else {
mIvRight.setVisibility(View.VISIBLE);
mIvRight.setOnClickListener(v -> getPresenter().changeRound(1));
}
if (schedule.getRound() == 0) {
mIvLeft.setVisibility(View.INVISIBLE);
} else {
mIvLeft.setVisibility(View.VISIBLE);
mIvLeft.setOnClickListener(v -> getPresenter().changeRound(-1));
}
}
@Override
public BaseViewHolder<Schedule> createViewHolder(ViewGroup parent, int viewType) {
return new ScheduleViewHolder(parent);
}
@Override
public int getLayout() {
return R.layout.match_fragment_schedule_list;
}
@Override
public ListConfig getListConfig() {
return super.getListConfig()
.setContainerEmptyRes(R.layout.empty_against_list)
.hasItemDecoration(false)
.setLoadMoreAble(false)
.setRefreshAble(false)
.setNoMoreAble(false);
}
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda' // lambda插件
Properties properties = new Properties();
properties.load(new FileInputStream(file("../config/signing.properties")))
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.miguan.otk"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
signingConfigs {
release {
keyAlias properties['KEY_ALIAS']
keyPassword properties['KEY_PASSWORD']
storeFile file(properties['KEYSTORE_FILE'])
storePassword properties['KEY_PASSWORD']
}
debug {
storeFile file('debug.keystore')
storePassword "<PASSWORD>"
keyAlias "androiddebugkey"
keyPassword "<PASSWORD>"
}
}
buildTypes {
release {
minifyEnabled false
signingConfig signingConfigs.debug
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
signingConfig signingConfigs.debug
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// 日历控件
// compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
// compile 'com.squareup.okhttp3:okhttp:3.5.0'
// compile 'com.android.support:gridlayout-v7:25.1.1'
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile project(':chain')
compile project(':PushSDK')
compile project(':umshare')
final RETROFIT_VERSION = '2.1.0'
compile "com.squareup.retrofit2:retrofit:$RETROFIT_VERSION"
compile "com.squareup.retrofit2:converter-gson:$RETROFIT_VERSION"
compile "com.squareup.retrofit2:adapter-rxjava:$RETROFIT_VERSION"
compile 'com.facebook.fresco:fresco:0.14.1'
compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.jude:imageprovider:2.1.1'
compile 'com.jude:exgridview:1.1.5'
compile 'com.prolificinteractive:material-calendarview:1.4.2'
compile 'com.android.support:cardview-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.jakewharton:butterknife:7.0.1'
testCompile 'junit:junit:4.12'
}
<file_sep>package com.miguan.otk.module.main;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Button;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Splash;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(AdPresenter.class)
public class AdActivity extends ChainBaseActivity<AdPresenter> {
@Bind(R.id.dv_ad_image)
SimpleDraweeView mDvImage;
@Bind(R.id.btn_ad_skip)
Button mBtnSkip;
private CountDownTimer mDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_ad);
ButterKnife.bind(this);
mBtnSkip.setOnClickListener(v -> {
mDownTimer.cancel();
startActivity(new Intent(this, MainActivity.class));
finish();
});
setData();
}
private void setData() {
Splash splash = getIntent().getParcelableExtra("splash");
mDvImage.setImageURI(splash.getImg_and());
mBtnSkip.setText(String.format(getString(R.string.btn_skip), splash.getShow_time()));
mDownTimer = new CountDownTimer(splash.getShow_time() * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mBtnSkip.setText(String.format(getString(R.string.btn_skip), millisUntilFinished / 1000));
}
@Override
public void onFinish() {
getPresenter().skip();
}
}.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
mDownTimer.cancel();
}
}
<file_sep>package com.miguan.otk.module.user;
import android.view.ViewGroup;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.list.BaseListActivity;
import com.dsk.chain.expansion.list.ListConfig;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.adapter.viewholder.AreaViewHolder;
import com.miguan.otk.model.bean.Area;
/**
* Copyright (c) 2017/1/19. LiaoPeiKun Inc. All rights reserved.
*/
@RequiresPresenter(AreaPresenter.class)
public class AreaActivity extends BaseListActivity<AreaPresenter> {
@Override
public BaseViewHolder<Area> createViewHolder(ViewGroup parent, int viewType) {
return new AreaViewHolder(parent);
}
@Override
protected int getLayout() {
return R.layout.activity_toolbar_list;
}
@Override
public ListConfig getListConfig() {
return super.getListConfig().setLoadMoreAble(false).setNoMoreAble(false).setRefreshAble(false);
}
}
<file_sep>package com.miguan.otk.module.main;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dsk.chain.bijection.ChainFragment;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import com.miguan.otk.adapter.TitlePagerAdapter;
import com.miguan.otk.module.news.NewsListFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/15. LiaoPeiKun Inc. All rights reserved.
*/
@RequiresPresenter(MainNewsPresenter.class)
public class MainNewsFragment extends ChainFragment<MainNewsPresenter> {
@Bind(R.id.tab_main_news)
TabLayout mTabLayout;
@Bind(R.id.pager_main_news)
ViewPager mPager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment_news, container, false);
ButterKnife.bind(this, view);
List<Fragment> fragments = new ArrayList<>();
for (int i = 1; i < getResources().getStringArray(R.array.tab_news_list).length + 1; i++) {
NewsListFragment fragment = new NewsListFragment();
Bundle bundle = new Bundle();
bundle.putInt("type", i);
fragment.setArguments(bundle);
fragments.add(fragment);
}
mPager.setAdapter(new TitlePagerAdapter(getActivity(), R.array.tab_news_list, fragments, getChildFragmentManager()));
mTabLayout.setupWithViewPager(mPager);
return view;
}
@Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (getView() != null) {
getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
}
}
}
<file_sep>package com.miguan.otk.model;
import com.dsk.chain.model.AbsModel;
import com.miguan.otk.model.bean.News;
import com.miguan.otk.model.services.DefaultTransform;
import com.miguan.otk.model.services.ServicesClient;
import java.util.List;
import rx.Observable;
/**
* Copyright (c) 2017/1/10. LiaoPeiKun Inc. All rights reserved.
*/
public class NewsModel extends AbsModel {
public static NewsModel getInstance() {
return getInstance(NewsModel.class);
}
public Observable<List<News>> getNewsList(int type, int page) {
return ServicesClient.getServices().newsList(type, page).compose(new DefaultTransform<>());
}
}
<file_sep>package com.miguan.otk.module.user;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataActivity;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Message;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(MessagePresenter.class)
public class MessageActivity extends BaseDataActivity<MessagePresenter, List<Message>> {
@Bind(R.id.ly_message_system)
RelativeLayout mLySystem;
@Bind(R.id.tv_message_system)
TextView mTvSystem;
@Bind(R.id.tv_message_match)
TextView mTvMatch;
@Bind(R.id.ly_message_match)
RelativeLayout mLyMatch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_message);
setToolbarTitle(R.string.title_activity_message);
ButterKnife.bind(this);
mLySystem.setOnClickListener(v -> getPresenter().showMessageList(1));
mLyMatch.setOnClickListener(v -> getPresenter().showMessageList(2));
}
@Override
public void setData(List<Message> messages) {
if (messages.size() > 0) mTvSystem.setText(messages.get(0).getContent());
if (messages.size() > 1) mTvMatch.setText(messages.get(1).getContent());
}
}
<file_sep>package com.miguan.otk.module.user;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.dsk.chain.expansion.list.BaseListActivityPresenter;
import com.miguan.otk.model.bean.Address;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
/**
* Copyright (c) 2016/12/19. LiaoPeiKun Inc. All rights reserved.
*/
public class AddressListPresenter extends BaseListActivityPresenter<AddressListActivity, Address> {
/**
* 选择模式,在订单确认页面中
*/
public static final int TYPE_CHOICE = 0x100;
/**
* 列表浏览模式
*/
public static final int TYPE_LIST = 0x200;
private int mType;
@Override
protected void onCreate(AddressListActivity view, Bundle saveState) {
super.onCreate(view, saveState);
mType = getView().getIntent().getIntExtra("type", 0);
getAdapter().setOnItemClickListener(position -> {
Intent intent = new Intent();
intent.putExtra("address", getAdapter().getItem(position));
getView().setResult(Activity.RESULT_OK, intent);
getView().finish();
});
}
@Override
protected void onCreateView(AddressListActivity view) {
super.onCreateView(view);
onRefresh();
}
@Override
public void onRefresh() {
List<Address> list = new ArrayList<>();
for (int i=0; i<10; i++) {
Address address = new Address();
address.setTrue_name("廖培坤");
address.setCity("福建省 厦门市");
address.setMob_phone("13215698921");
address.setAddress("思明区望海路16号之一301米冠网络");
list.add(address);
}
Observable.just(list).unsafeSubscribe(getRefreshSubscriber());
}
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Copyright (c) 2017/1/13. LiaoPeiKun Inc. All rights reserved.
*/
public class Splash implements Parcelable {
private String url;
private String img;
private String img_and;
private String img_ios;
private int show_time;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.url);
dest.writeString(this.img);
dest.writeString(this.img_and);
dest.writeString(this.img_ios);
dest.writeInt(this.show_time);
}
public Splash() {
}
protected Splash(Parcel in) {
this.url = in.readString();
this.img = in.readString();
this.img_and = in.readString();
this.img_ios = in.readString();
this.show_time = in.readInt();
}
public static final Creator<Splash> CREATOR = new Creator<Splash>() {
@Override
public Splash createFromParcel(Parcel source) {
return new Splash(source);
}
@Override
public Splash[] newArray(int size) {
return new Splash[size];
}
};
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getImg_and() {
return img_and;
}
public void setImg_and(String img_and) {
this.img_and = img_and;
}
public String getImg_ios() {
return img_ios;
}
public void setImg_ios(String img_ios) {
this.img_ios = img_ios;
}
public int getShow_time() {
return show_time;
}
public void setShow_time(int show_time) {
this.show_time = show_time;
}
}
<file_sep>package com.miguan.otk.module.user;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.User;
import com.miguan.otk.utils.LUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(ProfileModifyPresenter.class)
public class ProfileModifyActivity extends ChainBaseActivity<ProfileModifyPresenter> {
@Bind(R.id.tv_profile_modify_label)
TextView mTvLabel;
@Bind(R.id.et_profile_modify_input)
EditText mEtInput;
@Bind(R.id.btn_profile_modify_submit)
Button mBtnSubmit;
private User mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_profile_modify);
ButterKnife.bind(this);
mUser = getIntent().getParcelableExtra("user");
setLayout();
}
private void setLayout() {
switch (getIntent().getIntExtra("type", 0)) {
case 0:
setToolbarTitle(R.string.label_qq);
mTvLabel.setText(R.string.label_qq);
mEtInput.setHint(R.string.hint_qq);
mEtInput.setInputType(InputType.TYPE_CLASS_NUMBER);
mEtInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
if (!TextUtils.isEmpty(mUser.getQq())) {
mEtInput.setText(mUser.getQq());
mEtInput.setSelection(mUser.getQq().length());
}
mBtnSubmit.setOnClickListener(v -> checkInput("qq"));
break;
case 1:
setToolbarTitle(R.string.label_email);
mTvLabel.setText(R.string.label_email);
mEtInput.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
mEtInput.setHint(R.string.hint_email);
if (!TextUtils.isEmpty(mUser.getEmail())) {
mEtInput.setText(mUser.getEmail());
mEtInput.setSelection(mUser.getEmail().length());
}
mBtnSubmit.setOnClickListener(v -> checkInput("email"));
break;
case 2:
setToolbarTitle(R.string.label_introduction);
mTvLabel.setText(R.string.label_introduction);
if (!TextUtils.isEmpty(mUser.getSign())) {
mEtInput.setText(mUser.getSign());
mEtInput.setSelection(mEtInput.getText().length());
}
mEtInput.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LUtils.dp2px(128)));
mEtInput.setGravity(Gravity.TOP & Gravity.START);
int padding = (int) getResources().getDimension(R.dimen.horizontal_margin);
mEtInput.setPadding(padding, padding, padding, padding);
mEtInput.setHint(R.string.hint_introduction);
mBtnSubmit.setOnClickListener(v -> checkInput("sign"));
break;
}
}
private void checkInput(String key) {
if (TextUtils.isEmpty(mEtInput.getText().toString().trim())) {
LUtils.toast("请输入内容");
return;
}
getPresenter().submit(key, mEtInput.getText().toString().trim());
}
}
<file_sep>package com.miguan.otk.module.main;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataFragment;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.League;
import com.miguan.otk.module.league.AddLeagueActivity;
import com.miguan.otk.module.league.LeagueDetailActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by LPK on 2016/11/22.
*/
@RequiresPresenter(MainLeaguePresenter.class)
public class MainLeagueFragment extends BaseDataFragment<MainLeaguePresenter, League> {
@Bind(R.id.tv_league_detail)
Button mBtnDetail;
@Bind(R.id.tv_league_add)
Button mBtnAdd;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment_league, null);
ButterKnife.bind(this, view);
mBtnDetail.setOnClickListener(v -> startActivity(new Intent(getActivity(), LeagueDetailActivity.class)));
mBtnAdd.setOnClickListener(v -> startActivity(new Intent(getActivity(), AddLeagueActivity.class)));
return view;
}
@Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (getView() != null) {
getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
}
}
}
<file_sep>package com.miguan.otk.module.user;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.data.BaseDataActivity;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jude.exgridview.ExGridView;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.User;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(ProfilePresenter.class)
public class ProfileActivity extends BaseDataActivity<ProfilePresenter, User> {
@Bind(R.id.ly_profile_avatar)
LinearLayout mLyAvatar;
@Bind(R.id.dv_profile_avatar)
SimpleDraweeView mDvAvatar;
@Bind(R.id.tv_profile_username)
TextView mTvUsername;
@Bind(R.id.tv_profile_uid)
TextView mTvUid;
@Bind(R.id.tv_profile_qq)
TextView mTvQQ;
@Bind(R.id.tv_profile_email)
TextView mTvEmail;
@Bind(R.id.tv_profile_job)
TextView mTvJob;
@Bind(R.id.tv_profile_born)
TextView mTvBorn;
@Bind(R.id.tv_profile_area)
TextView mTvArea;
@Bind(R.id.tv_profile_intro)
TextView mTvIntro;
private BottomSheetDialog mDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_profile);
setToolbarTitle(R.string.title_activity_profile);
ButterKnife.bind(this);
mLyAvatar.setOnClickListener(v -> showPickDialog());
mTvArea.setOnClickListener(v -> startActivityForResult(new Intent(this, AreaActivity.class), 2));
}
@Override
public void setData(User user) {
setAvatar(Uri.parse(user.getPhoto()));
mTvUsername.setText(user.getUsername());
mTvUid.setText(String.format("%s", user.getUid()));
mTvQQ.setText(user.getQq());
mTvEmail.setText(user.getEmail());
mTvJob.setText(user.getActuality());
mTvJob.setOnClickListener(v -> showJobItems());
mTvBorn.setText(user.getBirthday());
mTvBorn.setOnClickListener(v -> showDatePick());
mTvArea.setText(String.format("%1$s %2$s %3$s", user.getProvince(), user.getCity(), user.getArea()));
mTvIntro.setText(user.getSign());
mTvQQ.setOnClickListener(v -> getPresenter().toModify(user, 0));
mTvEmail.setOnClickListener(v -> getPresenter().toModify(user, 1));
mTvIntro.setOnClickListener(v -> getPresenter().toModify(user, 2));
}
public void setAvatar(Uri uri) {
mDvAvatar.setImageURI(uri);
}
private void showPickDialog() {
if (mDialog == null) {
mDialog = new BottomSheetDialog(this);
View view = View.inflate(this, R.layout.dialog_bottom_pick_picture, null);
Button btnGallery = (Button) view.findViewById(R.id.btn_pick_from_gallery);
Button btnCamera = (Button) view.findViewById(R.id.btn_pick_from_camera);
Button btnDefault = (Button) view.findViewById(R.id.btn_pick_from_default);
Button btnCancel = (Button) view.findViewById(R.id.btn_pick_cancel);
btnDefault.setVisibility(View.VISIBLE);
btnGallery.setOnClickListener(v -> getPresenter().pickImage(0));
btnCamera.setOnClickListener(v -> getPresenter().pickImage(1));
btnDefault.setOnClickListener(v -> showDefaultDialog());
btnCancel.setOnClickListener(v -> dismissDialog());
mDialog.setContentView(view);
mDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
}
mDialog.show();
}
public void showJobItems() {
new AlertDialog.Builder(this).setItems(R.array.items_profile_jobs, (dialog, which) -> {
mTvJob.setText(getResources().getStringArray(R.array.items_profile_jobs)[which]);
getPresenter().setProfile("actuality", which + "");
}).show();
}
public void showDatePick() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
try {
Date date = format.parse(mTvBorn.getText().toString().trim().isEmpty() ? "1970-01-01" : mTvBorn.getText().toString().trim());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
DatePickerDialog dialog = new DatePickerDialog(this,
(datePicker, year, monthOfYear, dayOfMonth) -> {
String born = year + "-" + String.format("%02d", monthOfYear + 1) + "-" + dayOfMonth;
mTvBorn.setText(born);
getPresenter().setProfile("birthday", born);
},
calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
dialog.show();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void showDefaultDialog() {
View view = View.inflate(this, R.layout.dialog_default_avatar, null);
AlertDialog dialog = new AlertDialog.Builder(this).setView(view).show();
ExGridView gridView = (ExGridView) view.findViewById(R.id.grid_default_avatar);
String[] urlList = getResources().getStringArray(R.array.default_avatar_urls);
for (int i=0; i<urlList.length; i++) {
ImageView iv = new ImageView(this);
String avatar = urlList[i];
iv.setImageResource(getResources().getIdentifier("default_avatar_" + i, "mipmap", getPackageName()));
iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
iv.setOnClickListener(clickView -> {
getPresenter().setProfile("photo", avatar);
dialog.dismiss();
});
gridView.addView(iv);
}
view.findViewById(R.id.btn_default_avatar_cancel).setOnClickListener(v -> dialog.dismiss());
}
public void dismissDialog() {
if (null != mDialog && mDialog.isShowing()) mDialog.dismiss();
}
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Copyright (c) 2017/1/13. LiaoPeiKun Inc. All rights reserved.
*/
public class Version implements Parcelable {
private String version_number;
/**
* (0:不升级,1:提醒升级,2:强制升级)
*/
private int type;
private String apk_url;
private String upgrade_content;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.version_number);
dest.writeInt(this.type);
dest.writeString(this.apk_url);
dest.writeString(this.upgrade_content);
}
public Version() {
}
protected Version(Parcel in) {
this.version_number = in.readString();
this.type = in.readInt();
this.apk_url = in.readString();
this.upgrade_content = in.readString();
}
public static final Creator<Version> CREATOR = new Creator<Version>() {
@Override
public Version createFromParcel(Parcel source) {
return new Version(source);
}
@Override
public Version[] newArray(int size) {
return new Version[size];
}
};
public String getVersion_number() {
return version_number;
}
public void setVersion_number(String version_number) {
this.version_number = version_number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getApk_url() {
return apk_url;
}
public void setApk_url(String apk_url) {
this.apk_url = apk_url;
}
public String getUpgrade_content() {
return upgrade_content;
}
public void setUpgrade_content(String upgrade_content) {
this.upgrade_content = upgrade_content;
}
}
<file_sep>package com.miguan.otk.model;
import com.dsk.chain.model.AbsModel;
import com.miguan.otk.model.local.UserPreferences;
import com.miguan.otk.model.bean.Balance;
import com.miguan.otk.model.bean.Feedback;
import com.miguan.otk.model.bean.Game;
import com.miguan.otk.model.bean.Message;
import com.miguan.otk.model.bean.Sign;
import com.miguan.otk.model.bean.User;
import com.miguan.otk.model.bean.Withdraw;
import com.miguan.otk.model.services.DefaultTransform;
import com.miguan.otk.model.services.ServicesClient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rx.Observable;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
public class UserModel extends AbsModel {
public static UserModel getInstance() {
return getInstance(UserModel.class);
}
/**
* 注册验证码
* @param mobile 手机号
* @return 发送结果
*/
public Observable<Boolean> registerCaptcha(String mobile) {
return ServicesClient.getServices().sendCaptchaRegister(mobile).compose(new DefaultTransform<>());
}
/**
* 忘记密码验证码
* @param mobile 手机号
* @return 发送结果
*/
public Observable<Boolean> forgotCaptcha(String mobile) {
return ServicesClient.getServices().sendCaptchaReset(mobile).compose(new DefaultTransform<>());
}
/**
* 忘记密码验证码
* @param mobile 手机号
* @return 发送结果
*/
public Observable<Boolean> updateCaptcha(String mobile) {
return ServicesClient.getServices().sendCaptchaUpdate(mobile, UserPreferences.getToken()).compose(new DefaultTransform<>());
}
public Observable<User> login(String mobile, String password) {
return ServicesClient.getServices().login(mobile, password)
.doOnNext(this::saveAccount)
// .flatMap(new Func1<User, Observable<User>>() {
// @Override
// public Observable<User> call(User user) {
// return Observable.create(subscriber -> {
// String account = UserPreferences.getUserID();
// String token = UserPreferences.getNIMToken();
//
// LUtils.log("account: " + account + ", token: " + token);
//
// NimUIKit.doLogin(new LoginInfo(account, token), new RequestCallback<LoginInfo>() {
// @Override
// public void onSuccess(LoginInfo info) {
// LUtils.log("登录成功 account: " + info.getAccount() + ", token: " + info.getToken());
// subscriber.onNext(user);
// }
//
// @Override
// public void onFailed(int code) {
// if (code == 302 || code == 404) {
// LUtils.toast("账号或密码错误");
// subscriber.onError(new ServiceException(code, "账号或密码错误"));
// } else {
// LUtils.toast("登录失败: " + code);
// subscriber.onError(new ServiceException(code, "登录失败: " + code));
// }
// }
//
// @Override
// public void onException(Throwable throwable) {
// LUtils.toast("无效输入");
// subscriber.onError(new ServiceException(0, "无效输入"));
// }
// });
// });
// }
// })
.compose(new DefaultTransform<>());
}
public Observable<User> register(String username, String mobile, String code, String password) {
return ServicesClient.getServices().register(username, mobile, code, password)
.doOnNext(this::saveAccount)
.compose(new DefaultTransform<>());
}
public Observable<User> userInfo() {
return ServicesClient.getServices().userInfo(UserPreferences.getToken())
.compose(new DefaultTransform<>());
}
public Observable<Boolean> modifyPwd(String mobile, String code, String newPwd) {
return ServicesClient.getServices().modifyPwd(mobile, code, newPwd).compose(new DefaultTransform<>());
}
public Observable<User> getProfile() {
return ServicesClient.getServices().userProfile(UserPreferences.getToken()).compose(new DefaultTransform<>());
}
public Observable<Boolean> setProfile(Map<String, String> map) {
map.put("token", UserPreferences.getToken());
return ServicesClient.getServices().modifyProfile(map).compose(new DefaultTransform<>());
}
public Observable<Boolean> setProfile(String key, String value) {
Map<String, String> map = new HashMap<>();
map.put("token", UserPreferences.getToken());
map.put(key, value);
return ServicesClient.getServices().modifyProfile(map).compose(new DefaultTransform<>());
}
/**
* 签到信息
* @return
*/
public Observable<Sign> getSignInfo(String month, Integer year) {
return ServicesClient.getServices().signDetail(UserPreferences.getToken(), month, year).compose(new DefaultTransform<>());
}
/**
* 签到
* @return
*/
public Observable<Sign> sign() {
return ServicesClient.getServices().sign(UserPreferences.getToken()).compose(new DefaultTransform<>());
}
public Observable<List<Balance>> getBalanceList(String type, Integer page) {
return ServicesClient.getServices().balanceList(type, UserPreferences.getToken(), page)
.compose(new DefaultTransform<>());
}
/**
* 提现记录
*/
public Observable<Withdraw> getWithdrawList() {
return ServicesClient.getServices().withdrawRecord(UserPreferences.getToken())
.compose(new DefaultTransform<>());
}
/**
* 提现记录
*/
public Observable<List<Withdraw>> getWithdrawList(Integer page) {
return ServicesClient.getServices().withdrawRecord(UserPreferences.getToken(), page)
.compose(new DefaultTransform<>());
}
/**
* 提现
*/
public Observable<Boolean> withdraw(Integer money) {
return ServicesClient.getServices().withdraw(UserPreferences.getToken(), money).compose(new DefaultTransform<>());
}
/**
* 绑定支付宝
*/
public Observable<Boolean> bindAlipay(String mobile, String account, String captcha) {
return ServicesClient.getServices().bindAlipay(UserPreferences.getToken(), mobile, account, captcha).compose(new DefaultTransform<>());
}
/**
* 游戏帐号
*/
public Observable<List<Game>> getGameAccounts() {
return ServicesClient.getServices().gameAccounts(UserPreferences.getToken()).compose(new DefaultTransform<>());
}
/**
* 添加游戏帐号
*/
public Observable<Boolean> addGameAccount(String name, String account) {
return ServicesClient.getServices().addGameAccount(UserPreferences.getToken(), name, account).compose(new DefaultTransform<>());
}
/**
* 编辑游戏帐号
*/
public Observable<Boolean> updateGameAccount(int id, String account) {
return ServicesClient.getServices().updateGameAccount(UserPreferences.getToken(), id, account).compose(new DefaultTransform<>());
}
/**
* 消息分类最新一条
*/
public Observable<List<Message>> getMessageDesc() {
return ServicesClient.getServices().getMessageDesc(UserPreferences.getToken()).compose(new DefaultTransform<>());
}
/**
* 消息列表
*/
public Observable<List<Message>> getMessageList(Integer type, Integer page) {
return ServicesClient.getServices().getMessageList(UserPreferences.getToken(), type, page).compose(new DefaultTransform<>());
}
/**
* 吐槽一下
* @param type
* @return
*/
public Observable<Feedback> saveFeedback(Integer type, String contact, String content, String img) {
return ServicesClient.getServices()
.feedback(UserPreferences.getToken(), type, contact, content, img, 0)
.compose(new DefaultTransform<>());
}
private void saveAccount(User user) {
UserPreferences.setUserID(user.getUser_id() + "");
UserPreferences.setNIMToken(user.getAuth_key());
UserPreferences.setToken(user.getToken());
}
}
<file_sep>package com.miguan.otk.model.services;
import com.google.gson.Gson;
import com.miguan.otk.utils.LUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
public class WrapperResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private static final String TAG = "WrapperResponseBodyConverter";
private final Type mType;
WrapperResponseBodyConverter(Type type) {
this.mType = type;
}
@Override
public T convert(ResponseBody value) throws IOException {
try {
JSONObject data = new JSONObject(value.string());
LUtils.log(TAG, data.toString());
int status = data.getInt("status");
if (status != 1) {
throw new ServiceException(status, data.getString("msg"));
}
String result = "";
if (data.has("data")) {
if (!data.isNull("data")) result = data.opt("data").toString();
else return null;
} else {
return new Gson().fromJson(data.toString(), mType);
}
return new Gson().fromJson(result, mType);
} catch (JSONException e) {
throw new ServiceException(0, "数据解析错误");
}
}
}
<file_sep>package com.miguan.otk.model;
import com.dsk.chain.model.AbsModel;
import com.miguan.otk.model.local.UserPreferences;
import com.miguan.otk.model.bean.Battle;
import com.miguan.otk.model.bean.Home;
import com.miguan.otk.model.bean.Match;
import com.miguan.otk.model.bean.Mission;
import com.miguan.otk.model.bean.Schedule;
import com.miguan.otk.model.bean.User;
import com.miguan.otk.model.services.DefaultTransform;
import com.miguan.otk.model.services.ServicesClient;
import java.util.List;
import rx.Observable;
/**
* Copyright (c) 2017/1/6. LiaoPeiKun Inc. All rights reserved.
*/
public class MatchModel extends AbsModel {
public static MatchModel getInstance() {
return getInstance(MatchModel.class);
}
public Observable<Home> getHome() {
return ServicesClient.getServices().homeMatch(UserPreferences.getToken()).compose(new DefaultTransform<>());
}
/**
* 赛事详情
* @param matchID 赛事ID
* @return
*/
public Observable<Match> getMatchDetail(int matchID) {
return ServicesClient.getServices()
.matchDetail(UserPreferences.getToken(), matchID)
.compose(new DefaultTransform<>());
}
/**
* 赛事参加用户列表
* @param matchID 赛事ID
* @return
*/
public Observable<List<User>> getCompetitors(int matchID, int type) {
return ServicesClient.getServices().competitors(matchID, type).compose(new DefaultTransform<>());
}
/**
* 赛事参加用户列表
* @param matchID 赛事ID
* @return
*/
public Observable<Match> getCompetitionRule(int matchID) {
return ServicesClient.getServices().competitionRule(matchID).compose(new DefaultTransform<>());
}
/**
* 赛事对战表
* @param matchID 赛事ID
* @return
*/
public Observable<Schedule> getCompetitionSchedule(int matchID, int round) {
return ServicesClient.getServices().competitionSchedule(matchID, round).compose(new DefaultTransform<>());
}
/**
* 赛事报名
* @param matchID 赛事ID
* @return
*/
public Observable<Battle> enter(int matchID, String password, String code) {
return ServicesClient.getServices().competitionEnter(UserPreferences.getToken(), matchID, password, code).compose(new DefaultTransform<>());
}
/**
* 赛事签到
* @param matchID 赛事ID
* @return
*/
public Observable<Boolean> sign(int matchID) {
return ServicesClient.getServices().competitionSign(UserPreferences.getToken(), matchID).compose(new DefaultTransform<>());
}
public Observable<Battle> getBattleID(int competitionID) {
return ServicesClient.getServices().battleID(UserPreferences.getToken(), competitionID).compose(new DefaultTransform<>());
}
/**
* 我的参赛列表
* @param page 当前页数
* @return
*/
public Observable<List<Match>> getMyMatchList(int page) {
return ServicesClient.getServices().myMatchList(UserPreferences.getToken(), page).compose(new DefaultTransform<>());
}
/**
* 每日任务列表
*/
public Observable<List<Mission>> getMissionList() {
return ServicesClient.getServices().missionList(UserPreferences.getToken()).compose(new DefaultTransform<>());
}
/**
* 每日任务奖励领取
*/
public Observable<Mission> doleMission(int missionID) {
return ServicesClient.getServices().missionDole(UserPreferences.getToken(), missionID).compose(new DefaultTransform<>());
}
}
<file_sep>package com.miguan.otk.adapter.viewholder;
import android.support.annotation.LayoutRes;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Address;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/19. LiaoPeiKun Inc. All rights reserved.
*/
public class AddressViewHolder extends BaseViewHolder<Address> {
@Bind(R.id.tv_address_consignee)
TextView mTvConsignee;
@Bind(R.id.tv_address_mobile)
TextView mTvMobile;
@Bind(R.id.tv_address_city)
TextView mTvCity;
@Bind(R.id.tv_address_info)
TextView mTvInfo;
public AddressViewHolder(ViewGroup parent) {
this(parent, R.layout.item_list_address);
}
public AddressViewHolder(ViewGroup parent, @LayoutRes int res) {
super(parent, res);
ButterKnife.bind(this, itemView);
}
@Override
public void setData(Address data) {
mTvConsignee.setText(data.getTrue_name());
mTvMobile.setText(data.getMob_phone());
mTvCity.setText(data.getCity());
mTvInfo.setText(data.getAddress());
}
}
<file_sep>package com.miguan.otk.module.settings;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.miguan.otk.R;
import com.miguan.otk.model.local.PushPreferences;
import com.miguan.otk.utils.LUtils;
import com.umeng.message.IUmengCallback;
import com.umeng.message.PushAgent;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(SettingPushPresenter.class)
public class SettingPushActivity extends ChainBaseActivity<SettingPushPresenter> implements CompoundButton.OnCheckedChangeListener, IUmengCallback {
@Bind(R.id.switch_push_all)
Switch mSwitchAll;
@Bind(R.id.switch_push_match)
Switch mSwitchMatch;
private PushAgent mPushAgent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_activity_push);
ButterKnife.bind(this);
mPushAgent = PushAgent.getInstance(this);
mSwitchAll.setChecked(PushPreferences.isPushAll());
mSwitchMatch.setChecked(PushPreferences.isPushMatch());
mSwitchAll.setOnCheckedChangeListener(this);
mSwitchMatch.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
LUtils.log("onCheckedChanged : " + isChecked);
if (isChecked) {
mPushAgent.enable(this);
} else {
if (buttonView.getId() == R.id.switch_push_all) mSwitchMatch.setChecked(false);
mPushAgent.disable(this);
}
}
@Override
public void onSuccess() {
// PushPreferences.setPushAll(!PushPreferences.isPushAll());
LUtils.log("onSuccess");
}
@Override
public void onFailure(String s, String s1) {
LUtils.log("onFailure: " + s + ", " + s1);
}
}
<file_sep>package com.miguan.otk.adapter.viewholder;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.User;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/22. LiaoPeiKun Inc. All rights reserved.
*/
public class CompetitorViewHolder extends BaseViewHolder<User> {
@Bind(R.id.dv_player_avatar)
SimpleDraweeView mDvAvatar;
@Bind(R.id.tv_player_username)
TextView mTvUsername;
@Bind(R.id.tv_player_status)
TextView mTvStatus;
public CompetitorViewHolder(ViewGroup parent) {
super(parent, R.layout.item_list_enroll);
ButterKnife.bind(this, itemView);
}
@Override
public void setData(User data) {
mDvAvatar.setImageURI(Uri.parse(data.getPhoto()));
mTvUsername.setText(data.getUsername());
mTvStatus.setVisibility(data.getSign().equals("Y") ? View.VISIBLE : View.GONE);
}
}
<file_sep>package com.miguan.otk.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Banner;
import com.miguan.otk.model.bean.News;
import com.miguan.otk.module.common.WebActivity;
import com.miguan.otk.module.match.MatchDetailActivity;
import com.miguan.otk.module.news.NewsDetailActivity;
import com.miguan.otk.utils.LUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
*/
public class BannerPagerAdapter extends PagerAdapter {
private Context mContext;
private List<Banner> mBannerList;
private List<View> mViewList;
public BannerPagerAdapter(Context context, List<Banner> banners) {
this.mContext = context;
this.mBannerList = banners;
mViewList = new ArrayList<>();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(mContext.getResources());
GenericDraweeHierarchy hierarchy = builder
.setFadeDuration(300)
.setPlaceholderImage(R.mipmap.def_image_loading)
.setPlaceholderImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)
.setActualImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)
.build();
SimpleDraweeView dv = new SimpleDraweeView(mContext, hierarchy);
int height = LUtils.getScreenWidth() * 8 / 15;
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
dv.setLayoutParams(lp);
Banner banner = mBannerList.get(position);
dv.setImageURI(Uri.parse(banner.getImg()));
dv.setOnClickListener(v -> {
switch (banner.getType()) {
case 1 :
Intent newsIntent = new Intent(mContext, NewsDetailActivity.class);
News news = new News();
news.setUrl(banner.getUrl());
news.setTitle(banner.getTitle());
newsIntent.putExtra("news", news);
mContext.startActivity(newsIntent);
break;
case 2 :
Intent matchIntent = new Intent(mContext, MatchDetailActivity.class);
matchIntent.putExtra("match_id", banner.getUrl());
mContext.startActivity(matchIntent);
break;
default :
Intent intent = new Intent(mContext, WebActivity.class);
intent.putExtra("url", banner.getUrl());
mContext.startActivity(intent);
break;
}
});
container.addView(dv);
mViewList.add(dv);
return dv;
}
@Override
public int getCount() {
return mBannerList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(mViewList.get(position));
}
}
<file_sep>package com.miguan.otk.module.news;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.exgridview.ExGridView;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.News;
import com.miguan.otk.utils.LUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2017/1/11. LiaoPeiKun Inc. All rights reserved.
*/
public class NewsMultiViewHolder extends BaseViewHolder<News> {
@Bind(R.id.tv_news_title)
TextView mTvTitle;
@Bind(R.id.grid_news_images)
ExGridView mGridImages;
@Bind(R.id.tv_news_date)
TextView mTvDate;
public NewsMultiViewHolder(ViewGroup parent) {
super(parent, R.layout.item_list_news_multi);
ButterKnife.bind(this, itemView);
if (LUtils.getScreenWidth() >= 1080) {
mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getContext().getResources().getDimension(R.dimen.text_size_title_material));
}
}
@Override
public void setData(News news) {
mTvTitle.setText(news.getTitle());
mTvDate.setText(news.getCreate_time());
int height = (2 * (LUtils.getScreenWidth() - 4 * LUtils.dp2px(8)) / 9);
ViewGroup.LayoutParams layoutParams = mGridImages.getLayoutParams();
layoutParams.height = height;
mGridImages.setLayoutParams(layoutParams);
int width = (LUtils.getScreenWidth() - 4 * LUtils.dp2px(8)) / 3;
for (int i=0; i<news.getImg().length; i++) {
SimpleDraweeView dv = (SimpleDraweeView) LayoutInflater.from(getContext()).inflate(R.layout.item_grid_image, mGridImages, false);
dv.setImageURI(news.getImg()[i]);
mGridImages.addView(dv, width, height);
}
}
}
<file_sep>package com.miguan.otk.module.user;
import android.app.Activity;
import android.content.Intent;
import com.dsk.chain.expansion.list.BaseListActivityPresenter;
import com.miguan.otk.model.UserModel;
import com.miguan.otk.model.bean.Game;
/**
* Copyright (c) 2016/12/20. LiaoPeiKun Inc. All rights reserved.
*/
public class GameAccountPresenter extends BaseListActivityPresenter<GameAccountActivity, Game> {
@Override
protected void onCreateView(GameAccountActivity view) {
super.onCreateView(view);
onRefresh();
}
@Override
public void onRefresh() {
UserModel.getInstance().getGameAccounts().unsafeSubscribe(getRefreshSubscriber());
}
@Override
protected void onResult(int requestCode, int resultCode, Intent data) {
super.onResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
onRefresh();
}
}
}
<file_sep>package com.miguan.otk.module.store;
import com.dsk.chain.expansion.list.BaseListFragmentPresenter;
import com.miguan.otk.model.bean.Goods;
import com.miguan.otk.model.bean.Order;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
/**
* Copyright (c) 2016/12/19. LiaoPeiKun Inc. All rights reserved.
*/
public class OrderListPresenter extends BaseListFragmentPresenter<OrderListFragment, Order> {
@Override
protected void onCreateView(OrderListFragment view) {
super.onCreateView(view);
onRefresh();
}
@Override
public void onRefresh() {
List<Order> list = new ArrayList<>();
for (int i=0; i<10; i++) {
Order order = new Order();
order.setOrder_num(i + "574676765374564");
order.setState(i%2==0 ? "审核中" : "已完成");
Goods goods = new Goods();
order.setSpec("薄荷绿" + i);
goods.setGoods_name(i + "萌萌哒创意小耳机萌萌哒创意小耳机萌萌哒");
goods.setGoods_price("4000" + i);
goods.setGoods_image_url("http://static.otkpk.com/uploads/article/1481871059679989.jpg");
order.setGoods(goods);
list.add(order);
}
Observable.just(list).unsafeSubscribe(getRefreshSubscriber());
}
}
<file_sep>package com.miguan.otk.model.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Copyright (c) 2016/12/19. LiaoPeiKun Inc. All rights reserved.
*/
public class Order implements Parcelable {
private int order_id;
private String order_num;
private String state;
private Address address;
private Goods goods;
private String spec;
public Order() {
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public String getSpec() {
return spec;
}
public void setSpec(String spec) {
this.spec = spec;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.order_id);
dest.writeString(this.order_num);
dest.writeString(this.state);
dest.writeParcelable(this.address, flags);
dest.writeParcelable(this.goods, flags);
dest.writeString(this.spec);
}
protected Order(Parcel in) {
this.order_id = in.readInt();
this.order_num = in.readString();
this.state = in.readString();
this.address = in.readParcelable(Address.class.getClassLoader());
this.goods = in.readParcelable(Goods.class.getClassLoader());
this.spec = in.readString();
}
public static final Creator<Order> CREATOR = new Creator<Order>() {
@Override
public Order createFromParcel(Parcel source) {
return new Order(source);
}
@Override
public Order[] newArray(int size) {
return new Order[size];
}
};
public String getOrder_num() {
return order_num;
}
public void setOrder_num(String order_num) {
this.order_num = order_num;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
<file_sep>package com.miguan.otk.module.main;
import android.content.Intent;
import com.dsk.chain.bijection.Presenter;
/**
* Copyright (c) 2017/1/13. LiaoPeiKun Inc. All rights reserved.
*/
public class AdPresenter extends Presenter<AdActivity> {
public void skip() {
getView().startActivity(new Intent(getView(), MainActivity.class));
getView().finish();
}
}
<file_sep>package com.miguan.otk.module.user;
import com.dsk.chain.bijection.Presenter;
/**
* Copyright (c) 2016/12/19. LiaoPeiKun Inc. All rights reserved.
*/
public class MyOrderPresenter extends Presenter<MyOrderActivity> {
}
<file_sep>package com.miguan.otk.module.user;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.dsk.chain.bijection.ChainBaseActivity;
import com.dsk.chain.bijection.RequiresPresenter;
import com.jude.exgridview.ExGridView;
import com.miguan.otk.R;
import com.miguan.otk.utils.LUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
@RequiresPresenter(GameAccountAddPresenter.class)
public class GameAccountAddActivity extends ChainBaseActivity<GameAccountAddPresenter> {
@Bind(R.id.grid_game_type)
ExGridView mGridType;
@Bind(R.id.et_game_account)
EditText mEtAccount;
@Bind(R.id.btn_game_save)
Button mBtnSave;
private TextView mCurChecked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_game_account_add);
setToolbarTitle(R.string.title_activity_add_account);
ButterKnife.bind(this);
mBtnSave.setOnClickListener(v -> checkInput());
for (int i=0; i<mGridType.getChildCount(); i++) {
TextView tv = (TextView) mGridType.getChildAt(i);
if (i == 0) {
mCurChecked = tv;
tv.setSelected(true);
}
tv.setTag(i);
tv.setOnClickListener(v -> {
mCurChecked.setSelected(false);
v.setSelected(true);
mCurChecked = tv;
});
}
}
private void checkInput() {
if (TextUtils.isEmpty(mEtAccount.getText())) {
LUtils.toast("游戏帐号不能为空");
return;
}
getPresenter().save(mCurChecked.getText().toString().trim(), mEtAccount.getText().toString().trim());
}
}
<file_sep>package com.miguan.otk.module.user;
import android.view.ViewGroup;
import com.dsk.chain.bijection.RequiresPresenter;
import com.dsk.chain.expansion.list.BaseListActivity;
import com.dsk.chain.expansion.list.ListConfig;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.adapter.viewholder.MessageViewHolder;
@RequiresPresenter(MessageListPresenter.class)
public class MessageListActivity extends BaseListActivity<MessageListPresenter> {
@Override
protected BaseViewHolder createViewHolder(ViewGroup parent, int viewType) {
return new MessageViewHolder(parent);
}
@Override
protected int getLayout() {
return R.layout.activity_toolbar_list;
}
@Override
public ListConfig getListConfig() {
return super.getListConfig().hasItemDecoration(false);
}
}
<file_sep>package com.miguan.otk.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Match;
import com.miguan.otk.module.match.MatchDetailActivity;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2017/1/12. LiaoPeiKun Inc. All rights reserved.
*/
public class HomeMatchAdapter extends RecyclerView.Adapter<HomeMatchAdapter.MatchHomeViewHolder> {
private Context mContext;
private List<Match> mMatches;
public HomeMatchAdapter(Context context, List<Match> matches) {
mContext = context;
mMatches = matches;
}
@Override
public MatchHomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MatchHomeViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_list_match_home, parent, false));
}
@Override
public void onBindViewHolder(MatchHomeViewHolder holder, int position) {
Match match = mMatches.get(position);
holder.mTvTitle.setText(match.getTitle());
holder.mTvTime.setText(match.getGame_time());
holder.mTvFee.setText(match.getGame_all());
holder.mTvStatus.setText(match.getGame_status());
holder.mTvName.setText(match.getGame_name());
holder.mDvIcon.setImageURI(Uri.parse(match.getGame_img()));
holder.mIvType.setImageResource(match.getGame_type() == 0 ? 0 : (match.getGame_type() == 1 ? R.mipmap.ic_match_type_private : R.mipmap.ic_match_type_invite));
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(mContext, MatchDetailActivity.class);
intent.putExtra("match_id", match.getCompetition_id());
mContext.startActivity(intent);
});
}
@Override
public int getItemCount() {
return mMatches.size();
}
class MatchHomeViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.tv_match_home_title)
TextView mTvTitle;
@Bind(R.id.tv_match_home_time)
TextView mTvTime;
@Bind(R.id.tv_match_home_fee)
TextView mTvFee;
@Bind(R.id.tv_match_home_status)
TextView mTvStatus;
@Bind(R.id.dv_match_home_game_icon)
SimpleDraweeView mDvIcon;
@Bind(R.id.tv_match_home_game_name)
TextView mTvName;
@Bind(R.id.iv_match_home_type)
ImageView mIvType;
public MatchHomeViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
<file_sep>package com.miguan.otk.adapter.viewholder;
import android.content.Intent;
import android.net.Uri;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.miguan.otk.R;
import com.miguan.otk.model.bean.Goods;
import com.miguan.otk.module.store.GoodsDetailActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Copyright (c) 2016/12/16. LiaoPeiKun Inc. All rights reserved.
*/
public class GoodsViewHolder extends BaseViewHolder<Goods> {
@Bind(R.id.dv_goods_thumb)
SimpleDraweeView mDvThumb;
@Bind(R.id.tv_goods_name)
TextView mTvName;
@Bind(R.id.tv_goods_price)
TextView mTvPrice;
public GoodsViewHolder(ViewGroup parent) {
super(parent, R.layout.item_list_store_goods);
ButterKnife.bind(this, itemView);
}
@Override
public void setData(Goods data) {
mDvThumb.setImageURI(Uri.parse(data.getGoods_image_url()));
mTvName.setText(data.getGoods_name());
mTvPrice.setText(data.getGoods_price());
itemView.setOnClickListener(v -> {
Intent intent = new Intent(getContext(), GoodsDetailActivity.class);
intent.putExtra("goods_id", data.getGoods_id());
intent.putExtra("goods", data);
getContext().startActivity(intent);
});
}
}
<file_sep>package com.miguan.otk.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.miguan.otk.R;
/**
* Copyright (c) 2016/12/16. LiaoPeiKun Inc. All rights reserved.
*/
public class RecyclerStringAdapter extends RecyclerView.Adapter<RecyclerStringAdapter.SpecViewHolder> {
private Context mContext;
private String[] mList;
public RecyclerStringAdapter(Context context, String[] list) {
mContext = context;
mList = list;
}
@Override
public SpecViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
TextView textView = new Button(mContext);
textView.setBackgroundResource(R.drawable.btn_stroke_gray_radius_shape);
return new SpecViewHolder(textView);
}
@Override
public void onBindViewHolder(SpecViewHolder holder, int position) {
holder.mText.setText(mList[position]);
}
@Override
public int getItemCount() {
return mList.length;
}
class SpecViewHolder extends RecyclerView.ViewHolder {
TextView mText;
SpecViewHolder(View itemView) {
super(itemView);
mText = (TextView) itemView;
}
}
}
| f84a110f9746e57fc30cc97de79ac66945b7b342 | [
"Java",
"INI",
"Gradle"
] | 77 | Java | kenynw/OTK | f3acc3e95a4b7b67559028b51fe587f30c9906f3 | f55263bc4aeab768bc74c67ca63d0bf659f28fc6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.