branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>TatianaNarizhna/goit-react-hw-08-phonebook<file_sep>/src/redux/contacts-operations.js import axios from "axios"; import actions from './actions'; const fetchContacts = () => async dispatch => { dispatch(actions.fetchContactRequest()); try { const { data } = await axios.get('/contacts'); dispatch(actions.fetchContactSuccess(data)) } catch (error) { dispatch(actions.fetchContactError(error)); } } const addContact = data => async dispatch => { const contacts = { name:data.name, number: data.number }; dispatch(actions.addContactRequest()); try { const { data } = await axios.post('/contacts', contacts); dispatch(actions.addContactSuccess(data)); } catch (error) { dispatch(actions.addContactError(error)); } } const deleteItem = id => dispatch => { dispatch(actions.deleteItemRequest()); axios .delete(`/contacts/${id}`) .then(() => dispatch(actions.deleteItemSuccess(id))) .catch(error => dispatch(actions.deleteItemError(error))); } // eslint-disable-next-line import/no-anonymous-default-export export default { fetchContacts, addContact, deleteItem, }; <file_sep>/src/redux/auth/auth-selectors.js const getIsLoggedIn = state => state.auth.isLoggedIn; const getUserName = state => state.auth.user.name; const getIsLoadingCurrentUser = state => state.auth.isLoadingCurrentUser; // eslint-disable-next-line import/no-anonymous-default-export export default { getIsLoggedIn, getUserName, getIsLoadingCurrentUser };<file_sep>/src/redux/reducer.js import { combineReducers } from 'redux'; import { createReducer } from '@reduxjs/toolkit'; import actions from './actions'; const { fetchContactRequest, fetchContactSuccess, fetchContactError, addContactRequest, addContactSuccess, addContactError, deleteItemRequest, deleteItemSuccess, deleteItemError, changeFilter} = actions; const items = createReducer([], { [fetchContactSuccess]: (_, action) => action.payload, [addContactSuccess]: (state, action) => [...state, action.payload], [deleteItemSuccess]: (state, action) => state.filter(contact => contact.id !== action.payload) }); const loading = createReducer(false, { [fetchContactRequest]: () => true, [fetchContactSuccess]: () => false, [fetchContactError]: () => false, [addContactRequest]: () => true, [addContactSuccess]: () => false, [addContactError]: () => false, [deleteItemRequest]: () => true, [deleteItemSuccess]: () => false, [deleteItemError]: () => false, }); const filter = createReducer('', { [changeFilter]: (_, action) => action.payload, }); export default combineReducers({ items, filter, loading, }) <file_sep>/src/components/PhonebookList/PhonebookList.js import React from "react"; import { useEffect } from 'react'; // import { connect } from 'react-redux'; import { useSelector, useDispatch } from 'react-redux'; import contactsOperations from '../../redux/contacts-operations'; import PhoneBookItem from "../PhonebookItem/PhoneBookItem"; import { getVisibleContacts, getLoading } from "../../redux/contacts-selector"; import s from "./PhonebookList.module.css" // import PropTypes from "prop-types"; const PhonebookList = ({ title }) => { const contacts = useSelector(getVisibleContacts); const loading = useSelector(getLoading); const dispatch = useDispatch(); useEffect(() => dispatch(contactsOperations.fetchContacts()), [dispatch]); const onDeleteList = id => dispatch(contactsOperations.deleteItem(id)); return ( <div> <h2 className={s.title}>{title}</h2> <ul> {contacts.map(({ id, name, number }) => ( <PhoneBookItem key={id} name={name} number={number} onDeleteList={() => onDeleteList(id)} /> ))} </ul> {loading && <h1>Loading...</h1>} </div> ); }; export default PhonebookList; // const mapStateToProps = (state) => { // const { filter, items } = state.contacts; // const visibleContacts = getVisibleContacts(items, filter); // return { // contacts: visibleContacts, // } // } // const mapDispatchToProps = dispatch => ({ // onDeleteList: (id) => dispatch(deleteItem.deleteItem(id)) // }) // PhonebookList.propTypes = { // contacts: PropTypes.arrayOf(PropTypes.object).isRequired, // title: PropTypes.string.isRequired, // onDeleteList: PropTypes.func.isRequired, // }; // export default connect(mapStateToProps, mapDispatchToProps)(PhonebookList); <file_sep>/src/views/ContactsView/ContactsView.js import Container from "../../components/Container/Container"; import Input from "../../components/ContactForm/InputForm"; import Filter from "../../components/Filter/Filter"; import PhonebookList from "../../components/PhonebookList/PhonebookList"; import s from "./ContactsView.module.css" function ContactsView() { return ( <Container> <div className={s.Contacts}> <h1>Phonebook</h1> <Input /> <Filter /> <PhonebookList title="Contacts"/> </div> </Container> ) }; export default ContactsView;
9b246e957723cce738aef5462b3cdad038c1f7c4
[ "JavaScript" ]
5
JavaScript
TatianaNarizhna/goit-react-hw-08-phonebook
6fc3de4af691b564730c03873e8cd900af953e94
93778b69cca0bf3c2a1e4a3362eaf727ffb9550e
refs/heads/main
<file_sep>#include<bits/stdc++.h> #define magic ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define ll long long int #define v vector<ll> #define it iterator it #define pb push_back #define f(a, b) for(ll i=a; i<b; i++) int max(int a, int b) {return (a>b) ? a:b;} int min(int a, int b) {return (a<b) ? a:b;} using namespace std; int main() { while(1) { int n; cin >> n; if(n==42) break; cout << n << endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n, z, input, count=0, flag=0, f; cin >> n >> z; priority_queue<int> q; for(int i=0; i<n; i++) { cin >> input; q.push(input); } while(q.top()!=0 && z>0) { count++; f = q.top(); z -= f; q.pop(); q.push(f / 2); } if(z > 0) cout << "Evacuate\n"; else cout << count << "\n"; } return 0; }
a4df1fe0e3e146a8c842f152a4f6d84c8c95589c
[ "C++" ]
2
C++
shubhamp474/CodeChef-DSASeries
f89d5accaa8c80ec92c075d564fe56acf853149d
9e4d4b6ef3a0c64855c35fca70cd4dc66aabf889
refs/heads/master
<repo_name>thereactgirl/java-vending-machine<file_sep>/src/main/vend/Machine.java package main.vend; import java.util.ArrayList; import java.util.List; public class Machine implements VendingMachine, VendingMachineHardwareFunctions, AddProduct { //fields private int maxId = 0; private int id; private String name; private List<Product> products = new ArrayList<>(); private int balance; public Machine(String name) { maxId++; id = maxId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } @Override public void buttonPress(Integer productPosition) { //loop through products and print product name and price with said product position for(Product p : products) { if(p.getProductPosition() == productPosition && balance < p.getPrice()) { System.out.println(p.toString()); }; if(p.getProductPosition() == productPosition && balance >= p.getPrice()) { dispenseProduct(p.getProductPosition(), p.getName()); final int change = balance - p.getPrice(); dispenseChange(change); } } } @Override public void addUserMoney(Integer cents) { balance = balance + cents; } @Override public void addProductToMachine(int productPosition, String productName, int price) { getProducts().add(new Product(productPosition, productName, price)); } @Override public String toString() { return "Machine{" + "maxId=" + maxId + ", id=" + id + ", name='" + name + '\'' + ", products=" + products + ", balance=" + balance + '}'; } }<file_sep>/src/test/test/vend/MachineTest.java package test.vend; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; public class MachineTest { @Before public void setUp() throws Exception { //create a vending machine Machine SodaMachine = new Machine("Pepsi"); SodaMachine.getProducts().add(new Product(1, "Test Pepsi", 45)); SodaMachine.getProducts().add(new Product(2, "Test Big Red", 45)); SodaMachine.getProducts().add(new Product(3, "Test Mountain Dew", 45)); SodaMachine.getProducts().add(new Product(4, "Test Mug Root Beer", 45)); SodaMachine.addProductToMachine(5, "Test Water", 75); } @After public void tearDown() throws Exception { } @org.junit.Test public void buttonPress() { Machine SodaMachine = new Machine("Pepsi"); assertEquals(System.out.println("**Test Pepsi 45 cents**"), SodaMachine.buttonPress(1)); } }<file_sep>/src/main/vend/Main.java package main.vend; public class Main { public static void main(String[] args) { System.out.println("*** VENDING MACHINE ***"); //create a vending machine Machine SodaMachine = new Machine("Pepsi"); SodaMachine.getProducts().add(new Product(1, "Pepsi", 45)); SodaMachine.getProducts().add(new Product(2, "Big Red", 45)); SodaMachine.getProducts().add(new Product(3, "Mountain Dew", 45)); SodaMachine.getProducts().add(new Product(4, "Mug Root Beer", 45)); SodaMachine.addProductToMachine(5, "Water", 75); System.out.println(SodaMachine.toString()); System.out.println("User Presses 1"); SodaMachine.buttonPress(1); SodaMachine.addUserMoney(25); SodaMachine.addUserMoney(25); SodaMachine.buttonPress(1); } }
26c4dd34e0be2d1e73d2293d57db64d1e2c3715c
[ "Java" ]
3
Java
thereactgirl/java-vending-machine
637f15b48f28298eaf2dba8dda0fb1e21b31d99a
bd15ad4731392f39bf7bb06234128d8596c5e49a
refs/heads/master
<repo_name>vrr03/Minicurso-Git<file_sep>/main.c #include "stdlib.h" #include "stdio.h" int main () { int a = 5, b; b = a*a; printf ("\n%d\n", b); return 0; }
bbf44e9b420cf53b9778e666f1da039ba23f7acf
[ "C" ]
1
C
vrr03/Minicurso-Git
b7c844a5451cae3ae5f161eedec518d6fb4e0115
aaf98a0054e2746a8264a733eecb6d28be008f90
refs/heads/master
<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/ajaxfileupload.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> </head> <body> <form name="form1" method="post" action="__URL__/doaddapp" enctype="multipart/form-data" class="postappform addappform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1100" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">编辑应用</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td class="left_txt">当前位置:应用编辑</td> </tr> <tr> <td height="20"><table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC"> <tr> <td></td> </tr> </table></td> </tr> <tr> <td></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="nowtable"> <tr> <td class="left_bt2">&nbsp;&nbsp;&nbsp;&nbsp;应用编辑选项</td> </tr> </table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="20%" height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">应用名称:</td> <td width="3%" bgcolor="#f2f2f2">&nbsp;</td> <td width="32%" height="30" bgcolor="#f2f2f2"> <input name="title" type="text" id="title" size="30" value="<?php echo $app['title'] ?>" /> <span class="newsblock"><input type="checkbox" value="1" name="isdel" <?php if($app['isdel'] == 1): ?>checked<?php endif; ?> id="isdel" /><label for="isdel">取消发布</label></span> </td> <td width="45%" height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">应用所属类别:</td> <td>&nbsp;</td> <td height="30" style="display: block;width: 850px;"> 分类: <select name="cid" id="cid" class="addormodifyappcatgoryid"> <option value="0">==请选择应用分类==</option> <?php if(is_array($cid)): $i = 0; $__LIST__ = $cid;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option <?php if($vo['id'] == $app['cid']): ?>selected<?php endif; ?> value="<?php echo ($vo["id"]); ?>"><?php echo ($vo["catgory"]); ?></option><?php endforeach; endif; else: echo "" ;endif; ?> </select> 科目: <select name="courseid" id="courseid"> <option value="0">==请选择应用科目==</option> <?php if(is_array($course)): $i = 0; $__LIST__ = $course;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option <?php if($vo['id'] == $app['courseid']): ?>selected<?php endif; ?> value="<?php echo ($vo["id"]); ?>"><?php echo ($vo["title"]); ?></option><?php endforeach; endif; else: echo "" ;endif; ?> </select> <span class="isdownload"><input type="checkbox" value="1" name="" <?php if($app['downloadurl'] != ''): ?>checked<?php endif; ?> id="downloadurlcheckbox" /><label for="downloadurlcheckbox">下载类应用(如果是请打勾)</label></span> </td> <td height="30" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">应用图片:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"> <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input"> <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">上传应用的图像!(立即)</button> <span class="red">(仅允许jpg,gif,png三类图片,大小控制为60*60)</span> <input type="hidden" name="logo" id="logo" value="<?php echo $app['logo'] ?>" /> <img src="__PUBLIC__/images/appicon/<?php echo $app['logo'] ?>" <?php if($app['logo'] != ''): ?>style="display:block;"<?php endif; ?> alt="" class="applogo" /> </td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">应用期数:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="testqishu" id="testqishu" size="30" value="<?php echo $app['testqishu'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">试卷代码:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="testcode" id="testcode" size="30" value="<?php echo $app['testcode'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">适用对象描述:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="suitableusers" id="suitableusers" size="120" value="<?php echo $app['suitableusers'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">价格:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="price" id="price" size="30" value="<?php echo $app['price'] ?>" />元(¥)</td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">浏览基数:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="hitnum" id="hitnum" size="30" value="<?php echo $app['hitnum'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" class="left_txt2">应用简介: </td> <td>&nbsp;</td> <td height="30"> <textarea name="intro" id="discription" style="width:802px;" cols="30" rows="5"><?php echo $app['intro'] ?></textarea> </td> <td height="30" class="left_txt"></td> </tr> <tr class="articledownlink <?php echo $showx; ?>"> <td height="30" align="right" class="left_txt2">下载文件名: </td> <td>&nbsp;</td> <td height="30"> <input name="downloadurl" type="text" id="downloadurl" size="30" value="<?php echo $app['downloadurl']; ?>" /> <span>请用FTP工具将文件上传到网站<b class="red">Uploads/files目录</b>中!将<b class="red">英文文件名(如:app1.zip)</b>补充在左侧。</span> </td> <td height="30"><span class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2"></td> <td>&nbsp;</td> <td height="30"> <input class="submitapp addformbuttons" type="submit" value="提交数据" /> <input class="addformbuttons" type="reset" value="重新填写" /> </td> <td height="30" class="left_txt"><input type="hidden" name="id" value="<?php echo $app['id'] ?>" /></td> </tr> </table></td> </tr> </table> </td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </form> </body> </html><file_sep><?php class CityModel extends Model{ protected $_validate = array( // array(验证字段,验证规则,错误提示,[,验证条件][,附加规则][,验证时间]) array('name','','此地区已经存在!',0,'unique',3), // 在新增的时候验证name字段是否唯一 array('verify','checkverify','验证码不正确', 1,'callback', 1), // 自定义函数验证密码格式 ); protected $_auto = array( // array(填充字段,填充内容,[填充条件,附加规则]) array('path','mypath',1,'callback') ); function mypath(){ $pid=isset($_POST['pid'])?(int)$_POST['pid']:0; if($pid==0){ return 0; } $list=$this->find($pid); $data = $list['path'].'-'.$pid; return $data; } function checkverify(){ $verify = $_POST['verify']; if(session('verify') != md5($verify)) { return false; }else{ return true; } } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> </head> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1500" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">会员列表</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td colspan="2"> <div class="searchform"> <span class="deluser"><a class="delalink user" href="##">(解)锁定用户</a></span> <form action="__SELF__" method="post"> <input type="text" name="searchtext" class="searchtext"/> <input type="submit" value="搜索" class="searchbutton" /> </form> <div class="c"></div> </div> <table class="listtable"> <thead> <tr> <td class="knum">#</td> <td><input type="checkbox" onclick="checkAll('cid',this)" title="全选" name="checkall-toggle"></td> <!-- <td class="nickname"><a class="<?php echo ($order["nickname"]["p"]); ?>" href="__URL__/index/sortby/nickname/order/<?php echo ($order["nickname"]["s"]); ?>">昵称</a></td> --> <td><a class="<?php echo ($order["account"]["p"]); ?>" href="__URL__/index/sortby/account/order/<?php echo ($order["account"]["s"]); ?>">用户名</a></td> <td><a class="<?php echo ($order["status"]["p"]); ?>" href="__URL__/index/sortby/status/order/<?php echo ($order["status"]["s"]); ?>">状态</a></td> <td><a class="<?php echo ($order["email"]["p"]); ?>" href="__URL__/index/sortby/email/order/<?php echo ($order["email"]["s"]); ?>">邮箱</a></td> <!-- <td><a class="<?php echo ($order["rolename"]["p"]); ?>" href="__URL__/index/sortby/rolename/order/<?php echo ($order["rolename"]["s"]); ?>">用户角色</a></td> --> <td><a class="<?php echo ($order["last_login_time"]["p"]); ?>" href="__URL__/index/sortby/last_login_time/order/<?php echo ($order["last_login_time"]["s"]); ?>">最后访问日期</a></td> <td><a class="<?php echo ($order["create_time"]["p"]); ?>" href="__URL__/index/sortby/create_time/order/<?php echo ($order["create_time"]["s"]); ?>">注册日期</a></td> <td><a class="<?php echo ($order["id"]["p"]); ?>" href="__URL__/index/sortby/id/order/<?php echo ($order["id"]["s"]); ?>">ID编号</a></td> </tr> </thead> <tbody> <?php if(is_array($list)): $k = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($k % 2 );++$k;?><tr class="row<?php echo ($k%2); ?>"> <td><?php echo ($k); ?></td> <td><input type="checkbox" value="<?php echo ($vo["id"]); ?>" name="cid"></td> <!-- <td class="nickname"> <a href="__URL__/edit/id/<?php echo ($vo["id"]); ?>"><?php echo ($vo["nickname"]); ?></a> </td> --> <td><a href="__URL__/edit/id/<?php echo ($vo["id"]); ?>"><?php echo ($vo["account"]); ?></a></td> <td> <?php if(($vo["block"] == 0)): ?><img src="__PUBLIC__/images/admin/tick.png" alt="正常使用"> <?php else: ?> <img src="__PUBLIC__/images/admin/publish_x.png" alt="禁止使用"><?php endif; ?> </td> <td><?php echo ($vo["email"]); ?></td> <!-- <td><?php echo ($vo["rolename"]); ?></td> --> <td><?php echo (date("Y-m-d H:m:s",$vo["last_login_time"])); ?></td> <td><?php echo (date("Y-m-d H:m:s",$vo["create_time"])); ?></td> <td><?php echo ($vo["id"]); ?></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </tbody> <tfoot> <tr> <td colspan="15"><div class="result page"><?php echo ($page); ?></div></td> </tr> </tfoot> </table> </td> </tr> </table></td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </body> </html><file_sep><?php /*获得客户端真实的IP地址*/ function get_client_true_ip() { if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) { $ip = getenv("HTTP_CLIENT_IP"); } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) { $ip = getenv("HTTP_X_FORWARDED_FOR"); } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) { $ip = getenv("REMOTE_ADDR"); } else if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "unknown"; } return ($ip); } //判断浏览器 function browser(){ if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 8.0")) $browser = "IE8"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 7.0")) $browser = "IE7"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 9.0")) $browser = "IE9"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 6.0")) $browser = "IE6"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox")) $browser = "FF"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Chrome")) $browser = "Chrome"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Safari")) $browser = "Safari"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Opera")) $browser = "Opera"; else $browser = $_SERVER["HTTP_USER_AGENT"]; return $browser; } //用户头像 function getuseravatar(){ $uid = session('user_id'); $uid = abs(intval($uid)); $uid = sprintf("%09d", $uid); $dir1 = substr($uid, 0, 3); $dir2 = substr($uid, 3, 2); $dir3 = substr($uid, 5, 2); $savepath = $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2)."_avatar_middle.jpg"; $path = './Uploads/avatar/'.$savepath; if(!file_exists($path)){ $path = '/Public/images/home/defaultav.png'; }else{ $path = '/Uploads/avatar/'.$savepath; } return $path; } //自动登陆 function userautologin(){ $uid = cookie('autoLoginuserid'); //dump($uid); if($uid && !session('user_id')){ session('user_id',$uid); redirect('index.php'); } } //清空指定的Cookie,ThinkPHP官方的这个 cookie(null,"think_")好像有问题 function emptycookie($identify){ // 默认设置 $config = array( 'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀 'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间 'path' => C('COOKIE_PATH'), // cookie 保存路径 'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名 ); foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $identify)) { setcookie($key, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$key]); } } } //获得指定cookie的数量 function countcookie($identify){ $num = 0; foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $identify)) { $num++; } } return $num; } //获得Cookie中题目ID和题目顺序编号的关系  function getidjointtrueid(){ $arr = array(); foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, 'listquestionid')) { $a = explode("_", $key); $arr[$a[1]] = $val; } } return $arr; } //加密函数 function jiami($txt, $key = null) { if (empty ( $key )) $key = C ( 'SECURE_CODE' ); //$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_"; $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $nh = rand ( 0, 64 ); $ch = $chars [$nh]; $mdKey = md5 ( $key . $ch ); $mdKey = substr ( $mdKey, $nh % 8, $nh % 8 + 7 ); $txt = base64_encode ( $txt ); $tmp = ''; $i = 0; $j = 0; $k = 0; for($i = 0; $i < strlen ( $txt ); $i ++) { $k = $k == strlen ( $mdKey ) ? 0 : $k; $j = ($nh + strpos ( $chars, $txt [$i] ) + ord ( $mdKey [$k ++] )) % 64; $tmp .= $chars [$j]; } return $ch . $tmp; } //解密函数 function jiemi($txt, $key = null) { if (empty ( $key )) $key = C ( 'SECURE_CODE' ); $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $ch = $txt [0]; $nh = strpos ( $chars, $ch ); $mdKey = md5 ( $key . $ch ); $mdKey = substr ( $mdKey, $nh % 8, $nh % 8 + 7 ); $txt = substr ( $txt, 1 ); $tmp = ''; $i = 0; $j = 0; $k = 0; for($i = 0; $i < strlen ( $txt ); $i ++) { $k = $k == strlen ( $mdKey ) ? 0 : $k; $j = strpos ( $chars, $txt [$i] ) - $nh - ord ( $mdKey [$k ++] ); while ( $j < 0 ) $j += 64; $tmp .= $chars [$j]; } return base64_decode ( $tmp ); } function SendMail($address,$title,$message){ vendor('PHPMailer.class#phpmailer');//用vendor导入第三方邮件类 $mail = new PHPMailer(); $mail->CharSet='UTF-8'; $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = C('MAIL_SMTP'); // SMTP server $mail->SMTPDebug = 2; // enables SMTP debug information (for testing) // 1 = errors and messages // 2 = messages only $mail->SMTPAuth = true; // enable SMTP authentication $mail->Host = C('MAIL_SMTP'); // sets the SMTP server $mail->Port = C('MAIL_PORT'); // set the SMTP port for the GMAIL server $mail->SMTPSecure = 'ssl'; $mail->Username = C('MAIL_ADDRESS'); // SMTP account username $mail->Password = C('<PASSWORD>'); // SMTP account password $mail->SetFrom(C('MAIL_ADDRESS'), $title); // $mail->AddReplyTo("<EMAIL>","First Last"); $mail->Subject = $title; $body = $message; $mail->MsgHTML($body); $address = $address; $mail->AddAddress($address); return $mail->Send(); } /** * 获取目录的结构 * @author 李俊 * @param [string] $path [目录路径] * @return [array] [目录结构数组] * @使用方法:dump(dirtree('./ThinkPHP')); */ function dirtree($path) { $handle = opendir($path); $itemArray=array(); while (false !== ($file = readdir($handle))) { if (($file=='.')||($file=='..')){ }elseif (is_dir($path.$file)) { try { $dirtmparr=dirtree($path.$file.'/'); } catch (Exception $e) { $dirtmparr=null; }; $itemArray[$file]=$dirtmparr; }else{ array_push($itemArray, $file); } } return $itemArray; } ?><file_sep><?php class QuestionViewModel extends ViewModel { public $viewFields = array( 'question' => array('id','appid','type','title','intro','answer','_type'=>'RIGHT'), 'question_answer'=>array('answeridentify','answercontent','_on'=>'question.id=question_answer.questionid'), ); } ?><file_sep><?php Class EmptyAction extends CommonAction{ public function _initialize(){ parent::_initialize(); } public function index(){ $this->redirect('/'); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> </head> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1500" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">订单列表</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td colspan="2"> <div class="searchform"> <span class="deluser"><a class="delalink order" href="javascript:void(0);">删除订单</a></span> <div class="c"></div> </div> <table class="listtable"> <thead> <tr> <td style="width:20px;" class="knum">#</td> <td style="width:20px;"><input type="checkbox" onclick="checkAll('cid',this)" title="全选" name="checkall-toggle"></td> <td><a href="##">产品名称</a></td> <td><a href="##">交易人</a></td> <td><a href="##">金额</a></td> <td><a href="##">支付宝交易编号</a></td> <td style="width:40px;"><a href="##">状态</a></td> <td style="width:120px;"><a href="##">创建时间</a></td> <td style="width:120px;"><a href="##">支付时间</a></td> <td style="width:80px;"><a href="##">站内交易编号</a></td> <td style="width:60px;"><a href="##">处理</a></td> </tr> </thead> <tbody> <?php if(is_array($list)): $k = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($k % 2 );++$k;?><tr class="row<?php echo ($k%2); ?>"> <td><?php echo ($k); ?></td> <td><input type="checkbox" value="<?php echo ($vo["id"]); ?>" name="cid"></td> <td align="left"><?php echo ($vo["subject"]); ?></td> <td><a href="<?php echo U('User/edit','id='.$vo['uid']);?>"><?php echo ($vo["account"]); ?>_<?php echo ($vo["buyer_email"]); ?></a></td> <td><?php echo ($vo["total_fee"]); ?></td> <td><?php echo ($vo["trade_no"]); ?></td> <td> <?php if(($vo["trade_status"] == 'TRADE_FINISHED')): ?><img src="__PUBLIC__/images/admin/tick.png" alt="成功"> <?php else: ?> <img src="__PUBLIC__/images/admin/publish_x.png" alt="等待"><?php endif; ?> </td> <td><?php echo ($vo["gmt_create"]); ?></td> <td><?php echo ($vo["gmt_payment"]); ?></td> <td><?php echo ($vo["orderid"]); ?></td> <td> <?php if(($vo["trade_status"] == 'TRADE_FINISHED')): ?><input type="button" value="已经收款" class="yysk" onclick="return false;" readonly="readonly" /> <?php else: ?> <input type="button" value="手动确认" class="sdqr" onclick="sdqrsk(<?php echo ($vo["orderid"]); ?>)" /><?php endif; ?> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </tbody> <tfoot> <tr> <td colspan="15"><div class="result page"><?php echo ($page); ?></div></td> </tr> </tfoot> </table> </td> </tr> </table></td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </body> </html><file_sep><?php class EmptyAction extends CommonAction{ public function index(){ $moduleName = MODULE_NAME; $this->whereTogo($moduleName); } public function _empty($name){ redirect(__APP__.'/Public/login'); } protected function whereTogo($moduleName){ // echo '系统不知道你要去哪里,或者不认识:' . $moduleName; $this->redirect(__APP__.'/Public/login'); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <title><?php if(!empty($pagetitle)): echo ($pagetitle); ?>_<?php endif; echo (session('website_sitename')); ?>_<?php echo str_replace('www.','',session('website_siteurl')); ?></title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta http-equiv="expires" content="0" /> <meta name="resource-type" content="document" /> <meta name="distribution" content="global" /> <meta name="author" content="CrewExam" /> <meta name="generator" content="lamp99.com,zhangjichao.cn" /> <meta name="copyright" content="Copyright (c) 2013 CrewExam. All Rights Reserved." /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta name="robots" content="index, follow" /> <meta name="revisit-after" content="1 days" /> <meta name="rating" content="general" /> <meta name="keywords" content="<?php echo (session('website_keywords')); ?>" /> <meta name="description" content="<?php echo ($pagediscription); echo (session('website_sitediscription')); ?>" /> <link rel="stylesheet" type="text/css" href="/Public/css/home/template.css" /> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/json2.js"></script><script type="text/javascript" src="/Public/js/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=chrome"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> </head> <body class="<?php echo ($browser); ?>"> <div class="bshade"></div> <div class="navigation"> <div class="navigation-wrapper"> <div id="logo2"> <h1> <a href="/"> <img width="218" height="55" src="__PUBLIC__/images/home/herderlogo.png" /> </a> </h1> </div> <div class="nav-body"> <h2 class="nav-title">中国船员在线题库练习与模拟考试网</h2> <div class="nav-other"> <div class="menu"> <a href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo (session('website_myqq')); ?>&site=qq&menu=yes" stats="homenav_suggest" title="给我们提建议">在线客户服务</a> </div> <div class="menu more hidden"> <a class="show-more" id="moreWeb" stats="homenav_more" href="##">更多</a> </div> </div> </div> </div> </div> <div class="page-wrapper clearfix"> <div class="full-page"> <div class="login-page clearfix"> <div class="regboxcontent"> <link rel="stylesheet" type="text/css" href="/Public/images/home/tip-yellowsimple/tip-yellowsimple.css" /><link rel="stylesheet" type="text/css" href="/Public/images/home/datepicker/css/jquery-ui.css" /> <script type="text/javascript" src="/Public/js/jquery_poshytip.js"></script><script type="text/javascript" src="/Public/js/city.js"></script><script type="text/javascript" src="/Public/images/home/datepicker/js/jquery-ui-datepicker.js"></script> <style type="text/css">.tip-yellowsimple {z-index:1000;}</style> <form action="__URL__/doreg" method="post" class="reg-form"> <table class="regtableleft"> <tr> <th></th> <td><h2 class="reg_page_title">注册新账号</h2></td> </tr> <tr> <th>身份证号码:</th> <td><input type="text" name="identitycard" onchange="checkidentitycard(this)" id="person_id" class="person_id txt" title="15/18位有效身份证号!" /></td> </tr> <tr> <th>真实姓名:</th> <td><input type="text" name="account" id="account" class="account txt" title="请输入真实姓名!" /></td> </tr> <tr> <th>邮箱:</th> <td> <input type="text" name="email" id="usereamil" class="txt" title="可以通过邮箱找回密码!" /> </td> </tr> <tr> <th>生日:</th> <td><input type="text" name="birthday" id="birthday" class="birthday txt" title="请输入有效的出生日期!" /></td> </tr> <tr> <th>性别:</th> <td> <input type="radio" name="sex" id="sexman" value="1" /><label for="sexman">男</label> <span style="width: 20px;">&nbsp;</span> <input type="radio" name="sex" id="sexwoman" value="2" /><label for="sexwoman">女</label> </td> </tr> <tr> <th>密码:</th> <td><input type="<PASSWORD>" name="password" id="password" class="txt" title="6-12个字符组成!" /></td> </tr> <tr> <th>确认密码:</th> <td><input type="password" name="password2" id="password2" class="txt" title="重复上面的密码!" /></td> </tr> <tr> <th>现任职务:</th> <td><select name="job" id="job"> <?php echo (session('website_jobs')); ?> </select></td> </tr> <tr> <th>联系电话:</th> <td><input type="text" name="tel" id="telephone" class="telephone txt" title="你的手机或者固定电话!" /></td> </tr> <tr> <th>所在地:</th> <td class="pcabox"> <select name="Province"></select><select name="City"></select><select name="Area"></select> <script language="javascript">new PCAS("Province","City","Area");</script> <span class="defaultarea"></span> </td> </tr> <tr> <th class="verifyth">验证码:</th> <td> <script type="text/javascript">function updateverifyimg(obj){obj.src="__APP__/Public/GBVerify/?"+Math.random();}</script> <img onclick="updateverifyimg(this)" class="verifyimg" src="__APP__/Public/GBVerify/" alt="验证码" /><span>看不清楚点击图片换一张?</span><br /> <input type="text" name="verify" id="verify" class="verify txt" title="输入上面图片中的文字" /> </td> </tr> <tr> <th></th> <td><input type="submit" class="regsubbutton" value="注册" /></td> </tr> <tr> <th></th> <td> <input type="checkbox" checked name="xieyi" id="xieyi" style="vertical-align:middle;" /><label style="vertical-align:middle;" for="xieyi">我接受</label> <a style="vertical-align:middle;" target="_blank" href="<?php echo U('Public/news','id=89');?>">船员考试网服务条款</a> </td> </tr> </table> <table class="regtableright"> <tr><td>已经是船员考试网会员?<a href="/">直接登陆</a><br />还可以下载APP下载到手机<br /> <img src="__PUBLIC__/images/home/regerweima.png" alt="" /> </td></tr> </table> <div class="clearfix"></div> </form> </div> </div> </div> </div> <div class="clearfix"></div> <div id="footer"> <div class="site-footer"> <div id="footer0904"> <div class="footer_c"><?php echo (session('website_sitename')); ?>客户服务热线:<?php echo (session('website_tel')); ?>(工作日 9:00-17:30) <a target="_blank" href="<?php echo (session('website_weibo')); ?>" class="weibo"><?php echo (session('website_sitename2')); ?></a> </div> <div class="footer_about"> <ul class="about"> <li class="first"><a href="<?php echo U('Public/news','id=86');?>" >关于船员考试网</a></li> <li><a href="<?php echo U('Public/newslist','cid=1');?>" target="_blank">最新资讯</a></li> <li><a href="<?php echo U('Public/newslist','cid=2');?>" target="_blank">常见问题</a></li> <li><a href="<?php echo U('Public/news','id=87');?>" target="_blank">联系我们</a></li> <li><a href="<?php echo U('Public/newslist','cid=3');?>" target="_blank">海事规则</a></li> <li><a href="<?php echo U('Public/news','id=88');?>" target="_blank">法律声明</a></li> <li><a href="<?php echo U('Public/news','id=89');?>" target="_blank">会员服务</a></li> <li><a href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo (session('website_myqq')); ?>&site=qq&menu=yes" >在线客服</a></li> <li class="last"><a href="http://www.ship123.com" target="_blank">船员导航网</a></li> </ul> </div> <div class="footer_text"> <p>客户服务热线:<?php echo (session('website_tel')); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>邮箱:<?php echo (session('website_mymail')); ?>&nbsp;&nbsp;网站ICP备案:<?php echo (session('website_beianhao')); ?></p> <p>通用网址 网络关键词:<?php echo (session('website_keywords')); ?></p> <p>CopyRight &copy; 2010-<?php echo date('Y',time()); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>&nbsp;&nbsp;<?php echo (session('website_siteurl')); ?>,All Rights Reserved&nbsp;&nbsp;<?php echo (session('website_sitename')); ?>&nbsp;&nbsp;版权所有</p> </div> <div class="icpbox"> <a href="http://t.knet.cn/" target="_blank" class="icp"><img src="__PUBLIC__/images/home/footerbeian.png"></a></div> <div class="tongji"><?php echo (session('website_sitetonji')); ?></div> </div> </div> </div> </body> </html><file_sep><?php Class InitAction extends Action{ public function _initialize(){ header("Content-Type:text/html; charset=utf-8"); Load('extend'); //网址基本信息 if(!session('website_adminjiami')){ $rs = D('Config')->select(); session('website_weibo',$rs[13]['value']); session('website_apphotkey',$rs[12]['value']); session('website_examquestionnum',$rs[11]['value']); session('website_sitename2',$rs[10]['value']); session('website_siteurl',$rs[9]['value']); session('website_sitetonji',$rs[8]['value']); session('website_sitediscription',$rs[7]['value']); session('website_keywords',$rs[6]['value']); session('website_mymail',$rs[5]['value']); session('website_myqq',$rs[4]['value']); session('website_tel',$rs[3]['value']); session('website_beianhao',$rs[2]['value']); session('website_adminjiami',$rs[1]['value']); session('website_sitename',$rs[0]['value']); } } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><html> <head> <title><?php echo (session('website_sitename')); ?> 网站后台管理中心</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style> * { padding:0; margin:0;font-size: 12px; } html, body { height:100%; border:none 0; } #iframe { width:100%; height:100%; border:none 0; } </style> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/jquery_cookie.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <script type="text/javascript"> (function (config) { config['lock'] = true; config['fixed'] = true; config['okVal'] = '确定'; config['cancelVal'] = '取消'; // [more..] })(art.dialog.defaults); </script> </head> <body> <iframe id="iframe" src="__URL__/main"></iframe> </body> </html><file_sep><?php class UserModel extends Model { protected $_validate = array( array('username','require','用户名必须!'), //默认情况下用正则进行验证 array('username','','用户名已经存在!',0,'unique',1), // 在新增的时候验证name字段是否唯一 array('password','require','<PASSWORD>!'), //默认情况下用正则进行验证 array('email','','用邮箱已经被占用!',0,'unique',1), // 在新增的时候验证name字段是否唯一 array('email','email','邮箱不符合规则!'), //默认情况下用正则进行验证 ); protected $_auto = array( array('status','1'), // 新增的时候把status字段设置为1 array('block','0'), // 新增的时候把block字段设置为0,未激活状态 array('password','md5',1,'function') , // 对password字段在新增的时候使md5函数处理 array('name','getName',1,'callback'), // 对name字段在新增的时候回调getName方法 array('registerDate','time',1,'function'), // 对注册时间字段在新增的时候写入当前时间戳 array('lastvisitDate','time',3,'function'), // 对最后登陆时间字段在创建和修改的时候写入当前时间戳 ); function getName(){ $data = $_POST['username']; return $data; } function aa(){ $user = M('user'); $list = $user->find(); return $list; } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><html> <head> <title>网站后台管理中心</title> <meta http-equiv=Content-Type content=text/html;charset=utf-8> </head> <frameset rows="64,*" frameborder="NO" border="0" framespacing="0"> <frame src="__URL__/admin_top" noresize="noresize" frameborder="NO" name="topFrame" scrolling="no" marginwidth="0" marginheight="0" target="main" /> <frameset cols="185,*" rows="3560,*" id="frame"> <frame src="__URL__/admin_menu" name="leftFrame" noresize="noresize" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" target="main" /> <frame src="__URL__/welcome" name="main" marginwidth="0" marginheight="0" frameborder="0" scrolling="auto" target="_self" /> </frameset> <noframes> <body></body> </noframes> </html><file_sep><?php class IndexAction extends CommonAction{ public function _empty($name){ redirect(__APP__.'/Index/index'); } public function index(){ $this->display(); } public function main(){ $this->display(); } public function admin_top(){ $yourip = get_client_ip(); if($yourip=='127.0.0.1'){$yourip = '192.168.127.12';} import('ORG.Net.IpLocation');// 导入IpLocation类 $Ip = new IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件 $area = $Ip->getlocation($yourip); // 获取某个IP地址所在的位置 // dump($area); $where['key'] = 'sitename'; $rs = D('Config')->where($where)->find(); $this->assign('sitename',$rs['value']); $this->assign('area',$area); $this->display(); } public function admin_menu(){ $this->display(); } // 后台首页 查看系统信息 public function welcome() { $info = array( '操作系统'=>PHP_OS, '运行环境'=>$_SERVER["SERVER_SOFTWARE"], 'PHP运行方式'=>php_sapi_name(), 'ThinkPHP版本'=>THINK_VERSION.' [ <a href="http://thinkphp.cn" target="_blank">查看最新版本</a> ]', '上传附件限制'=>ini_get('upload_max_filesize'), '执行时间限制'=>ini_get('max_execution_time').'秒', '服务器时间'=>date("Y年n月j日 H:i:s"), '北京时间'=>gmdate("Y年n月j日 H:i:s",time()+8*3600), '服务器域名/IP'=>$_SERVER['SERVER_NAME'].' [ '.gethostbyname($_SERVER['SERVER_NAME']).' ]', '剩余空间'=>round((@disk_free_space(".")/(1024*1024)),2).'M', 'register_globals'=>get_cfg_var("register_globals")=="1" ? "ON" : "OFF", 'magic_quotes_gpc'=>(1===get_magic_quotes_gpc())?'YES':'NO', 'magic_quotes_runtime'=>(1===get_magic_quotes_runtime())?'YES':'NO', ); $this->assign('info',$info); //会员查询 $usernum = D('User')->where('block=0')->count(); $ordernum = D('Order')->where('trade_status<>"TRADE_FINISHED"')->count(); $allmoney = D('Order')->where('trade_status="TRADE_FINISHED"')->sum('total_fee'); $this->assign('usernum',$usernum); $this->assign('ordernum',$ordernum); $this->assign('allmoney',$allmoney); $this->display(); } }<file_sep><?php Class ConfigAction extends CommonAction{ public function index(){ $config = D('Config')->select(); $this->assign('config',$config); $this->display(); } //保存数据 public function dosaveconfig(){ foreach($_POST as $key=>$value){ $data['value'] = $value; $rs = D('Config')->where('`key`="'.$key.'"')->save($data); unset($data); } $this->redirect('admin.php/Config/index'); } public function create(){ $this->show('创建成功!'); } public function update(){ $this->show('修改成功!'); } public function delete(){ $this->show('删除成功!'); } //交易管理 public function order(){ $where['isdel'] = 0; //分页开始 $count = D('Order')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); $show = $Page->show();// 分页显示输出 $join = 'think_user ON think_order.uid=think_user.id'; $field = 'think_user.account,think_order.*'; $list = D('Order')->where($where)->join($join)->field($field)->order('think_order.id desc')->select(); $this->assign('list',$list); $this->assign('page',$show);// 赋值分页输出 $this->display(); } //删除记录 public function delorder(){ $delcid = $_POST['delcid']; $delcidarr = explode(',', $delcid); foreach ($delcidarr as $key=>$value){ $data['isdel'] = 1; D('Order')->where('id='.$value)->save($data); } } public function confirmorder(){ $orderid = $_POST['orderid']; $where['orderid'] = $orderid; $rs = D('Order')->where($where)->find(); if($rs){ $field = array("trade_status"=>"TRADE_FINISHED"); D('Order')->where($where)->setField($field); //更新扩展表 $where2['uid'] = $rs['uid']; $rs2 = D('Userextend')->where($where2)->find(); $rs_appid_arr = explode(',', $rs2['appid']); if(in_array($rs['appid'], $rs_appid_arr)){ echo "此用户已经购买过此产品了!"; exit; }else{ if(empty($rs2['appid'])){ $data2['appid'] = $rs['appid']; }else{ $data2['appid'] = $rs2['appid'].','.$rs['appid']; } $rs = D('Userextend')->where('uid='.$rs['uid'])->save($data2); echo 'ok'; } } } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><div class="trainingmiddleboxcontent item"> <div><img class="markgobackimg" src="__PUBLIC__/images/home/markback.png" alt="" /></div> <div class="kaosheninfo"> <ul> <li><strong>身份证号码:</strong><?php echo ($_SESSION['userinfo']['identitycard']); ?></li> <li><strong>姓名:</strong><?php echo ($_SESSION['userinfo']['account']); ?></li> <li><strong>期数:</strong>12365</li> <li><strong>试卷代码:</strong>568</li> </ul> </div> <?php echo ($topicslistmark); ?> </div><file_sep><?php if (!defined('THINK_PATH')) exit();?><div class="getpwdbox"> <form action="__URL__/dogetpwd" class="getuserpwdform"> 请输入您的注册邮箱地址:<br /> <input type="text" name="youremail" id="youremail" /> <input type="submit" value="找回密码" class="getpwdsubmit" /> </form> <img src="__PUBLIC__/images/home/sending.gif" class="sendingemail" alt="邮件发送中……" /> </div><file_sep><?php if (!defined('THINK_PATH')) exit();?><style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1100" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">基本设置</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td class="left_txt">当前位置:基本设置</td> </tr> <tr> <td height="20"><table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC"> <tr> <td></td> </tr> </table></td> </tr> <tr> <td><table width="100%" height="55" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="10%" height="55" valign="middle"><img src="__PUBLIC__/images/admin/title.gif" width="54" height="55"></td> <td width="90%" valign="top"><span class="left_txt2">在这里,您可以根据您的网站要求,修改设置网站的</span><span class="left_txt3">基本参数</span><span class="left_txt2">!</span><br> <span class="left_txt2">包括</span><span class="left_txt3">网站名称,网址,备案号,联系方式,船员职业,关键词,描述信息,支付宝信息,统计信息</span><span class="left_txt2">等以及网站</span><span class="left_txt3">其它相关设置</span><span class="left_txt2">。 </span></td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="nowtable"> <tr> <td class="left_bt2">&nbsp;&nbsp;&nbsp;&nbsp;系统参数设置</td> </tr> </table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <form name="form1" method="POST" action="__URL__/dosaveconfig"> <tr> <td width="20%" height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">设定网站名称:</td> <td width="3%" bgcolor="#f2f2f2">&nbsp;</td> <td width="32%" height="30" bgcolor="#f2f2f2"><input name="sitename" type="text" id="sitename" size="30" value="<?php echo $config[0]['value'] ?>" /></td> <td width="45%" height="30" bgcolor="#f2f2f2" class="left_txt">网站名称</td> </tr> <tr> <td width="20%" height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">网站第二名称:</td> <td width="3%" bgcolor="#f2f2f2">&nbsp;</td> <td width="32%" height="30" bgcolor="#f2f2f2"><input name="sitename2" type="text" id="sitename2" size="30" value="<?php echo $config[10]['value'] ?>" /></td> <td width="45%" height="30" bgcolor="#f2f2f2" class="left_txt">网站第二名称</td> </tr> <tr> <td width="20%" height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">设定网站网址:</td> <td width="3%" bgcolor="#f2f2f2">&nbsp;</td> <td width="32%" height="30" bgcolor="#f2f2f2"><input name="siteurl" type="text" id="siteurl" size="30" value="<?php echo $config[9]['value'] ?>" /></td> <td width="45%" height="30" bgcolor="#f2f2f2" class="left_txt">网站URL:如www.abc.com</td> </tr> <tr> <td height="30" align="right" class="left_txt2">网站后台密匙:</td> <td>&nbsp;</td> <td height="30"><input type="text" name="adminjiami" size="30" value="<?php echo $config[1]['value'] ?>" /></td> <td height="30" class="left_txt">默认密匙为:h8k30i2</td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">网站备案证号:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="beianhao" size="30" value="<?php echo $config[2]['value'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt">信息产业部备案号</td> </tr> <tr> <td height="30" align="right" class="left_txt2">联系电话信息: </td> <td>&nbsp;</td> <td height="30"><input type="text" name="tel" size="30" value="<?php echo $config[3]['value'] ?>" /></td> <td height="30" class="left_txt">设置网站联系电话</td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">网站客服QQ:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="myqq" size="30" value="<?php echo $config[4]['value'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt">设置网站客服QQ号</td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">网站微博地址:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="weibo" size="30" value="<?php echo $config[13]['value'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt">设置网站微博地址(全路径)</td> </tr> <tr> <td height="30" align="right" class="left_txt2">管理员邮箱:</td> <td>&nbsp;</td> <td height="30"><input name="mymail" type="text" id="mymail" size="30" value="<?php echo $config[5]['value'] ?>" /></td> <td height="30"><span class="left_txt">设置网站客服Email</span></td> </tr> <tr> <td height="30" align="right" class="left_txt2">随机考试题目:</td> <td>&nbsp;</td> <td height="30"><input name="examquestionnum" type="text" id="examquestionnum" size="30" value="<?php echo $config[11]['value'] ?>" /></td> <td height="30"><span class="left_txt">数量</span></td> </tr> <tr> <td height="30" align="right" class="left_txt2">船员职务:</td> <td>&nbsp;</td> <td height="30"><input name="jobs" type="text" id="jobs" size="55" value="<?php echo $config[14]['value'] ?>" /></td> <td height="30"><span class="left_txt">请用竖线“|”隔开!</span></td> </tr> <tr> <tr> <td height="30" align="right" class="left_txt2">热门应用搜索关键词:</td> <td>&nbsp;</td> <td height="30"><input name="apphotkey" type="text" id="apphotkey" size="55" value="<?php echo $config[12]['value'] ?>" /></td> <td height="30"><span class="left_txt">请用逗号隔开!</span></td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">关键词设置为: </td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="keywords" size="55" value="<?php echo $config[6]['value'] ?>" /></td> <td height="30" bgcolor="#f2f2f2"><span class="left_txt">设置网站的关键词,更容易被搜索引挚找到。</span></td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">签约支付宝账号: </td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="alipayemail" size="55" value="<?php echo $config[17]['value'] ?>" /></td> <td height="30" bgcolor="#f2f2f2"><span class="left_txt">仅支持即时到账签约账号。</span></td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">签约支付宝合作ID: </td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="alipaypartner" size="55" value="<?php echo $config[15]['value'] ?>" /></td> <td height="30" bgcolor="#f2f2f2"><span class="left_txt">支付宝商户中心获取。</span></td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">签约支付宝合作密钥: </td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="password" name="alipaykey" size="55" value="<?php echo $config[16]['value'] ?>" /></td> <td height="30" bgcolor="#f2f2f2"><span class="left_txt red">与上面相关的支付宝KEY。注意保密!</span></td> </tr> <tr> <td height="30" align="right" class="left_txt2">网站的描述信息: </td> <td>&nbsp;</td> <td height="30"><textarea name="sitediscription" cols="70" rows="2" class="left_txt"><?php echo $config[7]['value'] ?></textarea></td> <td height="30"><span class="left_txt">设置网站的描述信息,更容易被搜索引挚找到。</span></td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">网站统计代码:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><textarea name="sitetonji" cols="70" rows="2" class="left_txt"><?php echo $config[8]['value'] ?></textarea></td> <td height="30" bgcolor="#f2f2f2" class="left_txt">您可以申请51统计,百度统计,谷歌统计 (<a href="http://www.51.la/reg.asp" target="_blank">免费注册51la统计</a>)</td> </tr> <tr> <td height="30" align="right" class="left_txt2"></td> <td>&nbsp;</td> <td height="30"> <input type="submit" class="addformbuttons" value="提交数据" /> <input type="reset" value="重新填写" class="addformbuttons" /> </td> <td height="30" class="left_txt"></td> </tr> </form> </table></td> </tr> </table> </td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </body><file_sep><?php /** +公开访问的模块 */ Class PublicAction extends InitAction{ public function _initialize(){ parent::_initialize(); header("Content-Type:text/html; charset=utf-8"); } public function _empty($name){ redirect(__APP__.'/Public/login'); } //数字,字母,验证码 public function verify(){ $type = isset($_GET['type'])?$_GET['type']:'gif'; import('ORG.Util.Image'); Image::buildImageVerify($length=4, $mode=1, $type='png', $width=55, $height=20, $verifyName='verify'); } //中文验证码 Public function GBVerify(){ $type = isset($_GET['type'])?$_GET['type']:'gif'; import("ORG.Util.Image"); Image::GBVerify(); } // 检查用户是否登录 protected function checkUser() { if(!isset($_SESSION[C('USER_AUTH_KEY')])) { $this->error('没有登录',__APP__.'/Public/login'); } } // 用户登录页面 public function login() { if(!isset($_SESSION[C('USER_AUTH_KEY')])) { if(browser()!="FF"){ echo '<html><body><div style="width:800px;margin:200px auto;text-align:center;">'; echo '<b>友情提示:</b>请用<a target="_blank" href="http://firefox.com.cn/download/">火狐浏览器</a>管理网站后台!'; echo '</div></body></html>'; exit; } $this->display(); }else{ redirect(__APP__); } } public function index() { //如果通过认证跳转到首页 redirect(__APP__); } // 登录检测 public function checkLogin(){ //dump(session('website_adminjiami'));exit; if($_POST['adminjiami'] != session('website_adminjiami')) { $this->error('网站后台密匙错误!'); }elseif(empty($_POST['account'])) { $this->error('帐号错误!'); }elseif (empty($_POST['password'])){ $this->error('密码必须!'); }elseif (empty($_POST['verify'])){ $this->error('验证码必须!'); } //生成认证条件 $map = array(); // 支持使用绑定帐号登录 $map['account'] = $_POST['account']; $map["status"] = array('gt',0); if(session('verify') != md5($_POST['verify'])) { $this->error('验证码错误!'); } import ( 'ORG.Util.RBAC' ); $authInfo = RBAC::authenticate($map); //使用用户名、密码和状态的方式进行认证 if(false === $authInfo) { $this->error('帐号不存在或已禁用!'); }else { if($authInfo['password'] != md5($_POST['password'])) { $this->error('密码错误!'); } $_SESSION[C('USER_AUTH_KEY')] = $authInfo['id']; $_SESSION['email'] = $authInfo['email']; $_SESSION['loginUserName'] = $authInfo['nickname']; $_SESSION['lastLoginTime'] = $authInfo['last_login_time']; $_SESSION['login_count'] = $authInfo['login_count']; if($authInfo['account']=='admin') { $_SESSION['administrator'] = true; } //保存登录信息 $User = M('User'); $ip = get_client_ip(); $time = time(); $data = array(); $data['id'] = $authInfo['id']; $data['last_login_time'] = $time; $data['login_count'] = array('exp','login_count+1'); $data['last_login_ip'] = $ip; $User->save($data); $admininfo['username'] = $authInfo['account']; $admininfo['lastloginip'] = $ip; session('admininfo',$admininfo); // 缓存访问权限 RBAC::saveAccessList(); $this->success('登录成功!',__APP__.'/Index/index'); } } // 用户登出 public function logout() { if(isset($_SESSION[C('USER_AUTH_KEY')])) { unset($_SESSION[C('USER_AUTH_KEY')]); unset($_SESSION); session_destroy(); $this->success('登出成功!',__URL__.'/login/'); }else { $this->error('已经登出!'); } } // 更换密码 public function changePwd() { $this->checkUser(); //对表单提交处理进行处理或者增加非表单数据 if(md5($_POST['verify']) != $_SESSION['verify']) { $this->error('验证码错误!'); } $map = array(); $map['password']= <PASSWORD>($_POST['<PASSWORD>']); if(isset($_POST['account'])) { $map['account'] = $_POST['account']; }elseif(isset($_SESSION[C('USER_AUTH_KEY')])) { $map['id'] = $_SESSION[C('USER_AUTH_KEY')]; } //检查用户 $User = M("User"); if(!$User->where($map)->field('id')->find()) { $this->error('旧密码不符或者用户名错误!'); }else { $User->password = <PASSWORD>($_POST['password']); $User->save(); $this->success('密码修改成功!'); } } //获得用户的信息 public function profile() { $this->checkUser(); $User = M("User"); $vo = $User->getById($_SESSION[C('USER_AUTH_KEY')]); $this->assign('vo',$vo); $this->display(); } // 修改资料 public function change() { $this->checkUser(); $User = D("User"); if(!$User->create()) { $this->error($User->getError()); } $result = $User->save(); if(false !== $result) { $this->success('资料修改成功!'); }else{ $this->error('资料修改失败!'); } } } ?><file_sep><?php //判断浏览器 function browser(){ if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 8.0")) $browser = "IE8"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 7.0")) $browser = "IE7"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 9.0")) $browser = "IE9"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 6.0")) $browser = "IE6"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox")) $browser = "FF"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Chrome")) $browser = "Chrome"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Safari")) $browser = "Safari"; else if(strpos($_SERVER["HTTP_USER_AGENT"],"Opera")) $browser = "Opera"; else $browser = $_SERVER["HTTP_USER_AGENT"]; return $browser; } //用户头像 function getuseravatar($uid){ //$uid = session('user_id'); $uid = abs(intval($uid)); $uid = sprintf("%09d", $uid); $dir1 = substr($uid, 0, 3); $dir2 = substr($uid, 3, 2); $dir3 = substr($uid, 5, 2); $savepath = $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2)."_avatar_big.jpg"; $path = './Uploads/avatar/'.$savepath; if(!file_exists($path)){ $path = '/Public/images/home/defaultav.png'; }else{ $path = '/Uploads/avatar/'.$savepath; } return $path; } ?><file_sep><?php Class CityAction extends Action{ public function index(){ $city = D('city'); $alist = $city->field('id,name,pid,path,concat(path,"-",id) as bpath')->order('bpath')->select(); $this->assign('alist',$alist); //dump($alist); // 分页 开始 $count = $city->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,3);// 实例化分页类 传入总记录数和每页显示的记录数 $show = $Page->show();// 分页显示输出 // 进行分页数据查询 注意limit方法的参数要使用Page类的属性 // $list = $city->order('id')->limit($Page->firstRow.','.$Page->listRows)->select(); $list = $city->field('id,name,pid,path,concat(path,"-",id) as bpath')->order('bpath')->limit($Page->firstRow.','.$Page->listRows)->select(); $this->assign('list',$list);// 赋值数据集 $this->assign('page',$show);// 赋值分页输出 // 分页结束 $this->display(); } public function insert(){ // $city = new CityModel(); $city = D('City'); $vo = $city->create(); if($vo){ if($city->add()){ $this->success('添加成功'); }else{ $this->error('添加失败'); } }else{ $this->error($city->getError()); } } public function update(){ $city = D('City'); $id = $this->_get('id'); $name = $this->_get('name'); if(empty($id)){ $this->error('参数ID有误!'); } if($city->where("name='".$name."'")->find()){ $this->error('已经存在,请重新输入!'); } $city->id = $id; $city->name = $name; if($city->save()){ $this->success('更新成功!'); }else{ $this->error('更新失败!'); } } public function updateAjax(){ $city = D('City'); $vo = $city->create(); if($vo){ if($city->save()){ $this->ajaxReturn($this->_post('name'),'success',1); }else{ $this->ajaxReturn('修改失败','error',0); } }else{ $this->ajaxReturn($city->getError(),'create-error',0); } } public function delete(){ $city = D('city'); $id = $this->_get('id',intval,0); $onecity = $city->find($id); if(empty($onecity)){ $this->error('此地区不存在!'); }else{ $fid = $city->where('pid='.$onecity['id'])->find(); if($fid){ $this->error('请先删除此地区下面的子区域!'); }else{ $city->delete($cityid); $this->success('删除成功!'); } } } } ?><file_sep><?php $uid = $_GET['uid']; echo getAvatardir($uid); function getAvatardir($uid){ $ftid = str_pad($uid,9,"0",STR_PAD_LEFT); return './customavatars/'.$ftid[0].$ftid[1].$ftid[2].'/'.$ftid[3].$ftid[4].'/'.$ftid[5].$ftid[6].'/'.$ftid[7].$ftid[8].'_avatar_middle.jpg'; } ?><file_sep><?php Class InitAction extends Action{ public function _initialize(){ header("Content-Type:text/html; charset=utf-8"); Load('extend'); //网址基本信息 if(!session('website_sitename')){ $rs = D('Config')->select(); //支付宝相关 session('website_alipayemail',$rs[17]['value']); session('website_alipaykey',$rs[16]['value']); session('website_alipaypartner',$rs[15]['value']); //网站常规配制 session('website_weibo',$rs[13]['value']); session('website_apphotkey',$rs[12]['value']); session('website_examquestionnum',$rs[11]['value']); session('website_sitename2',$rs[10]['value']); session('website_siteurl',$rs[9]['value']); session('website_sitetonji',$rs[8]['value']); session('website_sitediscription',$rs[7]['value']); session('website_keywords',$rs[6]['value']); session('website_mymail',$rs[5]['value']); session('website_myqq',$rs[4]['value']); session('website_tel',$rs[3]['value']); session('website_beianhao',$rs[2]['value']); //session('website_adminjiami',$rs[1]['value']); session('website_sitename',$rs[0]['value']); $jobsarr = explode('|', $rs[14]['value']); $jobs = ''; foreach ($jobsarr as $key=>$value){ $jobs .= '<option value="'.$value.'">'.$value.'</option>'; } session('website_jobs',$jobs); } } } ?><file_sep><?php Class CommonAction extends InitAction{ public function _initialize(){ parent::_initialize(); //dump(session('userinfo')); header("Content-Type:text/html; charset=utf-8"); //session('user_id','36'); $this->resetpwd(); if(!session('user_id')){ $this->redirect('/'); }else{ if(!session('userinfo')){ $this->getUserinfo(); } } $this->assign('browser',browser()); } protected function getUserinfo(){ $uid = session('user_id'); $rs = D('User')->where('id='.$uid)->field('account,email,password,create_time,identitycard,sex,job,tel,address,birthday')->find(); session('userinfo',$rs); } protected function resetpwd(){ if($_GET['secretkey']){ $rs = D('User')->where("secretkey='".$_GET['secretkey']."'")->find(); session('user_id',$rs['id']); session('resetpwd',1);//标识,当前用户登陆是为了修改密码的. } } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #EEF2FB; } --> </style> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <body class="welcomebody"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td valign="top" <img src="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">欢迎界面</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td colspan="2" valign="top">&nbsp;</td> <td>&nbsp;</td> <td valign="top">&nbsp;</td> </tr> <tr> <td colspan="2" valign="top"><span class="left_bt">感谢您使用 <?php echo (session('website_sitename')); ?> 网站管理系统程序</span><br> <br> <span class="left_txt">&nbsp;<img src="__PUBLIC__/images/admin/ts.gif" width="16" height="16">快捷操作</span> <div class="kuaijiecaozuo"> <table> <tr> <td><a class="usermanage" href="__APP__/Config"><img src="__PUBLIC__/images/admin/applescript_utility.png" alt="" /></a></td> <td><a class="appmanage" href="__APP__/App/listapp"><img src="__PUBLIC__/images/admin/keyboard.png" alt="" /></a></td> <td><a class="coursemanage" href="__APP__/App/listcourse"><img src="__PUBLIC__/images/admin/kemu.png" alt="" /></a></td> <!-- <td><a href="##"><img src="__PUBLIC__/images/admin/folder_yellow_software_1.png" alt="" /></a></td> --> <td><a class="questionmanage" href="__APP__/App/listquestions"><img src="__PUBLIC__/images/admin/news_unsubscribe.png" alt="" /></a></td> <td><a class="articlemanage" href="__APP__/Articles/index"><img src="__PUBLIC__/images/admin/news.png" alt="" /></a></td> <td><a class="topupmanage" href="__APP__/User/index"><img src="__PUBLIC__/images/admin/money.png" alt="" /></a></td> <td><a class="applymanage" href="__APP__/User/onlineapplylist"><img src="__PUBLIC__/images/admin/on_line.png" alt="" /></a></td> </tr> <tr> <td>常规配置</td> <td>应用管理</td> <td>科目管理</td> <!-- <td>软件管理</td> --> <td>考题管理</td> <td>文章管理</td> <td>会员充值</td> <td>在线报名</td> </tr> </table> </div> </td> <td width="7%">&nbsp;</td> <td width="40%" valign="top"><table width="100%" height="144" border="0" cellpadding="0" cellspacing="0" class="line_table"> <tr> <td width="7%" height="27" background="__PUBLIC__/images/admin/news-title-bg.gif"><img src="__PUBLIC__/images/admin/news-title-bg.gif" width="2" height="27"></td> <td width="93%" background="__PUBLIC__/images/admin/news-title-bg.gif" class="left_bt2">最新统计</td> </tr> <tr> <td height="102" valign="top">&nbsp;</td> <td class="websitetongjitd" height="102" valign="top">会员:<?php echo ($usernum); ?>位 <br /> <a href="<?php echo U('Config/order');?>">未受理的订单:<?php echo ($ordernum); ?>个 <br /> 成功交易总金额:<?php echo ($allmoney); ?>元</a></td> </tr> <tr> <td height="5" colspan="2"></td> </tr> </table></td> </tr> <tr> <td colspan="2">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td colspan="2" valign="top"><!--JavaScript部分--> <SCRIPT language=javascript> function secBoard(n){ for(i=0;i<secTable.rows[0].cells.length;i++) secTable.rows[0].cells[i].className="sec1"; secTable.rows[0].cells[n].className="sec2"; for(i=0;i<mainTable.tBodies.length;i++) mainTable.tBodies[i].style.display="none"; mainTable.tBodies[n].style.display="block"; } </SCRIPT> <!--HTML部分--> <TABLE width=100% border=0 cellPadding=0 cellSpacing=0 id=secTable> <TBODY> <TR align=middle height=20> <TD align="center" class=sec2 onclick=secBoard(0)>系统参数</TD> <TD align="center" class=sec1 onclick=secBoard(1)>版权说明</TD> </TR> </TBODY> </TABLE> <TABLE class=main_tab id=mainTable cellSpacing=0 cellPadding=0 width=100% border=0> <!--关于tBodies集合--> <TBODY style="DISPLAY: block"> <TR> <TD vAlign=top align=middle width="579"> <TABLE width=98% border=0 align="center" cellPadding=0 cellSpacing=0> <TBODY> <TR> <TD colspan="3"></TD> </TR> <TR> <TD height="5" colspan="3"></TD> </TR> <TR> <TD width="4%" height="25" background="__PUBLIC__/images/admin/news-title-bg.gif"></TD> <TD height="25" colspan="2" background="__PUBLIC__/images/admin/news-title-bg.gif" class="left_txt"> <span class="TableRow2">运行环境:<?php echo ($info['运行环境']); ?></span> </TD> </TR> <TR> <TD height="25" bgcolor="#FAFBFC">&nbsp;</TD> <TD width="42%" height="25" bgcolor="#FAFBFC"><span class="left_txt"> 操作系统:<?php echo ($info['操作系统']); ?> </span></TD> <TD width="54%" height="25" bgcolor="#FAFBFC"><span class="left_txt">ThinkPHP版本:<?php echo ($info['ThinkPHP版本']); ?></span></TD> </TR> <TR> <TD height="25" bgcolor="#FAFBFC"></TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">上传附件限制:<?php echo ($info['上传附件限制']); ?></span></TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">执行时间限制:<?php echo ($info['执行时间限制']); ?></span></TD> </TR> <TR> <TD height="25" bgcolor="#FAFBFC"></TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">服务器时间: <?php echo ($info['服务器时间']); ?></span></TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">北京时间:<?php echo ($info['北京时间']); ?></span></TD> </TR> <TR> <TD height="25" bgcolor="#FAFBFC"></TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">服务器IP:<?php echo ($info['服务器域名/IP']); ?></span></TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">剩余空间: <?php echo ($info['剩余空间']); ?></span></TD> </TR> <TR> <TD height="25" bgcolor="#FAFBFC"></TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">Magic Quotes Runtime:<?php if($info['magic_quotes_runtime'] == 'YES' ): ?><img src="__PUBLIC__/images/admin/g.gif" width="12" height="12"><?php else: ?><img src="__PUBLIC__/images/admin/X.gif" width="12" height="13"><?php endif; ?> </span> </TD> <TD height="25" colspan="0" bgcolor="#FAFBFC"><span class="left_txt">Magic Quotes GPC: <?php if($info['magic_quotes_gpc'] == 'YES' ): ?><img src="__PUBLIC__/images/admin/g.gif" width="12" height="12"><?php else: ?><img src="__PUBLIC__/images/admin/X.gif" width="12" height="13"><?php endif; ?></span> </TD> </TR> <TR> <TD height="5" colspan="3"></TD> </TR> </TBODY> </TABLE></TD> </TR> </TBODY> <!--关于display属性--> <TBODY style="DISPLAY: none"> <TR> <TD vAlign=top align=middle width="579"> <TABLE width=98% border=0 align="center" cellPadding=0 cellSpacing=0> <TBODY> <TR> <TD colspan="3"></TD> </TR> <TR> <TD height="5" colspan="3"></TD> </TR> <TR> <TD width="4%" background="__PUBLIC__/images/admin/news-title-bg.gif"></TD> <TD width="91%" background="__PUBLIC__/images/admin/news-title-bg.gif" class="left_ts">本程序的相关说明:</TD> <TD width="5%" background="__PUBLIC__/images/admin/news-title-bg.gif" class="left_txt">&nbsp;</TD> </TR> <TR> <TD bgcolor="#FAFBFC">&nbsp;</TD> <TD bgcolor="#FAFBFC" class="left_txt"><span class="left_ts">1、</span>本程序是基于开源框架ThinkPHP开发完成(QQ:136553507) </TD> <TD bgcolor="#FAFBFC" class="left_txt">&nbsp;</TD> </TR> <TR> <TD bgcolor="#FAFBFC">&nbsp;</TD> <TD bgcolor="#FAFBFC" class="left_txt"><span class="left_ts">2、</span>本程序仅提供使用,任何违反互联网规定的行为,自行负责!</TD> <TD bgcolor="#FAFBFC" class="left_txt">&nbsp;</TD> </TR> <TR> <TD bgcolor="#FAFBFC">&nbsp;</TD> <TD bgcolor="#FAFBFC" class="left_txt"><span class="left_ts">3、</span> 支持作者的劳动,请保留版权。</TD> <TD bgcolor="#FAFBFC" class="left_txt">&nbsp;</TD> </TR> <TR> <TD bgcolor="#FAFBFC">&nbsp;</TD> <TD bgcolor="#FAFBFC" class="left_txt"><span class="left_ts">4、</span>程序使用,技术支持,二次开发,请联系www.lamp99.com(zhangjiachao.cn)</TD> <TD bgcolor="#FAFBFC" class="left_txt">&nbsp;</TD> </TR> <TR> <TD bgcolor="#FAFBFC">&nbsp;</TD> <TD bgcolor="#FAFBFC" class="left_txt"><span class="left_ts">5、</span>联系电话:13407131728</TD> <TD bgcolor="#FAFBFC" class="left_txt">&nbsp;</TD> </TR> <TR> <TD height="5" colspan="3"></TD> </TR> </TBODY> </TABLE></TD> </TR> </TBODY> </TABLE></td> <td>&nbsp;</td> <td valign="top"><table width="100%" height="144" border="0" cellpadding="0" cellspacing="0" class="line_table"> <tr> <td width="7%" height="27" background="__PUBLIC__/images/admin/news-title-bg.gif"><img src="__PUBLIC__/images/admin/news-title-bg.gif" width="2" height="27"></td> <td width="93%" background="__PUBLIC__/images/admin/news-title-bg.gif" class="left_bt2">程序说明</td> </tr> <tr> <td height="102" valign="top">&nbsp;</td> <td height="102" valign="top"><label></label> <label> <textarea name="textarea" cols="72" rows="6" class="left_txt">一、专业的PHP网站系统,在线ERP系统,门户网建设方案! 二、管理员首次登陆后台,请修改后台密码和后台登陆密钥! 三、请妥善保管好网站的后台信息,网站的FTP信息和数据库信息。 四、若是因为以上保密工作失误造成的网站一系列问题,或者引发不良后果,由运营团队自行全权负责。 五、如果网站出现异常,请及时和开发人员联系。 六、如果管理员忘记了密码,或者登陆址,也请联系开发人员处理。 七、网站即交付之日起后续仅提供操作和简单技术上的指导,不接受无条件再次开发和修改。 八、本系统程序仅<?php echo (session('website_sitename')); ?>独家授权使用,在未经开发团队许可的情况下不可以对任何第三方个人或公司复制、兜售本程序。</textarea> </label></td> </tr> <tr> <td height="5" colspan="2">&nbsp;</td> </tr> </table></td> </tr> <tr> <td height="40" colspan="4"><table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC"> <tr> <td></td> </tr> </table></td> </tr> <tr> <td width="2%">&nbsp;</td> <td width="51%" class="left_txt"><img src="__PUBLIC__/images/admin/icon-mail2.gif" width="16" height="11"> 客户服务邮箱:<EMAIL>&nbsp;&nbsp;&nbsp;&nbsp;<img src="__PUBLIC__/images/admin/icon-phone.gif" width="17" height="14"> 官方网站:http://www.lamp99.com</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="bottom" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17"></td> <td valign="bottom" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>管理页面</title> <script src="__PUBLIC__/js/admin/prototype.lite.js" type="text/javascript"></script> <script src="__PUBLIC__/js/admin/moo.fx.js" type="text/javascript"></script> <script src="__PUBLIC__/js/admin/moo.fx.pack.js" type="text/javascript"></script> <style> body { font:12px Arial, Helvetica, sans-serif; color: #000; background-color: #EEF2FB; margin: 0px; } #container { width: 182px; } H1 { font-size: 12px; margin: 0px; width: 182px; cursor: pointer; height: 30px; line-height: 20px; } H1 a { display: block; width: 182px; color: #000; height: 30px; text-decoration: none; moz-outline-style: none; background-image: url(__PUBLIC__/images/admin/menu_bgS.gif); background-repeat: no-repeat; line-height: 30px; text-align: center; margin: 0px; padding: 0px; } .content{ width: 182px; height: 26px; } .MM ul { list-style-type: none; margin: 0px; padding: 0px; display: block; } .MM li { font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 26px; color: #333333; list-style-type: none; display: block; text-decoration: none; height: 26px; width: 182px; padding-left: 0px; } .MM { width: 182px; margin: 0px; padding: 0px; left: 0px; top: 0px; right: 0px; bottom: 0px; clip: rect(0px,0px,0px,0px); } .MM a:link { font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 26px; color: #333333; background-image: url(__PUBLIC__/images/admin/menu_bg1.gif); background-repeat: no-repeat; height: 26px; width: 182px; display: block; text-align: center; margin: 0px; padding: 0px; overflow: hidden; text-decoration: none; } .MM a:visited { font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 26px; color: #333333; background-image: url(__PUBLIC__/images/admin/menu_bg1.gif); background-repeat: no-repeat; display: block; text-align: center; margin: 0px; padding: 0px; height: 26px; width: 182px; text-decoration: none; } .MM a:active { font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 26px; color: #333333; background-image: url(__PUBLIC__/images/admin/menu_bg1.gif); background-repeat: no-repeat; height: 26px; width: 182px; display: block; text-align: center; margin: 0px; padding: 0px; overflow: hidden; text-decoration: none; } .MM a:hover { font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 26px; font-weight: bold; color: #006600; background-image: url(__PUBLIC__/images/admin/menu_bg2.gif); background-repeat: no-repeat; text-align: center; display: block; margin: 0px; padding: 0px; height: 26px; width: 182px; text-decoration: none; } </style> </head> <body> <table width="100%" height="280" border="0" cellpadding="0" cellspacing="0" bgcolor="#EEF2FB"> <tr> <td width="182" valign="top"> <div id="container"> <h1 class="type"><a href="javascript:void(0)">应用管理</a></h1> <div class="content"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="__PUBLIC__/images/admin/menu_topline.gif" width="182" height="5" /></td> </tr> </table> <ul class="MM"> <li><a href="__APP__/App/listcourse" target="main">科目列表</a></li> <li><a href="__APP__/App/addcourse" target="main">添加科目</a></li> <li><a href="__APP__/App/listapp" target="main">应用列表</a></li> <li><a href="__APP__/App/addapp" target="main">添加应用</a></li> <li><a href="__APP__/App/listquestions" target="main">考题列表</a></li> <li><a href="__APP__/App/addquestions" target="main">添加考题</a></li> </ul> </div> <h1 class="type usermanage" id="typeusermanage"><a href="javascript:void(0)">会员管理</a></h1> <div class="content"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="__PUBLIC__/images/admin/menu_topline.gif" width="182" height="5" /></td> </tr> </table> <ul class="MM"> <li><a href="__APP__/User/index" target="main">会员列表</a></li> <!-- <li><a href="__APP__/User/adduser" target="main">添加会员</a></li> --> <li><a href="__APP__/User/onlineapplylist" target="main">在线报名</a></li> </ul> </div> <?php if(1==2){ ?> <h1 class="type"><a href="javascript:void(0)">用户权限管理</a></h1> <div class="content"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="__PUBLIC__/images/admin/menu_topline.gif" width="182" height="5" /></td> </tr> </table> <ul class="MM"> <li><a href="__APP__/User/index" target="main">用户列表</a></li> <li><a href="__APP__/Role/index" target="main">角色管理</a></li> <li><a href="__APP__/Node/index" target="main">节点管理</a></li> <li><a href="__APP__/Access/index" target="main">权限分配</a></li> <li><a href="##" target="main">举报管理</a></li> <li><a href="##" target="main">评论管理</a></li> </ul> </div> <?php } ?> <h1 class="type"><a href="javascript:void(0)">文章管理</a></h1> <div class="content"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="__PUBLIC__/images/admin/menu_topline.gif" width="182" height="5" /></td> </tr> </table> <ul class="MM"> <li><a href="__APP__/Articles/index" target="main">文章列表</a></li> <li><a href="__APP__/Articles/add" target="main">添加文章</a></li> </ul> </div> <h1 class="type"><a href="javascript:void(0)">常规选项</a></h1> <div class="content"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="__PUBLIC__/images/admin/menu_topline.gif" width="182" height="5" /></td> </tr> </table> <ul class="MM"> <li><a href="__APP__/Config" target="main">基本设置</a></li> <li><a href="__APP__/Config/order" target="main">交易管理</a></li> </ul> </div> <div class="programdiv"> <h1 class="type"><a href="javascript:void(0)">程序版本与技术支持</a></h1> <ul class="devinfo" style="color:#ddd;"> <li><?php echo (session('website_sitename2')); ?>-[测试版]</li> <li>开发:<a style="color:#ddd;" href="mailto:<EMAIL>.ji<EMAIL>">Jochen.zhang</a></li> <li>CopyRight©2012-<?php echo date('Y',time()); ?></li> </ul> </div> </div> <script type="text/javascript"> var contents = document.getElementsByClassName('content'); var toggles = document.getElementsByClassName('type'); var myAccordion = new fx.Accordion( toggles, contents, {opacity: true, duration: 400} ); myAccordion.showThisHideOpen(contents[0]); function con(event){ if(confirm("友情提示,退出系统请点击系统的右上角的 退出按钮!")){ return true; } return false; } window.onbeforeunload = con(); </script> </td> </tr> </table> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <title><?php if(!empty($pagetitle)): echo ($pagetitle); ?>_<?php endif; echo (session('website_sitename')); ?>_<?php echo str_replace('www.','',session('website_siteurl')); ?></title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta http-equiv="expires" content="0" /> <meta name="resource-type" content="document" /> <meta name="distribution" content="global" /> <meta name="author" content="CrewExam" /> <meta name="generator" content="lamp99.com,zhangjichao.cn" /> <meta name="copyright" content="Copyright (c) 2013 CrewExam. All Rights Reserved." /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta name="robots" content="index, follow" /> <meta name="revisit-after" content="1 days" /> <meta name="rating" content="general" /> <meta name="keywords" content="<?php echo (session('website_keywords')); ?>" /> <meta name="description" content="<?php echo ($pagediscription); echo (session('website_sitediscription')); ?>" /> <link rel="stylesheet" type="text/css" href="/Public/css/home/template.css" /> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/json2.js"></script><script type="text/javascript" src="/Public/js/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=chrome"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> </head> <body class="<?php echo ($browser); ?>"> <div class="bshade"></div> <div class="navigation"> <div class="navigation-wrapper"> <div id="logo2"> <h1> <a href="/"> <img width="218" height="55" src="__PUBLIC__/images/home/herderlogo2.png" /> </a> </h1> </div> <div class="nav-body site-nav exampage"> <div class="nav-main"> <div class="menu"> <div class="menu-title"> <a ui-async="async" href="<?php echo U('User/profile');?>" accesskey="1"><span stats="V6Hd_home" class="menu-title-text">会员首页</span></a> </div> </div> <div class="menu"> <div class="menu-title" id="profileMenuActive"> <a href="<?php echo U('User/myapp');?>" accesskey="2" id="showProfileMenu"><span class="menu-title-text" stats="V6Hd_Profile">我的应用</span></a> </div> </div> <div class="menu"> <div id="friendMenuActive" class="menu-title"> <a href="<?php echo U('User/allapp');?>" accesskey="3" id="showFriendMenu"><span stats="V6Hd_frd" class="menu-title-text">船员题库</span></a> </div> </div> </div> <div class="nav-other"> <div class="menu"> <a href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo (session('website_myqq')); ?>&site=qq&menu=yes" stats="homenav_suggest" title="给我们提建议">在线客户服务</a> </div> <div class="menu more hidden"> <a class="show-more" id="moreWeb" stats="homenav_more" href="##">更多</a> </div> </div> </div> </div> </div> <div class="page-wrapper clearfix"> <div class="full-page"> <div class="login-page clearfix"> <div class="main-columns"> <div id="login_area"> <div id="input_area" class="selecttypeh2page"> <div id="button_area" class="examloginbtn"> <img class="selecttypeh2img" src="__PUBLIC__/images/home/selecttypeh2.png" alt="" /> <div class="leftuserimgbox"><img src="<?php echo getuseravatar(); ?>" alt="" /></div> <div class="righuserinfotbox"> <table class="truserinfo"> <tbody> <tr> <th>身份证号</th> <td><?php echo ($_SESSION['userinfo']['identitycard']); ?></td> </tr> <tr> <th>准考证号</th> <td><?php echo (session('seatNo')); ?></td> </tr> <tr> <th>姓名</th> <td class="usernametd"><?php echo ($_SESSION['userinfo']['account']); ?></td> </tr> <tr> <th>期数</th> <td><?php echo ($rs["testqishu"]); ?></td> </tr> <tr> <th>科目</th> <td><?php echo ($rs["coursetitle"]); ?></td> </tr> <tr> <th>试卷代码</th> <td><?php echo ($rs["testcode"]); ?></td> </tr> <tr> <th>适用对象描述</th> <td class="shiyongduixiang"><?php echo ($rs["suitableusers"]); ?></td> </tr> </tbody> </table> </div> <div class="clearfix"></div> </div> </div> <div class="cbuttonbox"> <button title="<?php echo ($sappid); ?>" class="examselectbtn sutudyapp">题库练习</button> &nbsp;&nbsp;&nbsp;&nbsp; <button title="<?php echo ($sappid); ?>" class="examselectbtn gototest">开始考试</button> </div> </div> </div> </div> </div> </div> <div class="clearfix"></div> <div id="footer"> <div class="site-footer"> <div id="footer0904"> <div class="footer_c"><?php echo (session('website_sitename')); ?>客户服务热线:<?php echo (session('website_tel')); ?>(工作日 9:00-17:30) <a target="_blank" href="<?php echo (session('website_weibo')); ?>" class="weibo"><?php echo (session('website_sitename2')); ?></a> </div> <div class="footer_about"> <ul class="about"> <li class="first"><a href="<?php echo U('Public/news','id=86');?>" >关于船员考试网</a></li> <li><a href="<?php echo U('Public/newslist','cid=1');?>" target="_blank">最新资讯</a></li> <li><a href="<?php echo U('Public/newslist','cid=2');?>" target="_blank">常见问题</a></li> <li><a href="<?php echo U('Public/news','id=87');?>" target="_blank">联系我们</a></li> <li><a href="<?php echo U('Public/newslist','cid=3');?>" target="_blank">海事规则</a></li> <li><a href="<?php echo U('Public/news','id=88');?>" target="_blank">法律声明</a></li> <li><a href="<?php echo U('Public/news','id=89');?>" target="_blank">会员服务</a></li> <li><a href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo (session('website_myqq')); ?>&site=qq&menu=yes" >在线客服</a></li> <li class="last"><a href="http://www.ship123.com" target="_blank">船员导航网</a></li> </ul> </div> <div class="footer_text"> <p>客户服务热线:<?php echo (session('website_tel')); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>邮箱:<?php echo (session('website_mymail')); ?>&nbsp;&nbsp;网站ICP备案:<?php echo (session('website_beianhao')); ?></p> <p>通用网址 网络关键词:<?php echo (session('website_keywords')); ?></p> <p>CopyRight &copy; 2010-<?php echo date('Y',time()); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>&nbsp;&nbsp;<?php echo (session('website_siteurl')); ?>,All Rights Reserved&nbsp;&nbsp;<?php echo (session('website_sitename')); ?>&nbsp;&nbsp;版权所有</p> </div> <div class="icpbox"> <a href="http://t.knet.cn/" target="_blank" class="icp"><img src="__PUBLIC__/images/home/footerbeian.png"></a></div> <div class="tongji"><?php echo (session('website_sitetonji')); ?></div> </div> </div> </div> </body> </html><file_sep><?php Class PublicAction extends InitAction{ public function _initialize(){ parent::_initialize(); header("Content-Type:text/html; charset=utf-8"); date_default_timezone_set('PRC'); $this->assign('browser',browser()); } public function _empty(){ $this->redirect('/'); } public function reg(){ // $user = new Model('user'); $user = M('user'); $list = $user->find();//查询一条记录 $list = $user->select(); $list = $user->where('id=1 and username="admin"')->select(); $list = $user->getField('username,email,status',':'); $list = $user->select(array('where'=>'id>1','limit'=>'2','order'=>'id desc')); $list = $user->where('id=1')->field('username,email')->select(); //多表查询table方法之数组 $list = $user->table(array('think_user'=>'user','think_user_message'=>'message'))->where('user.id=message.uid')->select(); //多表查询table方法之字符串 $list = $user->table('think_user user,think_user_message message')->where('user.id=message.uid')->select(); //另外还有:data();field();group();lmite();having();join();distinac();relation();lock(); //$list = $user->distinac(true)->select(); // dump($list); //更新表中的数据用save()方法,数据存放在data数组中。 // $data['password'] = '<PASSWORD>'; // $list = $user->where('id=4')->save($data); //如果没有where,那data中得有主键元素 // $data['id']= '4'; // $data['password'] = '<PASSWORD>'; // $list = $user->where('id=4')->save($data); //或者用data()方法 // $list = $user->where('id=4')->data($data)->save(); // dump($list); //这里的$list 为受影响的行数。 /* // $user2 = new UserModel();//自定义的model $user2 = D('User');//它可以实例后台的类 eg. $user = D('admin','user');或者分组后用 $user = D('admin.user'); $list2 = $user2->aa(); dump($list2); // $user3 = new Model(); $user3 = M(); $list3 = $user3->query('select * from think_user'); dump($list3); */ //删除数据 // $list = $user->delete(4); // $list = $user->where('id>4')->delete(); //字段更新 加一 ,减一 /* $user->where('id=1')->setInc('money',2);//如不写2默认为1 $user->where('id=2')->setDec('money',1);//如不写2默认为1 $user->where('id=3')->setField('money','100');*/ $this->assign('pagetitle','会员注册'); $this->display(); } public function doreg(){ $data = $_POST; //验证码 if(md5($data['verify']) != session('verify')){ $this->error('验证码不正确!'); } //密码 if(strlen(trim($data['password']))<6){ $this->error('密码太短了,至少6位!'); } if($data['password'] != $data['password2']){ $this->error('两次密码不一致!'); } //邮箱 $rs = D('User')->where('email="'.$data['email'].'" or identitycard="'.$data['email'].'" or tel="'.$data['email'].'"')->find(); if($rs){ $this->error('此邮箱已经被注册!'); } //身份证 $rs = D('User')->where('identitycard="'.$data['identitycard'].'" or email="'.$data['identitycard'].'" or tel="'.$data['identitycard'].'"')->find(); if($rs){ $this->error('此身份证已经被注册!'); } //电话安全,不能是邮箱,也不能是身份证 $rs = D('User')->where('tel="'.$data['tel'].'" or email="'.$data['tel'].'" or identitycard="'.$data['tel'].'"')->find(); if($rs){ $this->error('此手机已经被注册!'); } //echo $_POST['Province'].'--'.$_POST['City'].'--'.$_POST['Area'];exit; $data['create_time'] = time(); $data['last_login_time'] = $data['create_time']; $data['status'] = 1; $data['login_count'] = 1; $data['last_login_ip'] = get_client_true_ip(); $data['password'] = md5($_POST['password']); $data['address'] = $_POST['Province'].'--'.$_POST['City'].'--'.$_POST['Area']; if($id = D('User')->add($data)){ //添加用户扩展表 $dataextend['uid'] = $id; D('Userextend')->add($dataextend); session('user_id',$id); //邮件通知,注册成功 $body = ' <html> <body style="background:#DCEEFC url(\"http://img.cnbeta.com/bg.png\")"> <a href="http://www.crewexam.com/"><img style="border:none;" src="http://www.crewexam.com/Public/images/home/herderlogo.png" /></a><br /><br /> 您好:'.$rs['account'].',欢迎注册本站会员<br /> 请牢记您的注册信息如下:<br /> 邮箱:'.$data['email'].'<br /> 电话:'.$data['tel'].'<br /> 身份证:'.$data['identitycard'].'<br /> <b>密码:'.$_POST['password'].'</b> <br /><br /> 说明:此邮件来自《中国航运导航网》系统,请不要回复。 </body> </html>'; SendMail($data['email'],session('website_sitename')." 注册成功",$body); $this->redirect('index.php/User/uploadavatar'); }else{ $this->redirect('index.php/Public/reg'); } } public function checkidentitycard(){ $identitycard = $_POST['identitycard']; //$identitycard = '420624198612117217x'; if($identitycard){ $baseurl = 'http://www.youdao.com/smartresult-xml/search.s?type=id&q='.$identitycard; $xml = file_get_contents($baseurl); $json = json_encode(simplexml_load_string($xml)); echo $json; /* $data = json_decode($json); $location = $data->product->location; $birthday = $data->product->birthday; $gender = $data->product->gender; */ } } public function dologin(){ $data['email'] = $_POST['uaccount']; $data['tel'] = $_POST['uaccount']; $data['identitycard'] = $_POST['uaccount']; $data['_logic'] = 'OR'; $map['_complex'] = $data; $map['password'] = array('eq',md5($_POST['password'])); if(strlen(trim($_POST['uaccount'])) == 0){ $this->error('用户名不能为空!'); } if(strlen(trim($_POST['password'])) == 0){ $this->error('密码不能为空!'); } $rs = D('User')->where($map)->find(); if($rs['block'] == 1){$this->error('此用户已经被锁定,请联系客服!');} if($rs){ $datas['last_login_time'] = time(); $datas['last_login_ip'] = get_client_true_ip(); D('User')->where('id='.$rs['id'])->setInc('login_count'); D('User')->where('id='.$rs['id'])->save($datas); session('user_id',$rs['id']); //是否自动登陆 if($_POST['autoLogin']){ cookie('autoLoginuserid',$rs['id'],360000); } $this->redirect('User/allapp'); }else{ $this->error('用户名或者密码不正确!'); } } public function logout(){ session(null);//删除所有的session cookie(null); cookie('autoLoginuserid',null); $this->redirect('index.php'); } function news(){ $id = $_GET['id']; $article = D('Articles')->where('id='.$id)->find(); if($article['cid'] != 6){ $description = true; } if($article['cid'] == 1){ $morearticle = true; $randarticles = D('Articles')->where('cid=1')->order('rand()')->limit(6)->select(); $this->assign('randarticles',$randarticles); } if($article['cid'] == 2 || $article['cid'] == 3){ $description = false; $morearticle = false; } $this->assign('description',$description); $this->assign('morearticle',$morearticle); if(!empty($article['discription'])){ $pagediscription = $article['discription']; } $this->assign('pagediscription',$pagediscription); $this->assign('pagetitle',$article['title']); $this->assign('article',$article); $this->display(); } function newslist(){ $cid = $_GET['cid'];//新闻分类 $where['cid'] = $cid; $articlecatgory = D('ArticlesCatogery')->where('id='.$cid)->find(); $this->assign('articlecatgory',$articlecatgory); //分页开始 $count = D('Articles')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条'); $Page->setConfig('theme','<div class="ttt">%upPage%</div> <div class="ttt">%downPage%</div> <div class="ttt">%prePage%</div> <div class="linkPage">%linkPage%</div> <div class="ttt">%nextPage%</div> <div class="ttt">%end%</div><div class="ttt">%totalRow%%header%</div>'); $article = D('Articles')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select(); $pagetitle = $articlecatgory['ctitle']; $show = $Page->show();// 分页显示输出 if($count > 15 ){ $this->assign('page',$show);// 赋值分页输出 } $this->assign('article',$article); $this->assign('pagetitle',$pagetitle); $this->display(); } //ajax 把你的app ID 定下来 public function selectapp(){ $sutudyappid = $_POST['sutudyappid']; //判断是否有权限 $uid = session('user_id'); $myappid = D('Userextend')->where('uid='.$uid)->find(); $myappidarr = split(',', $myappid['appid']); if(!in_array($sutudyappid, $myappidarr)){ echo 'nopermission';exit; } $type = $_POST['type']; if($sutudyappid){ session('sutudyappid',$sutudyappid); if(empty($type)){ session('istest',null); }else{ session('istest',$type); } //echo session('istest'); } } //点击进入考场时 public function selecttype(){ $sappid = $_GET['sutudyappid']; //判断当前用户是否购买了本套应用 $uid = session('user_id'); $myappid = D('Userextend')->where('uid='.$uid)->find(); $myappidarr = split(',', $myappid['appid']); if(!in_array($sappid, $myappidarr)){ $this->redirect('User/myapp'); exit; } //应用相关信息 $join = 'think_appcourse ON think_appcourse.id = think_app.courseid'; $field = 'think_app.*,think_appcourse.title as coursetitle'; $where['think_app.id'] = $sappid; $rs = D('App')->join($join)->field($field)->where($where)->find(); $this->assign('rs',$rs); $this->assign('sappid',$sappid); $this->assign('pagetitle','考生基本信息'); $this->display(); } public function getpwd(){ $this->display(); } public function dogetpwd(){ //发邮件 $youremail = $_POST['youremail']; $rs = D('User')->where("email='".$youremail."'")->find(); if(!$rs){ echo 'noemail';exit; } //生成服务器端的KEY,保存在用户信息中 $key = md5(md5(time()).time()); $data['secretkey'] = $key; D('User')->where("email='".$youremail."'")->save($data); $link = '<a tyle="color:red;font-weight:bolder;" href="http://www.crewexam.com/index.php/User/changepwd/secretkey/'.$key.'">点击这里修改密码!!!!</a>'; $body = ' <html> <body style="background:#DCEEFC url(\"http://img.cnbeta.com/bg.png\")"> <a href="http://www.crewexam.com/"><img style="border:none;" src="http://www.crewexam.com/Public/images/home/herderlogo.png" /></a><br /><br /> 您好:'.$rs['account'].',<br /> 您点击链接重置密码:'.$link.',<font color="green">请登陆后,立即更新您的密码,以确保账户的安全!</font><br /><br /> 说明:此邮件来自《中国航运导航网》系统,请不要回复。 </body> </html>'; SendMail($youremail,session('website_sitename')."修改新密码",$body); //$this->display('index'); } public function verify(){ import('ORG.Util.Image'); Image::buildImageVerify(); } public function GBVerify2(){ import("ORG.Util.Image"); Image::GBVerify($length=3, $type='png', $width=150, $height=50, $fontface='fanzhenjianzhiti.ttf', $verifyName='verify'); } public function GBVerify(){ vendor('Yzm.checkcode');//用第三方验证码类 YL_Security_Secoder::$useNoise = true; // 要更安全的话改成true YL_Security_Secoder::$useCurve = true; YL_Security_Secoder::entry(); } //支付 public function doalipay(){ //权限判断 if(empty($_POST['appid'])){ $this->error('无效操作!'); exit; } $where['uid'] = session('user_id'); $rs = D('Userextend')->where($where)->find(); $rs_appid_arr = explode(',', $rs['appid']); if(in_array($_POST['appid'], $rs_appid_arr)){ $this->error('请不要重复购买此产品!'); } $appinfo = D('App')->where('id='.$_POST['appid'])->field('id,title,price')->find(); //商户订单号 $out_trade_no = time(); $subject = '应用:'.$appinfo['id'].'--'.$appinfo['title']; //1.使用账户余额支付 if($rs['money'] >= $appinfo['price']){ D('Userextend')->where('uid='.session('user_id'))->setDec('money',$appinfo['price']); if(empty($rs['appid'])){ $data['appid'] = $appinfo['id']; }else{ $data['appid'] = $rs['appid'].','.$appinfo['id']; } $rs = D('Userextend')->where('uid='.session('user_id'))->save($data); if($rs){ $order['orderid'] = $out_trade_no; $order['uid'] = session('user_id'); $order['subject'] = $subject; $order['appid'] = $appinfo['id']; $userinfo = session('userinfo'); $order['buyer_email'] = $userinfo['email']; $order['trade_no'] = '站内全额交易'; $order['price'] = $appinfo['price']; $order['total_fee'] = $appinfo['price']; $order['trade_status'] = 'TRADE_FINISHED'; $order['gmt_create'] = $out_trade_no; $order['gmt_payment'] = $out_trade_no; D('Order')->add($order); $this->success('购买成功!','User/myapp'); }else{ D('Userextend')->where('uid='.session('user_id'))->setInc('money',$appinfo['price']); $this->success('购买失败!','User/allapp'); } exit; } //2.账户余额+支付宝一起支付 if(($rs['money'] > 0) && ($rs['money'] < $appinfo['price'])){ $chajia = $appinfo['price'] - $rs['money']; D('Userextend')->where('uid='.session('user_id'))->setDec('money',$rs['money']); $order['orderid'] = $out_trade_no; $order['uid'] = session('user_id'); $order['subject'] = $subject; $order['appid'] = $appinfo['id']; $userinfo = session('userinfo'); $order['buyer_email'] = $userinfo['email']; $order['trade_no'] = '站内部分余额交易'; $order['price'] = $rs['money']; $order['total_fee'] = $rs['money']; $order['trade_status'] = 'TRADE_FINISHED'; $order['gmt_create'] = $out_trade_no; $order['gmt_payment'] = $out_trade_no; D('Order')->add($order); //重新定义支付宝应该付款的金额和订单ID $appinfo['price'] = $chajia; $out_trade_no = $out_trade_no.'_alipay'; } //3.使用支付宝余额支付 vendor('Alipay.alipay#config'); vendor('Alipay.lib.alipay_submit#class'); $alipaySubmit = new AlipaySubmit($alipay_config); /**************************请求参数**************************/ //支付类型 $payment_type = "1"; //必填,不能修改 //服务器异步通知页面路径 $notify_url = "http://www.crewexam.com/index.php/Public/alipay_notify"; //需http://格式的完整路径,不能加?id=123这类自定义参数 //页面跳转同步通知页面路径 $return_url = "http://www.crewexam.com/index.php/Public/alipay_return"; //需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/ //卖家支付宝帐户 $seller_email = session('website_alipayemail'); //必填 //商户订单号 //$out_trade_no = $out_trade_no; //商户网站订单系统中唯一订单号,必填 //订单名称 //$subject = '应用:'.$appinfo['id'].'--'.$appinfo['title']; //必填 //付款金额 $total_fee = $appinfo['price']; //必填 //订单描述 $body = 'crewexam.app.com'; //商品展示地址 $show_url = 'http://www.crewexam.com/index.php'; //需以http://开头的完整路径,例如:http://www.xxx.com/myorder.html //防钓鱼时间戳 $anti_phishing_key = $alipaySubmit->query_timestamp(); //若要使用请调用类文件submit中的query_timestamp函数 //客户端的IP地址 $exter_invoke_ip = get_client_ip(); //非局域网的外网IP地址,如:192.168.127.12 /************************************************************/ //构造要请求的参数数组,无需改动 $parameter = array( "service" => "create_direct_pay_by_user", "partner" => trim($alipay_config['partner']), "payment_type" => $payment_type, "notify_url" => $notify_url, "return_url" => $return_url, "seller_email" => $seller_email, "out_trade_no" => $out_trade_no, "subject" => $subject, "total_fee" => $total_fee, "body" => $body, "show_url" => $show_url, "anti_phishing_key" => $anti_phishing_key, "exter_invoke_ip" => $exter_invoke_ip, "_input_charset" => trim(strtolower($alipay_config['input_charset'])) ); //保存订单 $order['orderid'] = $out_trade_no; $order['uid'] = session('user_id'); $order['subject'] = $subject; $order['appid'] = $appinfo['id']; $userinfo = session('userinfo'); $order['price'] = $total_fee; $order['total_fee'] = $total_fee; $order['trade_status'] = 'TRADE_PENDDING'; $order['gmt_create'] = $out_trade_no; D('Order')->add($order); //建立请求 $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "正在连接支付宝……"); echo $html_text; } public function alipay_notify(){ //业务逻辑处理 vendor('Alipay.alipay#config'); vendor('Alipay.lib.alipay_notify#class'); //计算得出通知验证结果 $alipayNotify = new AlipayNotify($alipay_config); $verify_result = $alipayNotify->verifyNotify(); if($verify_result) { //商户订单号 $out_trade_no = $_POST['out_trade_no']; //支付宝交易号 $trade_no = $_POST['trade_no']; $trade_status = $_POST['trade_status']; if($_POST['trade_status'] == 'TRADE_FINISHED') { //普通即时到账... $where['trade_no'] = $out_trade_no; $data['buyer_email'] = $_POST['buyer_email']; $data['trade_status'] = $trade_status; $data['gmt_payment'] = $_POST['gmt_payment']; D('Order')->where($where)->save($data); $rs = D('Order')->where($where)->find(); $where2['uid'] = $rs['uid']; $rs2 = D('Userextend')->where($where2)->find(); $rs_appid_arr = explode(',', $rs2['appid']); if(in_array($rs['appid'], $rs_appid_arr)){ echo "fail"; exit; }else{ if(empty($rs2['appid'])){ $data2['appid'] = $rs['appid']; }else{ $data2['appid'] = $rs2['appid'].','.$rs['appid']; } $rs = D('Userextend')->where('uid='.$rs['uid'])->save($data2); } }else if($_POST['trade_status'] == 'TRADE_SUCCESS'){ //高级即时到账... } echo "success"; exit; }else{ echo "fail"; exit; } } public function alipay_return(){ vendor('Alipay.alipay#config'); vendor('Alipay.lib.alipay_notify#class'); $alipayNotify = new AlipayNotify($alipay_config); $verify_result = $alipayNotify->verifyReturn(); if($verify_result) { $out_trade_no = $_GET['out_trade_no']; $trade_no = $_GET['trade_no']; $out_trade_no = $_GET['out_trade_no']; $trade_status = $_GET['trade_status']; if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 $where['trade_no'] = $trade_no; $where['orderid'] = $out_trade_no; $where['trade_status'] = $trade_status; $rs = D('Order')->where($where)->find(); if(!$rs){ $data['trade_status'] = $trade_status; $data['buyer_email'] = $_GET['buyer_email']; $data['gmt_payment'] = $_GET['gmt_payment']; D('Order')->where($where)->save($data); $rs = D('Order')->where($where)->find(); $where2['uid'] = $rs['uid']; $rs2 = D('Userextend')->where($where2)->find(); $rs_appid_arr = explode(',', $rs2['appid']); if(in_array($rs['appid'], $rs_appid_arr)){ echo "fail"; exit; }else{ if(empty($rs2['appid'])){ $data2['appid'] = $rs['appid']; }else{ $data2['appid'] = $rs2['appid'].','.$rs['appid']; } $rs = D('Userextend')->where('uid='.$rs['uid'])->save($data2); } } } else { //echo "trade_status=".$_GET['trade_status']; $this->error($trade_status,'User/myapp'); } $this->success('恭喜您,购买成功','User/myapp'); }else{ $this->error('支付失败,请联系客服或者重新操作!','User/myapp'); } } } ?><file_sep><?php Class UserAction extends CommonAction{ public function _after_index(){ $rs = $this->index(); //查询用户的角色 $list = $rs[0]; $order = $rs[1]; $roleuser = M('RoleUser'); foreach ($list as $key=>$value){ $userid = $value['id']; $rolelist = $roleuser->join('think_role ON think_role.id=think_role_user.role_id')->where('think_role_user.user_id='.$userid)->find(); $list[$key]['rolename'] = $rolelist['name']; } $order = $this->getSortby($list[0]); $this->assign('list',$list); $this->assign('order',$order); $this->display(); } public function _after_edit(){ $vo = $this->edit(); $role = M('role'); $listrole = $role->field('id,name,pid,path,concat(path,"-",id) as bpath')->order('bpath')->select(); $this->assign('listrole',$listrole); $roleuser = M('RoleUser'); $userid = $vo['id']; $rolelist = $roleuser->join('think_role ON think_role.id=think_role_user.role_id')->where('think_role_user.user_id='.$userid)->find(); $vo['roleid'] = $rolelist['id']; $vo['rolename'] = $rolelist['name']; $rsex = D('Userextend')->where('uid='.$userid)->find(); $money = $rsex['money']; $this->assign('vo', $vo); $this->assign('money',$money); $this->display(); } //添加用户 public function adduser(){ $user = M('role'); $listrole = $user->field('id,name,pid,path,concat(path,"-",id) as bpath')->order('bpath')->select(); $this->assign('listrole',$listrole); $this->display(); } //修改用户 public function edituser(){ $uid = $this->_request('uid'); $model = D('User'); $list = $model->where('User.id='.$uid)->find(); $this->assign('list',$list); // dump($list); $user = M('role'); $listrole = $user->field('id,name,pid,path,concat(path,"-",id) as bpath')->order('bpath')->select(); $this->assign('listrole',$listrole); $this->display(); } //删除用户 public function deluser(){ $delcid = $_POST['delcid']; $delcidarr = explode(',', $delcid); foreach ($delcidarr as $key=>$value){ if($value != 1){ //D('User')->where('id='.$value)->delete(); $rs = D('User')->where('id='.$value)->field('block')->find(); if($rs['block'] == 1){ $data['block'] = 0; }else{ $data['block'] = 1; } D('User')->where('id='.$value)->save($data); } } } //添加用户add public function add(){ $user = D('User'); $validate = array( array('username','require','用户名必须!'), // 仅仅需要进行验证码的验证 array('username','','用户名已经存在!',0,'unique',1), array('password','<PASSWORD>','密码长度需要8-12位!',0,'length'), // 验证确认密码是否和密码一致 array('repassword','password','两次密码不一致!',0,'confirm'), // 验证确认密码是否和密码一致 // array('email','require','邮箱必须!'), array('email','email','邮箱地址不符合规则!'), ); $auto = array( array('password','md5',1,'function') , // 对password字段在新增的时候使md5函数处理 array('createtime','time',1,'function'), // 对create_time字段在更新的时候写入当前时间戳 // array('lastloginip','get_client_ip',1,'function'), ); $user->setProperty("_validate",$validate); $user->setProperty("_auto",$auto); if($vo = $user->create()){ if($newUserID = $user->add()){ //添加用户到对应角色表 $role = M('RoleUser'); $data['role_id'] = $this->_post('userrole'); $data['user_id'] = $newUserID; $role->add($data); $this->success('添加用户成功!'); }else{ $this->error('新增用户失败!'); } }else{ $this->error($user->getError()); } } //修改用户save public function save(){ if($_POST['money']){ $where['id'] = $_POST['id']; $data['money'] = $_POST['money']; D('Userextend')->where($where)->save($data); } $this->redirect('User/index'); } public function onlineapplylist(){ $where['isdel'] = 0; //分页开始 $count = D('Onlineapply')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); //查询所有 $list = D('Onlineapply')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select(); $show = $Page->show();// 分页显示输出 $this->assign('page',$show);// 赋值分页输出 $this->assign('list',$list); $this->display(); } public function deletonlineapply(){ $delcid = $_POST['delcid']; $delcidarr = explode(',', $delcid); foreach ($delcidarr as $key=>$value){ $data['isdel'] = 1; D('Onlineapply')->where('id='.$value)->save($data); } } } ?><file_sep><?php // 本类由系统自动生成,仅供测试用途 class IndexAction extends InitAction { public function _initialize(){ parent::_initialize(); header("Content-Type:text/html; charset=utf-8"); $this->assign('browser',browser()); userautologin(); } public function index(){ $ip = get_client_ip(); $ip = get_client_true_ip(); import('ORG.Net.IpLocation');// 导入IpLocation类 $Ip = new IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件 $area = $Ip->getlocation('172.16.17.32'); // 获取某个IP地址所在的位置 //dump($area); //$this->show('我来了','utf-8'); //$this->show(C('DB_USER')); $news = D('Articles')->where('cid=1')->limit(4)->order('id desc')->select(); $fqas = D('Articles')->where('cid=2')->limit(4)->order('id desc')->select(); $imgs = D('Articles')->where('id=95')->find(); $this->assign('news',$news); $this->assign('fqas',$fqas); $this->assign('imgs',$imgs); //$this->assign('pagetitle','网站首页'); $this->display(); // $this->display('index','utf-8','text/html'); // $this->display('login'); // $this->display('User:login'); // $this->display('./Home/Tpl/default/Index/index.html'); } public function login(){ echo __ROOT__.'<br>'; echo __APP__.'<br>'; echo __URL__.'<br>'; echo __ACTION__.'<br>'; echo __SELF__.'<br>'; echo APP_NAME.'<BR>'; echo APP_PATH.'<BR>'; echo NOW_TIME.'<br>'; echo DATA_PATH.'<BR>'; echo THEME_NAME.'<br>'; } }<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <script charset="utf-8" src="__PUBLIC__/js/editor/kindeditor/kindeditor.js"></script> <script charset="utf-8" src="__PUBLIC__/js/editor/kindeditor/lang/zh_CN.js"></script> <script> var editor; KindEditor.ready(function(K) { editor = K.create('textarea[name="intro"]', { allowFileManager : true }); }); </script> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> </head> <body> <form name="form1" method="post" action="__URL__/doaddquestion" enctype="multipart/form-data" class="postquestionform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1100" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">编辑题目</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td class="left_txt">当前位置:题目编辑</td> </tr> <tr> <td height="20"><table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC"> <tr> <td></td> </tr> </table></td> </tr> <tr> <td></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="nowtable"> <tr> <td class="left_bt2">&nbsp;&nbsp;&nbsp;&nbsp;题目选项</td> </tr> </table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="20%" height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">题目标题:</td> <td width="3%" bgcolor="#f2f2f2">&nbsp;</td> <td width="32%" height="30" bgcolor="#f2f2f2"> <input name="title" type="text" id="title" size="60" value="<?php echo $question['title'] ?>" /> <span class="newsblock"><input type="checkbox" value="1" name="isdel" <?php if($question['isdel'] == 1): ?>checked<?php endif; ?> id="isdel" /><label for="isdel">取消发布</label></span> </td> <td width="45%" height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">所属应用:</td> <td>&nbsp;</td> <td height="30" style=""> <select name="appid" id="appid" class="addormodifyappid"> <option value="0">==请选择应用名称==</option> <?php if(is_array($appid)): $i = 0; $__LIST__ = $appid;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option <?php if($vo['id'] == $question['appid']): ?>selected<?php endif; ?> value="<?php echo ($vo["id"]); ?>"><?php echo ($vo["title"]); ?> <?php if($vo['testqishu'] != ''): ?>-<?php echo ($vo["testqishu"]); endif; ?> </option><?php endforeach; endif; else: echo "" ;endif; ?> </select> </td> <td height="30" class="left_txt"></td> </tr> <tr class=""> <td height="30" align="right" class="left_txt2">题目描述: </td> <td>&nbsp;</td> <td height="30"> <textarea name="intro" id="discription" style="width:670px;" cols="30" rows="5"><?php echo $question['intro'] ?></textarea> </td> <td height="30" class="left_txt">根据情况填写,如果没有,可以不填写!</td> </tr> </table></td> </tr> <tr> <td><table style="margin-top: 5px;" width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="nowtable"> <tr> <td class="left_bt2">&nbsp;&nbsp;&nbsp;&nbsp;答案与选项 <span class="addnewanswer">添加一个新选项!</span> </td> </tr> </table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0" class="answertable"> <?php ?> <?php if(is_array($answers)): $i = 0; $__LIST__ = $answers;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr class="answertritembox <?php if($i%2 == 0): ?>oushu<?php endif; ?>"> <td width="14%" height="30" align="right" class="left_txt2"> <input type="text" name="answeridentify[]" value="<?php echo ($vo["answeridentify"]); ?>" class="answeridentifyid"/> </td> <td width="3%">&nbsp;</td> <td width="32%" height="30"> <input type="text" name="answercontent[]" value="<?php echo ($vo["answercontent"]); ?>" class="answercontentid" /></td> <td width="45%" height="30" class="left_txt rightansweridtd"> 正解:<input type="checkbox" name="rightanswer[]" class="rightanswerid" <?php if(strpos($question['answer'],$vo['answeridentify']) !== false){echo "checked";} ?> value="<?php echo ($vo["answeridentify"]); ?>" /> <img class="delansweritemimg" src="__PUBLIC__/images/admin/publish_x.png" alt="删除" /> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> <tr class="submitquestitemtrbox"> <td width="14%" height="30" align="right" class="left_txt2"></td> <td width="3%">&nbsp;</td> <td width="32%" height="30"> <input class="submitnews addformbuttons" type="submit" value="提交数据" /> <input class="addformbuttons" type="reset" value="重新填写" /> </td> <td width="45%" height="30" class="left_txt"><input type="hidden" name="id" value="<?php echo $question['id'] ?>" /></td> </tr> </table></td> </tr> </table> </td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </form> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title><?php echo (session('website_sitename')); ?>---管理员登陆</title> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <script language="JavaScript"> function correctPNG() { var arVersion = navigator.appVersion.split("MSIE") var version = parseFloat(arVersion[1]) if ((version >= 5.5) && (document.body.filters)) { for(var j=0; j<document.images.length; j++) { var img = document.images[j] var imgName = img.src.toUpperCase() if (imgName.substring(imgName.length-3, imgName.length) == "PNG") { var imgID = (img.id) ? "id='" + img.id + "' " : "" var imgClass = (img.className) ? "class='" + img.className + "' " : "" var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' " var imgStyle = "display:inline-block;" + img.style.cssText if (img.align == "left") imgStyle = "float:left;" + imgStyle if (img.align == "right") imgStyle = "float:right;" + imgStyle if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" img.outerHTML = strNewHTML j = j-1 } } } } function updateverifyimg(obj){ obj.src="__APP__/Public/verify/?"+Math.random(); } // window.attachEvent("onload", correctPNG); </script> </head> <body class="loginpage"> <table width="100%" height="166" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="42" valign="top"><table width="100%" height="42" border="0" cellpadding="0" cellspacing="0" class="login_top_bg"> <tr> <td width="1%" height="21">&nbsp;</td> <td height="42">&nbsp;</td> <td width="17%">&nbsp;</td> </tr> </table></td> </tr> <tr> <td valign="top"><table width="100%" height="532" border="0" cellpadding="0" cellspacing="0" class="login_bg"> <tr> <td width="49%" align="right"><table width="91%" height="532" border="0" cellpadding="0" cellspacing="0" class="login_bg2"> <tr> <td height="138" valign="top"><table width="89%" height="427" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="149">&nbsp;</td> </tr> <tr> <td height="80" align="right" valign="top"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="35%">&nbsp;</td> <td class="left_txt"><img src="__PUBLIC__/images/admin/logo.png" width="279" height="68"></td> </tr> </table> </td> </tr> <tr> <td height="198" align="right" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="35%">&nbsp;</td> <td height="25" colspan="2" class="left_txt"><p>1.系统将自动锁定登陆用户的IP地址,非管理人员请离开!</p></td> </tr> <tr> <td>&nbsp;</td> <td height="25" colspan="2" class="left_txt"><p>2.如果管理员忘记密码,请联系客服,或者网站开发人员!</p></td> </tr> <tr> <td>&nbsp;</td> <td height="25" colspan="2" class="left_txt"><p>3.其它问题,请及时与客服联系完成系统更新服务。</p></td> </tr> <tr> <td>&nbsp;</td> <td width="30%" height="40" class="left_txt"><img src="__PUBLIC__/images/admin/icon-demo.gif" width="16" height="16"><a href="javascript:void(0);" class="left_txt3"> 使用说明</a> </td> <td width="35%" class="left_txt"><img src="__PUBLIC__/images/admin/icon-login-seaver.gif" width="16" height="16"><a href="javascript:void(0);" class="left_txt3"> 在线客服</a></td> </tr> </table></td> </tr> </table></td> </tr> </table></td> <td width="1%" >&nbsp;</td> <td width="50%" valign="bottom"><table width="100%" height="59" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="4%">&nbsp;</td> <td width="96%" height="38"><span class="login_txt_bt">登陆网站后台管理</span></td> </tr> <tr> <td>&nbsp;</td> <td height="21"><table cellSpacing="0" cellPadding="0" width="100%" border="0" id="table211" height="328"> <tr> <td height="164" colspan="2" align="middle"> <form name="loginform" class="loginform" action="__URL__/checkLogin" method="post"> <table cellSpacing="0" cellPadding="0" width="100%" border="0" height="143" id="table212"> <tr> <td width="13%" height="38" class="top_hui_text"><span class="login_txt">管理员:&nbsp;&nbsp; </span></td> <td height="38" colspan="2" class="top_hui_text"><input name="account" class="editbox4 useraccount" value="" size="20" autocomplete="off" /></td> </tr> <tr> <td width="13%" height="35" class="top_hui_text"><span class="login_txt"> 密 码: &nbsp;&nbsp; </span></td> <td height="35" colspan="2" class="top_hui_text"><input class="editbox4 userpwd" type="<PASSWORD>" size="20" name="password" autocomplete="off" /> <img style="vertical-align: middle;" src="__PUBLIC__/images/admin/luck.gif" width="19" height="18"> </td> </tr> <tr> <td width="13%" height="35" class="top_hui_text"><span class="login_txt"> 密 匙: &nbsp;&nbsp; </span></td> <td height="35" colspan="2" class="top_hui_text"><input class="editbox4 userpwdmishi" type="<PASSWORD>" size="20" name="adminjiami" autocomplete="off" /> <img style="vertical-align: middle;" src="__PUBLIC__/images/admin/luck.gif" width="19" height="18"> </td> </tr> <tr> <td width="13%" height="35" class="top_hui_text" ><span class="login_txt">验证码:</span></td> <td height="35" colspan="2" class="top_hui_text"><input class="wenbenkuang uservali" name="verify" type="text" value="" maxLength=4 size=10 autocomplete="off" /> <img onclick="updateverifyimg(this)" class="verify" alt="点击图片可以刷新验证码" src='__APP__/Public/verify/' /> </td> </tr> <tr> <td height="35" >&nbsp;</td> <td width="50%" height="35" class="top_hui_text"><input name="Submit" type="submit" class="button" id="Submit" value="登 陆"> <input name="cs" type="reset" class="button cancelbutton" id="cs" value="重 置" onClick="showConfirmMsg1()"> </td> <td width="65%" class="top_hui_text"></td> </tr> </table> <br> </form> </td> </tr> <tr> <td width="433" height="164" align="right" valign="bottom"><img src="__PUBLIC__/images/admin/login-wel.gif" width="242" height="138"></td> <td width="57" align="right" valign="bottom">&nbsp;</td> </tr> </table></td> </tr> </table> </td> </tr> </table></td> </tr> <tr> <td height="20"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="login-buttom-bg"> <tr> <td align="center"><span class="login-buttom-txt">Copyright &copy; 2011-<?php echo date('Y',time()) ?> www.crewexam.com</span></td> </tr> </table></td> </tr> </table> </body> </html><file_sep><?php $config1 = array( //'配置项'=>'配置值' // 'URL_CASE_INSENSITIVE' =>true,//URL不区分大小写 'DEFAULT_THEME'=>'default',//默认模板 'TMPL_L_DELIM'=>'<{', 'TMPL_R_DELIM'=>'}>', //默认错误跳转对应的模板文件 'TMPL_ACTION_ERROR' => 'Public:error', //默认成功跳转对应的模板文件 'TMPL_ACTION_SUCCESS' => 'Public:success', 'TOKEN_ON'=>true, // 是否开启令牌验证 'TOKEN_NAME'=>'__hash__', // 令牌验证的表单隐藏字段名称 'TOKEN_TYPE'=>'MD5', //令牌哈希验证规则 默认为MD5 'TOKEN_RESET'=>true, //令牌验证出错后是否重置令牌 默认为true // 'SHOW_RUN_TIME'=>true, //运行时间显示 // 'SHOW_ADV_TIME'=>true,//显示详细的运行时间 // 'SHOW_DB_TIMES'=>true,//显示数据库的操作次数 // 'SHOW_CACHE_TIMES'=>true,//显示缓存操作次数 // 'SHOW_USE_MEM'=>true,//显示内存开销 'USER_AUTH_ON' => true, //开启用户认证 'USER_AUTH_TYPE' => 2, // 默认认证类型 1 登录认证 2 实时认证 'USER_AUTH_KEY' => 'authId', // 用户认证SESSION标记 'ADMIN_AUTH_KEY' => 'administrator', 'USER_AUTH_MODEL' => 'User', // 默认验证数据表模型 'AUTH_PWD_ENCODER' => 'md5', // 用户认证密码加密方式 'USER_AUTH_GATEWAY' => '/Public/login',// 默认认证网关 'NOT_AUTH_MODULE' => 'Public', // 默认无需认证模块 'REQUIRE_AUTH_MODULE' => '', // 默认需要认证模块 'NOT_AUTH_ACTION' => '', // 默认无需认证操作 'REQUIRE_AUTH_ACTION' => '', // 默认需要认证操作 'GUEST_AUTH_ON' => false, // 是否开启游客授权访问 'GUEST_AUTH_ID' => 0, // 游客的用户ID 'DB_LIKE_FIELDS' => 'title|remark', 'RBAC_ROLE_TABLE' => 'think_role', 'RBAC_USER_TABLE' => 'think_role_user', 'RBAC_ACCESS_TABLE' => 'think_access', 'RBAC_NODE_TABLE' => 'think_node', 'SHOW_PAGE_TRACE' => 0,//显示调试信息 ); $config2 = include './config.inc.php'; return array_merge($config1,$config2); ?><file_sep><?php // 本类由系统自动生成,仅供测试用途 class UserAction extends CommonAction { public function _initialize(){ parent::_initialize(); } public function _empty(){ $this->redirect('/'); } public function iwantapply(){ $appid = $_GET['appid']; $rs = D('App')->where('id='.$appid)->find(); $this->assign('appname',$rs['title']); $this->display(); } public function doiwantapply(){ if(md5($_POST['verify']) != session('verify')){ $this->error('验证码错误!'); } $_POST['address'] = $_POST['Province'].','.$_POST['City'].','.$_POST['Area']; $_POST['ctime'] = time(); $_POST['isdel'] = 0; D('Onlineapply')->add($_POST); $this->success('报名成功!'); } public function login(){ } public function insert(){ //注册用户的信息写入数据库 $user = D('User'); $vo = $user->field('username,password,email,photo')->create(); if($vo){ $photoinfo = $this->upload(); // dump($photoinfo);exit; $user->photo = $photoinfo[0]['savename']; if($user->add()){ $this->success('注册成功'); }else{ $this->error('注册失败'); } }else{ $this->error($user->getError()); } } public function update(){ //注册用户的信息写入数据库 $user = M('user'); if($user->create()){ $user->password = md5($user->password); $user->name = $user->username; if($user->save()){ $this->success('修改成功'); }else{ $this->error('修改失败'); } } } // 图片上传 Public function upload(){ import('ORG.Net.UploadFile'); $upload = new UploadFile();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 $upload->savePath = './Uploads/images/';// 设置附件上传目录 if(!$upload->upload()) {// 上传错误提示错误信息 $this->error($upload->getErrorMsg()); }else{// 上传成功 获取上传文件信息 $info = $upload->getUploadFileInfo(); } return $info; } //用户app public function myapp(){ $uid = session('user_id'); $myappid = D('Userextend')->where('uid='.$uid)->find(); $where['id'] = array('in',$myappid['appid']); //分页开始 $count = D('App')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); $appslist = D('App')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select(); $show = $Page->show();// 分页显示输出 $this->assign('page',$show);// 赋值分页输出 $this->assign('appslist',$appslist); $this->assign('pagetitle','我的应用'); $this->display(); } public function dodownloadapp(){ $appid = $_POST['id']; $uid = session('user_id'); $myappid = D('Userextend')->where('uid='.$uid)->find(); $myappidarr = split(',', $myappid['appid']); if(in_array($appid, $myappidarr)){ $rs = D('App')->where('id='.$appid)->field('downloadurl')->find(); echo 'http://'.session('website_siteurl').'/Uploads/files/'.$rs['downloadurl']; }else{ echo 'error'; } } public function profile(){ $this->assign('pagetitle','修改资料'); $this->display(); } public function changepwd(){ $this->assign('pagetitle','修改密码'); $this->display(); } public function uploadavatar(){ $this->assign('pagetitle','上传头像'); $this->display(); } public function allapp(){ //$this->assign('appslist',array('a','b','c','d','a','b','c','d','a','b','c','d')); switch ($_GET['gid']){ case 1: $pagetitle = '适任证书-D'; break; case 2: $pagetitle = '适任证书-E'; break; case 3: $pagetitle = '基本证书'; break; case 4: $pagetitle = '特殊证书'; break; case 5: $pagetitle = '知识更新'; break; case 6: $pagetitle = '内河证书'; break; case 7: $pagetitle = '其它'; break; default: $pagetitle = '全部船员题库练习与模拟考试'; } $this->assign('pagetitle',$pagetitle); //查询当前用户已经购买过的应用 $uid = session('user_id'); $myextend = D('Userextend')->where('uid='.$uid)->find(); if($myextend['appid']){ $where['id'] = array('not in',$myextend['appid']); } $where['isdel'] = 0; if($_GET['gid']){ $cid = $_GET['gid']; $courseid = D('Appcourse')->where('cid='.$cid)->field('id')->select(); foreach ($courseid as $key=>$value){ $courseids .= $value['id'].','; } $where['courseid'] = array('in',substr($courseids, 0,strlen($courseids)-1)); } if($_GET['sort']){ $sort = $_GET['sort']; if($sort == 'download'){ $order = 'hitnum desc'; } if($sort == 'latestonline'){ $order = 'ctime desc'; } } if($_GET['appsearchvalue']){ $where['title'] = array('like','%'.$_GET['appsearchvalue'].'%'); } //分页开始 $count = D('App')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,12);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); $appslist = D('App')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order($order)->select(); $show = $Page->show();// 分页显示输出 $this->assign('page',$show);// 赋值分页输出 $this->assign('appslist',$appslist); $this->display(); } //购买APP public function buyapp(){ $appid = $_GET['appid']; if(!$appid){ $this->error('无效参数'); } $where['isdel'] = 0; $where['id'] = $appid; $appinfo = D('App')->where($where)->find(); $this->assign('appinfo',$appinfo); $this->display(); } //购买APP操作 public function dobuy(){ //$rs:1/成功, 2/已经购买 ,3/购买失败 echo $rs = 1; } //修改用户资料 public function domodifyuserinfo(){ $data = $_POST; //验证码 if(md5($data['verify']) != session('verify')){ $this->error('验证码不正确!'); } $data['address'] = $_POST['Province'].'--'.$_POST['City'].'--'.$_POST['Area']; //电话安全,不能是邮箱,也不能是身份证 $rs = D('User')->where('(tel="'.$data['telephone'].'" or email="'.$data['telephone'].'" or identitycard="'.$data['telephone'].'") and id <>'.session('user_id'))->find(); //echo D('User')->getLastSql(); //dump($data);exit; if($rs){ $this->error('修改失败,此手机已经被注册!'); } $id = D('User')->where('id='.session('user_id'))->save($data); parent::getUserinfo(); $this->redirect('index.php/User/profile'); } //修改用户密码 public function dochangepwd(){ $data = $_POST; if(!session('resetpwd')){ if(md5($data['password0']) != $_SESSION['userinfo']['password']){ $this->error('原密码不正确!'); } } if(strlen(trim($data['password'])) < 7){ $this->error('密码长度不能小于7位'); } if(trim($data['password']) != trim($data['password2'])){ $this->error('两次密码不一致,请重新输入!'); } $data['password'] = md5($data['<PASSWORD>']); D('User')->where('id='.session('user_id'))->save($data); parent::getUserinfo(); $this->success('恭喜您:密码修改成功!'); } }<file_sep><?php /** * */ class CommonModel extends Model { function __construct(argument) { # code... } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title><?php echo ($pagetitle); ?>_<?php echo C('SITE_NAME') ?></title> <link rel="stylesheet" type="text/css" href="/Public/css/home/template.css" /> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/json2.js"></script><script type="text/javascript" src="/Public/js/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=chrome"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> </head> <body class="<?php echo ($browser); ?>"> <div class="bshade"></div> <div class="navigation"> <div class="navigation-wrapper"> <div id="logo2"> <h1> <a href="/"> <img width="218" height="55" src="__PUBLIC__/images/home/herderlogo2.png" /> </a> </h1> </div> <div class="nav-body site-nav exampage"> <div class="nav-main"> <div class="menu"> <div class="menu-title"> <a ui-async="async" href="<?php echo U('User/profile');?>" accesskey="1"><span stats="V6Hd_home" class="menu-title-text">会员首页</span></a> </div> </div> <div class="menu"> <div class="menu-title" id="profileMenuActive"> <a href="<?php echo U('User/myapp');?>" accesskey="2" id="showProfileMenu"><span class="menu-title-text" stats="V6Hd_Profile">我的应用</span></a> </div> </div> <div class="menu"> <div id="friendMenuActive" class="menu-title"> <a href="<?php echo U('User/allapp');?>" accesskey="3" id="showFriendMenu"><span stats="V6Hd_frd" class="menu-title-text">船员题库</span></a> </div> </div> </div> <div class="nav-other"> <div class="menu"> <a href="##" stats="homenav_suggest" title="给我们提建议">在线客户服务</a> </div> <div class="menu more hidden"> <a class="show-more" id="moreWeb" stats="homenav_more" href="##">更多</a> </div> </div> </div> </div> </div> <div class="page-wrapper clearfix"> <div class="full-page"> <div class="login-page clearfix"> <div class="main-columns"> <div id="login_area"> <form action="__URL__/doexamlogin" method="post"> <div id="input_area"> <div id="button_area" class="examloginbtn"> <img src="__PUBLIC__/images/home/selecttypeh2.png" alt="" /> <div class="leftuserimgbox"><img src="<?php echo getuseravatar(); ?>" alt="" /></div> <div class="righuserinfotbox"> <table class="truserinfo"> <tbody> <tr> <th>身份证号</th> <td><?php echo ($_SESSION['userinfo']['identitycard']); ?></td> </tr> <tr> <th>准考证号</th> <td>B12431234565</td> </tr> <tr> <th>姓名</th> <td class="usernametd"><?php echo ($_SESSION['userinfo']['account']); ?></td> </tr> <tr> <th>期数</th> <td><?php echo ($rs["testqishu"]); ?></td> </tr> <tr> <th>科目</th> <td><?php echo ($rs["coursetitle"]); ?></td> </tr> <tr> <th>试卷代码</th> <td><?php echo ($rs["testcode"]); ?></td> </tr> <tr> <th>适用对象描述</th> <td><?php echo ($rs["suitableusers"]); ?></td> </tr> </tbody> </table> </div> <div class="clearfix"></div> </div> </div> <div class="cbuttonbox"> <button title="<?php echo (session('sutudyappid')); ?>" class="examselectbtn sutudyapp">题库练习</button> &nbsp;&nbsp;&nbsp;&nbsp; <button title="<?php echo (session('sutudyappid')); ?>" class="examselectbtn gototest">开始考试</button> </div> </form> </div> </div> </div> </div> </div> <div class="clearfix"></div> <div id="footer"> <div class="site-footer"> <div id="footer0904"> <div class="footer_c"><?php echo (session('website_sitename')); ?>客户服务热线:<?php echo (session('website_tel')); ?>(工作日 9:00-17:30) <a target="_blank" href="http://e.weibo.com/yiche" class="weibo"><?php echo (session('website_sitename2')); ?></a> </div> <div class="footer_about"> <ul class="about"> <li class="first"><a href="http://corp.bitauto.com/" target="_blank">关于船员考试网</a></li> <li><a href="http://corp.bitauto.com/business/" target="_blank">最新资讯</a></li> <li><a href="http://corp.bitauto.com/news/" target="_blank">常见问题</a></li> <li><a href="http://corp.bitauto.com/job/" target="_blank">联系我们</a></li> <li><a href="http://corp.bitauto.com/about/contact-us.shtml" target="_blank">海事规则</a></li> <li><a href="http://corp.bitauto.com/about/legal-notices.shtml" target="_blank">法律声明</a></li> <li><a href="http://i.bitauto.com/authenservice/register/Licence.aspx" target="_blank">会员服务</a></li> <li><a href="http://www.bitauto.com/feedback/" target="_blank">在线客服</a></li> <li class="last"><a href="http://dealer.easypass.cn/" target="_blank">船员导航网</a></li> </ul> </div> <div class="footer_text"> <p>客户服务热线:<?php echo (session('website_tel')); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>邮箱:<?php echo (session('website_mymail')); ?>&nbsp;&nbsp;网站ICP备案:<?php echo (session('website_beianhao')); ?></p> <p>通用网址 网络关键词:<?php echo (session('website_keywords')); ?></p> <p>CopyRight &copy; 2010-<?php echo date('Y',time()); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>&nbsp;&nbsp;<?php echo (session('website_siteurl')); ?>,All Rights Reserved&nbsp;&nbsp;<?php echo (session('website_sitename')); ?>&nbsp;&nbsp;版权所有</p> </div> <div class="icpbox"> <a href="http://t.knet.cn/" target="_blank" class="icp"><img src="__PUBLIC__/images/home/footerbeian.png"></a></div> <div class="tongji"><?php echo (session('website_sitetonji')); ?></div> </div> </div> </div> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><div class="appbuybox"> <form action=""> <div class="buyapptitle"> 你要购买的产品如下: </div> <div class="buyappinfo"> <div class="buyappinfoleft"> <img src="__PUBLIC__/images/appicon/<?php echo ($appinfo["logo"]); ?>" alt="" /> </div> <div class="buyappinforight"> <div class="apptitle"><?php echo ($appinfo["title"]); ?></div> <div class="lxline"></div> 价格:<span class="buyappprice">¥<?php echo ($appinfo["price"]); ?></span> </div> <div class="clearfix"></div> </div> <div class="productinfo1"> <b>产品介绍</b> <?php echo ($appinfo["intro"]); ?> </div> <div class="productinfo2"> <b>适用对象</b> <?php echo ($appinfo["suitableusers"]); ?> </div> <div class="buyappnote"> 重要提示:购买应用产品前,请认真阅读船员考试网使用规则,支付购买即代表您已经接受产品使用协议! </div> <div class="oktobuy"> <button class="clicktobuy oktobuyappbtn">确认购买</button> <input type="checkbox" name="aplyxieyi" checked id="aplyxieyi" /> <label for="aplyxieyi">我接受</label> <a target="_blank" href="<?php echo U('Public/news','id=89');?>">船员考试网使用规则</a> </div> </form> </div><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <title><?php if(!empty($pagetitle)): echo ($pagetitle); ?>_<?php endif; echo (session('website_sitename')); ?>_<?php echo str_replace('www.','',session('website_siteurl')); ?></title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta http-equiv="expires" content="0" /> <meta name="resource-type" content="document" /> <meta name="distribution" content="global" /> <meta name="author" content="CrewExam" /> <meta name="generator" content="lamp99.com,zhangjichao.cn" /> <meta name="copyright" content="Copyright (c) 2013 CrewExam. All Rights Reserved." /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta name="robots" content="index, follow" /> <meta name="revisit-after" content="1 days" /> <meta name="rating" content="general" /> <meta name="keywords" content="<?php echo (session('website_keywords')); ?>" /> <meta name="description" content="<?php echo ($pagediscription); echo (session('website_sitediscription')); ?>" /> <link rel="stylesheet" type="text/css" href="/Public/css/home/template.css" /> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/json2.js"></script><script type="text/javascript" src="/Public/js/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=chrome"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> </head> <body class="<?php echo ($browser); ?>"> <div class="bshade"></div> <div class="userapplyinfobox"> <div class="regboxcontent iwantapplypopupbox"> <link rel="stylesheet" type="text/css" href="/Public/images/home/tip-yellowsimple/tip-yellowsimple.css" /><link rel="stylesheet" type="text/css" href="/Public/images/home/datepicker/css/jquery-ui.css" /> <script type="text/javascript" src="/Public/js/jquery_poshytip.js"></script><script type="text/javascript" src="/Public/js/city.js"></script><script type="text/javascript" src="/Public/images/home/datepicker/js/jquery-ui-datepicker.js"></script> <form action="__URL__/doiwantapply" class="reg-form" method="post"> <table class="regtableleft"> <tr> <th>应用名称:</th> <td><?php echo ($appname); ?> <input type="hidden" name="appname" value="<?php echo ($appname); ?>" /> </td> </tr> <tr> <th>身份证号码:</th> <td><?php echo ($_SESSION['userinfo']['identitycard']); ?> <input type="hidden" name="personcard" value="<?php echo ($_SESSION['userinfo']['identitycard']); ?>" /> </td> </tr> <tr> <th>姓名:</th> <td><?php echo ($_SESSION['userinfo']['account']); ?> <input type="hidden" name="name" value="<?php echo ($_SESSION['userinfo']['account']); ?>" /> </td> </tr> <tr> <th>邮箱:</th> <td> <input type="text" name="email" id="usereamil" value="<?php echo ($_SESSION['userinfo']['email']); ?>" class="txt" title="请输入常用邮箱" /> </td> </tr> <tr> <th>性别:</th> <td> <?php $sex = $_SESSION['userinfo']['sex'];if($sex==1){$m = 'checked';}else{$w = 'checked';} ?> <input type="radio" <?php echo $m; ?> name="sex" id="sexman" value="男" /><label for="sexman">男</label> <span style="width: 20px;">&nbsp;</span> <input type="radio" <?php echo $w; ?> name="sex" id="sexwoman" value="女" /><label for="sexwoman">女</label> </td> </tr> <tr> <th>现任职务:</th> <td><select name="job" id="job"> <option value="<?php echo ($_SESSION['userinfo']['job']); ?>"><?php echo ($_SESSION['userinfo']['job']); ?></option> <option value="大力水手">大力水手</option> <option value="船长">船长</option> <option value="大副">大副</option> </select></td> </tr> <tr> <th>联系电话:</th> <td><input type="text" name="tel" id="telephone" value="<?php echo ($_SESSION['userinfo']['tel']); ?>" class="telephone txt" title="你的手机或者固定电话!" /></td> </tr> <tr> <th>所在地:</th> <td class="pcabox"> <select name="Province"></select><select name="City"></select><select name="Area"></select> <?php $address = explode('--',$_SESSION['userinfo']['address']); ?> <script language="javascript">new PCAS("Province","City","Area",'<?php echo $address[0] ?>','<?php echo $address[1] ?>','<?php echo $address[2] ?>');</script> </td> </tr> <tr class="buchongyuming"> <th>补充说明:</th> <td> <textarea name="note" id="buchongyuming" cols="30" rows="3"></textarea> </td> </tr> <tr> <th class="verifyth">验证码:</th> <td> <script type="text/javascript">function updateverifyimg(obj){obj.src="__APP__/Public/GBVerify/?"+Math.random();}</script> <img onclick="updateverifyimg(this)" class="verifyimg" src="__APP__/Public/GBVerify/" alt="验证码" /><span>点击图片换一张?</span><br /> <input type="text" name="verify" id="verify" class="verify txt" title="输入上面图片中的文字" /> </td> </tr> <tr class="dianjibaoming"> <th></th> <td><input type="submit" class="applysubbutton" value="点击报名" /></td> </tr> </table> <div class="clearfix"></div> </form> </div> </div> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> </head> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1500" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">考题列表</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td colspan="2"> <div class="searchform"> <span class="deluser"><a class="delalink question" href="javascript:void(0);">删除试题</a></span> <form action="__SELF__" method="get" id="newslistform"> <select name="cid" id="cid"> <option value="0">应用的全部分类</option> <?php if(is_array($catgory)): $i = 0; $__LIST__ = $catgory;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option <?php if($vo['id'] == $getcid): ?>selected<?php endif; ?> value="<?php echo ($vo["id"]); ?>"><?php echo ($vo["catgory"]); ?></option><?php endforeach; endif; else: echo "" ;endif; ?> </select> <select name="courseid" id="courseid" class="applistpage"> <option value="0">应用的全部科目</option> <?php if(is_array($course)): $i = 0; $__LIST__ = $course;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option <?php if($vo['id'] == $getcourseid): ?>selected<?php endif; ?> value="<?php echo ($vo["id"]); ?>"><?php echo ($vo["title"]); ?></option><?php endforeach; endif; else: echo "" ;endif; ?> </select> <select name="appid" id="appid" class="applistpage"> <option value="0">全部应用</option> <?php if(is_array($app)): $i = 0; $__LIST__ = $app;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option <?php if($vo['id'] == $getappid): ?>selected<?php endif; ?> value="<?php echo ($vo["id"]); ?>"><?php echo ($vo["title"]); ?></option><?php endforeach; endif; else: echo "" ;endif; ?> </select> </form> <div class="c"></div> </div> <table class="listtable"> <thead> <tr> <td style="width:20px;" class="knum">#</td> <td style="width:20px;"><input type="checkbox" onclick="checkAll('cid',this)" title="全选" name="checkall-toggle"></td> <td style="width:500px;"><a href="##">题目标题</a></td> <td style="width:140px;"><a href="##">所属应用</a></td> <td style="width:40px;"><a href="##">类型</a></td> <td style="width:60px;"><a href="##">正确答案</a></td> <td style="width:40px;"><a href="##">状态</a></td> <td style="width:120px;"><a href="##">发布日期</a></td> <td style="width:60px;"><a href="##">ID编号</a></td> </tr> </thead> <tbody> <?php if(is_array($list)): $k = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($k % 2 );++$k;?><tr class="row<?php echo ($k%2); ?>"> <td><?php echo ($k); ?></td> <td><input type="checkbox" value="<?php echo ($vo["id"]); ?>" name="cid"></td> <td align="left"><a href="__URL__/addquestions/id/<?php echo ($vo["id"]); ?>"><?php echo ($vo["title"]); ?></a></td> <td><?php echo ($vo["apptitle"]); ?></td> <td><?php echo ($vo["type"]); ?></td> <td><?php echo ($vo["answer"]); ?></td> <td> <?php if(($vo["isdel"] == 0)): ?><img src="__PUBLIC__/images/admin/tick.png" alt="已经发布"> <?php else: ?> <img src="__PUBLIC__/images/admin/publish_x.png" alt="禁止发布"><?php endif; ?> </td> <td><?php echo (date("Y-m-d H:m:s",$vo["ctime"])); ?></td> <td><?php echo ($vo["id"]); ?></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </tbody> <tfoot> <tr> <td colspan="15"><div class="result page"><?php echo ($page); ?></div></td> </tr> </tfoot> </table> </td> </tr> </table></td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1500" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">修改用户</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td class="left_txt location">当前位置:用户管理</td> <td class="left_txt curdbuttonbox"> <a class="historygoback" href="javascript:window.history.go(-1)">返回</a> </td> </tr> <tr> <td height="20" colspan="2">&nbsp;</td> </tr> <tr> <td colspan="2"> <img class="useradavtar" src="<?php echo (getuseravatar($vo["id"])); ?>" alt="" /> <form action="__URL__/save" method="post"> <table width="100%" cellspacing="0" cellpadding="0" border="0"> <tr> <td width="20%" height="30" align="right" class="left_txt2">用户名:</td> <td width="3%">&nbsp;</td> <td width="32%" height="30"> <?php echo ($vo['account']); ?> </td> <td width="45%" height="30" class="left_txt"></td> </tr> <tr bgcolor="#f2f2f2" > <td height="30" align="right" class="left_txt2">邮箱地址:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" ><?php echo ($vo['email']); ?></td> <td height="30" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">身份证号码:</td> <td>&nbsp;</td> <td height="30" ><?php echo ($vo['identitycard']); ?></td> <td height="30" class="left_txt"></td> </tr> <tr bgcolor="#f2f2f2" > <td height="30" align="right" class="left_txt2">生日:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" ><?php echo ($vo['birthday']); ?></td> <td height="30" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">性别:</td> <td>&nbsp;</td> <td height="30" > <?php if($vo['sex'] == 1): ?>男<?php else: ?>女<?php endif; ?> </td> <td height="30" class="left_txt"></td> </tr> <tr bgcolor="#f2f2f2" > <td height="30" align="right" class="left_txt2">职务:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" ><?php echo ($vo['job']); ?></td> <td height="30" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">电话:</td> <td>&nbsp;</td> <td height="30" ><?php echo ($vo['tel']); ?></td> <td height="30" class="left_txt"></td> </tr> <tr bgcolor="#f2f2f2" > <td height="30" align="right" class="left_txt2">所在地:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" ><?php echo ($vo['address']); ?></td> <td height="30" class="left_txt"></td> </tr> <tr > <td height="30" align="right" class="left_txt2">账户余额:</td> <td>&nbsp;</td> <td height="30" ><input type="text" name="money" id="money" value="<?php echo ($money); ?>" />元</td> <td height="30" class="left_txt"></td> </tr> <?php if(1==2){ ?> <tr bgcolor="#f2f2f2"> <td height="30" align="right" class="left_txt2">用户分组:</td> <td>&nbsp;</td> <td height="30" ><select name="userrole" style="width:225px;"> <option value="<?php echo ($vo['roleid']); ?>"><?php echo ($vo['rolename']); ?></option> <?php if(is_array($listrole)): $i = 0; $__LIST__ = $listrole;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option value="<?php echo ($vo['id']); ?>"> |<?php $con = count(split('-', $vo['path'])); for ($i=0; $i < $con; $i++) { echo '--'; } ?> <?php echo ($vo['name']); ?> </option><?php endforeach; endif; else: echo "" ;endif; ?> </select></td> <td height="30" class="left_txt">用户在本系统中的角色</td> </tr> <?php } ?> <tr> <td height="30" align="right" class="left_txt2"></td> <td>&nbsp;</td> <td height="30"> <input type="hidden" name="id" value="<?php echo ($vo["id"]); ?>" /> <input type="submit" name="submit" class="addformbuttons" value="修改信息" style="margin-right:68px;"> <input type="reset" name="reset" value="重新填写" class="addformbuttons"> </td> <td height="30" class="left_txt"></td> </tr> </table> </form> </td> </tr> </table></td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <title><?php if(!empty($pagetitle)): echo ($pagetitle); ?>_<?php endif; echo (session('website_sitename')); ?>_<?php echo str_replace('www.','',session('website_siteurl')); ?></title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta http-equiv="expires" content="0" /> <meta name="resource-type" content="document" /> <meta name="distribution" content="global" /> <meta name="author" content="CrewExam" /> <meta name="generator" content="lamp99.com,zhangjichao.cn" /> <meta name="copyright" content="Copyright (c) 2013 CrewExam. All Rights Reserved." /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta name="robots" content="index, follow" /> <meta name="revisit-after" content="1 days" /> <meta name="rating" content="general" /> <meta name="keywords" content="<?php echo (session('website_keywords')); ?>" /> <meta name="description" content="<?php echo ($pagediscription); echo (session('website_sitediscription')); ?>" /> <link rel="stylesheet" type="text/css" href="/Public/css/home/template.css" /> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/json2.js"></script><script type="text/javascript" src="/Public/js/common.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=chrome"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> </head> <body class="<?php echo ($browser); ?>"> <div class="bshade"></div> <div class="navigation"> <div class="navigation-wrapper"> <div id="logo2"> <h1> <a href="/"> <img width="218" height="55" src="__PUBLIC__/images/home/herderlogo.png" /> </a> </h1> </div> <div class="nav-body"> <h2 class="nav-title">中国船员在线题库练习与模拟考试网</h2> <div class="nav-other"> <div class="menu"> <a href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo (session('website_myqq')); ?>&site=qq&menu=yes" stats="homenav_suggest" title="给我们提建议">在线客户服务</a> </div> <div class="menu more hidden"> <a class="show-more" id="moreWeb" stats="homenav_more" href="##">更多</a> </div> </div> </div> </div> </div> <div class="page-wrapper clearfix"> <div class="full-page"> <div class="login-page clearfix"> <?php if($_SESSION['user_id']== ''): ?><div class="side-column"> <div class="login-panel"> <form action="<?php echo U('Public/dologin');?>" class="login-form" id="loginForm" method="post"> <dl class="top clearfix"> <dt> <label for="email">帐号:</label> </dt> <dd style="border-color: rgb(173, 182, 201);"> <input type="text" value="邮箱/身份证/电话号码" tabindex="1" id="email" class="input-text" name="uaccount" style="color: rgb(136, 136, 136);"> </dd> </dl> <dl class="pwd clearfix"> <dt> <label for="password">密码:</label> </dt> <dd> <input type="password" autocomplete="off" tabindex="2" class="input-text" error="请输入密码" name="password" id="password"> <label for="password" id="pwdTip" class="pwdtip">请输入密码</label> </dd> </dl> <div class="clearfix"></div> <dl class="savepassword clearfix"> <dt> <label class="labelCheckbox" for="autoLogin" title="为了确保您的信息安全,请不要在网吧或者公共机房勾选此项!"> <input type="checkbox" tabindex="4" value="true" id="autoLogin" name="autoLogin">下次自动登录 </label> </dt> <dd> <span id="getpassword" class="getpassword"><a stats="home_findpassword" href="##">忘记密码?</a></span> </dd> </dl> <dl class="bottom"> <input type="hidden" value="/" name="origURL"> <input type="hidden" value="crewexam.com" name="domain"> <input type="hidden" value="1" name="key_id"> <input type="hidden" value="web_login" id="captcha_type" name="captcha_type"> <input type="submit" tabindex="5" value="登录" stats="loginPage_login_button" class="input-submit login-btn" id="login"> </dl> </form> <div class="regnow"> <input type="button" stats="loginPage_signUp_button" tabindex="6" value="立即注册帐号" class="input-button login-btn" id="regnow" onclick="window.location='<?php echo U('__APP__/index.php/Public/reg') ?>'"> </div> <div class="regnow noet"> <span class="noteleft">船员考试网使用说明</span> 根据《中华人民共和国海船船员适任考试和发证规则》(简称11规则)的颁布实施,自2012年下半年开始,省事局船员考试开始启用2012年版新考试大纲。 船员考试网根据11规则考试大纲要求,推出最新最全面的适任证书相关和模拟考试,为广大船员服务。<br> <span class="readmore"><a href="<?php echo U('Public/news','id=89');?>">更多>></a></span> </div> </div> </div> <?php else: ?> <div class="side-column"> <div class="login-panel logoutpanel"> <div class="userinfoleftbox1"> <table> <tr> <td><img id="leftuseravar" src="<?php echo getuseravatar(); ?>" class="leftuseravar" alt="" /></td> <td> <h4><?php echo ($_SESSION['userinfo']['account']); ?></h4><span class="personcard"><?php echo ($_SESSION['userinfo']['identitycard']); ?></span><br />职务:<?php echo ($_SESSION['userinfo']['job']); ?><br /><span class="viplog">0</span><?php echo ceil((time()-$_SESSION['userinfo']['create_time'])/3600/24); ?>天 </td> </tr> </table> </div> <div class="userinfoleftbox2"> <h3>我的个人资料</h3> <ul> <li><a href="<?php echo U('User/profile');?>">资料修改</a></li> <li><a href="<?php echo U('User/changepwd');?>">密码修改</a></li> <li><a href="<?php echo U('User/uploadavatar');?>">上传头像</a></li> <li><a href="<?php echo U('User/myapp');?>">我的应用</a></li> </ul> </div> <div class="userinfoleftbox3"> <h3><a href="<?php echo U('User/allapp');?>">船员题库练习与模拟考试</a></h3> <ul> <li><a href="<?php echo U('User/allapp','gid=1');?>">适任证书考试</a></li> <li><a href="<?php echo U('User/allapp','gid=3');?>">基本证书培训</a></li> <li><a href="<?php echo U('User/allapp','gid=4');?>">特殊传播证书培训</a></li> <li><a href="<?php echo U('User/allapp','gid=7');?>">其他证书培训</a></li> </ul> </div> <div class="userinfoleftbox4"> <ul class="otherlink"> <li class="item1"><a href="##">船员电子申报</a></li> <li class="item2"><a href="##">船员考试成绩查询</a></li> <li class="item3"><a href="##">海事局考试公告</a></li> <li class="item4"><a href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo (session('website_myqq')); ?>&site=qq&menu=yes">联系客服</a></li> <li class="item5"><a href="<?php echo U('Public/logout');?>">退出</a></li> </ul> </div> </div> </div><?php endif; ?> <div class="main-column"> <div class="rightmainloginbox"> <?php echo (htmlspecialchars_decode($imgs["content"])); ?> </div> <div class="loginnewbox"> <div class="loginnewboxleft"> <div class="newsheaderline"><a href="<?php echo U('Public/newslist','cid=1');?>">船员考试网最新船员资讯</a></div> <ul> <?php if(is_array($news)): $i = 0; $__LIST__ = $news;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><li class="newsitem"><a href="<?php echo U('Public/news','id='.$vo['id']);?>"><?php echo (date("m-d",$vo["ctime"])); ?>:<?php echo ($vo["title"]); ?></a></li><?php endforeach; endif; else: echo "" ;endif; ?> </ul> </div> <div class="loginnewboxrihgt"> <div class="newsheaderline red"><a href="<?php echo U('Public/newslist','cid=2');?>">船员考试常见问题解答</a></div> <ul> <?php if(is_array($fqas)): $i = 0; $__LIST__ = $fqas;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><li class="newsitem"><a href="<?php echo U('Public/news','id='.$vo['id']);?>"><?php echo (date("m-d",$vo["ctime"])); ?>:<?php echo ($vo["title"]); ?></a></li><?php endforeach; endif; else: echo "" ;endif; ?> </ul> </div> <div class="clearfix"></div> </div> <div class="fourphonebox"> <img class="telimgfirst" src="__PUBLIC__/images/home/userloginicon_15.png" alt="" /> <img src="__PUBLIC__/images/home/userloginicon_16.png" alt="" /> <img src="__PUBLIC__/images/home/userloginicon_17.png" alt="" /> <img src="__PUBLIC__/images/home/userloginicon_18.png" alt="" /> <div class="undernewsmoreinfoline"> 想了解更多船员考试信息,<a href="<?php echo U('Public/newslist','cid=3');?>">点击此处∨</a> </div> </div> </div> </div> </div> </div> <div class="clearfix"></div> <div id="footer"> <div class="site-footer"> <div id="footer0904"> <div class="footer_c"><?php echo (session('website_sitename')); ?>客户服务热线:<?php echo (session('website_tel')); ?>(工作日 9:00-17:30) <a target="_blank" href="<?php echo (session('website_weibo')); ?>" class="weibo"><?php echo (session('website_sitename2')); ?></a> </div> <div class="footer_about"> <ul class="about"> <li class="first"><a href="<?php echo U('Public/news','id=86');?>" >关于船员考试网</a></li> <li><a href="<?php echo U('Public/newslist','cid=1');?>" target="_blank">最新资讯</a></li> <li><a href="<?php echo U('Public/newslist','cid=2');?>" target="_blank">常见问题</a></li> <li><a href="<?php echo U('Public/news','id=87');?>" target="_blank">联系我们</a></li> <li><a href="<?php echo U('Public/newslist','cid=3');?>" target="_blank">海事规则</a></li> <li><a href="<?php echo U('Public/news','id=88');?>" target="_blank">法律声明</a></li> <li><a href="<?php echo U('Public/news','id=89');?>" target="_blank">会员服务</a></li> <li><a href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo (session('website_myqq')); ?>&site=qq&menu=yes" >在线客服</a></li> <li class="last"><a href="http://www.ship123.com" target="_blank">船员导航网</a></li> </ul> </div> <div class="footer_text"> <p>客户服务热线:<?php echo (session('website_tel')); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>邮箱:<?php echo (session('website_mymail')); ?>&nbsp;&nbsp;网站ICP备案:<?php echo (session('website_beianhao')); ?></p> <p>通用网址 网络关键词:<?php echo (session('website_keywords')); ?></p> <p>CopyRight &copy; 2010-<?php echo date('Y',time()); ?>&nbsp;&nbsp;<?php echo (session('website_sitename2')); ?>&nbsp;&nbsp;<?php echo (session('website_siteurl')); ?>,All Rights Reserved&nbsp;&nbsp;<?php echo (session('website_sitename')); ?>&nbsp;&nbsp;版权所有</p> </div> <div class="icpbox"> <a href="http://t.knet.cn/" target="_blank" class="icp"><img src="__PUBLIC__/images/home/footerbeian.png"></a></div> <div class="tongji"><?php echo (session('website_sitetonji')); ?></div> </div> </div> </div> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><button value="<?php echo ($pqid); ?>" class="prevquestion">上一题[PgUp]</button> <button value="<?php echo ($nqid); ?>" class="nextquestion">下一题[PgDn]</button> <button value="<?php echo ($mqid); ?>" class="markquestion <?php echo ($disabled); ?>">标&nbsp;记[M]</button> <button value="<?php echo ($mqid); ?>" class="unmarkquestion <?php echo ($undisabled); ?>">取消标记[U]</button> <button value="<?php echo ($mqid); ?>" class="selectquestion">选&nbsp;题[L]</button> <button class="handinpaper">交&nbsp;卷[K]</button><file_sep><?php if (!defined('THINK_PATH')) exit();?><style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1500" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">添加用户</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td class="left_txt location">当前位置:注册用户管理&nbsp;&raquo;&nbsp;添加用户</td> <td class="left_txt curdbuttonbox"> <a class="historygoback" href="javascript:window.history.go(-1)">返回</a> </td> </tr> <tr> <td height="20" colspan="2">&nbsp;</td> </tr> <tr> <td colspan="2"> <form action="__URL__/add" method="post"> <table width="100%" cellspacing="0" cellpadding="0" border="0"> <tr bgcolor="#f2f2f2"> <td width="20%" height="30" align="right" class="left_txt2">用户名:</td> <td width="3%">&nbsp;</td> <td width="32%" height="30"><input type="text" size="30" name="username"></td> <td width="45%" height="30" bgcolor="#f2f2f2" class="left_txt">用于系统登陆的用户名</td> </tr> <tr bgcolor=""> <td width="20%" height="30" align="right" class="left_txt2">密码:</td> <td width="3%">&nbsp;</td> <td width="32%" height="30"><input type="text" size="30" name="password"></td> <td width="45%" height="30" class="left_txt">用户登陆系统的密码,长度8-12位</td> </tr> <tr bgcolor="#f2f2f2"> <td width="20%" height="30" align="right" class="left_txt2">重复密码:</td> <td width="3%">&nbsp;</td> <td width="32%" height="30"><input type="text" size="30" name="repassword"></td> <td width="45%" height="30" class="left_txt">重复密码</td> </tr> <tr> <td height="30" align="right" class="left_txt2">昵称:</td> <td>&nbsp;</td> <td height="30"><input type="text" size="30" name="nickname"></td> <td height="30" class="left_txt">用户在系统中显示的昵称</td> </tr> <tr bgcolor="#f2f2f2" > <td height="30" align="right" class="left_txt2">邮箱地址:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" ><input type="text" size="30" name="email"></td> <td height="30" class="left_txt">重要的验证和密保条件</td> </tr> <tr> <td height="30" align="right" class="left_txt2">联系电话信息: </td> <td>&nbsp;</td> <td height="30"><input type="text" size="30" name="telphone"></td> <td height="30" class="left_txt">联系电话</td> </tr> <tr bgcolor="#f2f2f2"> <td height="30" align="right" class="left_txt2">用户分组:</td> <td>&nbsp;</td> <td height="30" ><select name="userrole" style="width:225px;"> <option value="2">默认权限</option> <?php if(is_array($listrole)): $i = 0; $__LIST__ = $listrole;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option value="<?php echo ($vo['id']); ?>"> |<?php $con = count(split('-', $vo['path'])); for ($i=0; $i < $con; $i++) { echo '--'; } ?> <?php echo ($vo['name']); ?> </option><?php endforeach; endif; else: echo "" ;endif; ?> </select></td> <td height="30" class="left_txt">用户在本系统中的角色</td> </tr> <tr> <td height="30" align="right" class="left_txt2">备注信息: </td> <td>&nbsp;</td> <td height="30"><textarea name="remark" id="remark" cols="30" rows="3" style="resize:none;"></textarea></td> <td height="30" class="left_txt">简单的备注</td> </tr> <tr bgcolor="#f2f2f2"> <td height="30" align="right" class="left_txt2">是否停用此账号:</td> <td>&nbsp;</td> <td height="30"> <label for="block1">停用:</label> <input id="block1" type="radio" size="30" value="1" name="block" style="margin-right:50px"> <label for="block0">开启:</label> <input id="block0" checked type="radio" size="30" value="0" name="block"> </td> <td height="30" class="left_txt">屏蔽以后,就不可以登陆</td> </tr> <tr> <td height="30" align="right" class="left_txt2"></td> <td>&nbsp;</td> <td height="30"> <input type="submit" name="submit" value="提交信息" style="margin-right:68px;"> <input type="reset" name="reset" value="重新填写"> </td> <td height="30" class="left_txt"></td> </tr> </table> </form> </td> </tr> </table></td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </body><file_sep><?php Class ArticlesAction extends CommonAction{ public function index(){ //查询条件 if($_GET['cid'] !== null){ if($_GET['cid'] !== 0){ $where['cid'] = $_GET['cid']; } } //分页开始 $count = D('Articles')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); //查询所有文章 $list = D('Articles')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select(); $show = $Page->show();// 分页显示输出 $cid = D('ArticlesCatogery')->select(); $this->assign('page',$show);// 赋值分页输出 $this->assign('cid',$cid); $this->assign('postcid',$_GET['cid']); $this->assign('list',$list); $this->display(); } //添加文章 public function add(){ //列表 if($_GET['id']){ $article = D('Articles')->where('id='.$_GET['id'])->find(); $this->assign('article',$article); //判断文章是下载类,还是展示类 if(($article['cid'] == 4) || ($article['cid'] == 5)){ $hidden1 = 'hidden'; }else{ $hidden2 = 'hidden'; } } $cid = D('ArticlesCatogery')->select(); $this->assign('cid',$cid); $this->assign('hidden1',$hidden1); $this->assign('hidden2',$hidden2); $this->display(); } public function kindedtor(){ dump($_POST); $this->display(); } public function doadd(){ //修改或者添加 $_POST['content'] = htmlspecialchars(stripslashes($_POST['content'])); $_POST['ctime'] = time(); if(empty($_POST['isdel'])){ $_POST['isdel'] = 0; } if($_POST['id']){ D('Articles')->save($_POST); $rs = $_POST['id']; }else{ $rs = D('Articles')->add($_POST); } if($rs){ $this->success('操作成功','__APP__/Articles/add/id/'.$rs); }else{ $this->success('操作失败','__APP__/Articles/add/id/'.$rs); } } //删除文章 public function deletenews(){ $delcid = $_POST['delcid']; $delcidarr = explode(',', $delcid); foreach ($delcidarr as $key=>$value){ D('Articles')->where('id='.$value.' and cid<>6')->delete(); } } } ?><file_sep><?php Class ExamAction extends CommonAction{ public function _initialize(){ parent::_initialize(); if(!session('sutudyappid')){ $this->redirect('/User/myapp'); } } public function _empty(){ $this->redirect('/'); } public function index(){ } public function login(){ //cookie(null); $this->assign('pagetitle','船员身份验证'); $this->display(); } public function training(){ //dump(session('身份证号'));exit;//座位号 //dump(session('seatNo'));exit;//座位号 //获得题目的总数 生成右上角类似日历的表格 $url = $_SERVER["HTTP_REFERER"];//获取完整的来路URL if(strpos($url, '/selecttype/sutudyappid/') === false){ $this->redirect('/User/myapp'); } //初始化 $this->init_question(); $idarr = session('all_questions_id'); session('currentapp_question_num',count($idarr)); $topics_total = session('currentapp_question_num'); $tables = ceil($topics_total/30); $getidjointtrueidarray = getidjointtrueid(); //dump($getidjointtrueidarray); //应用相关信息 $sappid = session('sutudyappid'); $join = 'think_appcourse ON think_appcourse.id = think_app.courseid'; $field = 'think_app.*,think_appcourse.title as coursetitle'; $where['think_app.id'] = $sappid; $rs = D('App')->join($join)->field($field)->where($where)->find(); $this->assign('rs',$rs); $alltables = ''; for ($i = 0; $i < $tables; $i++){ $alltables .= '<table class="topicslist topicslist'.$i.'">'; for ($l = 1;$l <= 5;$l++){ $alltables .= '<tr>'; for ($r = 0;$r < 6;$r++){ $tid = $l+(5*$r)+($i*30); //曾经回答过的当前题目的答案 $youranswer = cookie('studentanswerforid'.$getidjointtrueidarray[$tid]); if($youranswer){ $trueanswer = D('Question')->where('id='.$getidjointtrueidarray[$tid])->find(); if($youranswer == $trueanswer['answer']){ $m = 'r'; }else{ $m = 'w'; } if(session('istest')){ $m = 't'; } unset($youranswer); } $alltables .= '<td class="'.$m.'">'; unset($m); if($tid <= $topics_total){ $alltables .= $tid; } $alltables .= '</td>'; } $alltables .= '</tr>'; } $alltables .= '</table>'; } //dump(cookie('markquestionid')); $this->assign('alltables',$alltables); $this->assign('pagetitle','题库练习与考试'); $this->display(); } public function mark(){ $questionid = $_POST['questionid']; $topics_total = session('currentapp_question_num'); $h = ceil($topics_total/4); $t = 1; //把当前APP中的题目再查询一次 $questions = session('all_questions_id'); $topicslistmark = ''; $topicslistmark .= '<table class="topicslistmark">'; for ($l = 1;$l <= $h;$l++){ $topicslistmark .= '<tr>'; for ($r = 0;$r < 4;$r++){ //判断是否被标记了,如果有就标记当前题目 if(strpos(cookie('markquestionid'), '__'.$t.'__') !== false){ $biaojiti = "biaojiti"; }else{ $biaojiti = ""; } //判断是否为当前题 if($t == $questionid){ $dangqianti = "dangqianti"; }else{ $dangqianti = ''; } //如果当前题和标记题目重复,则标记题优先 if($biaojiti && $dangqianti){ $dangqianti = ' zhuangqiangliao'; } $topicslistmark .= '<td><span class="'.$biaojiti.$dangqianti.' ">'; $tid = $t++; if($tid <= $topics_total){ $youranswer = cookie('studentanswerforid'.$questions[$t-2]['id']); if($youranswer == ''){ $youranswer = '未做答'; } $topicslistmark .= $tid.'.['.$questions[$t-2]['type'].']'.$youranswer; } $topicslistmark .= '</span></td>'; } $topicslistmark .= '</tr>'; } $topicslistmark .= '</table>'; //dump($topicslistmark);exit; //echo cookie('markquestionid'); $this->assign('topicslistmark',$topicslistmark); $this->assign('questionid',$questionid); $this->display(); } public function doexamlogin(){ if($_POST['idCard'] == $_SESSION['userinfo']['identitycard']){ session('seatNo',$_POST['seatNo']); //清空之前的做题 COOKIE 信息 emptycookie('markquestionid'); emptycookie('studentanswerforid'); emptycookie('listquestionid'); session('all_questions_id',null); $this->redirect('Public/selecttype','sutudyappid='.session('sutudyappid')); }else{ $this->error('身份证号码不正确!','/index.php/Exam/login'); } } public function doexamlogin2(){ //清空之前的做题 COOKIE 信息 emptycookie('markquestionid'); emptycookie('studentanswerforid'); emptycookie('listquestionid'); session('all_questions_id',null); session('begintime',time()); $this->redirect('Exam/training'); } //获得时间 将秒转换成 时分秒 public function timer(){ $begintime = session('begintime'); $sec = time()-$begintime; $hours = floor($sec / 3600); $remainSeconds = $sec % 3600; $minutes = floor($remainSeconds / 60); $seconds = intval($sec-(3600*$hours)-(60*$minutes)); $gotime = str_pad($hours,2,"0",STR_PAD_LEFT).':'.str_pad($minutes,2,"0",STR_PAD_LEFT).':'.str_pad($seconds,2,"0",STR_PAD_LEFT); //剩下多少题没有做 $leftquestionum = session('currentapp_question_num') - countcookie('studentanswerforid'); echo $gotime.'##'.$leftquestionum; } //题目ID初始化 private function init_question(){ //判断当前用户是否购买了本套应用 $uid = session('user_id'); $myappid = D('Userextend')->where('uid='.$uid)->find(); $myappidarr = split(',', $myappid['appid']); if(!in_array(session('sutudyappid'), $myappidarr)){ echo 'nopermission';exit; } $where['appid'] = session('sutudyappid'); $where['isdel'] = 0; if(session('istest')){ //echo session('istest');//是测试 //如果是考试,那么第一次进来 就要把所有题目的ID和顺序存入Cookie if(!session('all_questions_id')){ $all_rand_questions = D('Question')->where($where)->field('id,type,answer')->order('rand()')->limit(session('website_examquestionnum'))->select(); session('all_questions_id',$all_rand_questions); } }else{ //是练习,也存入COOKIE,统一操作。 if(!session('all_questions_id')){ $all_questions = D('Question')->where($where)->field('id,type,answer')->select(); session('all_questions_id',$all_questions); } } } //获得题目 public function getQuestion(){ if(!session('sutudyappid')){return false;} $questionid = $_POST['questionid']; $questionid_ = $questionid-1; //初始化 $this->init_question(); $idarr = session('all_questions_id'); $question = D('Question')->where('id='.$idarr[$questionid_]['id'])->select(); $answer = D('QuestionAnswer')->where('questionid='.$question[0]['id'])->select(); if($question[0]['type'] == '多选'){ $inputtype = 'checkbox'; } if($question[0]['type'] == '单选'){ $inputtype = 'radio'; } $this->assign('studentanswerforid',cookie('studentanswerforid'.$question[0]['id'])); $this->assign('question',$question[0]); $this->assign('inputtype',$inputtype); $this->assign('answer',$answer); $this->assign('questionid',$questionid); $this->display('questions'); } //问题下面的按钮 public function questionbuttons(){ $questionid = $_POST['questionid']; if($questionid == session('currentapp_question_num')){ $nqid = ''; }else{ $nqid = $questionid+1; } //判断是否被标记了 if(strpos(cookie('markquestionid'),'__'.$questionid.'__') === false ){ $undisabled = 'disabled'; $this->assign('undisabled',$undisabled); }else{ $disabled = 'disabled'; $this->assign('disabled',$disabled); } $this->assign('pqid',$questionid-1); $this->assign('nqid',$nqid); $this->assign('mqid',$questionid); $this->display(); } //标记题目 public function markquestion(){ $questionid = $_POST['questionid']; //cookie('markquestionid',null); if(cookie('markquestionid')){ $markquestionid = cookie('markquestionid'); } $markquestionid_new = $markquestionid.'__'.$questionid.'__'; cookie('markquestionid',$markquestionid_new); } //取消标记题目 public function unmarkquestion(){ $questionid = $_POST['questionid']; //cookie('markquestionid',null); if(cookie('markquestionid')){ $markquestionid = cookie('markquestionid'); } $markquestionid_new = str_replace('__'.$questionid.'__', '', $markquestionid); if($markquestionid_new == ''){ $markquestionid_new = null; } cookie('markquestionid',$markquestionid_new); } //保存答案 public function saveAnswer(){ $question_true_id = $_POST['question_true_id']; $questionid = $_POST['questionid']; $answer = $_POST['answer']; $answertype = $_POST['answertype']; if($answertype == 'checkbox'){ //判断已经存在的答案 if(cookie('studentanswerforid'.$question_true_id)){ $oldanswer = cookie('studentanswerforid'.$question_true_id); $newarray = array(); for($i=0;$i<strlen($oldanswer);$i++){ array_push($newarray, $oldanswer[$i]); } //添加新答案 array_push($newarray, $answer); //排序A-Z,去重复,并把新答案赋值给$answer $newarray_ = array_unique($newarray); sort($newarray_); $answer = implode('',$newarray_); } } cookie('studentanswerforid'.$question_true_id,$answer); cookie('listquestionid_'.$questionid,$question_true_id); } //更新答案 public function savecaneledAnswer(){ $question_true_id = $_POST['question_true_id']; $questionid = $_POST['questionid']; $answer = $_POST['answer']; $answertype = $_POST['answertype']; if($answertype == 'checkbox'){ if(cookie('studentanswerforid'.$question_true_id)){ $oldanswer = cookie('studentanswerforid'.$question_true_id); $newarray = array(); for($i=0;$i<strlen($oldanswer);$i++){ array_push($newarray, $oldanswer[$i]); } //删除当前答案 foreach ($newarray as $key=>$value){ if($value == $answer){ unset($newarray[$key]); } } //排序A-Z,去重复,并把新答案赋值给$answer $newarray_ = array_unique($newarray); sort($newarray_); if(empty($newarray_)){ $answer = null; }else{ $answer = implode('',$newarray_); } } } cookie('studentanswerforid'.$question_true_id,$answer); cookie('listquestionid_'.$questionid,$question_true_id); } //点击答案,更新右上角的题目列表对错显示 public function updatequestionlistanswer(){ $question_true_id = $_POST['question_true_id']; $youranswer = cookie('studentanswerforid'.$question_true_id); $trueanswer = D('Question')->where('id='.$question_true_id)->find(); //没有做答 if(!$youranswer){ echo 'null'; exit; } //回答正确 if($youranswer == $trueanswer['answer']){ $r = 'right'; if(session('istest')){ $r = 'test'; } echo $r; exit; }else{ //回答错误 $w = 'wrong'; if(session('istest')){ $w = 'test'; } echo $w; exit; } } //交卷 public function handinpaper(){ // dump($_SESSION); // echo '<hr>'; // dump($_COOKIE); //每题平均多少分 $per_score = 100/session('currentapp_question_num'); $righti = 0; //取出所有题目的答案 根据正确答案去核对用户的选择 $rightanswerarr = session('all_questions_id'); foreach ($rightanswerarr as $key=>$value){ $questiontureid = $value['id']; $questiontureanswer = $value['answer']; $questionyouranswer = cookie('studentanswerforid'.$questiontureid); if($questionyouranswer == $questiontureanswer){ $righti++; } } emptycookie('markquestionid'); emptycookie('studentanswerforid'); emptycookie('listquestionid'); session('all_questions_id',null); session('begintime',null); session('sutudyappid',null); $score = $righti*$per_score; $this->assign('score',round($score,1)); $this->assign('pagetitle','考生成绩'); $this->display(); } } ?><file_sep><?php $config1 = array( //'配置项'=>'配置值' // 'URL_CASE_INSENSITIVE' =>true,//URL不区分大小写 'DEFAULT_THEME'=>'default',//默认模板 'TMPL_L_DELIM'=>'<{', 'TMPL_R_DELIM'=>'}>', //默认错误跳转对应的模板文件 'TMPL_ACTION_ERROR' => 'Public:error', //默认成功跳转对应的模板文件 'TMPL_ACTION_SUCCESS' => 'Public:success', 'TOKEN_ON'=>true, // 是否开启令牌验证 'TOKEN_NAME'=>'__hash__', // 令牌验证的表单隐藏字段名称 'TOKEN_TYPE'=>'MD5', //令牌哈希验证规则 默认为MD5 'TOKEN_RESET'=>true, //令牌验证出错后是否重置令牌 默认为true 'URL_MODEL' => '2', 'URL_CASE_INSENSITIVE' =>true, //忽略大小写 // 'SHOW_RUN_TIME'=>true, //运行时间显示 // 'SHOW_ADV_TIME'=>true,//显示详细的运行时间 // 'SHOW_DB_TIMES'=>true,//显示数据库的操作次数 // 'SHOW_CACHE_TIMES'=>true,//显示缓存操作次数 // 'SHOW_USE_MEM'=>true,//显示内存开销 'MAIL_ADDRESS'=>'<EMAIL>', // 邮箱地址 'MAIL_SMTP'=>'smtp.exmail.qq.com', // 邮箱SMTP服务器 'MAIL_PASSWORD'=>'<PASSWORD>', // 邮箱密码 'MAIL_PORT'=>'465', ); $config2 = include './config.inc.php'; return array_merge($config1,$config2); ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html lang="en-US"> <head> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; background-color: #F8F9FA; } --> </style> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/admin/common.js"></script> <script charset="utf-8" src="__PUBLIC__/js/editor/kindeditor/kindeditor.js"></script> <script charset="utf-8" src="__PUBLIC__/js/editor/kindeditor/lang/zh_CN.js"></script> <script> var editor; KindEditor.ready(function(K) { editor = K.create('textarea[name="content"]', { allowFileManager : true }); }); </script> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css" /> </head> <body> <form name="form1" method="post" action="__URL__/doadd"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17" height="29" valign="top" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/left-top-right.gif" width="17" height="29" /></td> <td width="1100" height="29" valign="top" background="__PUBLIC__/images/admin/content-bg.gif"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="left_topbg" id="table2"> <tr> <td height="31"><div class="titlebt">编辑文章</div></td> </tr> </table></td> <td width="16" valign="top" background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/nav-right-bg.gif" width="16" height="29" /></td> </tr> <tr> <td height="71" valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif">&nbsp;</td> <td valign="top" bgcolor="#F7F8F9"><table width="100%" height="138" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="13" valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td class="left_txt">当前位置:文章编辑</td> </tr> <tr> <td height="20"><table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC"> <tr> <td></td> </tr> </table></td> </tr> <tr> <td></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" class="nowtable"> <tr> <td class="left_bt2">&nbsp;&nbsp;&nbsp;&nbsp;文章编辑选项</td> </tr> </table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="20%" height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">文章标题:</td> <td width="3%" bgcolor="#f2f2f2">&nbsp;</td> <td width="32%" height="30" bgcolor="#f2f2f2"> <input name="title" type="text" id="" size="30" value="<?php echo $article['title'] ?>" /> <span class="newsblock"><input type="checkbox" value="1" name="isdel" <?php if($article['isdel'] == 1): ?>checked<?php endif; ?> id="isdel" /><label for="isdel">取消发布</label></span> </td> <td width="45%" height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">文章所属分类:</td> <td>&nbsp;</td> <td height="30"> <select name="cid" id="cid"> <?php if(is_array($cid)): $i = 0; $__LIST__ = $cid;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option <?php if($vo['id'] == $article['cid']): ?>selected<?php endif; ?> value="<?php echo ($vo["id"]); ?>"><?php echo ($vo["ctitle"]); ?></option><?php endforeach; endif; else: echo "" ;endif; ?> </select> </td> <td height="30" class="left_txt"></td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">文章正文:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"> <textarea id="content" name="content" style="width:806px;height:300px;"><?php echo $article['content'] ?></textarea> </td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">文章简介: </td> <td>&nbsp;</td> <td height="30"> <textarea name="discription" id="discription" style="width:802px;" cols="30" rows="5"><?php echo $article['discription'] ?></textarea> </td> <td height="30" class="left_txt"></td> </tr> <tr> <td height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">文章关键字:</td> <td bgcolor="#f2f2f2">&nbsp;</td> <td height="30" bgcolor="#f2f2f2"><input type="text" name="keywords" size="30" value="<?php echo $article['keywords'] ?>" /></td> <td height="30" bgcolor="#f2f2f2" class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2">下载链接: </td> <td>&nbsp;</td> <td height="30"> <input name="dowloadurl" type="text" id="dowloadurl" size="60" value="<?php echo $article['dowloadurl'] ?>" /> 这里推荐使用 <a href="http://pan.baidu.com" target="_blank">百度网盘</a>存储文件,以减小服务器压力!</span> </td> <td height="30"><span class="left_txt"></td> </tr> <tr> <td height="30" align="right" class="left_txt2"></td> <td>&nbsp;</td> <td height="30"> <input class="submitnews" type="submit" value="提交数据" /> <input type="reset" value="重新填写" /> </td> <td height="30" class="left_txt"><input type="hidden" name="id" value="<?php echo $article['id'] ?>" /></td> </tr> </table></td> </tr> </table> </td> </tr> </table></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif">&nbsp;</td> </tr> <tr> <td valign="middle" background="__PUBLIC__/images/admin/mail_leftbg.gif"><img src="__PUBLIC__/images/admin/buttom_left2.gif" width="17" height="17" /></td> <td height="17" valign="top" background="__PUBLIC__/images/admin/buttom_bgs.gif"><img src="__PUBLIC__/images/admin/buttom_bgs.gif" width="17" height="17" /></td> <td background="__PUBLIC__/images/admin/mail_rightbg.gif"><img src="__PUBLIC__/images/admin/buttom_right2.gif" width="16" height="17" /></td> </tr> </table> </form> </body> </html><file_sep><?php class CommonAction extends Action { public function _empty($name){ redirect(__APP__.'/Public/login'); } public function _initialize() { header ( "Content-Type:text/html; charset=utf-8" ); import ( 'ORG.Util.Cookie' ); date_default_timezone_set('PRC'); // 用户权限检查 if (C ( 'USER_AUTH_ON' ) && ! in_array ( MODULE_NAME, explode ( ',', C ( 'NOT_AUTH_MODULE' ) ) )) { import ( 'ORG.Util.RBAC' ); if (! RBAC::AccessDecision ()) { // 检查认证识别号 if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) { // 跳转到认证网关 redirect ( PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) ); } // 没有权限 抛出错误 if (C ( 'RBAC_ERROR_PAGE' )) { // 定义权限错误页面 redirect ( C ( 'RBAC_ERROR_PAGE' ) ); } else { if (C ( 'GUEST_AUTH_ON' )) { $this->assign ( 'jumpUrl', PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) ); } // 提示错误信息 $this->error ( L ( '_VALID_ACCESS_' ) ); } } } } public function index(){ $name = $this->getActionName(); $model = D($name); //分页开始 $count = $model->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); //搜索条件 $searchtext = $this->_post('searchtext'); $map = $this->_searchs($searchtext); if(empty($searchtext)){ $map = null; } $list = $model->limit($Page->firstRow.','.$Page->listRows)->where($map)->select(); //排序 if($this->_request('sortby')){ $list = $this->sortby($list, $this->_request('sortby'),$this->_request('order')); } //排序切换 $order = $this->getSortby($list[0]); $show = $Page->show();// 分页显示输出 $this->assign('page',$show);// 赋值分页输出 return array($list,$order,$show); } //新增一条记录 function insert() { $name = $this->getActionName(); $model = D($name); if (false === $model->create()) { $this->error($model->getError()); } //保存当前数据对象 $list = $model->add(); if ($list !== false) { //保存成功 $this->success('新增成功!',cookie('_currentUrl_')); } else { //失败提示 $this->error('新增失败!'); } } //读取一条记录 function read() { $this->edit(); } function edit() { $name = $this->getActionName(); $model = M($name); $id = $_REQUEST [$model->getPk()]; $vo = $model->getById($id); return $vo; } //更新一条记录 function update() { $name = $this->getActionName(); $model = D($name); if (false === $model->create()) { $this->error($model->getError()); } // 更新数据 $list = $model->save(); if (false !== $list) { //成功提示 $this->success('编辑成功!',cookie('_currentUrl_')); } else { //错误提示 $this->error('编辑失败!'); } } public function delete() { //删除指定记录 $name = $this->getActionName(); $model = M($name); if (!empty($model)) { $pk = $model->getPk(); $id = $_REQUEST [$pk]; if (isset($id)) { $condition = array($pk => array('in', explode(',', $id))); $list = $model->where($condition)->setField('status', - 1); if ($list !== false) { $this->success('删除成功!'); } else { $this->error('删除失败!'); } } else { $this->error('非法操作'); } } } public function foreverdelete(){ //删除指定记录 $name = $this->getActionName(); $model = D($name); if (!empty($model)) { $pk = $model->getPk(); $id = $_REQUEST [$pk]; if (isset($id)) { $condition = array($pk => array('in', explode(',', $id))); if (false !== $model->where($condition)->delete()) { $this->success('删除成功!'); } else { $this->error('删除失败!'); } } else { $this->error('非法操作'); } } $this->forward(); } public function clear() { //删除指定记录 $name = $this->getActionName(); $model = D($name); if (!empty($model)) { if (false !== $model->where('status=1')->delete()) { $this->success(L('_DELETE_SUCCESS_'),$this->getReturnUrl()); } else { $this->error(L('_DELETE_FAIL_')); } } $this->forward(); } /** +---------------------------------------------------------- * 默认禁用操作 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws FcsException +---------------------------------------------------------- */ public function forbid() { $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_REQUEST [$pk]; $condition = array($pk => array('in', $id)); $list = $model->forbid($condition); if ($list !== false) { $this->success('状态禁用成功',$this->getReturnUrl()); } else { $this->error('状态禁用失败!'); } } public function checkPass() { $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_GET [$pk]; $condition = array($pk => array('in', $id)); if (false !== $model->checkPass($condition)) { $this->success('状态批准成功!',$this->getReturnUrl()); } else { $this->error('状态批准失败!'); } } public function recycle() { $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_GET [$pk]; $condition = array($pk => array('in', $id)); if (false !== $model->recycle($condition)) { $this->success('状态还原成功!',$this->getReturnUrl()); } else { $this->error('状态还原失败!'); } } public function recycleBin() { $map = $this->_search(); $map ['status'] = - 1; $name = $this->getActionName(); $model = D($name); if (!empty($model)) { $this->_list($model, $map); } $this->display(); } /** +---------------------------------------------------------- * 默认恢复操作 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws FcsException +---------------------------------------------------------- */ function resume() { //恢复指定记录 $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_GET [$pk]; $condition = array($pk => array('in', $id)); if (false !== $model->resume($condition)) { $this->success('状态恢复成功!',$this->getReturnUrl()); } else { $this->error('状态恢复失败!'); } } function saveSort() { $seqNoList = $_POST ['seqNoList']; if (!empty($seqNoList)) { //更新数据对象 $name = $this->getActionName(); $model = D($name); $col = explode(',', $seqNoList); //启动事务 $model->startTrans(); foreach ($col as $val) { $val = explode(':', $val); $model->id = $val [0]; $model->sort = $val [1]; $result = $model->save(); if (!$result) { break; } } //提交事务 $model->commit(); if ($result !== false) { //采用普通方式跳转刷新页面 $this->success('更新成功'); } else { $this->error($model->getError()); } } } /** * +----------------------------------------------------------- * 查询列表根据字段返回 三种状态 用于输出到模板 * +----------------------------------------------------------- */ protected function getSortby($list){ $map = array(); foreach ($list as $key => $val) { if (isset($_REQUEST ['sortby']) && $_REQUEST ['sortby'] == $key) { //正向 if($_REQUEST['order']=='asc'){ $map[$key]['s'] = 'desc'; $map[$key]['p'] = 'asc'; } //反向 if($_REQUEST['order']=='desc'){ $map[$key]['s'] = 'nat'; $map[$key]['p'] = 'desc'; } //自然 if($_REQUEST['order']=='nat'){ $map[$key]['s'] = 'asc'; $map[$key]['p'] = ''; } }else{ $map[$key]['s'] = 'asc'; } } return $map; } /** * +---------------------------------------------------------- * 数据排序 * +---------------------------------------------------------- */ protected function sortby($list,$field,$sortby='asc'){ if(is_array($list)){ $refer = $resultSet = array(); foreach($list as $i => $data){ $refer[$i] = &$data[$field]; } switch($sortby){ case 'asc': // 正向排序 asort($refer); break; case 'desc':// 逆向排序 arsort($refer); break; case 'nat': // 自然排序 natcasesort($refer); break; } foreach($refer as $key=> $val){ $resultSet[] = &$list[$key]; } return $resultSet; } return false; } /** * +---------------------------------------------------------- * 数据查询,生成查询where的条件。 * +---------------------------------------------------------- */ protected function _searchs($searchtext) { $name = $this->getActionName(); $model = D($name); $map = ''; $fields = ''; foreach ($model->getDbFields() as $key => $val) { if($key==0){ $fields .= $val; }else{ $fields .= '|'.$val; } } $map[$fields] = array('like','%'.$searchtext.'%','OR'); return $map; } /** * +---------------------------------------------------------- * 系统取回当前路径 * +---------------------------------------------------------- */ public function location($model = '', $action = '', $root_id = 24) { $model = $model == '' ? MODULE_NAME : $model; $action = ACTION_NAME; $action = $action == '' ? 'index' : $action; $filename = DATA_PATH . "~location.php"; if (file_exists ( $filename )) { // 存在缓存文件 $cloation = Include $filename; $var = '当前位置:' . $cloation [strtoupper ( $model )] ['title'] . '>>' . $cloation [strtoupper ( $model )] ['_ch'] [$action] ['title']; return $var; } else { // 不存在缓存 $conditon ['status'] = array ( 'eq', 1 ); $_model_ = D ( "Node" ); $list = $_model_->where ( $conditon )->Findall ( array ( 'Field' => 'id,name,title,remark,level,pid' ) ); if (( int ) $root_id == 0) { // 取回RBAC 相关值 建议手动输入 以减少服务器开销 $node_info = $_model_->getByName ( APP_NAME ); $root_id = $node_info ['id']; } $cloation = array (); if (is_array ( $list )) { // 创建基于主键的数组引用 $refer = array (); foreach ( $list as $key => $data ) { $refer [$data ["id"]] = & $list [$key]; } foreach ( $list as $key => $data ) { // 判断是否存在parent $parentId = $data ["pid"]; if ($root_id == $parentId) { $cloation [$data ['name']] = & $list [$key]; } else { if (isset ( $refer [$parentId] )) { $parent = & $refer [$parentId]; $parent ["_ch"] [$data ['name']] = & $list [$key]; } } } } $content = "<?php\nreturn " . var_export ( array_change_key_case ( $cloation, CASE_UPPER ), true ) . ";\n?>"; file_put_contents ( $filename, $content ); $var = '当前位置:' . $cloation [$model] ['title'] . '>>' . $cloation [$model] ['_ch'] [$action] ['title']; return $var; } } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><div class="trainingmiddleboxcontent item"> <div class="questionintro"><?php echo (htmlspecialchars_decode($question["intro"])); ?></div> <div class="trtitle"><?php echo ($questionid); ?>.【<?php echo ($question["type"]); ?>】<?php echo ($question["title"]); ?></div> <table class="answerbox"> <?php if(is_array($answer)): $i = 0; $__LIST__ = $answer;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr <?php if(strpos($studentanswerforid,$vo['answeridentify']) !== false){echo 'class="checked"';} ?>> <td class="abcheck"><input type="<?php echo ($inputtype); ?>" <?php if(strpos($studentanswerforid,$vo['answeridentify']) !== false){echo "checked";} ?> name="answer_<?php echo ($question["id"]); ?>" value="<?php echo ($vo["answeridentify"]); ?>" questionid="<?php echo ($questionid); ?>" /></td> <td class="abc"><?php echo ($vo["answeridentify"]); ?>.</td> <td class="lableanswer"><?php echo ($vo["answercontent"]); ?></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> </div><file_sep><?php Class AppAction extends CommonAction{ /*************************科目*******************************/ public function listcourse(){ //查询条件 if($_GET['cid'] !== null){ if($_GET['cid'] !== 0){ $where['cid'] = $_GET['cid']; } } //分页开始 $count = D('Appcourse')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); //查询所有科目 $join = ' think_appcatgory ON think_appcourse.cid = think_appcatgory.id'; $field = 'think_appcourse.*,think_appcatgory.catgory as ctitle'; $list = D('Appcourse')->where($where)->join($join)->field($field)->limit($Page->firstRow.','.$Page->listRows)->order('think_appcourse.id desc')->select(); $show = $Page->show();// 分页显示输出 //所有分类 $cid = D('Appcatgory')->select(); $this->assign('page',$show);// 赋值分页输出 $this->assign('cid',$cid); $this->assign('postcid',$_GET['cid']); $this->assign('list',$list); $this->assign('order',$order); $this->display(); } //添加科目 public function addcourse(){ //列表 if($_GET['id']){ $appcourse = D('Appcourse')->where('id='.$_GET['id'])->find(); $this->assign('appcourse',$appcourse); } $cid = D('Appcatgory')->select(); $this->assign('cid',$cid); $this->display(); } public function doaddcourse(){ //修改或者添加 $_POST['ctime'] = time(); if($_POST['id']){ D('Appcourse')->save($_POST); $rs = $_POST['id']; }else{ $rs = D('Appcourse')->add($_POST); } if($rs){ $this->success('操作成功','__APP__/App/addcourse/id/'.$rs); }else{ $this->success('操作失败','__APP__/App/addcourse/id/'.$rs); } } public function deletecourse(){ $delcid = $_POST['delcid']; $delcidarr = explode(',', $delcid); foreach ($delcidarr as $key=>$value){ D('Appcourse')->where('id='.$value)->delete(); } } /*************************应用*******************************/ public function listapp(){ //查询条件 大类 if($_GET['cid'] !== null){ if($_GET['cid'] != 0){ $where['think_appcatgory.id'] = $_GET['cid']; //获得当前分类的所有科目 $course = D('Appcourse')->where('cid='.$_GET['cid'])->select(); $this->assign('course',$course); } } if($_GET['courseid'] !== null){ if($_GET['courseid'] != 0){ $where['think_app.courseid'] = $_GET['courseid']; unset($where['think_appcatgory.id']);//忽略大类 } } //分页开始 $count = D('App')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); //查询所有文章 $join = 'think_appcourse ON think_appcourse.id = think_app.courseid'; $join2 = 'think_appcatgory ON think_appcourse.cid = think_appcatgory.id'; $field = 'think_app.*,think_appcourse.title as ctitle'; $list = D('App')->join($join)->join($join2)->where($where)->field($field)->limit($Page->firstRow.','.$Page->listRows)->order('think_app.id desc')->select(); //echo D('App')->getLastSql(); $show = $Page->show();// 分页显示输出 $cid = D('Appcatgory')->select(); $this->assign('page',$show);// 赋值分页输出 $this->assign('cid',$cid); $this->assign('postcid',$_GET['cid']); $this->assign('postcourse',$_GET['courseid']); $this->assign('list',$list); $this->display(); } //添加应用 public function addapp(){ //列表 if($_GET['id']){ $join = 'think_appcourse ON think_appcourse.id = think_app.courseid'; $join2 = 'think_appcatgory ON think_appcourse.cid = think_appcatgory.id'; $where = 'think_app.id='.$_GET['id']; $field = 'think_app.*,think_appcatgory.id as cid'; $app = D('App')->join($join)->join($join2)->where($where)->field($field)->find();//dump($app); $this->assign('app',$app); //根据上面的父类ID查询科目 $course = D('Appcourse')->where('cid='.$app['cid'])->select();//dump($course); //判断应用是下载类,还是试题类 if(!empty($app['downloadurl'])){ $showx = 'show'; } } $cid = D('Appcatgory')->select(); $this->assign('cid',$cid); $this->assign('course',$course); $this->assign('cid_cur',$cid_cur); $this->assign('showx',$showx); $this->display(); } public function doaddapp(){ $_POST['ctime'] = time(); if(empty($_POST['isdel'])){ $_POST['isdel'] = 0; } if($_POST['id']){ D('App')->save($_POST); $rs = $_POST['id']; }else{ $rs = D('App')->add($_POST); } if($rs){ $this->success('操作成功','__APP__/App/addapp/id/'.$rs); }else{ $this->success('操作失败','__APP__/App/addapp/id/'.$rs); } } //删除应用 public function deleteapp(){ $delcid = $_POST['delcid']; $delcidarr = explode(',', $delcid); foreach ($delcidarr as $key=>$value){ $data['isdel'] = 1; D('App')->where('id='.$value)->save($data); unset($data); } } //上传LOGO public function doajaxfileupload(){ $error = ""; $msg = ""; $fileElementName = 'fileToUpload'; if(!empty($_FILES[$fileElementName]['error'])) { switch($_FILES[$fileElementName]['error']) { case '1': $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini'; break; case '2': $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; break; case '3': $error = 'The uploaded file was only partially uploaded'; break; case '4': $error = 'No file was uploaded.'; break; case '6': $error = 'Missing a temporary folder'; break; case '7': $error = 'Failed to write file to disk'; break; case '8': $error = 'File upload stopped by extension'; break; case '999': default: $error = 'No error code avaiable'; } }elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none') { $error = 'No file was uploaded..'; }else { $msg .= " File Name: " . $_FILES['fileToUpload']['name'] . ", "; $msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name']); //for security reason, we force to remove all uploaded file #允许的文件扩展名 $allowed_types = array('jpg', 'gif', 'png'); $filename = $_FILES['fileToUpload']['name']; #正则表达式匹配出上传文件的扩展名 preg_match('|\.(\w+)$|', $filename, $ext); #print_r($ext); #转化成小写 $ext = strtolower($ext[1]); #判断是否在被允许的扩展名里 if(!in_array($ext, $allowed_types)){ $error = '请上传jpg,gif,png三种类型的图片,大小最好控制为60*60'; }else{ $fname = time().'.'.$ext; move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"./Public/images/appicon/".$fname); } @unlink($_FILES['fileToUpload']); } echo "{"; echo "error: '" . $error . "',\n"; echo "fname:'".$fname."',\n"; echo "msg: '" . $msg . "'\n"; echo "}"; } public function getcourse(){ $cid = $_POST['cid']; if(empty($cid)){ echo '<option value="0">==请选择应用分类==</option>'; exit; } $where['cid'] = $cid; $rs = D('Appcourse')->where($where)->select(); echo '<option value="0">==请选择应用分类==</option>'; foreach ($rs as $key=>$value){ echo '<option value="'.$value['id'].'">'; echo $value['title']; echo '</option>'; } } /*************************题目*******************************/ public function listquestions(){ //查询条件 大类 if($_GET['cid'] !== null){ if($_GET['cid'] != 0){ $where['think_question.cid'] = $_GET['cid']; //获得当前分类的所有科目 $course = D('Appcourse')->where('cid='.$_GET['cid'])->select(); $this->assign('course',$course); } } if($_GET['courseid'] !== null){ if($_GET['courseid'] != 0){ $where['think_question.courseid'] = $_GET['courseid']; unset($where['cid']);//忽略大类 //获得当前科目下面的应用 $app = D('App')->where('courseid='.$_GET['courseid'])->select(); $this->assign('app',$app); } } if($_GET['appid'] !== null){ if($_GET['appid'] != 0){ $where['think_question.appid'] = $_GET['appid']; unset($where['cid']);//忽略大类 unset($where['courseid']);//忽略科目 } } //分页开始 $count = D('Question')->where($where)->count(); import('ORG.Util.Page');// 导入分页类 $Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数 $Page->setConfig('header','条数据'); //查询所有题目 $join = 'think_app ON think_app.id=think_question.appid'; $field = 'think_question.*,think_app.title as apptitle'; $list = D('Question') ->join($join) ->field($field) ->where($where) ->limit($Page->firstRow.','.$Page->listRows) ->order('think_question.id desc')->select(); //echo D('Question')->getLastSql(); $show = $Page->show();// 分页显示输出 $catogry = D('Appcatgory')->select();//dump($catogry); $this->assign('page',$show);// 赋值分页输出 $this->assign('catgory',$catogry); $this->assign('getcid',$_GET['cid']); $this->assign('getcourseid',$_GET['courseid']); $this->assign('getappid',$_GET['appid']); $this->assign('list',$list); $this->display(); } //添加题目 public function addquestions(){ if($_GET['id']){ $question = D('Question')->where('id='.$_GET['id'])->find(); $this->assign('question',$question); $answers = D('QuestionAnswer')->where('questionid='.$question['id'])->select(); $this->assign('answers',$answers); } $appid = D('App')->select(); $this->assign('appid',$appid); $this->display(); } //获得一个答案选项 public function getnewanswer(){ $answeridentify = $_POST['answeridentify']; $html = '<tr class="answertritembox"> <td width="20%" height="30" align="right" class="left_txt2"> <input type="text" value="'.$answeridentify.'" name="answeridentify[]" class="answeridentifyid" /> </td> <td width="3%">&nbsp;</td> <td width="32%" height="30"> <input type="text" name="answercontent[]" value="" class="answercontentid" /></td> <td width="45%" height="30" class="left_txt rightansweridtd"> 正解:<input type="checkbox" name="rightanswer[]" class="rightanswerid" value="'.$answeridentify.'" /> <img class="delansweritemimg" src="/Public/images/admin/publish_x.png" alt="删除" /> </td> </tr>'; echo $html; } public function doaddquestion(){ //修改或者添加 $_POST['intro'] = htmlspecialchars(stripslashes($_POST['intro'])); $_POST['ctime'] = time(); if(empty($_POST['isdel'])){ $_POST['isdel'] = 0; } //获得当前appid的courseid 和 cid $app = D('App')->where('id='.$_POST['appid'])->field('courseid')->find(); $course = D('Appcourse')->where('id='.$app['courseid'])->field('cid')->find(); $_POST['cid'] = $course['cid']; $_POST['courseid'] = $app['courseid']; //正解 $rightanswer = $_POST[rightanswer]; sort($rightanswer); $_POST['answer'] = implode('',$rightanswer); //单选还是多选 if(strlen($_POST['answer']) > 1){ $_POST['type'] = '多选'; }else{ $_POST['type'] = '单选'; } //dump($_POST);exit; //保存问题 if($_POST['id']){ D('Question')->save($_POST); $rs = $_POST['id']; }else{ $rs = D('Question')->add($_POST); } //保存答案选项 D('QuestionAnswer')->where('questionid='.$rs)->delete(); foreach ($_POST['answeridentify'] as $key=>$value){ $datas['questionid'] = $rs; $datas['answeridentify'] = $value; $datas['answercontent'] = $_POST['answercontent'][$key]; D('QuestionAnswer')->add($datas); unset($datas); } if($rs){ $this->success('操作成功','__APP__/App/addquestions/id/'.$rs); }else{ $this->success('操作失败','__APP__/App/addquestions/id/'.$rs); } } //删除试题 public function deletequestion(){ $delcid = $_POST['delcid']; $delcidarr = explode(',', $delcid); foreach ($delcidarr as $key=>$value){ $data['isdel'] = 1; D('Question')->where('id='.$value)->save($data); } } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html> <head> <title>管理页面 头部</title> <meta http-equiv=Content-Type content=text/html;charset=utf-8> <meta http-equiv="refresh" content="1800"> <script type="text/javascript" src="/Public/js/jquery_min.js"></script><script type="text/javascript" src="/Public/js/jquery_cookie.js"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/artDialog.js?skin=black"></script> <script type="text/javascript" src="__PUBLIC__/js/artDialog/plugins/iframeTools.js"></script> <script language=JavaScript> function logout(){ var jumpurl = "__APP__/Public/logout"; var throughBox = art.dialog.through; throughBox({ title:'警告', content: '您确定真的要退出本系统么?', icon:'warning', ok: function () { top.location=jumpurl; return false; }, cancelVal: '关闭', cancel: true //为true等价于function(){} }); return false; } </script> <script language=JavaScript1.2> function showsubmenu(sid) { var whichEl = eval("submenu" + sid); var menuTitle = eval("menuTitle" + sid); if (whichEl.style.display == "none"){ eval("submenu" + sid + ".style.display=\"\";"); }else{ eval("submenu" + sid + ".style.display=\"none\";"); } } </script> <base target="main"> <link href="__PUBLIC__/css/admin/skin.css" rel="stylesheet" type="text/css"> </head> <body leftmargin="0" topmargin="0"> <table width="100%" height="64" border="0" cellpadding="0" cellspacing="0" class="admin_topbg"> <tr> <td width="40%" height="64"><a class="adminlogobox" href="/admin.php/Index/welcome"> <?php echo ($sitename); ?><span>网站后台</span> </a></td> <td width="60%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="74%" height="38" class="admin_txt">您好:<b><?php echo ($_SESSION['admininfo']['username']); ?></b>,欢迎登陆使用本系统!您的IP地址为:<?php echo ($_SESSION['admininfo']['lastloginip']); ?>,来自:<?php echo ($area["country"]); echo ($area["area"]); ?></td> <td width="22%"><a href="#" target="_self" onClick="logout();"><img src="__PUBLIC__/images/admin/out.gif" alt="安全退出" width="46" height="20" border="0"></a></td> <td width="4%">&nbsp;</td> </tr> <tr> <td height="19" colspan="3">&nbsp;</td> </tr> </table></td> </tr> </table> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script charset="utf-8" src="__PUBLIC__/js/editor/kindeditor/kindeditor.js"></script> <script charset="utf-8" src="__PUBLIC__/js/editor/kindeditor/lang/zh_CN.js"></script> <script> var editor; KindEditor.ready(function(K) { editor = K.create('textarea[name="content"]', { allowFileManager : true }); }); </script> </head> <body> <form action="" method="post"> <textarea name="content"></textarea> <input type="submit" value="..." /> </form> </body> </html>
732d26dd992478433d6c18ee2a10dc2d592c3e72
[ "PHP" ]
52
PHP
zhangjiachao/c_r_e_w
df5f91646a9ac747c2236b7bbdcc7bf0fbef2bd4
d4d04348296877c09ae013435db8ec3f76b1a042
refs/heads/master
<file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { val scanner = Scanner(System.`in`) val n = scanner.nextInt() println(if (n % 2 == 1) "Alice" else "Bob") }<file_sep>package my.kattis.problem.simple import java.util.* enum class Op(val priority : Int) { PLUS(0), MINUS(0), MULT(1), DIVIDE(1); companion object { val items = Op.values().toList() } } fun main(args: Array<String>) { val scanner = Scanner(System.`in`) val caseCount = scanner.nextInt() for(i in 1..caseCount){ val targetNumber = scanner.nextInt() val resultOps = findExpr(listOf(Op.PLUS, Op.PLUS, Op.PLUS), targetNumber) val result = buildResult(resultOps) println(result) } } fun buildResult(resultOps: List<Op>): String { if (resultOps.isEmpty()) return "no solution" return resultOps.joinToString (" 4 ", "4", "4") } fun findExpr(opList: List<Op>, targetNum: Int) : List<Op> { if( calculateResult(opList) == targetNum ) return opList val minOp = opList.min() ?: return emptyList() if (minOp == Op.DIVIDE) return emptyList() val nextOps = Op.items.filter { it > minOp } for ((index, op) in opList.withIndex()) { if (op == minOp) { for (newOp in nextOps) { val newOpList : List<Op> = replaceOp(opList, index, newOp) val expr = findExpr(newOpList, targetNum) if( !expr.isEmpty() ) return expr } } } return emptyList() } fun replaceOp(opList: List<Op>, index: Int, newOp: Op): List<Op> { val left = opList.subList(0, index) val right = opList.subList(index + 1, opList.size) return left + newOp + right } sealed class Expr data class Const(val number: Int) : Expr() data class Operation(val op: Op) : Expr() fun calculateResult(ops: List<Op>): Int { val exprList = buildExprList(ops) return evalExprList(exprList) } fun evalExprList(exprList: List<Expr>) : Int { val stack = Stack<Int>() fun eval(expr: Expr) { when (expr) { is Const -> stack.push(expr.number) is Operation -> { val arg2: Int = stack.pop() val arg1: Int = stack.pop() val result = when (expr.op) { Op.PLUS -> arg1 + arg2 Op.MINUS -> arg1 - arg2 Op.MULT -> arg1 * arg2 Op.DIVIDE -> arg1 / arg2 } stack.push(result) } } } exprList.forEach(::eval) return stack.pop() } fun buildExprList(ops: List<Op>): List<Expr> { val four = Const(4) var result = mutableListOf<Expr>() result.add(four) TODO("Not implemented") // for (op in ops) { // when (op) { // // } // } // ops.sortedByDescending { it.priority } } <file_sep>package my.kattis.problem.simple import java.util.* fun findQuadrant(x: Int, y: Int): Int { if (x > 0){ return if (y > 0) 1 else 4 }else{ return if (y > 0) 2 else 3 } } fun main(args: Array<String>) { with(Scanner(System.`in`)){ val x = nextInt() val y = nextInt() println(findQuadrant(x, y)) } }<file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { with(Scanner(System.`in`)){ var n = nextInt() while(n != -1){ var distance = 0 var prevTime = 0 for(i in 1..n){ val speed = nextInt() val time = nextInt() distance += speed * (time - prevTime) prevTime = time } println("$distance miles") n = nextInt() } } } <file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { with(Scanner(System.`in`)){ val n = nextInt() for(i in 1..n){ val r = nextInt() val e = nextInt() val c = nextInt() println(advertiseOrNot(r, e, c)) } } } fun advertiseOrNot(r: Int, e: Int, c: Int): String { if(e == r + c) return "does not matter" return if(e < r + c) "do not advertise" else "advertise" } <file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { with(Scanner(System.`in`)){ val n = nextInt() (1..n).forEach{ println("$it Abracadabra") } } }<file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { with(Scanner(System.`in`)) { val name = nextLine() println(convertToSimple(name)) } } fun convertToSimple(name: String): String { return name.fold(Pair("", ' '), { acc, c -> if(acc.second == c) acc else Pair(acc.first + c, c) }).first } <file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { with(Scanner(System.`in`)){ val say = nextLine() val hear = nextLine() println (if (say.length < hear.length) "no" else "go") } }<file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { with(Scanner(System.`in`)){ val r1 = nextInt() val s = nextInt() println(2*s - r1) } }<file_sep>package my.kattis.problem.simple import java.util.* fun main(args: Array<String>) { with(Scanner(System.`in`)){ val l = nextInt() val d = nextInt() val x = nextInt() var minResult = -1 for(i in l..d){ val sumDigits = calculateDigitSum(i) if( sumDigits == x ){ minResult = i break } } println(minResult) var maxResult = -1 for(i in d downTo l){ val sumDigits = calculateDigitSum(i) if( sumDigits == x ){ maxResult = i break } } println(maxResult) } } fun calculateDigitSum(n: Int): Int = n.toString().fold(0, { acc, c -> acc + c.toString().toInt() })
3b6408d1c9210581c16d872fc20e52cf5e962f8d
[ "Kotlin" ]
10
Kotlin
leonate/kattis
5a871340423d698485ad8c50be84a537d11018e1
845022829175acde312146b8200b1f5959d718f3
refs/heads/master
<repo_name>Nidhoggrr/awning-remote<file_sep>/awningRemote/awningRemote.ino #include <Basecamp.hpp> #include <Esp.h> extern "C" { #include "freertos/FreeRTOS.h" #include "freertos/timers.h" } static const bool debug = false; Basecamp iot; static const int outPin = 25; static const int stopPin = 26; static const int inPin = 27; static const int ledPin = 22; int triggeredPin = 22; //in ms / 100 static const int totalTravelTime = 180; unsigned long TriggerTimer = 0; int i = 0; bool moving = false; TimerHandle_t movementStopTimer; TimerHandle_t sendStatusTimer; TimerHandle_t mqttWatchdog; String mqttTopic = "homie/empty/percent"; String mqttTopicWD = "homie/empty/watchdog/set"; int percentage = 1; int getValidNumber(String str) { if (strcmp(str.substring(0,2).c_str(),"0.") == 0) { str=str.substring(2,4); } if (strcmp(str.substring(0,3).c_str(),"1.0") == 0) { str="100"; } for (int i = 0; i < str.length(); i++) { if (!isDigit(str[i])) { return 0; } } return str.toInt(); } void triggerPin(int Pin) { TriggerTimer = millis(); triggeredPin = Pin; digitalWrite(Pin, LOW); } void onMqttConnect(bool sessionPresent) { if (debug) Serial.println("Connected to MQTT."); iot.mqtt.subscribe((mqttTopic + "/set").c_str(), 2); iot.mqtt.subscribe((mqttTopicWD + "/set").c_str(), 2); iot.mqtt.publish(("homie/" + iot.hostname + "/$homie").c_str(), 1, true, "3.0" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$name").c_str(), 1, true, "Markise" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$state").c_str(), 1, true, "init" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$localip").c_str(), 1, true, iot.wifi.getIP().toString().c_str() ); iot.mqtt.publish(("homie/" + iot.hostname + "/$mac").c_str(), 1, true, iot.wifi.getHardwareMacAddress().c_str() ); iot.mqtt.publish(("homie/" + iot.hostname + "/$fw/name").c_str(), 1, true, "adke.awning" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$fw/version").c_str(), 1, true, "0.4" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$implementation").c_str(), 1, true, "esp32" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$stats").c_str(), 1, true, "" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$stats/interval").c_str(), 1, true, "120" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$stats/uptime").c_str(), 1, true, String(millis()).c_str() ); iot.mqtt.publish(("homie/" + iot.hostname + "/$nodes").c_str(), 1, true, "status" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/$name").c_str(), 1, true, "Prozent" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/$properties").c_str(), 1, true, "percent,watchdog" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/percent/$datatype").c_str(), 1, true, "integer" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/percent").c_str(), 1, true, "0" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/percent/$name").c_str(), 1, true, "Abdeckung" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/percent/$unit").c_str(), 1, true, "%" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/percent/$settable").c_str(), 1, true, "true" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/watchdog/$datatype").c_str(), 1, true, "string" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/watchdog").c_str(), 1, true, "0" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/watchdog/$settable").c_str(), 1, true, "true" ); iot.mqtt.publish(("homie/" + iot.hostname + "/status/watchdog/$name").c_str(), 1, true, "Watchdog Tick" ); iot.mqtt.publish(("homie/" + iot.hostname + "/$state").c_str(), 1, true, "ready" ); iot.mqtt.setWill(("homie/" + iot.hostname + "/$state").c_str(), 1, true, "lost" ); if (debug) Serial.println("Subscribing to " + mqttTopic); } void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { if ( strcmp(topic, (mqttTopic + "/set").c_str()) == 0 ) { if (debug) Serial.println("Got command " + String(payload)); int p = getValidNumber(payload); if ( p >= 0 && p <= 100) { setPercentage(p); } } xTimerReset(mqttWatchdog, 0); } void setPercentage(int gotoPercentage) { if (!xTimerIsTimerActive(movementStopTimer)) { if (debug) Serial.println("Starting movement to: " + String(gotoPercentage)); int travelTime = totalTravelTime * abs(gotoPercentage - percentage); xTimerChangePeriod(movementStopTimer, pdMS_TO_TICKS(travelTime), 0); if ( gotoPercentage < percentage ) { triggerPin(inPin); } else if ( gotoPercentage > percentage ) { triggerPin(outPin); } if (gotoPercentage != percentage) { digitalWrite(ledPin, LOW); percentage = gotoPercentage; xTimerStart(movementStopTimer, 0); } } } void movementStop() { digitalWrite(ledPin, HIGH); if ( percentage != 0 && percentage != 100 ) { if (debug) Serial.println("triggerPin(stopPin);"); triggerPin(stopPin); } moving = false; if (debug) Serial.println("Done going to " + String(percentage)); sendStatus(); } void sendStatus() { iot.mqtt.publish(mqttTopic.c_str(), 1, true, String(percentage).c_str() ); iot.mqtt.publish(("homie/" + iot.hostname + "/$stats/uptime").c_str(), 1, true, String(millis()).c_str() ); } void reset() { ESP.restart(); } void setup() { pinMode(outPin, OUTPUT); pinMode(ledPin, OUTPUT); digitalWrite(outPin, HIGH); pinMode(stopPin, OUTPUT); digitalWrite(stopPin, HIGH); pinMode(inPin, OUTPUT); digitalWrite(inPin, HIGH); iot.begin(); sendStatusTimer = xTimerCreate("statusTime", pdMS_TO_TICKS(120000), pdTRUE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(sendStatus)); movementStopTimer = xTimerCreate("movementStopTimer", pdMS_TO_TICKS(totalTravelTime), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(movementStop)); mqttWatchdog = xTimerCreate("WD", pdMS_TO_TICKS(122000), pdTRUE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(reset)); mqttTopic = "homie/" + iot.hostname + "/status/percent"; mqttTopicWD = "homie/" + iot.hostname + "/status/watchdog"; setPercentage(0); iot.mqtt.onMessage(onMqttMessage); iot.mqtt.onConnect(onMqttConnect); iot.mqtt.connect(); xTimerStart(sendStatusTimer, 0); xTimerStart(mqttWatchdog, 0); } void loop() { if (millis() - TriggerTimer >= 60UL) digitalWrite(triggeredPin, HIGH); } <file_sep>/README.md # awning-remote homie-mqtt compatible ESP32 implementation to press some buttons on the awning remote via Wifi using: https://github.com/merlinschumacher/Basecamp
85278403aba89e94684ee37d5a4a0033514e8b6c
[ "Markdown", "C++" ]
2
C++
Nidhoggrr/awning-remote
e33cc661e0f23e4dc22738f253e0ec48019bce40
3c589f8a0920a88eb131d6250d17e750caa1c9bc
refs/heads/master
<file_sep># Custom logic to be included in OrdersController. It has intentionally been isolated in its own library to make it # easier for developers to customize the checkout process. module Spree::Checkout def checkout build_object load_object load_data load_checkout_steps @order.update_attributes(params[:order]) # additional default values needed for checkout if current_user @order.bill_address ||= current_user.bill_address && current_user.bill_address.clone @order.ship_address ||= current_user.ship_address && current_user.ship_address.clone end @order.bill_address ||= Address.default(current_user) @order.ship_address ||= Address.default(current_user) if @order.creditcards.empty? @order.creditcards.build(:month => Date.today.month, :year => Date.today.year) end @shipping_method = ShippingMethod.find_by_id(params[:method_id]) if params[:method_id] @shipping_method ||= @order.shipping_methods.first @order.shipments.build(:address => @order.ship_address, :shipping_method => @shipping_method) if @order.shipments.empty? if request.post? @order.creditcards.clear @order.attributes = params[:order] @order.creditcards[0].address = @order.bill_address if @order.creditcards.present? @order.user = current_user @order.ip_address = request.env['REMOTE_ADDR'] @order.update_totals @order.email = current_user.email if @order.email.blank? && current_user begin # need to check valid b/c we dump the creditcard info while saving if @order.valid? if params[:final_answer].blank? @order.save else @order.creditcards[0].authorize(@order.total) @order.complete # remove the order from the session session[:order_id] = nil end else flash.now[:error] = t("unable_to_save_order") render :action => "checkout" and return unless request.xhr? end rescue Spree::GatewayError => ge flash.now[:error] = t("unable_to_authorize_credit_card") + ": #{ge.message}" render :action => "checkout" and return end respond_to do |format| format.html do flash[:notice] = t('order_processed_successfully') order_params = {:checkout_complete => true} order_params[:order_token] = @order.token unless @order.user redirect_to order_url(@order, order_params) end format.js {render :json => { :order_total => number_to_currency(@order.total), :ship_amount => number_to_currency(@order.ship_amount), :tax_amount => number_to_currency(@order.tax_amount), :available_methods => rate_hash}.to_json, :layout => false} end end end def load_checkout_steps @checkout_steps = %w{registration billing shipping shipping_method payment confirmation} @checkout_steps.delete "registration" if current_user end end <file_sep>map.resources :users, :has_many => :addresses<file_sep>namespace :db do desc "Bootstrap your database for Spree." task :bootstrap => :environment do # load initial database fixtures (in db/sample/*.yml) into the current environment's database ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym) Dir.glob(File.join(DefaultAddressesExtension.root, "db", 'sample', '*.{yml,csv}')).each do |fixture_file| Fixtures.create_fixtures("#{DefaultAddressesExtension.root}/db/sample", File.basename(fixture_file, '.*')) end end end namespace :spree do namespace :extensions do namespace :default_addresses do desc "Copies public assets of the Default Addresses to the instance public/ directory." task :update => :environment do is_svn_git_or_dir = proc {|path| path =~ /\.svn/ || path =~ /\.git/ || File.directory?(path) } Dir[DefaultAddressesExtension.root + "/public/**/*"].reject(&is_svn_git_or_dir).each do |file| path = file.sub(DefaultAddressesExtension.root, '') directory = File.dirname(path) puts "Copying #{path}..." mkdir_p RAILS_ROOT + directory cp file, RAILS_ROOT + path end end end end end desc "Imports last addresses as defaults" task :get_default_addresses => :environment do User.find(:all).each do |user| orders_with_addresses = user.orders(:order => "created_at ASC").select{|o| o.bill_address && o.shipment && o.shipment.address } if last_order = orders_with_addresses.last puts "#{user.email}: Found addresses" bill_address = last_order.bill_address ship_address = last_order.shipment.address user.update_attribute(:bill_address_id, bill_address && bill_address.id) user.update_attribute(:ship_address_id, ship_address && ship_address.id) else puts "#{user.email}: Could not find any usefull addresses associated with user" end end end<file_sep># Uncomment this if you reference any of your controllers in activate # require_dependency 'application' class DefaultAddressesExtension < Spree::Extension version "1.0" description "Describe your extension here" url "http://yourwebsite.com/default_addresses" # Please use default_addresses/config/routes.rb instead for extension routes. # def self.require_gems(config) # config.gem "gemname-goes-here", :version => '1.2.3' # end def activate Address.class_eval do belongs_to :user has_many :shipments if Spree::Version::Major.to_i > 0 || Spree::Version::Minor.to_i > 8 has_many :checkouts, :foreign_key => "bill_address_id" # can modify an address if it's not been used in an order (but checkouts controller has finer control) def editable? new_record? || (shipments.empty? && checkouts.empty?) end else has_many :orders, :foreign_key => "bill_address_id" # can modify an address if it's not been used in an order (but checkouts controller has finer control) def editable? new_record? || (shipments.empty? && orders.empty?) end end # can modify an address if it's not been used in an order (but checkouts controller has finer control) def self.default(user = nil) new(:country => Country.find(Spree::Config[:default_country_id]), :user => user) end def zone (state && state.zone) || (country && country.zone) end def zones Zone.match(self) end def same_as?(other) attributes.except("id", "updated_at", "created_at") == other.attributes.except("id", "updated_at", "created_at") end alias same_as same_as? def clone editable? ? self : super end def to_s "#{full_name}: #{address1}" end end User.class_eval do has_many :addresses belongs_to :ship_address, :class_name => "Address", :foreign_key => "ship_address_id" belongs_to :bill_address, :class_name => "Address", :foreign_key => "bill_address_id" # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :email, :password, :password_confirmation, :ship_address_id, :bill_address_id end OrderTransactionObserver.instance end end <file_sep>class OrderTransactionObserver < ActiveRecord::Observer observe :order # Generic transition callback *after* the transition is performed def after_transition(order, attribute_name, event_name, from_state, to_state) if event_name.to_s == "complete" if order.bill_address_id && order.ship_address_id order.user.update_attributes!( :bill_address_id => order.bill_address_id, :ship_address_id => order.ship_address_id ) end end end end<file_sep>require 'test_helper' class AddressesControllerTest < ActionController::TestCase fixtures :countries, :states context AddressesController do setup do @complete_checkout = Factory(:checkout) @user = Factory(:user, { :orders => [@complete_checkout.order], }) @bill_address = Factory(:address, :user => @user) @ship_address = Factory(:address, :user => @user) assert @bill_address.valid? @user.update_attribute(:bill_address_id, @bill_address.id) @user.update_attribute(:ship_address_id, @ship_address.id) @controller.stub!(:current_user, :return => @user) end context "on get to :index" do setup do get :index, :user_id => @user.id end should "assign correct addresses" do assert_equal @bill_address, @user.reload.bill_address assert_equal @ship_address, @user.reload.ship_address end should "assign current @user" do assert_equal(@user, assigns(:user)) end should_respond_with :success should_assign_to :addresses should_assign_to :states should_assign_to :bill_address, :ship_address context "@addresses" do should "return 2 addresses" do assert_equal 2, assigns(:addresses).length end end end context "on post to :update of editable bill_address" do setup do assert @bill_address.editable? @request.env['HTTP_REFERER'] = 'http://whatever' post :update, :user_id => @user.id, :id => @bill_address.id end should_respond_with :redirect should_not_change "Address.count" should_assign_to :address end context "on post to :update of not editable bill_address" do setup do @bill_address.shipments << Factory(:shipment, :address => @bill_address) assert !@bill_address.reload.editable? @request.env['HTTP_REFERER'] = 'http://whatever' post :update, :user_id => @user.id, :id => @bill_address.id, :address_type => "bill_address" end should_respond_with :redirect should_change "Address.count", :by => 1 should_assign_to :address should "clone object" do assert !@bill_address.reload.editable? assert assigns(:object).editable? end should "be valid" do assert assigns(:address).valid? end should "assign new address to @user" do assert_not_equal(@user.reload.bill_address, @bill_address) assert_equal(@user.reload.bill_address, assigns(:address)) end should "have no errors" do assert(assigns(:address).errors.empty?) end should "not be new record" do assert_not_equal(@bill_address, assigns(:address)) assert(!assigns(:address).new_record?) end end context "on post to :create" do setup do assert @bill_address.editable? @ship_address.shipments << Factory(:shipment, :address => @ship_address) assert !@ship_address.reload.editable? post :create, { :user_id => @user.id, :ship_address => @ship_address.attributes.merge("firstname"=>"NewNameShip"), :bill_address => @bill_address.attributes.merge("firstname"=>"NewNameBill"), } end should_respond_with :redirect should_change "Address.count", :by => 1 should_assign_to :ship_address, :bill_address should "clone object" do assert assigns(:ship_address).editable? end should "be valid" do assert assigns(:ship_address).valid? assert assigns(:bill_address).valid? end should "assign new address to @user" do assert_equal(@user.reload.bill_address, assigns(:bill_address)) assert_equal(@user.reload.ship_address, assigns(:ship_address)) end should "have no errors" do assert(assigns(:bill_address).errors.empty?) assert(assigns(:ship_address).errors.empty?) end should "update addresses" do assert_equal("NewNameShip", assigns(:ship_address).firstname) assert_equal("NewNameBill", assigns(:bill_address).firstname) end end context "on post to :create with use_bill_address" do setup do assert @bill_address.editable? post :create, { :user_id => @user.id, :ship_address => {:use_bill_address => "on"}, :bill_address => @bill_address.attributes.merge("firstname"=>"NewNameBill"), } end should_respond_with :redirect should_change "Address.count", :by => 1 should_assign_to :ship_address, :bill_address should "clone object" do assert assigns(:ship_address).editable? end should "be valid" do assert assigns(:ship_address).valid? assert assigns(:bill_address).valid? end should "assign new address to @user" do assert_equal(@user.reload.bill_address, assigns(:bill_address)) assert_equal(@user.reload.ship_address, assigns(:ship_address)) end should "have no errors" do assert(assigns(:bill_address).errors.empty?) assert(assigns(:ship_address).errors.empty?) end should "update addresses" do assert_equal("NewNameBill", assigns(:ship_address).firstname) assert_equal("NewNameBill", assigns(:bill_address).firstname) end end end end<file_sep>class PrepareDefaultAddresses < ActiveRecord::Migration def self.up add_column :users, :bill_address_id, :integer unless User.column_names.include?('bill_address_id') add_column :users, :ship_address_id, :integer unless User.column_names.include?('ship_address_id') end def self.down end end<file_sep>= Default Addresses Extension provides a way to have default addresses assigned to user. His addresses will be filled by with these defaults on checkout. ======================================== You can import most recent addresses and set them as defaults by running rake get_default_addresses ======================================== For spree 0.8.3 you have to replace 2 lines in lib/spree/checkout.rb. 14,15c14,15 < @order.bill_address ||= Address.new(:country => @default_country) < @order.ship_address ||= Address.new(:country => @default_country) --- > @order.bill_address ||= (current_user && current_user.bill_address.clone) || Address.default(current_user) > @order.ship_address ||= (current_user && current_user.ship_address.clone) || Address.default(current_user)<file_sep>class AddressesController < Spree::BaseController resource_controller belongs_to :user actions :index, :update def create load_collection before :create if update_addresses after :create set_flash :update response_for :create else after :create_fails set_flash :update_fails response_for :create_fails end end private def update_addresses @bill_address = @bill_address.clone unless @bill_address.editable? @ship_address = @ship_address.clone unless @ship_address.editable? bstatus = sstatus = nil Address.transaction do bstatus = @bill_address.update_attributes(params[:bill_address]) if params[:ship_address][:use_bill_address] @ship_address = @bill_address.clone sstatus = @ship_address.save else sstatus = @ship_address.update_attributes(params[:ship_address]) end end if bstatus && sstatus @user.update_attribute(:bill_address, @bill_address) @user.update_attribute(:ship_address, @ship_address) return(true) else return(false) end end def collection @user ||= current_user @ship_address = @user.ship_address || Address.default(@user) @bill_address = @user.bill_address || Address.default(@user) @countries = Country.find(:all).sort @shipping_countries = ShippingMethod.all.collect{|method| method.zone.country_list }.flatten.uniq.sort_by{|item| item.name} default_country = @bill_address.country @states = default_country ? default_country.states.sort : [] @addresses = [@bill_address, @ship_address] end update.after do if ["bill_address", "ship_address"].include? params[:address_type] @user.update_attribute(params[:address_type].to_sym, @object) end end [update, create].each do |response| response.wants.html { redirect_back_or_default :action => :index } end [update.failure, create.failure].each do |response| response.wants.html { render :action => :index } end def object if params[:ship_address] && params[:ship_address][:use_bill_address] @object ||= @user.bill_address && @user.bill_address.clone else @object ||= @user.addresses.find_by_id(param) end @object = @object.clone if @object && !@object.editable? @object end end
75e40db9724794e7ad41f6c49ecf04a1c65eb32a
[ "Markdown", "Ruby" ]
9
Ruby
swistak/spree-default-addresses
2d8759f7098057ec0d214bd96c7d307d5711abb1
1e135a80c77b38dd22b201aa3097fc155f63b0e3
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.stylelabs.assessment</groupId> <artifactId>stylelabsAssesment</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>stylelabsAssesment</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.141.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.3.0</version> </dependency> <dependency> <groupId>org.apache.directory.studio</groupId> <artifactId>org.apache.commons.io</artifactId> <version>2.4</version> </dependency> </dependencies> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.3</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>3.0.0-M1</version> </plugin> </plugins> </reporting> <profiles> <profile> <id>google-search-runner</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> <id>Run in chrome</id> <goals> <goal>integration-test</goal> </goals> <configuration> <testSourceDirectory>src/test/java</testSourceDirectory> <includes> <include> **/GoogleRunner.java </include> </includes> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <properties> <property> <name>junit</name> <value>true</value> </property> </properties> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>flight-search-runner</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> <id>Run in chrome</id> <goals> <goal>integration-test</goal> </goals> <configuration> <testSourceDirectory>src/test/java</testSourceDirectory> <includes> <include> **/FlightRunner.java </include> </includes> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <properties> <property> <name>junit</name> <value>true</value> </property> </properties> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project> <file_sep># StyleLabAssessment # This assisgnment gives about opening the google page and focus on searching with two city searches Note: This assignment can be tested only with windows # Pre-requisite installation Java 1.8 or higher Maven 3.x # Environment variables to be set - Preferably System Variables JAVA_HOME = <Path to Java Home> <M2_HOME> = <Path to Maven Home> Path = %JAVA_HOME%\bin;%M2_HOME%\bin;%PATH% # Commands to run the assignment # This assignment opens a browser with google and makes a seach with 2 values mvn verify -Pgoogle-search-runner # This assignment opens a browser with expedia.com and makes a sample booking and banking page is validated mvn verify -Pflight-search-runner # Alternate way to run Run the GoogleRunner.java file in Eclipse/Intellij IDE and test the google search feature Run the FlightRunner.java file in Eclipse/Intellij IDE and test the flight search feature <file_sep>package com.stylelabs.assessment.stylelabsAssesment.StepDefinition; import cucumber.api.PendingException; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.io.File; import java.io.IOException; public class GoogleSearch { WebDriver driver = null; @Given("^user navigated to google$") public void user_navigated_to_google() { System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe"); driver = new ChromeDriver(); driver.get("http://www.google.com"); } @When("^the page is loaded$") public void the_page_is_loaded() { String actualTitle = driver.getTitle(); String expectedTitle = "Google"; if (actualTitle.equalsIgnoreCase(expectedTitle)) System.out.println("Title Matched"); else System.out.println("Title didn't match"); } @Then("^search for \"([^\"]*)\"$") public void search_for_Bahamas(String searchText) { WebElement element = driver.findElement(By.name("q")); element.sendKeys(searchText); element.submit(); } @Then("^take screenshot of the result page$") public void take_screenshot_of_the_result_page() throws InterruptedException { TakesScreenshot ts = (TakesScreenshot) driver; File source = ts.getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(source, new File("src/test/resources/Screenshot/Google.png")); System.out.print("ScreenShot Taken"); } catch (IOException e) { System.out.println(e.getMessage()); } Thread.sleep(2000); driver.close(); } }
ad6af28545f6d9f2253737616fca404dd983806e
[ "Markdown", "Java", "Maven POM" ]
3
Maven POM
SureshChinnusamy1986/StyleLabAssessment
8e56e78752e9438dd7d280b9b208e0a4dadeae38
673c325abe5f2322f0552a3400770b6993e3f449
refs/heads/master
<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { useQuery } from 'react-apollo-hooks'; import Spinner from '../components/Spinner'; import Photos from './Photos'; import { GET_PHOTOS } from './queries'; export default function GetPhotos(props) { const { tags } = props; const { data, loading } = useQuery(GET_PHOTOS, { variables: { tags }, }); if (loading) { return <Spinner />; } const { getPhotos } = data; const { title, items } = getPhotos; return <Photos title={title} items={items} data-testid="photos" />; } GetPhotos.propTypes = { tags: PropTypes.string, }; GetPhotos.defaultProps = { tags: '', }; <file_sep>/* eslint-disable */ export default { "data": { "getPhotos": { "title": "Recent Uploads tagged cats", "link": "https://www.flickr.com/photos/tags/cats/", "description": "", "modified": "2019-07-02T03:07:17Z", "items": [ { "title": "Cats Eyes", "media": { "m": "https://live.staticflickr.com/65535/48176159702_a6eb9f970a_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-07-01T19:18:39-08:00", "author": "<EMAIL> (\"lanelg68\")", "author_id": "153563623@N05", "tags": "cats eyes cat anima fur furry beautiful whiskers green feline wild domesticate pet pets kitty", "link": "https://www.flickr.com/photos/153563623@N05/48176159702/", "__typename": "PhotoType" }, { "title": "Mandy Monday; M is for Mandy and Monday", "media": { "m": "https://live.staticflickr.com/65535/48175806662_8ca36d032b_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-07-01T07:53:17-08:00", "author": "<EMAIL> (\"Photo Amy\")", "author_id": "39683033@N08", "tags": "50mm adorable canon50d cat cats cuddly cute fur furty ginger kitten kittens longhaired longhariedcat orange whisters", "link": "https://www.flickr.com/photos/photos_amy/48175806662/", "__typename": "PhotoType" }, { "title": "Bill the princess", "media": { "m": "https://live.staticflickr.com/65535/48175384831_e673ae288d_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-10T07:55:24-08:00", "author": "<EMAIL> (\"Steve only\")", "author_id": "<PASSWORD>", "tags": "googlepixel2 cellphone pixel2 cats bill", "link": "https://www.flickr.com/photos/behappy1_98/48175384831/", "__typename": "PhotoType" }, { "title": "Bill the princess", "media": { "m": "https://live.staticflickr.com/65535/48175384951_9aec2c7ced_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-03-03T14:49:49-08:00", "author": "<EMAIL> (\"Steve only\")", "author_id": "<PASSWORD>", "tags": "fujifilm xt3 canon ef 50mm 114 5014 f14 fringer cats bill", "link": "https://www.flickr.com/photos/behappy1_98/48175384951/", "__typename": "PhotoType" }, { "title": "Bill the princess", "media": { "m": "https://live.staticflickr.com/65535/48175384876_1e63103aee_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-03-10T22:21:27-08:00", "author": "<EMAIL> (\"Steve only\")", "author_id": "49271313@N00", "tags": "googlepixel2 cellphone pixel2 cats bill", "link": "https://www.flickr.com/photos/behappy1_98/48175384876/", "__typename": "PhotoType" }, { "title": "Cat", "media": { "m": "https://live.staticflickr.com/65535/48175094926_1d05687ab5_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-07-01T17:22:11-08:00", "author": "<EMAIL> (\"morrisonbordercollie\")", "author_id": "181903536@N08", "tags": "feline kitten kitty cats cat", "link": "https://www.flickr.com/photos/181903536@N08/48175094926/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174718706_d26d5845a7_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:49:07-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "52885918@N07", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174718706/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174791807_34958bcf89_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:52:40-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "52885918@N07", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174791807/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174721136_69fc6ce70b_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:37:04-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "52885918@N07", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174721136/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174724966_182effabea_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:05:37-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "52885918@N07", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174724966/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174792097_3f56b969a5_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:51:29-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174792097/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174792487_28683d9762_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:50:47-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174792487/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174797372_ee3108f7c2_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:10:20-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>@N07", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174797372/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174720826_7ff4262a9d_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:41:12-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174720826/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174723731_79cb602f65_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:07:22-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174723731/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174796987_273f2356dc_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:10:37-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "5<PASSWORD>", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174796987/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174722331_1a40504b5d_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:12:35-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "5<PASSWORD>", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174722331/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174796192_e5497c3014_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:14:27-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>@N07", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174796192/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174798352_09dd8cb349_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:06:51-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>@N07", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174798352/", "__typename": "PhotoType" }, { "title": "County of Santa Clara, Animal Services Center", "media": { "m": "https://live.staticflickr.com/65535/48174717031_80994b78c8_m.jpg", "__typename": "ImageType" }, "date_taken": "2019-06-26T11:56:36-08:00", "author": "<EMAIL> (\"Dreyfuss + Blackford Architecture\")", "author_id": "<PASSWORD>", "tags": "b6034 santa clara county animal services center san martin california 2017 healthcare clinic 2016 dreyfuss blackford architecture architects design shelter 2019 leed silver certification dogs cats small animals barn community 2018 2021", "link": "https://www.flickr.com/photos/dreyfussblackford/48174717031/", "__typename": "PhotoType" } ], "__typename": "Photos" } } }<file_sep>### Flapi-UI A simple UI layer for a web application which hits the Flickr public API to retrieve photos. A Node backend is required for this project which can be found [here](https://github.com/ollyd/flapi-bff). You can test out a live demo version of the app [here](http://oilymutton-flapi-ui.s3-website-ap-southeast-2.amazonaws.com/). Note: the first time you hit the backend it will take a few seconds. This is because it's hosted on Heroku and it needs some time for the dyno to fire up. Subsequent hits will be much faster. ### Tech It uses React, Apollo, GraphQL and Styled Components. Eslint for linting, which runs on a pre-commit hook. React Testing Library, Jest, Jest Styled Components for testing, which also runs pre-commit. ### Installation Clone this repo. ```sh $ yarn install $ yarn dev ``` For a production build: ```sh $ yarn build ``` ### Todo Lots to do still!... | Field | Task | | ------ | ------ | | UI | Disable Search when on individual Photo page as it's redundant. | | UI | Add filtering and addition search params to GraphQL query. | | UI | Fix the jump in image size on the individual Photo page. | | UI | Add logic to hit a photo directly with a url. | | Errors | Add Error Boundaries and better GraphQL error handling | | Optimisation | The bundle is a bit large around 500kb. Would implement gzip compression, and potentially code splitting. | | Testing | I have only provided an example style, unit and integration tests. Coverage is extremely thin. | | Security | Would add https for production. | | Bugs | Fix loading animation. | ### Considerations | Field | Task | | ------ | ------ | | UI | Potentially smaller thumbnail images to reduce blur. | | UI | Perhaps scrap the masonry thumbnail effect with uniform sizes. | <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Title from '../components/Title'; import PhotoGallery from '../components/PhotoGallery'; export default function Photos(props) { const { title, items } = props; return ( <> <Title title={title} /> <PhotoGallery items={items} /> </> ); } Photos.propTypes = { title: PropTypes.string.isRequired, items: PropTypes.arrayOf(PropTypes.shape({})).isRequired, }; <file_sep>/* eslint no-undef: "off" */ import React from 'react'; import { render, cleanup } from '@testing-library/react'; import { BrowserRouter } from 'react-router-dom'; import { ApolloClient } from 'apollo-client'; import { ApolloProvider } from 'react-apollo'; import { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { MockLink } from 'apollo-link-mock'; import { ThemeProvider } from 'styled-components'; import theme from '../themes/theme'; import GetPhotos from '../pages/GetPhotos'; import { GET_PHOTOS } from '../pages/queries'; import mockedResponse from './mocks/mockedResponse'; const waitForNextTick = () => new Promise(resolve => setTimeout(resolve), 300); afterEach(cleanup); const getPhotosMocks = ({ tags, data }) => { return [ { request: { operationName: 'getPhotos', query: GET_PHOTOS, variables: { tags }, }, result: { data, }, }, ]; }; function createClient(mocks) { return new ApolloClient({ cache: new InMemoryCache(), link: new MockLink(mocks), }); } const renderWrapper = (mocks, props) => { const { tags } = props; const { getByText, container } = render( <ApolloProvider client={createClient(getPhotosMocks(mocks))}> <ApolloHooksProvider client={createClient(getPhotosMocks(mocks))}> <BrowserRouter> <ThemeProvider theme={theme}> <GetPhotos tags={tags} /> </ThemeProvider> </BrowserRouter> </ApolloHooksProvider> </ApolloProvider>, ); return { getByText, container }; }; // ---- INTEGRATION ---- // describe('<GetPhotos />', () => { it('should render title and images correctly', async () => { const mocks = { tags: 'cats', ...mockedResponse, }; const { container } = renderWrapper(mocks, { tags: 'cats' }); await waitForNextTick(); expect(container.querySelector('h1').textContent).toBe('Recent Uploads tagged cats'); expect(container.querySelectorAll('img').length).toEqual(20); expect(container.querySelector('img')).toHaveAttribute('src'); }); }); <file_sep>import React, { useState, useEffect } from 'react'; import { BrowserRouter, Switch, Route, } from 'react-router-dom'; import { ApolloProvider } from 'react-apollo'; import { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks'; import { useDebounce } from 'use-debounce'; import { ThemeProvider } from 'styled-components'; import { Normalize } from 'styled-normalize'; import theme from './themes/theme'; import GlobalStyles from './themes/GlobalStyles'; import apolloClient from './utils/apolloClient'; import GetPhotos from './pages/GetPhotos'; import Photo from './pages/Photo'; import Navbar from './components/Navbar'; import Input from './components/Input'; export default function App() { const [searchInput, setSearchInput] = useState(''); const [value] = useDebounce(searchInput, 500); useEffect(() => { const script = document.createElement('script'); script.src = '//embedr.flickr.com/assets/client-code.js'; script.async = true; document.body.appendChild(script); }); return ( <ApolloProvider client={apolloClient}> <ApolloHooksProvider client={apolloClient}> <BrowserRouter> <ThemeProvider theme={theme}> <> <Normalize /> <GlobalStyles /> <Navbar /> <Input setSearchInput={setSearchInput} value={searchInput} /> <Switch> <Route exact path="/" render={() => <GetPhotos tags={value} />} /> <Route path="/:user/:photoId" component={Photo} /> </Switch> </> </ThemeProvider> </BrowserRouter> </ApolloHooksProvider> </ApolloProvider> ); } <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; export default function Input(props) { const { value, setSearchInput } = props; return ( <InputGroup> <StyledInput type="text" placeholder="Search" value={value} onChange={e => setSearchInput(e.target.value)} /> <Bar /> </InputGroup> ); } const InputGroup = styled.div` position: fixed; top: 15px; z-index: 2; margin-left: auto; right: 15rem; @media (max-width: 960px) { right: 5rem; } @media (max-width: 600px) { right: 0.8rem; } `; const StyledInput = styled.input` ${({ theme }) => ` font-size: 1.8rem; font-weight: 300; color: ${theme.palette.secondary}; padding: 0.8rem 0.8rem 0.8rem 0.4rem; display: block; width: 30rem; border: none; border-bottom: 1px solid ${theme.palette.secondary}; background-color: ${theme.palette.primary}; margin-left: auto; margin-top: 0.8rem; &:focus { outline: none; } @media (max-width: 600px) { width: 20rem; } `} `; const Bar = styled.span` ${({ theme }) => ` position: relative; display: block; width: 30rem; &:before, &:after { content: ''; height: 0.2rem; width: 0; bottom: 0.1rem; position: absolute; background: ${theme.palette.secondary}; transition: 0.2s ease all; } `} `; Input.propTypes = { value: PropTypes.string, setSearchInput: PropTypes.func.isRequired, }; Input.defaultProps = { value: '', }; <file_sep>export default { text: { color: { primary: 'rgba(0,0,0,0.67)', contrast: '#fff', }, }, palette: { primary: '#34495e', secondary: '#1abc9c', contrast: '#ecf0f1', }, border: '1px solid #d2d2d2', }; <file_sep>/* eslint no-undef: "off" */ import React from 'react'; import { render, cleanup, fireEvent } from '@testing-library/react'; import 'jest-styled-components'; import { ThemeProvider } from 'styled-components'; import Input from '../components/Input'; import theme from '../themes/theme'; import GlobalStyles from '../themes/GlobalStyles'; afterEach(cleanup); const waitForNextTick = () => new Promise(resolve => setTimeout(resolve), 501); const setup = (setSearchInput, value) => { const { container, rerender, getByPlaceholderText } = render( <ThemeProvider theme={theme}> <> <GlobalStyles /> <Input setSearchInput={setSearchInput} value={value} /> </> </ThemeProvider>, ); const input = getByPlaceholderText('Search'); return { input, container, rerender, }; }; describe('<Input>: Style snapshot tests', () => { it('should have correct styles', () => { const { container } = setup(jest.fn(), 'cats'); expect(container).toMatchSnapshot(); }); }); describe('<Input>: Unit tests', () => { it('should have the correct value after onChange', async () => { let value = 'cats'; const setSearchInput = jest.fn((ev) => { value = ev; }); const { input } = setup(setSearchInput, value); expect(value).toBe('cats'); fireEvent.change(input, { target: { value: 'dogs' } }); await waitForNextTick(); expect(setSearchInput).toHaveBeenCalledTimes(1); expect(value).toBe('dogs'); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Title from '../components/Title'; export default function Photo(props) { const { match, location } = props; const { params } = match; const { user, photoId } = params; const { state } = location; const { title, tags, link } = state; const tagsArr = tags.split(' '); return ( <> <Title title={title} /> <ImgContainer> <a data-flickr-embed="true" href={link}><img height="540" width="540" src={`https://live.staticflickr.com/${user}/${photoId}.jpg`} alt={title} /></a> </ImgContainer> <Tags> {tagsArr[0] !== '' ? ( tagsArr.map(tag => ( <Tag key={tag}>{tag}</Tag> )) ) : ( <Tag>No tags</Tag> )} </Tags> </> ); } const ImgContainer = styled.div` ${({ theme }) => ` padding: 1.6rem; display: flex; justify-content: center; align-items: center; width: 100% background-color: ${theme.palette.contrast}; `} `; const Tags = styled.div`; display: flex; flex-wrap: wrap; margin-bottom: 5rem; justify-content: center; `; const Tag = styled.span` ${({ theme }) => ` display: block; padding: 0.8rem; margin: 0.8rem; height: 3.2rem; line-height: 1.7rem; border-radius: 3px; font-weight: 300; background-color: ${theme.palette.secondary}; color: ${theme.text.color.contrast}; `} `; Photo.propTypes = { title: PropTypes.string, }; Photo.defaultProps = { title: 'No Title Provided', }; <file_sep>import path from 'path'; import HtmlPlugin from 'html-webpack-plugin'; export default { entry: [ '@babel/polyfill', './src', ], output: { path: path.join(__dirname, '../dist'), publicPath: '/', filename: 'app/[name].[chunkhash].js', }, module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/, }, { test: /\.(png|jpe?g|gif|woff|ico)$/, loader: 'file-loader?name=[hash].[ext]', exclude: /node_modules/, }, { test: /\.svg$/, use: ['@svgr/webpack'], }, ], }, plugins: [ new HtmlPlugin({ template: './public/index.html', title: 'Flapi', }), ], optimization: { splitChunks: { cacheGroups: { vendor: { chunks: 'initial', name: 'vendor', test: 'vendor', enforce: true, }, }, }, runtimeChunk: true, }, }; <file_sep>import merge from 'webpack-merge'; import CleanPlugin from 'clean-webpack-plugin'; import path from 'path'; import webpack from 'webpack'; import MiniCssExtractPlugin from 'mini-css-extract-plugin'; import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin'; import common from './webpack.common'; export default merge(common, { mode: 'production', module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:3]', 'postcss-loader', ], }, ], }, plugins: [ new CleanPlugin(['dist'], { root: path.join(__dirname, '..'), verbose: true }), new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' }), new webpack.EnvironmentPlugin({ API_URL: `${process.env.API_URL}`, }), new OptimizeCssAssetsPlugin(), ], }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; export default function Title(props) { const { title } = props; return ( <TitleContainer> <H1>{title}</H1> </TitleContainer> ); } const TitleContainer = styled.div` ${({ theme }) => ` display: flex; border-bottom: ${theme.border}; justify-content: space-between; align-items: center; `} `; const H1 = styled.h1` ${({ theme }) => ` margin-bottom: 0.8rem; font-size: 2.4rem; color: ${theme.text.color.primary}; font-weight: 300; `} `; Title.propTypes = { title: PropTypes.string.isRequired, }; <file_sep>import merge from 'webpack-merge'; import webpack from 'webpack'; import common from './webpack.common'; export default merge(common, { mode: 'development', devtool: 'inline-source-map', output: { filename: 'app/[name].js', }, resolve: { alias: { 'react-dom': '@hot-loader/react-dom' } }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:3]', 'postcss-loader', ], }, ], }, plugins: [ new webpack.EnvironmentPlugin({ API_URL: `${process.env.API_URL}`, }), new webpack.HotModuleReplacementPlugin(), ], devServer: { hot: true, open: true, inline: true, contentBase: './dist', publicPath: '/', port: 3000, historyApiFallback: true, }, }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import ThumbnailImage from './ThumbnailImage'; export default function PhotoGallery(props) { const { items } = props; const imageCount = items.length; const imagesPerColumn = imageCount / 4; const newItemsArr = [...items]; return ( <Container> {[1, 2, 3, 4].map(i => ( <Column key={`column${i}`}> {newItemsArr.splice(0, imagesPerColumn).map(item => ( <ThumbnailImage key={`${item.author_id}_${item.date_taken}`} date={item.date_taken} src={item.media.m} author={item.author} link={item.link} title={item.title} tags={item.tags} /> ))} </Column> ))} </Container> ); } const Container = styled.div` display: flex; flex-wrap: wrap; padding: 0 0.4rem; margin-top: 0.8rem; `; const Column = styled.div` flex: 25%; max-width: 25%; padding: 0 0.4rem; @media (max-width: 960px) { flex: 50%; max-width: 50%; } @media (max-width: 450px) { flex: 100%; max-width: 100%; } `; PhotoGallery.propTypes = { items: PropTypes.arrayOf(PropTypes.shape({})).isRequired, };
b95eda2bd0a40561bfe67d63fe45410cf9b01a44
[ "JavaScript", "Markdown" ]
15
JavaScript
ollyd/flapi-ui
205f73ef7ee2b3276a4b889c0c14f66baf7cde41
bd6d48779a403ae62eed5fe24eeff8ca59ec5d68
refs/heads/master
<repo_name>conradbm/test<file_sep>/ui.R # # This is the user-interface definition of a Shiny web application. You can # run the application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) source("C:/Users/Jenn/Desktop/CSCI490/GroupProject/ShinyApp/ShinyApp/test/functions.R") # Define UI for application that draws a histogram shinyUI(fluidPage( # Application title titlePanel("Chicago crime data"), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( sliderInput("latbins", "Latitude Min:", min = 41.70, max = 42.65, value = 30), sliderInput("lonbins", "Longitude Min:", min = -87.95, max = -87.51, value = 30), sliderInput("latbins2", "Latitude Max:", min = 41.70, max = 42.65, value = 30), sliderInput("lonbins2", "Longitude Max:", min = -87.95, max = -87.51, value = 30) ), # Show a plot of the generated distribution mainPanel( plotOutput("distPlot") ) ) )) <file_sep>/server.R # # This is the server logic of a Shiny web application. You can run the # application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # https://data.cityofchicago.org/resource/6zsd-86xi.json library(shiny) library(ggmap) #install.packages("GeomRasterAnn") setwd("C:/Users/Jenn/Desktop/CSCI490/GroupProject/ShinyApp/ShinyApp/test/") source("C:/Users/Jenn/Desktop/CSCI490/GroupProject/ShinyApp/ShinyApp/test/functions.R") # Define server logic required to draw a histogram shinyServer(function(input, output) { output$distPlot <- renderPlot({ # generate bins based on input$bins from ui.R x <- faithful[, 2] bins1 <- seq(minLat, maxLat, length.out = input$latbins + 1) bins2 <- seq(minLon, maxLon, length.out = input$latbins + 1) cat(input$latbins, " ", input$lonbins ,"\n") cat(input$latbins2, " ", input$lonbins2, "\n") inputLat <- as.numeric(input$latbins) inputLon <- as.numeric(input$lonbins) validHits <- df_lat_lon_type[which(df_lat_lon_type$latitude >= input$latbins & df_lat_lon_type$latitude <= input$latbins2),] validHits <- validHits[which(validHits$longitude >= input$lonbins & validHits$longitude <= input$lonbins2),] cat("First Valid Hit: ", validHits$primary_type[1], "\n") # draw the histogram with the specified number of bins # hist(x, breaks = bins, col = 'darkgray', border = 'white') map <- get_map(location = "chicago", zoom = 11) ggmap(map) + geom_point(data=validHits, aes(x=longitude, y=latitude, color=primary_type)) }) }) <file_sep>/README.md <h2>Repository Contains: </h2> <ul> <li>HW12 Data Science Group Shiny App Group Solution</li> </ul> <h2>Contributors to this Repository: </h2> <ul> <li>Blake</li> <li>Jennifer</li> <li>Turki</li> </ul> <h2> Functionality Contains: </h2> <ul> <li>Working Web App that, given a range of latitude, longitude inputs we color the different types of crime in that region.</li> </ul> <file_sep>/data_pulled.R # data api: https://data.cityofchicago.org/resource/6zsd-86xi.json library("rjson") json_file <- "https://data.cityofchicago.org/resource/6zsd-86xi.json" json_data <- fromJSON(paste(readLines(json_file), collapse="")) lat1 <- json_data[[1]]$latitude lon1 <- json_data[[1]]$longitude df <- data.frame(matrix(unlist(json_data), nrow=1000, byrow=T),stringsAsFactors=FALSE) head(df) <file_sep>/functions.R # data api: https://data.cityofchicago.org/resource/6zsd-86xi.json # Store functions in this file library("rjson") setwd("C:/Users/Jenn/Desktop/CSCI490/GroupProject/ShinyApp/ShinyApp/test/") # Functions fillDataFrameWithList <- function(someList){ df <- data.frame(latitude=c(0), longitude=c(0), primary_type=c("")) df$latitude <- as.numeric(df$latitude) df$longitude <- as.numeric(df$longitude) df$primary_type <- as.character(df$primary_type) cat("Populating data frame.") for(i in 1:length(someList)){ row <- c(someList[[i]]$latitude, someList[[i]]$longitude, someList[[i]]$primary_type) df <- rbind(df, row) cat(df[i,"latitude"]," ", df[i,"longitde"]," ", df[i,"primary_type"]) } cat("Data frame successfully populated.") return(df) } removeNonNumericRows <- function(df){ df_2 <- df_lat_lon_type[!is.na(as.numeric(as.character(df_lat_lon_type$latitude))),] df_3 <- df_lat_lon_type[!is.na(as.numeric(as.character(df_lat_lon_type$longitude))),] df_lat_lon_type <- df_3 return(df_lat_lon_type) } # Read the 'live' json data as a list object # This dataframe will repopulate everytime you refresh the app json_file <- "https://data.cityofchicago.org/resource/6zsd-86xi.json" json_data <- fromJSON(paste(readLines(json_file), collapse="")) # # # df_lat_lon_type structure # # Columns # ___________________________________________________ # latitude | longitude | primary_type # ROW1 | | # ROW2 | | # ... | | # ___________________________________________________ # Example, df_lat_lon_type[1,"latitude"] // returns the first rows latitude # df_lat_lon_type[1:3,c("latitude,"longitude")] // returns latitude and longitude for the first 3 rows # # # df_lat_lon_type <- fillDataFrameWithList(json_data) df_lat_lon_type <- removeNonNumericRows(df_lat_lon_type) df_lat_lon_type[,c("latitude")] <- as.numeric(df_lat_lon_type[,c("latitude")]) df_lat_lon_type[,c("longitude")] <- as.numeric(df_lat_lon_type[,c("longitude")]) minLat <- min(df_lat_lon_type[,"latitude"]) maxLat <- max(df_lat_lon_type[,"latitude"]) meanLat <- mean(df_lat_lon_type[,"latitude"]) minLon <- min(df_lat_lon_type[,"longitude"]) maxLon <- max(df_lat_lon_type[,"longitude"]) meanLon <- mean(df_lat_lon_type[,"longitude"]) cat("Min Latitude: ", minLat, "\n") cat("Max Latitude: ", maxLat, "\n") cat("Mean Latitude: ", meanLat, "\n") cat("Min Longitude: ", minLon, "\n") cat("Max Longitude: ", maxLon, "\n") cat("Mean Longitude: ", meanLon, "\n")
131385a93d7c6f73400746181fde688be85ce59b
[ "Markdown", "R" ]
5
R
conradbm/test
07a59d6fd89f47d97416e9a7977a542671e726fd
b6c55bad90c274efcee8d3a2afc230de9f74cb22
refs/heads/main
<file_sep>platform :ios, '8.0' inhibit_all_warnings! target ‘AVPlayerDemo’ do pod 'pop', '~> 1.0.7' end <file_sep># AVPlayerDemo 简单的AVPlayerDemo
f2f47968f9d4aabb3392a89353141c6a0e974de9
[ "Markdown", "Ruby" ]
2
Ruby
JudeTian/AVPlayerDemo
1717ba61ac3abab2b50b0f0869c66af7d4715609
47fb05bdb38b7fe2814ed921d65bd07c132cf19d
refs/heads/master
<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Services\Hash; /** * Class Token * @package App\Models */ class Token extends Model { /** * @var array */ protected $fillable = ['token', 'user_id', 'hash']; /** * @var array */ protected $hidden = ['token', 'hash']; /** * @var array */ protected $appends = ['card']; /** * @return mixed */ public function getCardAttribute() { return json_decode((new Hash)->decrypt($this->token)); } } <file_sep><?php namespace App\Services\Subscribers\Twitch; use App\Interfaces\Subscribers; class Followers implements Subscribers { public function getMethod(): string { return 'followers'; } public function getField(): string { return 'follows'; } public function getType(): string { return 'free'; } public function isReset(): bool { return true; } public function setDefaultValue(): array { return [ $this->getType() => null ]; } public function setAttributes($subscriber, $user): array { return [ $this->getType() => $this->getValue($subscriber) ]; } public function getValue($subscriber): string { return '1'; } }<file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Validator; use App\Models\{Paykeeper, Notification}; use Illuminate\Http\Request; use App\User; use Carbon\Carbon; class PaykeeperController extends Controller { public function test() { $token = paykeeper()->auth()->request([], '/info/settings/token/')->fetch('token'); $options = [ "pay_amount" => 42.50, "clientid" => "<NAME>", "orderid" => "Заказ № 10", "client_email" => "<EMAIL>", "service_name" => "Услуга", "client_phone" => "8 (910) 123-45-67" ]; $paykeeper = paykeeper()->setToken($token)->request($options, '/change/invoice/preview/'); $invoice_id = $paykeeper->fetch('invoice_id'); dd($paykeeper->fetchLink()); } /** * для теста */ public function status() { $invoice_id = '20190106014554404'; $status = paykeeper()->auth()->status($invoice_id)->fetch('status'); dd($status); } public function fethPayment(int $paykeeper_id) { if (!$paykeeper = Paykeeper::whereStatus('created')->find($paykeeper_id)) { return $this->fail('Платеж не найден'); } return $this->success($paykeeper); } public function paykeeperAlert(Request $request) { // https://docs.paykeeper.ru/metody-integratsii/priyom-post-opoveshhenij/ $validator = Validator::make($request->all(), [ 'id' => 'required|integer', # Уникальный номер платежа 'sum' => 'required|numeric', # Сумма платежа 'clientid' => 'string', # Фамилия Имя Отчество 'orderid' => 'required|integer', # Номер заказа 'key' => 'required|string', # Цифровая подпись запроса, строка из символов a-f и 0-9 'ps_id' => 'required|integer', # Идентификатор платежной системы 'service_name' => 'string', # Наименование услуги 'client_email' => 'nullable|string', # Адрес электронной почты 'batch_date' => 'string', # Дата списания авторизованного платежа 'client_phone' => 'nullable|string', # Телефон 'fop_receipt_key' => 'string', # Код страницы чека 54-ФЗ 'bank_id' => 'integer', # Идентификатор привязки карты 'card_number' => 'string', # Маскированный номер карты 'card_holder' => 'string', # Держатель карты 'card_expiry' => 'string', # Срок действия карты ]); if ($validator->fails()) { \Log::info($validator->errors()); return 'Error validator!'; // dd($validator->errors()); } $paykeeper = Paykeeper::whereOrderid($request->orderid)->orderByDesc('id')->first(); $signature = md5 ($request->id.number_format($request->sum, 2, ".", "").$request->clientid.$request->orderid.paykeeper()->secret_seed); if ($request->key != $signature) { \Log::info("paykeeperAlert: {$signature}"); return 'Error! Hash mismatch'; } $paykeeper->status = 'paid'; $paykeeper->save(); if ($paykeeper->service_name == 'subscription') { $user = User::find($paykeeper->user_id); $ank = User::find($paykeeper->who_id); $subscribe = checkSubscribe($user, $ank, 'premium'); $date = $subscribe ? Carbon::parse($subscribe) : Carbon::now(); $mounth = floor($request->sum / settings('subscribers')->settings['costPremium']); $date = $date->addMonth($mounth)->format('Y-m-d H:i:s'); subscribe($ank, $paykeeper->order, [ 'premium' => $date ]); } // TODO: создать нотификейшин $hash = md5($request->id . paykeeper()->secret_seed); \Log::info("OK {$hash}"); return "OK {$hash}"; } } <file_sep>export const config = { baseURL: 'https://donatesupp.ru/api' }<file_sep><?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use Validator; use App\Models\Setting; use JWTAuth; class SettingsController extends Controller { public function fetchDonate() { return $this->success(donate()->settings); } public function fetchSubscriber() { return $this->success(settings('subscribers')); } public function saveSubscriber(Request $request) { Validator::make($request->all(), [ 'costPremium' => 'required|integer', ])->validate(); $settings = $request->only([ 'costPremium' ]); if (settings('subscribers')->save($settings)) { return $this->success('Настройки сохранены'); } return $this->fail('Ошибка при сохранении настроек'); } public function saveDonate(Request $request) { Validator::make($request->all(), [ 'commission' => 'required|numeric', 'minAmount' => 'required|integer', 'minCommissionAmount' => 'required|integer', 'percent' => 'required|boolean', ])->validate(); $settings = $request->only([ 'commission', 'minAmount', 'minCommissionAmount', 'percent' ]); if (donate()->save($settings)) { return $this->success('Настройки сохранены'); } return $this->fail('Ошибка при сохранении настроек'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use App\Models\Notification; class AddIsTestToNotificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('notifications', function (Blueprint $table) { $table->boolean('is_test')->default(0)->after('is_show'); }); Notification::whereTitle('{{user}} перевел вам {{amount}}')->update(['is_test' => true]); } /** * Reverse the migrations. * * @return void */ public function down() { Notification::whereTitle('{{user}} перевел вам {{amount}}')->update(['is_test' => false]); Schema::table('notifications', function (Blueprint $table) { $table->dropColumn(['is_test']); }); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\View\View; use App\Models\{WidgetCategory, Widget}; use Illuminate\Http\Request; class WidgetCategoryController extends Controller { /** * @return JsonResponse */ public function index() { $widget_categories = WidgetCategory::select(['title AS value', 'message', 'slug'])->get(); return $this->success($widget_categories); } /** * @param WidgetCategory $widgetCategory * @return Factory|JsonResponse|View */ public function show(WidgetCategory $widgetCategory) { if ( !$widget = Widget::whereActive(1)->whereWidgetCategoryId($widgetCategory->id)->first() ) { return response()->json(['error' => 'Нету активных виджетов']); } $widget->stream_hash_link = $widget->user->stream_hash_link; return view('widget', compact('widget', 'widgetCategory')); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\User; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\View\View; use App\Models\{Transaction, Notification, PushNotification}; use Illuminate\Http\Request; use Validator; use Symfony\Component\HttpFoundation\StreamedResponse; class PushController extends Controller { /** * @param User $user * @param string $token * @return JsonResponse */ public function uploadmusic(User $user, string $token) { $validator = Validator::make($_FILES, [ 'filepond' => 'required|array', 'filepond.tmp_name' => 'required|string', 'filepond.name' => 'required|string', ])->validate(); $file = $_FILES['filepond']; $mime = mime_content_type($file['tmp_name']); if (!in_array($mime, ['audio/mpeg', 'application/octet-stream'])) { return $this->fail(['Только музыка', $mime]); } $path = "storage/uploads/{$user->id}/music"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $filename = str_slug(basename($file['name'], '.mp3')) . '.mp3'; copy($file['tmp_name'], "{$dir}/{$filename}"); return $this->success(['src' => "/{$path}/{$filename}", 'name' => $filename]); } /** * @param User $user * @param int $push_id * @param string $token * @return JsonResponse */ public function uploadvideo(User $user, int $push_id, string $token) { if (!$notification = PushNotification::whereUserId($user->id)->find($push_id)) { return $this->fail('Ошибка при выборе уведомления'); } $validator = Validator::make($_FILES, [ 'filepond' => 'required|array', 'filepond.tmp_name' => 'required|string', 'filepond.name' => 'required|string', ])->validate(); $file = $_FILES['filepond']; $path = "storage/uploads/{$user->id}/video"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $fileinfo = pathinfo($file['name']); $filename = str_slug($fileinfo['filename']) . '.' . $fileinfo['extension']; copy($file['tmp_name'], "{$dir}/{$filename}"); $settings = $notification->settings; $settings['video'] = [ 'src' => "/{$path}/{$filename}", 'name' => $filename, ]; $notification->settings = $settings; $notification->save(); return $this->success([ 'src' => $settings['video']['src'], 'name' => $settings['video']['name'] ]); } /** * @param User $user * @param int $push_id * @param string $token * @return JsonResponse */ public function uploadimage(User $user, int $push_id, string $token) { if (!$notification = PushNotification::whereUserId($user->id)->find($push_id)) { return $this->fail('Ошибка при выборе уведомления'); } $validator = Validator::make($_FILES, [ 'filepond' => 'required|array', 'filepond.tmp_name' => 'required|string', 'filepond.name' => 'required|string', ])->validate(); $file = $_FILES['filepond']; $type = explode('/', $file['type'])[0]; $path = "storage/uploads/{$user->id}/{$type}"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $fileinfo = pathinfo($file['name']); $filename = str_slug($fileinfo['filename']) . '.' . $fileinfo['extension']; copy($file['tmp_name'], "{$dir}/{$filename}"); $settings = $notification->settings; $settings['attachment'] = [ 'src' => "/{$path}/{$filename}", 'name' => $filename, 'type' => $type, ]; $notification->settings = $settings; $notification->save(); return $this->success($settings['attachment']); } /** * @param User $user * @param string $type * @param string $token * @return StreamedResponse */ public function server(User $user, string $type, string $token) { Notification::whereIsShow('0') ->whereType($type) ->whereUserId($user->id) ->update(['is_show' => '1']); $response = new StreamedResponse(function() use ($user, $type) { while(true) { $notifications = PushNotification::whereUserId($user->id)->get(); if ( $notification = Notification::where([ ['type', $type], ['is_show', '=', '0'], ['user_id', '=', $user->id] ])->first() ) { $notification->is_show = '1'; $notification->save(); $pushSettings = $notifications->where('type', '=', $type) ->where('activate', '<=', (int) $notification->counter) ->where('activate_end', '>=', (int) $notification->counter) ->sortByDesc('activate') ->first(); $settings = fetchSettings($user, $pushSettings, $type); $settings['pushSettings'] = $pushSettings; // echo "data: " . json_encode([]) . "\n\n"; echo 'data: ' . json_encode(compact('notification', 'settings')) . "\n\n"; } else { echo "data: " . json_encode(compact('settings')) . "\n\n"; } ob_flush(); flush(); sleep(6); } }); $response->headers->set('Content-Type', 'text/event-stream'); $response->headers->set('X-Accel-Buffering', 'no'); $response->headers->set('Cach-Control', 'no-cache'); return $response; } /** * @param User $user * @param int $push_id * @param string $token * @return Factory|View */ public function client(User $user, int $push_id, string $token) { $serverLink = "/api/push/server/{$user->id}/{$token}"; $settingsLink = "/api/push/settings/{$user->id}/{$token}"; return view('push', compact('serverLink', 'settingsLink', 'token', 'user', 'push_id')); } /** * @param User $user * @param string $type * @param string $token * @return Factory|View */ public function clientView(User $user, string $type, string $token) { $serverLink = "/api/push/server/{$user->id}/{$token}"; $settingsLink = "/api/push/settings/{$user->id}/{$token}"; return view('push', compact('serverLink', 'settingsLink', 'token', 'user', 'type')); } /** * @param User $user * @param int $push_id * @param string $token * @return JsonResponse */ public function reset(User $user, int $push_id, string $token) { if (!$notification = PushNotification::whereUserId($user->id)->find($push_id)) { return $this->fail('Ошибка при выборе уведомления'); } $default = settings('PushDonate')->settings; $notification->settings = []; return $this->success($default); } /** * @param User $user * @param int $push_id * @param string $token * @return JsonResponse */ public function fetch(User $user, int $push_id, string $token) { if (!$notification = PushNotification::whereUserId($user->id)->find($push_id)) { return $this->fail('Ошибка при выборе уведомления'); } $settings = settings('PushDonate')->settings; $keys = array_keys($settings); for ($i = 0; $i < count($keys); $i++) { if (empty($notification->settings[$keys[$i]])) { continue; } $mySettings = collect($notification->settings[$keys[$i]]); $mySettings = $mySettings->filter(function ($value, $key) { return $value !== null; }); $mySettings->all(); $settings[$keys[$i]] = array_merge($settings[$keys[$i]], $mySettings->all()); } $musics = []; getMusic("storage/uploads/{$user->id}/music/", $musics); getMusic("storage/music/", $musics); $settings['music'] = $musics; return $this->success($settings); } /** * @param User $user * @param int $push_id * @return JsonResponse */ public function testNotification(User $user, int $push_id) { if (!$push = PushNotification::whereUserId($user->id)->find($push_id)) { return $this->fail('Ошибка при выборе уведомления'); } $notification = Notification::create([ 'user_id' => $user->id, 'counter' => $push->activate . ' ' . ($push->type == 'donate' ? 'руб.' : 'мес.'), 'type' => $push->type, 'title' => $user->login ?? 'Аноним', 'message' => 'Тестовое уведомление', ]); return $this->success($notification); } /** * @param Request $request * @param User $user * @param int $push_id * @param string $token * @return JsonResponse */ public function save(Request $request, User $user, int $push_id, string $token) { if (!$notification = PushNotification::whereUserId($user->id)->find($push_id)) { return $this->fail('Ошибка при выборе уведомления'); } $validator = Validator::make($request->all(), [ 'settings' => 'required|array', 'settings.*' => 'required|array', 'settings.main.minVoice' => 'nullable|integer', 'settings.main.minDonate' => 'nullable|integer', 'settings.main.duration' => 'required|integer|min:10', 'settings.main.sound' => 'required|array', 'settings.main.sound.src' => 'nullable|string', 'settings.main.sound.volume' => 'required|integer|min:1|max:9', 'settings.image.color' => 'nullable|string', 'settings.image.tile' => 'required|boolean', 'settings.image.size' => 'integer', 'settings.image.src' => 'required|string', 'settings.name.color' => 'nullable|string', 'settings.name.size' => 'required|integer', 'settings.name.font' => 'nullable|exists:fonts,class', 'settings.amount.color' => 'nullable|string', 'settings.amount.size' => 'required|integer', 'settings.amount.font' => 'nullable|exists:fonts,class', 'settings.message.color' => 'nullable|string', 'settings.message.size' => 'required|integer', 'settings.message.font' => 'nullable|exists:fonts,class', ])->validate(); $notification->settings = $request->settings; $notification->save(); return $this->success($request->settings); } } <file_sep><?php namespace App\Traits; use Validator; trait SubscriberValidate { public function validate() { $validator = Validator::make($this->subscriber, [ '_id' => 'required|string', 'bio' => 'required|string', 'display_name' => 'required|string', 'logo' => 'required|string', 'name' => 'required|string', 'service_id' => 'required|string', ]); return $validator; } }<file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Auth; use App\User; use Illuminate\Http\JsonResponse; use Validator; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; class AuthController extends Controller { /** * @param Request $request * @return JsonResponse */ public function register(Request $request) { Validator::make($request->all(), [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => '<PASSWORD>|string|min:6|<PASSWORD>', ])->validate(); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => <PASSWORD>($request->password), 'api_token' => str_random(128), ]); return $this->success(['message' => 'Register success', 'user' => $user]); } /** * @param Request $request * @return JsonResponse */ public function login(Request $request) { Validator::make($request->all(), [ 'email' => 'required|string|email|max:255', 'password' => '<PASSWORD>', ])->validate(); $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { $user = User::whereEmail($credentials['email'])->first(); return $this->success(['message' => 'Авторизация успешна', 'api_token' => $user->api_token, 'user_data' => $user]); } return $this->fail(['message' => 'Ошибка авторизации']); } } <file_sep><?php namespace App\Services; /** * Class VK * @package App\Services */ class VK { protected $APP_ID; protected $TOKEN; protected $PROXY_IP; protected $PROXY_PORT; protected $SCOPE; protected $MY_GROUP_ID; protected $response; public function __construct() { $this->setConfig(); } /** * @return mixed */ public function response() { return $this->response; } /** * @param string $title * @return string */ public function oauthLink(string $title): string { return "<a href='https://oauth.vk.com/authorize?client_id={$this->APP_ID}&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope={$this->SCOPE}&response_type=token&v=5.37'>{$title}</a>"; } /** * @param string $message * @param string $attachment * @return $this */ public function sendGroupMessage(string $message, string $attachment = '') { $params = array_merge(['owner_id' => $this->MY_GROUP_ID, 'attachment' => $attachment], compact('message')); return $this->request('wall.post', $params); } /** * @param string $method * @param array $params * @return $this */ public function request(string $method, array $params) { $params = array_merge($params, [ 'access_token' => $this->TOKEN, 'v' => '5.37', ]); $url = "https://api.vk.com/method/{$method}"; $proxy = $this->PROXY_IP && $this->PROXY_IP ? "{$this->PROXY_IP}:{$this->PROXY_PORT}" : null; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); if ($proxy) { curl_setopt($ch, CURLOPT_PROXY, $proxy); } curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); $this->response = json_decode(curl_exec($ch)); curl_close($ch); return $this; } protected function setConfig() { $config = config('vk'); foreach ($config as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } } } <file_sep><?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, SparkPost and others. This file provides a sane | default location for this type of information, allowing packages | to have a conventional place to find your various credentials. | */ 'mailgun' => [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), ], 'ses' => [ 'key' => env('SES_KEY'), 'secret' => env('SES_SECRET'), 'region' => env('SES_REGION', 'us-east-1'), ], 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], 'twitch' => [ 'client_id' => env('TWITCH_CLIENT_ID'), // Your GitHub Client ID 'client_secret' => env('TWITCH_CLIENT_SECRET'), // Your GitHub Client Secret 'redirect' => env('TWITCH_REDIRECT'), ], 'google' => [ 'client_id' => env('GOOGLE_CLIENT_ID', '1006735515237-289taqj0uc01g3qsek2vk8bl031u9546.apps.googleusercontent.com'), 'client_secret' => env('GOOGLE_CLIENT_SECRET', '<KEY>'), 'redirect' => env('GOOGLE_CLIENT_REDIRECT', 'https://api.donatesupp.com/oauth/google/rollback'), ], 'vkontakte' => [ 'client_id' => env('VK_CLIENT_ID', 6858642), 'client_secret' => env('VK_CLIENT_SECRET', '<KEY>'), 'redirect' => 'https://api.donatesupp.com/oauth/vkontakte/rollback', ], ]; <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSubscribeUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('subscribers_user', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('service_id'); $table->unsignedInteger('user_id')->comment('Чей это подписчик'); $table->enum('free', [0, 1])->nullable()->comment('Простая подписка'); $table->enum('paid', [1000, 2000, 3000])->nullable()->comment('Платная подписка'); $table->dateTime('premium')->nullable()->comment('Премиум подписка'); $table->unsignedInteger('subscribers_id')->comment('ID анкеты подписчика'); $table->timestamps(); $table->foreign('service_id')->references('id')->on('services'); $table->foreign('user_id')->references('id')->on('users'); $table->foreign('subscribers_id')->references('id')->on('subscribers'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('subscribers_user'); } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Setting; class SettingDonate extends Seeder { /** * Run the database seeds. * composer dump-autoload * php artisan db:seed --class=SettingDonate * * @return void */ public function run() { Setting::whereName('Donate')->delete(); $set = new Setting; $set->name = 'Donate'; $settings = config('settings_default.Donate'); $set->settings = $settings; $set->save(); } } <file_sep><?php namespace App\Services\Oauth; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Request; use TwitchApi; class Twitch extends App { public $user; public $twitch_user; public $access_token; protected $response; protected $request; public function __construct(Request $request) { $this->request = $request; $this->response = $this->getResponse(); $this->user = $this->getUser(); } /** * @return bool */ private function getResponse() { $response = TwitchApi::getAccessObject($this->request->code); if (is_object($response) && $response->status != 200) { dd($response->message); \Log::channel('twitch-webhook') ->info("Ошибка авторизации", $response->message); return false; } $this->access_token = $response['access_token']; TwitchApi::setToken($this->access_token); return $response; } /** * @return array|bool */ private function getUser() { $user = TwitchApi::authUser(); if (is_object($user) && $user->status != 200) { \Log::channel('twitch-webhook') ->info("Ошибка авторизации", $user->message); return false; } $this->twitch_user = $user; $data = [ 'name' => $user['name'], 'display_name' => $user['display_name'], 'twitch_id' => $user['_id'], 'password' => <PASSWORD>(str_<PASSWORD>(128)), 'api_token' => str_random(128), 'avatar' => $user['logo'], 'info' => ['twitch' => $user], 'service_id' => service('Twitch'), ]; $this->email = $user['email']; return $data; } } <file_sep><?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\{Admin, User}; use App\Models\Transaction; class DashboardController extends Controller { public function index() { $count = [ 'users' => [ 'count' => User::count() ], 'transactions' => [ 'count' => Transaction::count(), 'amount_sum' => Transaction::sum('amount'), ], ]; return $this->success(['count' => $count]); } } <file_sep>import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) import Donate from '../pages/Donate' import DonateV2 from '../pages/DonateV2' import Test from '../pages/Test' export default new Router({ routes: [ { path: '/', name: 'Donate', component: DonateV2, }, { path: '/test', name: 'Test', component: Test, }, ] }) <file_sep><?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::post('/test', 'HomeController@test'); Route::post('/paykeeper/alert', 'PaykeeperController@paykeeperAlert'); Route::get('/paykeeper/{id}', 'PaykeeperController@fethPayment'); Route::get('/mainsettings', 'SettingsController@mainSettings'); Route::middleware('jwt.verify')->group(function () { Route::get('/mystreamlink', 'UserController@myStreamLink'); Route::get('/recentoperations', 'UserController@recentoperations'); Route::get('/user', 'UserController@profile'); Route::put('/user', 'UserController@update'); Route::delete('/user/service/{service}', 'UserController@serviceDisconnect'); // Route::get('/mycards', 'UserController@mycards'); Route::get('/subscribers', 'UserController@subscribers'); Route::get('/subscribers/statistic', 'StatisticController@fetchSubscribers'); Route::get('/fetchlinks', 'UserController@fetchlinks'); Route::get('/transactions', 'TransactionController@transactions'); Route::get('/transactions/statistic', 'TransactionController@transactionsStatistic'); Route::get('/statistic/donate', 'StatisticController@fetchDonate'); Route::post('/image/upload', 'SettingsController@imageUpload'); Route::post('/video/upload', 'SettingsController@videoUpload'); Route::post('/donate/settings/{user}', 'SettingsController@donateSettingsSave'); Route::put('/donate/settings/{user}', 'SettingsController@donateSettingsReset'); Route::prefix('payments')->group(function() { Route::post('/add', 'PaymentMethodsController@add'); Route::delete('/{paymentMethod}', 'PaymentMethodsController@remove'); Route::get('/list', 'PaymentMethodsController@list'); Route::post('/{method}', 'PaymentMethodsController@update'); }); Route::prefix('twitch')->group(function () { Route::get('/followsList', 'TwitchController@followsList'); Route::get('/test', 'TwitchController@test'); Route::get('/channels/{channel}', 'TwitchController@channelInfoById'); }); Route::prefix('mailstone')->group(function () { Route::get('/list', 'MailstonesController@list'); Route::delete('/{milestone}', 'MailstonesController@remove'); Route::post('/add', 'MailstonesController@add'); Route::get('/badges', 'MailstonesController@badges'); Route::get('/{user}/badge', 'MailstonesController@badge'); Route::get('/{user}/sound', 'MailstonesController@music'); Route::get('/animations', 'MailstonesController@animations'); Route::get('/closest', 'MailstonesController@closets'); Route::post('/badge/upload', 'MailstonesController@imageUpload'); Route::post('/sound/upload', 'MailstonesController@soundUpload'); Route::post('/badge/add', 'BadgesController@add'); }); Route::prefix('premium')->group(function () { Route::get('/{user}/milestones', 'UserController@milestones'); Route::get('/{user}/checksubscribe', 'UserController@checkSubscriber'); Route::post('/{user}/premiumsubscribe', 'UserController@premiumSubscribed'); }); Route::get('/{user}/mydonat', 'UserController@mydonat'); Route::get('/mynotification', 'UserController@mynotification'); Route::post('/mynotification', 'UserController@mynotificationAdded'); Route::put('/mynotification/{id}', 'UserController@notificationDelete'); }); Route::prefix('widget')->group(function () { Route::middleware('jwt.verify')->group(function () { Route::post('/add', 'WidgetController@add'); Route::post('/', 'WidgetController@addV2'); Route::get('/list', 'WidgetController@list'); Route::get('/list-v2', 'WidgetController@listV2'); Route::get('/options', 'WidgetCategoryController@index'); Route::delete('/{widget}', 'WidgetController@delete'); Route::get('/activate/{widget}', 'WidgetController@activate'); Route::put('/{widget}', 'WidgetController@editWidget'); Route::put('/{widget}/v2', 'WidgetController@editWidgetV2'); }); Route::get('/{widgetCategory}', 'WidgetCategoryController@show')->name('widget.view'); // Route::get('/{widget}', 'WidgetController@widget')->name('widget.view'); }); Route::prefix('alerts')->group(function () { Route::middleware('jwt.verify')->group(function () { Route::get('/', 'AlertController@index'); Route::post('/', 'AlertController@create'); Route::post('/preview/{type}', 'AlertController@preview'); Route::delete('/{alert}', 'AlertController@destroy'); Route::put('/{alert}', 'AlertController@update'); Route::post('/file', 'AlertController@image'); }); }); Route::prefix('push')->middleware('TokenPushMessage')->group(function () { Route::post('/video/{user}/{push_id}/{token}', 'PushController@uploadvideo'); Route::delete('/video/{user}/{push_id}/{token}', 'PushController@uploadvideo'); Route::post('/image/{user}/{push_id}/{token}', 'PushController@uploadimage'); Route::delete('/image/{user}/{push_id}/{token}', 'PushController@uploadimage'); Route::post('/music/{user}/{token}', 'PushController@uploadmusic'); Route::delete('/music/{user}/{token}', 'PushController@uploadmusic'); Route::get('/server/{user}/{type}/{token}', 'PushController@server'); Route::get('/client/{user}/{push_id}/{token}', 'PushController@client'); Route::get('/client/{user}/{type}/{token}/view', 'PushController@clientView'); Route::get('/settings/{user}/{type}/{token}', 'PushController@fetch'); Route::post('/settings/{user}/{push_id}/{token}', 'PushController@save'); Route::put('/settings/{user}/{push_id}/{token}', 'PushController@reset'); Route::put('/test_notification/{user}/{push_id}/{token}', 'PushController@testNotification'); }); Route::prefix('insidestreaming/{user}/{token}')->middleware('TokenPushMessage')->group(function () { Route::post('/lastmessage', 'InsideStreamingController@lastMessage'); Route::post('/mostexpensive', 'InsideStreamingController@mostExpensive'); Route::post('/largestdonater', 'InsideStreamingController@largestDonater'); Route::post('/lastdonater', 'InsideStreamingController@lastDonater'); Route::post('/lastsubscriber', 'InsideStreamingController@lastSubscriber'); Route::post('/numbersubscribers', 'InsideStreamingController@numberSubscribers'); Route::post('/amountcollected', 'InsideStreamingController@amountCollected'); }); Route::post('/donate', 'TransactionController@donate'); Route::get('/donate', 'TransactionController@donateInfo'); Route::post('/donate/settings/', 'SettingsController@donateSettings'); Route::get('/user/donationformdata/', 'UserController@getDonationFormData'); Route::get('/user/info/{user}', 'UserController@userInfo'); Route::get('/user/streams/{user}', 'TwitchController@getUserStreams'); Route::get('/fonts', 'HomeController@fonts'); Route::get('/icons', 'HomeController@icons'); Route::namespace('Admin')->prefix('admin')->group(function () { Route::post('/login', 'AuthController@authenticate'); Route::group(['middleware' => ['jwt.verify', '2fa']], function() { Route::get('/transaction/all', 'TransactionController@list'); Route::get('/dashboard', 'DashboardController@index'); Route::get('/users/list', 'UserController@list'); Route::post('/user/update', 'UserController@update'); Route::post('/user/status/update', 'UserController@updateStatus'); Route::get('/settings/donate', 'SettingsController@fetchDonate'); Route::post('/settings/donate', 'SettingsController@saveDonate'); Route::get('/settings/subscriber', 'SettingsController@fetchSubscriber'); Route::post('/settings/subscriber', 'SettingsController@saveSubscriber'); Route::get('/statistic/donate', 'StatisticController@fetchDonate'); }); Route::group(['middleware' => ['jwt.verify']], function() { Route::get('/user', 'UserController@info'); Route::get('/login2fa', 'AuthController@login2faQR'); Route::post('/login2fa', 'AuthController@login2fa'); }); }); // Route::post('/login', 'AuthController@login'); Route::apiResource('{user}/{token}/youtube', 'YoutubeController') ->middleware('TokenPushMessage'); Route::any('/twitch/webhook', 'TwitchController@webhook'); <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use App\Models\WidgetCategory; class CreateWidgetCategoriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('widget_categories', function (Blueprint $table) { $table->increments('id'); $table->string('title')->unique(); $table->timestamps(); }); $categories = [ ['title' => 'Последнее сообщение'], ['title' => 'Самый крупный донатер'], ['title' => 'Последний донатер'], ['title' => 'Последний подписчик'], ['title' => 'Количество подписчиков за период'], ]; WidgetCategory::insert($categories); Schema::table('widgets', function (Blueprint $table) { $table->dropColumn(['name']); $table->unsignedInteger('widget_category_id')->nullable()->after('user_id'); $table->foreign('widget_category_id')->references('id')->on('widget_categories'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('widgets', function (Blueprint $table) { $table->dropForeign(['widget_category_id']); }); Schema::table('widgets', function (Blueprint $table) { $table->dropColumn(['widget_category_id']); $table->string('name')->nullable(); }); Schema::dropIfExists('widget_categories'); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use App\Jobs\Subscribers\YouTubeImport; use App\User; use Illuminate\Routing\Redirector; use Socialite; use JWTAuth; use Hash; class OAuthController extends Controller { /** * @param string $service * @return RedirectResponse */ public function redirectToProvider(string $service) { if (!in_array($service, ['google', 'vkontakte'])) { return redirect()->route('home'); } $is_streamer = $this->request->is_streamer ?? 0; setcookie('is_streamer', (int) $is_streamer, time() + 900, '/'); setcookie('redirect', $this->request->redirect, time() + 900, '/'); return Socialite::driver($service)->redirect(); } /** * @param string $service * @return RedirectResponse|Redirector */ public function handleProviderCallback(string $service) { $redirect = !empty($_COOKIE['redirect']) ? url('/', [], true) . '/' . $_COOKIE['redirect'] : null; try { $userService = Socialite::driver($service)->user(); } catch (\Exception $e) { return redirect(route('error', ['message' => 'Ошибка при авторизации. Повторите попытку.'])); } $userService->email = $userService->email ?? $userService->accessTokenResponseBody['email'] ?? null; if (!$userService->email) { return redirect(route('error', ['message' => 'Не удалось получить E-mail'])); } $user = User::withTrashed()->firstOrCreate(['email' => $userService->email], [ 'name' => $userService->name, 'password' => <PASSWORD>::make(str_random(128)), 'api_token' => str_random(128), 'avatar' => $userService->avatar, 'info' => [$service => $userService], ]); if ($user->trashed()) { return redirect('/#/login/?locked=error'); } $user->avatar = $userService->avatar; $user->accout_type = $service; $user->profile_mode = !empty($_COOKIE['is_streamer']) && $_COOKIE['is_streamer'] ? 'streamer' : 'user'; $info = $user->info; $info[$service] = $userService; $info[$service]['token'] = $userService->token; $user->info = $info; $user->save(); $token = JWTAuth::fromUser($user); return clientRedirect("/auth/?token={$token}"); } } <file_sep><?php namespace App\Services; /** * Class Twitch * @package App\Services */ class Twitch { /** * @var mixed */ public $info; /** * @var string */ protected $client_id; /** * @var string */ protected $client_secret; /** * @var string */ protected $redirect_url; /** * @var mixed */ protected $webhooks_callback; /** * @var array */ protected $scopes; /** * @var string */ protected $type; /** * @var mixed */ protected $response; public function __construct() { $this->setConfig(); } /** * @return mixed */ public function response() { return $this->response; } /** * @param int $twitch_id * @return $this */ public function subscribeStream(int $twitch_id) { $request = [ 'hub.mode' => 'subscribe', 'hub.topic' => "https://api.twitch.tv/helix/streams?user_id={$twitch_id}", 'hub.callback' => $this->webhooks_callback, 'hub.lease_seconds' => 864000, ]; $this->request('webhooks/hub', $request); if ($this->info['http_code'] != 202) { $errors = json_decode($this->response(), true); \Log::channel('twitch-webhook') ->info("Не удалось подписаться на стрим: #twitch_id-{$twitch_id}", compact('request', 'errors')); } return $this; } /** * @param string $method * @param array $params * @return $this */ public function request(string $method, array $params) { $url = "https://api.twitch.tv/{$this->type}/{$method}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', "Client-ID: {$this->client_id}", ]); $this->response = curl_exec($ch); $this->info = curl_getinfo($ch); curl_close($ch); return $this; } /** * @return void */ protected function setConfig() { $config = config('twitch-api'); foreach ($config as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } } } <file_sep><?php namespace App\Jobs\Subscribers; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Services\Subscribers\YouTube\Subscriber as YouTubeSubscriber; use App\Services\Subscribers\Subscriber; use App\User; class YouTubeImport implements ShouldQueue { /** * @var int */ public $tries = 3; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $user; /** * YouTubeImport constructor. * @param User $user */ public function __construct(User $user) { $this->user = $user; } /** * @throws \Google_Exception */ public function handle() { $client = new \Google_Client(); $client->setAuthConfig(storage_path('client_secret.json')); $client->addScope(\Google_Service_YouTube::YOUTUBE_READONLY); $client->setAccessType('offline'); // offline access $client->setIncludeGrantedScopes(true); // incremental auth $client->setAccessToken(json_encode($this->user->info['youtube']['token'])); $youtube = new \Google_Service_YouTube($client); $subscriptions = $youtube->subscriptions->listSubscriptions('subscriberSnippet,snippet,contentDetails', array('mySubscribers' => true)); $subscribers = []; foreach ($subscriptions->items as $subscriber) { if (!$this->user->youtube_id) { $this->user->youtube_id = $subscriber->snippet->resourceId->channelId ?? null; $this->user->save(); } $YouTubeSubscriber = new YouTubeSubscriber($subscriber); $subscriber = new Subscriber($YouTubeSubscriber->getData()); if ($subscriber->_id) { $subscribers[] = $subscriber; } } (new \App\Services\Subscribers\Import($subscribers, $this->user))->startImport(); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Class MusicMilestone * @package App\Models */ class MusicMilestone extends Model { /** * @var array */ protected $fillable = ['src', 'milestone_id']; /** * @var array */ protected $appends = ['name']; /** * @return string */ public function getNameAttribute() { return basename($this->src); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Class Font * @package App\Models */ class Font extends Model { /** * @var array */ protected $fillable = ['name', 'class', 'path']; /** * @var array */ protected $appends = ['value']; /** * @return mixed */ public function getValueAttribute() { return $this->attributes['name']; } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\PaymentMethods; use App\User; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Validator; class PaymentMethodsController extends Controller { /** * @param Request $request * @return JsonResponse */ public function add(Request $request) { $validator = Validator::make($this->request->all(), [ 'code' => 'required|string', 'number' => 'required|string', ])->validate(); $paymentMethod = PaymentMethods::create([ 'code' => $request->code, 'number' => $request->number, 'user_id' => $this->user()->id ]); return $this->success($paymentMethod); } /** * @return JsonResponse */ public function list() { return $this->success( PaymentMethods::where('user_id', $this->user()->id)->get() ); } /** * @param PaymentMethods $paymentMethod * @return JsonResponse */ public function remove(PaymentMethods $paymentMethod) { try { $paymentMethod->delete(); return $this->success('Платежный метод успешно удалён'); } catch (\Exception $e) { report($e); } return $this->fail('Не удалось удалить'); } /** * @param int $paymentId * @param Request $request * @return JsonResponse */ public function update(int $paymentId, Request $request) { if ($request->toggle) { PaymentMethods::where([ ['user_id', $this->user()->id], ['id', '!=', $paymentId] ])->update(['active' => false]); $active = PaymentMethods::find($paymentId); $active->active = true; $active->save(); } else { PaymentMethods::whereUserId($this->user()->id)->whereId($paymentId)->update($request->only(['number', 'code'])); } return $this->success(PaymentMethods::whereUserId($this->user()->id)); } } <file_sep><?php namespace App\Models; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Hash; use Storage; use Lang; /** * Class PushNotification * @package App\Models */ class PushNotification extends Model { /** * @var array */ protected $fillable = ['user_id', 'type', 'settings', 'activate', 'activate_end', 'active']; /** * @var array */ protected $appends = ['amount', 'icon', 'strick', 'link', 'image', 'sound']; /** * @var array */ protected $casts = [ 'settings' => 'array', 'active' => 'boolean', ]; /** * @var static $_token */ public static $_token; /** * @return array */ public function getAmountAttribute() { return [ 'min' => $this->attributes['activate'], 'max' => $this->attributes['activate_end'], ]; } /** * @return UrlGenerator|string */ public function getImageAttribute() { if (!$image = $this->settings['image']['src'] ?? null) { return ''; } return url(Storage::url($image['src'])); } /** * @return UrlGenerator|string */ public function getSoundAttribute() { if (!$sound = $this->settings['sound'] ?? null) { return ''; } return url(Storage::url($sound)); } /** * @return string */ public function getIconAttribute() { if ($this->attributes['type'] == 'free') { return 'simple-icon'; } return 'prem-dark'; } /** * @return string */ public function getStrickAttribute() { $strick = $this->attributes['activate'] ?? 0; $text = Lang::choice('месяц|месяца|месяцев', $strick); return "{$strick} {$text}"; } /** * @return string */ public function getLinkAttribute() { if (static::$_token === null && request()->user()) { static::$_token = base64_encode(Hash::make(request()->user()->streamlink)); } $token = static::$_token; return request()->root() . "/api/push/client/{$this->attributes['user_id']}/{$this->attributes['type']}/{$token}/view"; } } <file_sep><?php namespace App\Console\Commands; use App\User; use TwitchApi; use Carbon\Carbon; use Illuminate\Console\Command; use App\Services\Subscribers\Twitch\{Followers, Subscriber}; use App\Jobs\Subscribers\Import; class ImportSubscribe extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'ImportSubscribe'; /** * The console command description. * * @var string */ protected $description = 'Импорт подписчиков'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $users = User::where('updated_at', '>', Carbon::now()->subHours(3)->toDateTimeString())->get(); // \Log::info($users); foreach ($users as $user) { dispatch(new Import($user, new Followers)); dispatch(new Import($user, new Subscriber)); sleep(1); } } } <file_sep><?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use Validator; use App\Models\Transaction; use Carbon\Carbon; use JWTAuth; use DB; class StatisticController extends Controller { public function fetchDonate() { $transactions = Transaction:: // where('created_at', '>=', Carbon::now()->subMonth()) groupBy('date') ->get([ DB::raw('CONCAT_WS("/", month(created_at), DAY(created_at)) as date'), DB::raw('COUNT(*) as "count"'), DB::raw('SUM(`amount`) as "sum_donate"'), DB::raw('SUM(`commission`) as "sum_commission"'), ] ); $labels = $transactions->pluck('date'); $series = $transactions->pluck('count'); $sum_donate = $transactions->pluck('sum_donate'); $sum_commission = $transactions->pluck('sum_commission'); return $this->success(compact('labels', 'series', 'sum_donate', 'sum_commission')); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class PaykeeperStatus extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('paykeepers', function (Blueprint $table) { $table->enum('status', ['created', 'sent', 'paid', 'expired']) ->default('created') ->after('id') ->comment('Статус плятежа'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('paykeepers', function (Blueprint $table) { $table->dropColumn('paykeepers'); }); } } <file_sep><?php return [ 'user' => env('PAYKEEPER_USER', 'demo'), 'password' => env('PAYKEEPER_PASSWORD', '<PASSWORD>'), 'server_paykeeper' => env('PAYKEEPER_SERVER', 'demo.paykeeper.ru'), 'secret_seed' => env('PAYKEEPER_SEED', 'verysecretseed'), ];<file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\Services\VK; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Models\Font; use App\User; use Illuminate\View\View; class HomeController extends Controller { public function vkauth() { echo (new Vk)->oauthLink('VK oauth'); } /** * @param Request $request * @return Factory|View */ public function index(Request $request) { return view('home'); } /** * @param Request $request * @return JsonResponse */ public function test(Request $request) { $message = ''; switch ($request->type) { case 1: $message = 'Пример последнего сообщения'; break; case 2: $message = 'Это самое дорогое сообщение'; break; case 3: $message = 'Тут самый крупный донатер'; break; case 4: $message = 'Последний подписчки'; break; case 5: $message = '1025 подписчиков'; break; case 6: $message = '1025 подписчиков за'; break; case 7: $message = '1,000,000руб.'; break; default: # code... break; } if ($request->type == 4 || $request->type == 5 || $request->type == 6) { switch ($request->subscriber) { case 1: $message .= ' (премиум)'; break; case 2: $message .= ' (платный)'; break; case 3: $message .= ' (бесплатный)'; break; case 4: $message .= ' (любой)'; break; default: # code... break; } } if ($request->type == 6) { switch ($request->period) { case 1: $message .= ' (день)'; break; case 2: $message .= ' (неделя)'; break; case 3: $message .= ' (месяц)'; break; case 4: $message .= ' (квартал)'; break; case 5: $message .= ' (пол года)'; break; case 6: $message .= ' (год)'; break; default: # code... break; } } return $this->success($message); } /** * @return JsonResponse */ public function fonts() { $fonts = Font::get(['name', 'class']); return $this->success($fonts); } /** * @return JsonResponse */ public function icons() { $icons = ['mdi-arrow-all', 'mdi-arrow-bottom-left', 'mdi-arrow-bottom-left-bold-outline', 'mdi-arrow-expand-left', 'mdi-arrow-left', 'mdi-arrow-left-bold', 'mdi-arrow-left-bold-box', 'mdi-arrow-left-bold-box-outline', 'mdi-arrow-left-bold-circle', 'mdi-arrow-left-bold-circle-outline', 'mdi-arrow-left-bold-outline', 'mdi-arrow-left-drop-circle', 'mdi-arrow-left-thick', 'mdi-comment-arrow-left', 'mdi-ray-end-arrow', 'mdi-bullseye-arrow', 'mdi-comment-arrow-right', 'mdi-comment-arrow-right-outline', 'mdi-arrow-right', 'mdi-arrow-right-bold', 'mdi-arrow-right-bold-circle', 'mdi-arrow-right-drop-circle', 'mdi-arrow-right-thick', 'mdi-gnome', 'mdi-golf', 'mdi-cash-usd', 'mdi-currency-usd', 'mdi-currency-usd-off', 'mdi-eye-off-outline']; return $this->success($icons); } } <file_sep><?php namespace App\Models; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Database\Eloquent\Model; use App\User; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class Widget * @package App\Models */ class Widget extends Model { /** * @var array */ protected $fillable = [ 'name', 'uri', 'slug', 'options', 'settings', 'user_id', 'widget_category_id', 'animation', 'active', 'settings2', ]; /** * @var array */ protected $hidden = ['created_at', 'updated_at']; /** * @var array */ protected $appends = ['link', 'animation_ru']; /** * @var array */ protected $casts = [ 'options' => 'array', 'settings' => 'array', 'settings2' => 'array', 'active' => 'bool', ]; /** * @return string */ public function getAnimationRuAttribute() { switch ($this->attributes['animation'] ?? '') { case 'crawl-line': return 'Бегущая строка'; case 'widget-slider': return 'Слайдер'; default: return 'Стандарт'; } } /** * @return string */ public function getRouteKeyName() { return 'slug'; } /** * @return BelongsTo */ public function user() { return $this->belongsTo(User::class); } /** * @return UrlGenerator|string */ public function getLinkAttribute() { return url("api/widget/{$this->slug}"); } public static function boot() { parent::boot(); static::creating(function ($model) { $hash = static::slugGenerate(); while(Widget::whereSlug($hash)->first()) { $hash = static::slugGenerate(); } $model->slug = $hash; }); } /** * @return string */ private static function slugGenerate() { return md5(microtime()) . str_random(mt_rand(40, 80)); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Class PaymentMethods * @package App\Models */ class PaymentMethods extends Model { /** * @var array */ protected $fillable = ['code', 'user_id', 'number']; /** * @var bool */ public $timestamps = false; } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Class Animation * @package App\Models */ class Animation extends Model { /** * @var array */ protected $fillable = ['animate']; /** * @var array */ protected $appends = ['duration', 'test']; /** * @return int */ public function getDurationAttribute() { return 1000; } /** * @return array */ public function getTestAttribute() { return ['duration' => 1000, 'id' => $this->id, 'animate' => $this->animate]; } } <file_sep>export const searchResults = (state) => state.searchResults // export const playlists = (state) => state.playlists.filter(x => x.id !== state.selected.id) export const playlists = (state) => state.playlists // export const playlistsAll = (state) => state.playlists export const selected = (state) => state.selected export const videoInfo = (state) => state.videoInfo export const token = (state) => state.token export const user = (state) => state.user export const showPlaylist = (state) => state.showPlaylist <file_sep><?php namespace App\Services; use App\Models\Setting as MSetting; // Model settings /** * Class Setting * @package App\Services */ class Setting { /** * @var String */ public $type; /** * @var mixed */ public $settings; /** * Setting constructor. * @param String $name */ public function __construct(String $name) { $this->type = $name; $this->settings = $this->getSettings(); } /** * @return mixed */ protected function getSettings() { $settings = $this->getModel()['settings']; return $settings; } /** * @return MSetting */ protected function getModel() { if ($settings = $this->settings()->where('name', $this->type)->first()) { return $settings; } $settings = new MSetting; $settings->name = $this->type; $settings->settings = config("settings_default.{$this->type}"); $settings->save(); return $settings; } /** * @param array $settings * @return bool */ public function save(array $settings): bool { return $this->getModel()->update(['settings' => $settings]); } /** * @return mixed */ protected function settings() { static $settings; if (!$settings) { $settings = MSetting::get(); } return $settings; } } <file_sep><?php return [ 'APP_ID' => env('VK_APP_ID', 6858642), 'TOKEN' => env('VK_TOKEN', '<PASSWORD>'), 'PROXY_IP' => env('VK_PROXY_IP'), 'PROXY_PORT' => env('VK_PROXY_PORT'), 'SCOPE' => env('VK_SCOPE', 'offline,messages,wall'), 'MY_GROUP_ID' => env('VK_MY_GROUP_ID', -178376738), ];<file_sep><?php namespace App\Http\Controllers\Oauth; use App\Services\Subscribers\Twitch\{Followers, Subscriber}; use App\Jobs\Subscribers\TwitchImport; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Request; use App\Models\Subscribers; use TwitchApi; use App\User; use JWTAuth; use App\Services\Oauth\Twitch; class TwitchController extends Controller { public function redirect() { $is_streamer = $this->request->is_streamer ?? 0; setcookie('is_streamer', (int) $is_streamer, time() + 900, '/'); setcookie('redirect', $this->request->redirect, time() + 900, '/'); return redirect(TwitchApi::getAuthenticationUrl()); } public function rollback(Request $request) { $service = new Twitch($request); $user = $service->createUser(); if ($user->trashed()) { return redirect('/#/login/?locked=error'); } $user->twitch_id = $service->twitch_user['_id']; $user->avatar = $service->twitch_user['logo']; $user->accout_type = 'twitch'; $user->profile_mode = !empty($_COOKIE['is_streamer']) && $_COOKIE['is_streamer'] ? 'streamer' : 'user'; if ($user->profile_mode == 'streamer' && $user->is_vk) { (new Twitch)->subscribeStream($user->twitch_id); } $info = $user->info; $info['twitch'] = $service->twitch_user; $info['twitch']['token'] = $service->access_token; $user->info = $info; $user->save(); // dispatch(new TwitchImport($user, new Followers)); // dispatch(new TwitchImport($user, new Subscriber)); $token = JWTAuth::fromUser($user); $redirect = $service->redirect; // dd([$user, $token]); return redirect(env('FRONT_URL', 'http://localhost:8080') . "/auth/?token={$token}"); //return clientRedirect("/auth/?token={$token}"); // rsseturn view('home', compact('user', 'token', 'redirect')); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class UsersNotifyInVK extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->smallInteger('is_vk')->default(0)->after('info')->comment('Уведомлять в ВК о начале трансляции'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn(['is_vk']); }); } } <file_sep><?php namespace App\Models; use App\User; use App\Models\Paykeeper; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class Transaction * @package App\Models */ class Transaction extends Model { /** * @var array */ protected $fillable = ['user_id', 'who_id', 'amount', 'message', 'name', 'info', 'commission']; /** * @var array */ protected $appends = ['created_at_humans']; /** * @var array */ protected $with = ['who', 'user']; /** * @var array */ protected $casts = [ 'info' => 'array', ]; /** * @return |null */ public function getCreatedAtHumansAttribute() { if ($date = $this->created_at) { return $date->diffForHumans(); } return null; } /** * @return mixed */ public function paykeeper() { return $this->belongsTo(Paykeeper::class, 'id', 'orderid')->whereServiceName('donate'); } /** * @return BelongsTo */ public function user() { return $this->belongsTo(User::class); } /** * @return BelongsTo */ public function who() { return $this->belongsTo(User::class); } } <file_sep><?php namespace App\Services\Subscribers; use Log; class Subscriber { use \App\Traits\SubscriberValidate; public $subscriber; public $_id; public $bio; public $name; public $logo; public $service_id; public $display_name; /** * Subscriber constructor. * @param array $subscriber */ public function __construct(Array $subscriber) { $this->subscriber = $subscriber; if ($this->validate()->fails()) { return Log::channel('failed-subscriber') ->error( json_encode($this->subscriber), $this->validate()->errors()->all() ); } $this->_id = $subscriber['_id']; $this->bio = $subscriber['bio']; $this->name = $subscriber['name']; $this->logo = $subscriber['logo']; $this->service_id = $subscriber['service_id']; $this->display_name = $subscriber['display_name']; } } <file_sep><?php return [ 'client_id' => env('YOUTUBE_CLIENT_ID', '1006735515237-289taqj0uc01g3qsek2vk8bl031u9546.apps.googleusercontent.com'), 'client_secret' => env('YOUTUBE_CLIENT_SECRET', '<KEY>'), 'redirect' => env('YOUTUBE_REDIRECT', 'https://api.donatesupp.com/oauth2callback'), ]; <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\SubscribeUser; use App\Models\Service; use App\User; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; /** * Class Subscribers * @package App\Models */ class Subscribers extends Model { /** * @var bool */ public $timestamps = false; /** * @var array */ protected $with = ['service']; /** * @var array */ protected $fillable = ['_id', 'bio', 'display_name', 'logo', 'name', 'service_id', 'type']; /** * @param $query * @param string $service * @return mixed */ public function scopeService($query, string $service) { return $query->whereHas('service', function ($query) use ($service) { return $query->whereName($service)->orWhere('name', 'Streamdonations'); }); } /** * @param $query * @return mixed */ public function scopeCurrentMonth($query) { return $query->whereRaw('MONTH(subscribers_user.created_at) = ?', [date('m')]); } /** * @return BelongsToMany */ public function users() { return $this->belongsToMany(User::class)->using(SubscribeUser::class)->withPivot([ 'free', 'paid', 'premium', ]); } /** * @return BelongsTo */ public function service() { return $this->belongsTo(Service::class); } } <file_sep><?php namespace App\Models; use App\Models\Paykeeper; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class YoutubePlaylist * @package App\Models */ class YoutubePlaylist extends Model { /** * @var array */ protected $fillable = ['paykeeper_id', 'video_id', 'user_id']; /** * @return BelongsTo */ public function paykeeper () { return $this->belongsTo(Paykeeper::class); } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Transaction; use App\User; class Transactions extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker\Factory::create(); $user = User::inRandomOrder()->where('id', '!=', 19)->first(); Transaction::create([ 'user_id' => '19', 'who_id' => $user->id, 'amount' => mt_rand(100, 999), 'platform' => 1 == mt_rand(0, 1) ? 'paypal' : 'ripple', 'message' => $faker->city, 'created_at' => 2018 . $faker->dateTimeThisCentury->format('-m-d H:i:s') ]); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Validator; use App\Models\Transaction; use Carbon\Carbon; use JWTAuth; use DB; class StatisticController extends Controller { /** * @return JsonResponse */ public function fetchSubscribers () { $user = $this->user(); $subscribers = $user->subscribers()->service($user->accout_type)->select(['display_name'])->get()->toArray() ?? []; $subscribers = collect($subscribers); $total = $subscribers->count(); $count_free = $subscribers->where('pivot.free', 1)->count(); $count_paid = $subscribers->where('pivot.paid', '>=', Carbon::now())->count(); $count_premium = $subscribers->where('pivot.premium', '>=', Carbon::now())->count(); $statistic = [ 'all' => $total, 'mounth' => $user->subscribers()->currentMonth()->count(), 'chart' => [ ['label' => 'Простая', 'value' => averageValue($count_free, $total), 'color' => '#D6D6EA'], ['label' => 'Премиум', 'value' => averageValue($count_premium, $total), 'color' => '#8280FF'], ['label' => 'Платная', 'value' => averageValue($count_paid, $total), 'color' => '#636393'], ] ]; return $this->success($statistic); } /** * @param Request $request * @return JsonResponse */ public function fetchDonate(Request $request) { $user = $request->user(); $currentMonth = $request->mounth ?? date('m'); $transactions = Transaction::whereUserId($user->id) ->groupBy('date') ->orderBy('date', 'DESC') ->whereRaw('MONTH(created_at) = ?',[$currentMonth]) ->get([ DB::raw('CONCAT_WS(" ", DAY(created_at), MONTHNAME(created_at)) as date'), DB::raw('COUNT(*) as "count"'), DB::raw('SUM(`amount`) as "sum_donate"'), DB::raw('SUM(`commission`) as "sum_commission"'), ] ); $labels = $transactions->pluck('date'); $series = $transactions->pluck('count'); $sum_donate = $transactions->pluck('sum_donate'); $sum_commission = $transactions->pluck('sum_commission'); return $this->success(compact('labels', 'series', 'sum_donate', 'sum_commission')); } } <file_sep><?php use App\User; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use App\Services\{Setting, Donate, Paykeeper, VK}; use App\Models\{Subscribers, SubscribeUser, Service, Notification}; /** * @return Donate */ function donate() { return (new Donate); } /** * @param string $name * @return Setting */ function settings(string $name) { return (new Setting($name)); } /** * @param string $pathDir * @param array $music */ function getMusic(string $pathDir, array &$music) { $files = glob(public_path("{$pathDir}*.mp3")); for ($i = 0; $i < count($files); $i++) { $music[] = [ 'name' => basename($files[$i]), 'src' => '/'. $pathDir . basename($files[$i]) ]; } } /** * @param User $user * @param $pushSettings * @param string $type * @return mixed */ function fetchSettings(User $user, $pushSettings, string $type) { $settings = settings('PushDonate')->settings; $keys = array_keys($settings); for ($i = 0; $i < count($keys); $i++) { if (!$pushSettings) { break; } if (empty($pushSettings->settings[$keys[$i]])) { continue; } $mySettings = collect($pushSettings->settings[$keys[$i]]); $mySettings = $mySettings->filter(function ($value, $key) { return $value !== null; }); $mySettings->all(); $settings[$keys[$i]] = array_merge($settings[$keys[$i]], $mySettings->all()); } $musics = []; getMusic("storage/uploads/{$user->id}/music/", $musics); getMusic("storage/music/", $musics); $settings['music'] = $musics; return $settings; } /** * @param $user * @param string $type * @return mixed */ function pushSettings($user, string $type) { $settings = settings('PushDonate')->settings; $keys = array_keys($settings); for ($i = 0; $i < count($keys); $i++) { if (empty($user->settings['notification'][$type][$keys[$i]])) { continue; } $mySettings = collect($user->settings['notification'][$type][$keys[$i]]); $mySettings = $mySettings->filter(function ($value, $key) { return $value !== null; }); $mySettings->all(); $settings[$keys[$i]] = array_merge($settings[$keys[$i]], $mySettings->all()); } $musics = []; getMusic("storage/uploads/{$user->id}/music/", $musics); getMusic("storage/music/", $musics); $settings['music'] = $musics; return $settings; } /** * @param User $user * @param Subscribers $subscriber * @param array $subscribe * @param string $service_name */ function subscribe(User $user, Subscribers $subscriber, array $subscribe, string $service_name = 'Twitch') { $subscribeUser = SubscribeUser::updateOrCreate( ['subscribers_id' => $subscriber->id, 'service_id' => $subscriber->service_id, 'user_id' => $user->id], $subscribe ); if ($subscribeUser->wasRecentlyCreated) { $notification = Notification::create([ 'user_id' => $user->id, 'counter' => '', 'type' => array_keys($subscribe)[0] ?? 'free', 'title' => $subscriber->display_name, 'message' => 'Подписался', ]); } } /** * @param string $name * @param bool $id_only * @return string */ function service(string $name, bool $id_only = true): string { $service = Service::firstOrCreate(['name' => $name]); return $id_only ? $service->id : $service; } /** * @param User $user * @param User $ank * @param string $type * @return bool */ function checkSubscribe(User $user, User $ank, string $type = 'premium') { if (!$subscribe = $ank->subscribers()->where('_id', $user->twitch_id)->orWhere('_id', $user->youtube_id)->orWhere('_id', $user->id)->first()) { return false; } if (\Carbon\Carbon::now() >= $subscribe->pivot->premium) { return false; } return $subscribe->pivot->{$type}; } /** * @return Paykeeper */ function paykeeper() { return (new Paykeeper); } /** * @return VK */ function vk() { return (new VK); } /** * @param int $count * @param int $total * @param int $precision * @return float|int */ function averageValue(int $count, int $total, int $precision = 2) { if (!$count) { return 0; } return round($count / $total * 100, $precision); } /** * @param string $uri * @return RedirectResponse|Redirector */ function clientRedirect(string $uri = '/') { return redirect(env('FRONT_URL', "http://localhost:8080{$uri}")); } <file_sep><?php namespace App\Console\Commands; use Illuminate\Support\Facades\Hash; use Illuminate\Console\Command; use App\Console\Helper; use App\Admin; use Validator; class AdminCreate extends Command { use Helper; /** * The name and signature of the console command. * * @var string */ protected $signature = 'AdminCreate'; /** * The console command description. * * @var string */ protected $description = 'Создание профиля администратора'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->comment($this->description); $profile = []; $profile['name'] = $this->ask('Имя'); $profile['email'] = $this->ask('Email'); $profile['password'] = $this->secret('<PASSWORD>'); $profile['password_confirmation'] = $this->secret('<PASSWORD>'); $validator = Validator::make($profile, [ 'name' => 'required|string', 'email' => 'required|string|email|max:255|unique:admins', 'password' => '<PASSWORD>|min:<PASSWORD>', ]); if ($this->showErrors($validator)) { return; } $user = Admin::create([ 'name' => $profile['name'], 'email' => $profile['email'], 'password' => <PASSWORD>($profile['password']), 'roles' => ['admin'], ]); $this->info("Профиль \"{$profile['email']}\" успешно создан"); } } <file_sep><?php namespace App\Models; // use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Pivot; /** * Class SubscribeUser * @package App\Models */ class SubscribeUser extends Pivot { /** * @var string */ protected $table = 'subscribers_user'; /** * @var array */ protected $fillable = ['free', 'paid', 'paid_counter', 'premium', 'service_id', 'user_id', 'subscribers_id']; /** * @return int */ public function getFreeAttribute() { return (int) $this->attributes['free']; } /** * @return int */ public function getPaidAttribute() { return (int) $this->attributes['paid']; } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use App\Models\Transaction; class TransactionCommissionsField extends Migration { /** * Run the migrations. * * @return void */ public function up() { Transaction::whereNotNull('id')->delete(); Schema::table('transactions', function ($table) { $table->json('info')->after('amount'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('transactions', function (Blueprint $table) { $table->dropColumn('info'); }); } } <file_sep># DonateSupp ## artisan commands <dl> <dt>Create admin profile</dt> <dd> php artisan AdminCreate </dd> <dt>Running queues</dt> <dd> php artisan queue:work </dd> <dt>Reset Google2fa</dt> <dd> php artisan AdminGoogleReset </dd> <dt>Set up file upload</dt> <dd> sudo chmod 775 ./public/storage/uploads/ sudo chown www-data:www-data ./public/storage/uploads/ </dd> <dt>Customize Donate Page</dt> <dd> php artisan db:seed --class=SettingDonateForm </dd> <dt>Sides</dt> <dd> php artisan db:seed --class=WidgetsCategory </dd> </dl> ## Site installation <dl> <dt>Settings Apache2 (if used)</dt> <dd> - enable support .htaccess - enable module rewrite (a2enmod rewrite) - enable module headers (a2enmod headers) - restart the server (service apache2 restart) </dd> <dt>Install composer</dt> <dd> composer install </dd> <dt>Create file .env</dt> <dd> cp .env.example .env </dd> <dt>Create key</dt> <dd> openssl genrsa -out ./storage/keys/private.key 1024 sudo chmod 775 ./storage/keys/private.key </dd> <dt>Set up database connection (.env)</dt> <dd> DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE= DB_USERNAME=root DB_PASSWORD= </dd> <dt>Run a list of artisan commands</dt> <dd> php artisan key:generate php artisan jwt:secret php artisan migrate php artisan FontGenerate php artisan storage:link </dd> <dt>Set permissions</dt> <dd> sudo chmod -R 777 storage/logs/ sudo chmod -R 777 storage/framework/sessions/ sudo chmod -R 777 storage/framework/views/ sudo chmod -R 777 storage/framework/cache/ sudo chmod -R 777 public/storage </dd> </dl> - create a tweak service in services ------------------- https://github.com/zircote/swagger-php/blob/d191b5fca4f08786605316895f0542938bacb4a8/Examples/petstore.swagger.io/controllers/PetController.php#L65 <file_sep><?php namespace App\Services\Subscribers; use App\Services\Subscribers\Subscriber; use App\Jobs\Subscribers\Synchronization; use App\User; use DB; /** * Class Import * @package App\Services\Subscribers */ class Import { public $subscribers; public $user; public $fileds; /** * Import constructor. * @param array $subscribers * @param User $user */ public function __construct(Array $subscribers, User $user) { $this->subscribers = $subscribers; $this->user = $user; $this->fileds = $this->getFieldsStr(); } public function startImport() { $values = $users = []; foreach ($this->subscribers as $subscriber) { $users[] = $subscriber->subscriber; $values[] = $this->getValuesStr($subscriber); } $insertStr = implode(',', $values); try { DB::insert("INSERT IGNORE INTO `subscribers` ({$this->fileds}) VALUES {$insertStr}"); dispatch((new Synchronization( $this->user, $users, new \App\Services\Subscribers\YouTube\Followers ))); } catch (\Exception $e) { // не получилось добавить подписчиков в бд \Log::info($e->getMessage()); } // dd($this->fileds); } /** * @param \App\Services\Subscribers\Subscriber $subscriber * @return string */ protected function getValuesStr(Subscriber $subscriber) { if (!$subscriber->_id) { return ''; } $values = array_values($subscriber->subscriber); foreach ($values as &$value) { $value = \str_replace('\'', "\\'", $value); $value = "'{$value}'"; } return '(' . implode(',', $values) . ')'; } /** * @return String */ protected function getFieldsStr(): String { if (!count($this->subscribers)) { return ''; } $fileds = array_keys($this->subscribers[0]->subscriber); return implode(',', $fileds); } } <file_sep><?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Console\Helper; use App\Admin; use Validator; class AdminGoogleReset extends Command { use Helper; /** * The name and signature of the console command. * * @var string */ protected $signature = 'AdminGoogleReset'; /** * The console command description. * * @var string */ protected $description = 'Сброс Google2fa для админ-профиля'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->comment($this->description); $profile = []; $profile['email'] = $this->ask('Email'); $validator = Validator::make($profile, [ 'email' => 'required|string|email|max:255|exists:admins', ]); if ($this->showErrors($validator)) { return; } $admin = Admin::whereEmail($profile['email'])->first(); $admin->google2fa_secret = $admin->google2fa_code = null; if ($admin->save()) { return $this->info('Google2fa успешно сброшен'); } return $this->error('Ошибка при сохранеии профиля'); } } <file_sep>export default { loader({ commit }, loader) { commit('loader', loader) }, mainSettings({ commit }, settings) { commit('mainSettings', settings) }, setToken({ commit }, api_token) { commit('setToken', api_token) commit('snackbar', {text: 'Вы успешно авторизовались'}) }, setJWTToken({ commit }, jwt_token) { commit('setJWTToken', jwt_token) }, setUser({ commit }, user) { commit('setUser', user) }, rightDrawerToggle({ commit }, val = 'none') { commit('rightDrawerToggle', val) }, rightDrawerChange({ commit }, val) { commit('rightDrawerChange', val) }, settingsDonatePage({ commit }, settings) { commit('settingsDonatePage', settings) }, setDesign({ commit }, design) { commit('setDesign', design) }, logout({ commit }) { commit('logout') }, errors({ commit }, errors) { commit('errors', errors) }, snackbar({ commit }, snackbar) { commit('snackbar', snackbar) }, }<file_sep>webpackJsonp([1],{ /***/ "./node_modules/babel-loader/lib/index.js?{\"cacheDirectory\":true,\"presets\":[[\"env\",{\"modules\":false,\"targets\":{\"browsers\":[\"> 2%\"],\"uglify\":true}}]],\"plugins\":[\"transform-object-rest-spread\",[\"transform-runtime\",{\"polyfill\":false,\"helpers\":false}],\"syntax-dynamic-import\"]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/App/components/LoginTwitch.vue": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_axios__ = __webpack_require__("./node_modules/axios/index.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_axios___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_axios__); // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ data: function data() { return { twitchLoading: false // params: { // code: this.$route.query.code, // scope: this.$route.query.scope, // state: this.$route.query.state, // }, }; }, methods: { twitch: function twitch() { this.$store.dispatch('loader', true); this.twitchLoading = true; window.location.href = "/twitch/login"; } }, created: function created() { __WEBPACK_IMPORTED_MODULE_0_axios___default.a.get('/session/test').then(function (response) { console.log('sss', response.data); }); // axios.get('/twitch/login/rollback', {params: this.params}).then(response => { // console.log('response', response.data) // this.$store.dispatch('setToken', response.data.api_token) // // this.$router.push({name: 'MyProfile'}) // }) // console.log(this.params) } }); /***/ }), /***/ "./node_modules/babel-loader/lib/index.js?{\"cacheDirectory\":true,\"presets\":[[\"env\",{\"modules\":false,\"targets\":{\"browsers\":[\"> 2%\"],\"uglify\":true}}]],\"plugins\":[\"transform-object-rest-spread\",[\"transform-runtime\",{\"polyfill\":false,\"helpers\":false}],\"syntax-dynamic-import\"]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/App/pages/Login.vue": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_axios__ = __webpack_require__("./node_modules/axios/index.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_axios___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_axios__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__components_LoginTwitch__ = __webpack_require__("./resources/assets/js/App/components/LoginTwitch.vue"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__components_LoginTwitch___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__components_LoginTwitch__); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ components: { LoginTwitch: __WEBPACK_IMPORTED_MODULE_1__components_LoginTwitch___default.a }, data: function data() { return { // form: { // email: '', // password: '', // }, loading: false }; }, computed: { // disabled: function () { // return this.form.email.length > 2 && this.form.password.length > 5 // } }, methods: { // submit() { // this.loading = true // axios.post('/login', this.form).then(response => { // this.loading = false // let api_token = response.data.api_token // this.$store.dispatch('setToken', api_token) // this.$router.push({name: 'MyProfile'}) // }).catch(error => { // this.loading = false // }) // } } }); /***/ }), /***/ "./node_modules/vue-loader/lib/template-compiler/index.js?{\"id\":\"data-v-423c3824\",\"hasScoped\":false,\"buble\":{\"transforms\":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./resources/assets/js/App/pages/Login.vue": /***/ (function(module, exports, __webpack_require__) { var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "v-layout", [ _c( "v-content", [ _c( "v-container", { attrs: { fluid: "", "fill-height": "" } }, [ _c( "v-layout", { attrs: { "align-center": "", "justify-center": "" } }, [ _c( "v-flex", { attrs: { xs12: "", sm8: "", md4: "" } }, [_c("login-twitch")], 1 ) ], 1 ) ], 1 ) ], 1 ) ], 1 ) } var staticRenderFns = [] render._withStripped = true module.exports = { render: render, staticRenderFns: staticRenderFns } if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api") .rerender("data-v-423c3824", module.exports) } } /***/ }), /***/ "./node_modules/vue-loader/lib/template-compiler/index.js?{\"id\":\"data-v-5e770bfa\",\"hasScoped\":false,\"buble\":{\"transforms\":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./resources/assets/js/App/components/LoginTwitch.vue": /***/ (function(module, exports, __webpack_require__) { var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "div", [ _c( "v-btn", { attrs: { round: "", color: "purple", loading: _vm.twitchLoading, large: "" }, on: { click: _vm.twitch } }, [ _c("v-icon", { attrs: { left: "" } }, [_vm._v("mdi-twitch")]), _vm._v("\n TWITCH\n ") ], 1 ) ], 1 ) } var staticRenderFns = [] render._withStripped = true module.exports = { render: render, staticRenderFns: staticRenderFns } if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api") .rerender("data-v-5e770bfa", module.exports) } } /***/ }), /***/ "./resources/assets/js/App/components/LoginTwitch.vue": /***/ (function(module, exports, __webpack_require__) { var disposed = false var normalizeComponent = __webpack_require__("./node_modules/vue-loader/lib/component-normalizer.js") /* script */ var __vue_script__ = __webpack_require__("./node_modules/babel-loader/lib/index.js?{\"cacheDirectory\":true,\"presets\":[[\"env\",{\"modules\":false,\"targets\":{\"browsers\":[\"> 2%\"],\"uglify\":true}}]],\"plugins\":[\"transform-object-rest-spread\",[\"transform-runtime\",{\"polyfill\":false,\"helpers\":false}],\"syntax-dynamic-import\"]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/App/components/LoginTwitch.vue") /* template */ var __vue_template__ = __webpack_require__("./node_modules/vue-loader/lib/template-compiler/index.js?{\"id\":\"data-v-5e770bfa\",\"hasScoped\":false,\"buble\":{\"transforms\":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./resources/assets/js/App/components/LoginTwitch.vue") /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = null /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __vue_script__, __vue_template__, __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "resources/assets/js/App/components/LoginTwitch.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-5e770bfa", Component.options) } else { hotAPI.reload("data-v-5e770bfa", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} module.exports = Component.exports /***/ }), /***/ "./resources/assets/js/App/pages/Login.vue": /***/ (function(module, exports, __webpack_require__) { var disposed = false var normalizeComponent = __webpack_require__("./node_modules/vue-loader/lib/component-normalizer.js") /* script */ var __vue_script__ = __webpack_require__("./node_modules/babel-loader/lib/index.js?{\"cacheDirectory\":true,\"presets\":[[\"env\",{\"modules\":false,\"targets\":{\"browsers\":[\"> 2%\"],\"uglify\":true}}]],\"plugins\":[\"transform-object-rest-spread\",[\"transform-runtime\",{\"polyfill\":false,\"helpers\":false}],\"syntax-dynamic-import\"]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/App/pages/Login.vue") /* template */ var __vue_template__ = __webpack_require__("./node_modules/vue-loader/lib/template-compiler/index.js?{\"id\":\"data-v-423c3824\",\"hasScoped\":false,\"buble\":{\"transforms\":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./resources/assets/js/App/pages/Login.vue") /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = null /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __vue_script__, __vue_template__, __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "resources/assets/js/App/pages/Login.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-423c3824", Component.options) } else { hotAPI.reload("data-v-423c3824", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} module.exports = Component.exports /***/ }) });<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnimationMilestonesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('animation_milestone', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('milestone_id'); $table->unsignedInteger('animation_id'); $table->timestamps(); $table->foreign('animation_id')->references('id')->on('animations'); $table->foreign('milestone_id')->references('id')->on('milestones'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('animation_milestone'); } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Animation as MAnimation; class Animation extends Seeder { /** * Run the database seeds. * composer dump-autoload * php artisan db:seed --class=Animation * * @return void */ public function run() { $animations = [ ['animate' => 'bounce'], ['animate' => 'flash'], ['animate' => 'pulse'], ['animate' => 'shake'], ['animate' => 'jello'], ['animate' => 'headShake'], ['animate' => 'swing'], ['animate' => 'tada'], ['animate' => 'wobble'], ]; MAnimation::insert($animations); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePaykeepersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('paykeepers', function (Blueprint $table) { $table->bigIncrements('id'); // $table->decimal('sum', 8, 2)->comment('Сумма платежа'); $table->string('clientid')->nullable()->comment('Фамилия Имя Отчество'); $table->unsignedInteger('orderid')->comment('Номер транзакции'); $table->integer('ps_id')->nullable()->comment('Идентификатор платежной системы'); $table->string('service_name')->nullable()->comment('Наименование услуги'); $table->string('client_email')->nullable()->comment('Адрес электронной почты'); $table->string('batch_date')->nullable()->comment('Дата списания авторизованного платежа'); $table->string('client_phone')->nullable()->comment('Телефон'); $table->string('fop_receipt_key')->nullable()->comment('Код страницы чека 54-ФЗ'); $table->integer('bank_id')->nullable()->comment('Идентификатор привязки карты'); $table->string('card_number')->nullable()->comment('Маскированный номер карты'); $table->string('card_holder')->nullable()->comment('Держатель карты'); $table->string('card_expiry')->nullable()->comment('Срок действия карты'); $table->timestamps(); $table->foreign('orderid')->references('id')->on('transactions'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('paykeepers'); } } <file_sep><?php namespace App\Services\Oauth; use App\Models\Subscribers; use App\User; /** * Class App * @package App\Services\Oauth */ class App { /** * @var string|null */ public $redirect; /** * @var string */ protected $email; // User email /** * @var mixed */ public $newUser; public function __construct() { $this->redirect = $this->getRedirect(); } /** * @return string|null */ private function getRedirect() { return !empty($_COOKIE['redirect']) ? url('/', [], env('HTTPS_FORCE')) . '/' . $_COOKIE['redirect'] : null; } /** * @return mixed */ public function createUser() { $data = collect($this->user)->only([ 'bio', 'type', 'display_name', 'logo', 'avatar', 'name', 'service_id' ])->toArray(); if (!isset($data['logo']) && isset($data['avatar'])) { $data['logo'] = $data['avatar']; unset($data['avatar']); } Subscribers::updateOrCreate(['_id' => $this->user['twitch_id']], $data); return User::withTrashed()->firstOrCreate(['email' => $this->email], $this->user); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\{Badge, Animation, Milestone, MusicMilestone}; use Exception; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Validator; use App\User; class MailstonesController extends Controller { /** * @return JsonResponse */ public function closets() { if (!$this->user()->id) { return response()->json(['status' => 'error'], 401); } return $this->success( Milestone::getClosestMilestone($this->user()->id, $this->request->who_id) ->with(['badges', 'animations', 'music'])->first() ); } /** * @return JsonResponse */ public function add() { $validator = Validator::make($this->request->all(), [ 'donate' => 'required|integer', 'badges' => 'nullable|array', 'music' => 'nullable|array', 'animations' => 'nullable|array', ])->validate(); $badges = Badge::find($this->request->badges); $animations = Animation::whereIn('animate', $this->request->animations)->get(); $milestone = Milestone::create([ 'user_id' => $this->user()->id, 'donate' => $this->request->donate ]); $milestone->badges()->attach($badges->pluck('id')); $milestone->animations()->attach($animations->pluck('id')); $music = []; foreach ($this->request->music as $src) { $music[] = [ 'milestone_id' => $milestone->id, 'src' => $src, ]; } MusicMilestone::insert($music); $milestone = Milestone::withCount(['badges', 'animations', 'music'])->find($milestone->id); return $this->success($milestone); } /** * @return JsonResponse */ public function list() { $milestones = Milestone::withCount(['badges', 'animations', 'music']) ->whereUserId($this->user()->id) ->get(); return $this->success($milestones); } /** * @param Milestone $milestone * @return JsonResponse * @throws Exception */ public function remove(Milestone $milestone) { $milestone->badges()->detach(); $milestone->animations()->detach(); $milestone->music()->delete(); if ($milestone->delete()) { return $this->success('Майлстоун успешно удалён'); } return $this->fail('Не удалось удалить'); } /** * @return JsonResponse */ public function badges() { $badges = Badge::get(); return $this->success($badges); } /** * @param User $user * @param Request $request * @return JsonResponse */ public function badge(User $user, Request $request) { $badges = Badge::where('user_id', $request->loaded ? $user->id : null)->get(); return $this->success($badges); } /** * @param User $user * @return JsonResponse */ public function music(User $user) { $music = []; getMusic("storage/uploads/{$user->id}/milestone/sound/", $music); getMusic("storage/music/", $music); return $this->success($music); } /** * @return JsonResponse */ public function animations() { $animations = Animation::get(); return $this->success($animations); } /** * @param Request $request * @return JsonResponse */ public function imageUpload(Request $request) { $validator = Validator::make($_FILES, [ 'file' => 'required|array', 'file.tmp_name' => 'required|string', 'file.name' => 'required|string', ])->validate(); $user = $request->user(); $file = $_FILES['file']; $path = "/storage/uploads/{$user->id}/milestone/badge"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $fileinfo = pathinfo($file['name']); $filename = 'badge_' . time() . '_' . rand(0, time()) . '_' . '.' . $fileinfo['extension']; copy($file['tmp_name'], "{$dir}/{$filename}"); return $this->success(['src' => "{$path}/{$filename}", 'name' => $filename]); } /** * @param Request $request * @return JsonResponse */ public function soundUpload(Request $request) { $validator = Validator::make($_FILES, [ 'file' => 'required|array', 'file.tmp_name' => 'required|string', 'file.name' => 'required|string', ])->validate(); $user = $request->user(); $file = $_FILES['file']; $mime = mime_content_type($file['tmp_name']); if (!in_array($mime, ['audio/mpeg', 'application/octet-stream'])) { return $this->fail(['Только музыка', $mime]); } $path = "storage/uploads/{$user->id}/milestone/sound"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $filename = str_slug(basename($file['name'], '.mp3')) . '.mp3'; copy($file['tmp_name'], "{$dir}/{$filename}"); return $this->success(['src' => "/{$path}/{$filename}", 'name' => $filename]); } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Setting; class SettingDonateForm extends Seeder { /** * Run the database seeds. * composer dump-autoload * php artisan db:seed --class=SettingDonateForm * * @return void */ public function run() { Setting::whereName('DonateForm')->delete(); $set = new Setting; $set->name = 'DonateForm'; $settings = config('settings_default.DonateForm'); $set->settings = $settings; $set->save(); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use JWTAuth; use App\User; use App\Models\{Transaction, Subscribers, PushNotification, Paykeeper, Notification}; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Validator; use Carbon\Carbon; use DB; class UserController extends Controller { /** * @SWG\Get( * path="/api/user", * summary="Профиль пользователя", * tags={"Users"}, * description="Профиль авторизованного пользователя", * security={ * {"passport": {}}, * }, * @SWG\Response( * response=200, * description="Анкетные данные", * @SWG\Schema(ref="#/definitions/UserProfile"), * ), * @SWG\Response( * response="401", * description="Unauthorized user", * ), * @SWG\Response( * response="404", * description="User is not found", * ) * ) */ /** * @param Request $request * @return JsonResponse */ public function profile(Request $request) { $user = $this->user()->append('stream_hash_link'); return $this->success($user); } /** * @param User $user * @return JsonResponse */ public function milestones(User $user) { $ank = $this->user(); if (!checkSubscribe($ank, $user)) { return $this->success([ 'badges' => [], 'animations' => [], 'music' => [], ]); } $sumDonate = Transaction::whereWhoId($ank->id)->whereUserId($user->id)->sum('amount'); // return $this->success($sumDonate); $milestones = $user->milestones() ->whereHas('user', function($q) use ($ank) { return $q->whereHas('subscribers', function($q) use ($ank) { return $q->where('_id', '=', $ank->twitch_id)->orWhere('_id', '=', $ank->youtube_id); }); }) ->where('donate', '<=', $sumDonate) ->get(); $badges = collect([]); $animations = collect([]); $music = collect([]); foreach ($milestones as $milestone) { $badges->push($milestone->badges); $animations->push($milestone->animations); $music->push($milestone->music); } $badges = $badges->flatten(); $animations = $animations->flatten(); $music = $music->flatten(); return $this->success(compact('badges', 'animations', 'music')); } /** * @param Request $request * @return JsonResponse */ public function mycards(Request $request) { $user = $this->user(); return $this->success($user->cards); } /** * @param Request $request * @return JsonResponse */ public function subscribers(Request $request) { $user = $this->user(); $subscribers = $user->subscribers()->whereHas('service', function ($query) use ($user) { return $query->whereName($user->accout_type)->orWhere('name', 'Streamdonations'); })->get(); return $this->success($subscribers); } /** * @param User $user * @return JsonResponse */ public function checkSubscriber(User $user) { return $this->success(checkSubscribe($this->user(), $user)); } /** * @param User $user * @return JsonResponse */ public function mydonat(User $user) { $sumDonate = Transaction::whereWhoId($this->user()->id)->whereUserId($user->id)->sum('amount'); return $this->success(number_format($sumDonate, 0, '.', '')); } /** * @param User $user * @return JsonResponse */ public function mynotification(User $user) { $notifications = $this->getNotifications(); return $this->success($notifications); } /** * @param $notifi_id * @return JsonResponse */ public function notificationDelete($notifi_id) { if (!$notification = PushNotification::whereUserId($this->user()->id)->find($notifi_id)) { return $this->fail('Ошибка при удалении'); } $notification->delete(); $notifications = $this->getNotifications(); return $this->success($notifications); } /** * @param Request $request * @return JsonResponse */ public function mynotificationAdded(Request $request) { Validator::make($request->all(), [ 'value' => 'required|integer|min:1', 'type' => 'required|in:donate,free,paid,premium', ])->validate(); if (PushNotification::whereUserId($this->user()->id) ->whereActivate($request->value) ->whereType($request->type) ->first() ) { return $this->fail('Уведомление такого типа уже существует'); } $notification = PushNotification::create([ 'activate' => $request->value, 'type' => $request->type, 'user_id' => $this->user()->id, ]); $notifications = $this->getNotifications(); return $this->success($notifications); } /** * @param Request $request * @param User $user * @return JsonResponse */ public function premiumSubscribed(Request $request, User $user) { Validator::make($request->all(), [ 'mounth' => 'required|integer|min:1', ])->validate(); $subscribe = checkSubscribe($this->user(), $user, 'premium'); $date = $subscribe ? Carbon::parse($subscribe) : Carbon::now(); $date = $date->addMonth($request->mounth)->format('Y-m-d H:i:s'); DB::beginTransaction(); try { if (!$subscriber = Subscribers::where('_id', $this->user()->twitch_id)->orWhere('_id', $this->user()->youtube_id)->orWhere('_id', $this->user()->id)->first()) { $subscriber = Subscribers::create([ '_id' => $this->user()->id, 'name' => $this->user()->name, 'display_name' => $this->user()->name, 'bio' => '', 'logo' => $this->user()->avatar, 'service_id' => service('Streamdonations'), ]); } $token = paykeeper()->request([], '/info/settings/token/')->fetch('token'); $options = [ 'pay_amount' => settings('subscribers')->settings['costPremium'] * $request->mounth, 'clientid' => $this->user()->name, 'orderid' => $subscriber->id, 'service_name' => 'Подписка', ]; $paykeeper = paykeeper()->setToken($token)->request($options, '/change/invoice/preview/'); $invoice_id = $paykeeper->fetch('invoice_id'); $link = $paykeeper->fetchLink(); Paykeeper::create([ 'id' => $invoice_id, 'user_id' => $this->user()->id, 'who_id' => $user->id, 'orderid' => $subscriber->id, 'service_name' => 'subscription', ]); DB::commit(); return $this->success([ 'message' => 'Выберите способ оплаты', 'order_id' => $invoice_id, ], null); } catch (\Exception $e) { \Log::info($e->getMessage()); DB::rollBack(); return $this->fail('Ошибка. Попробуйте позже.'); } return $this->fail('Ошибка. Попробуйте позже.'); } /** * @param string $service * @return JsonResponse */ public function serviceDisconnect(string $service) { $service = strtolower($service); $user = $this->user(); $info = $user->info; unset($info[$service]); $user->info = $info; $user->save(); return $this->success(['success' => true, 'user' => $user]); } /** * @param Request $request * @return JsonResponse */ public function update(Request $request) { $settings = $request->only([ 'currency', 'time_zone', 'language' ]); $user = $this->user(); $user->settings = $settings; $user->save(); return $this->success(['success' => true]); } /** * @param User $user * @return JsonResponse */ public function userInfo(User $user) { return $this->success($user); } /** * @param Request $request * @return JsonResponse */ public function recentoperations(Request $request) { $operations = Notification::whereIsTest(false)->whereUserId($this->user()->id)->paginate(7); return $this->success($operations); } /** * @return string */ public function myStreamLink() { return base64_encode(Hash::make($this->user()->streamlink)); } /** * @SWG\Get( * path="/api/fetchlinks", * summary="Ссылки для отображения в профиле", * tags={"Users"}, * description="Список ссылок на страницу доната, подписку, видео...", * security={ * {"passport": {}}, * }, * @SWG\Response( * response=200, * description="Массив ссылок: Донат, Подписка, ", * @SWG\Schema(ref="#/definitions/FetchLinks"), * ), * @SWG\Response( * response="401", * description="Unauthorized user", * ), * @SWG\Response( * response="404", * description="User is not found", * ) * ) */ /** * @param Request $request * @return JsonResponse */ public function fetchlinks(Request $request) { $links = []; $types = ['donate', 'free', 'paid', 'premium']; $user = $request->user(); $token = base64_encode(Hash::make($user->streamlink)); for ($i = 0; $i < count($types); $i++) { $links[$types[$i]] = $request->root() . "/api/push/client/{$user->id}/{$types[$i]}/{$token}/view"; } $list = [ ['name' => 'Донат', 'type' => 'donate', 'link' => $links['donate']], ['name' => 'Подписка', 'type' => 'free', 'link' => $links['free']], ['name' => 'Платная подписка', 'type' => 'paid', 'link' => $links['paid']], ['name' => 'Премиум подписка', 'type' => 'premium', 'link' => $links['premium']], ['name' => 'Форма для доната', 'type' => 'donate_form', 'link' => url("/#/payment/{$user->id}")], ['name' => 'Видео', 'type' => 'videoplay', 'link' => url("/{$user->id}/{$token}/youtube")], ]; return $this->success($list); } /** * @param Request $request * @return JsonResponse */ public function getDonationFormData(Request $request) { $user = $request->streamer ? User::findOrFail($request->streamer) : $this->user(); $data = []; $data['form_settings'] = $user->settings['donate']; $data['streamer_info'] = $user; return $this->success($data); } /** * @return mixed */ private function getNotifications() { return PushNotification::whereUserId($this->user()->id)->get()->groupBy('type'); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use JWTAuth; use Exception; use Illuminate\Support\Facades\Hash; use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; class Google2faMiddleware extends BaseMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = JWTAuth::parseToken()->authenticate(); if (!Hash::check($request->header('google2fa'), $user->google2fa_code)) { return response()->json(['error' => 'Not authorized Google2fa', 'status' => 'google2fa'], 401); } return $next($request); } }<file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Models\{Transaction, SubscribeUser}; use App\User; use Validator; use Carbon\Carbon; class InsideStreamingController extends Controller { public function __construct(Request $request) { parent::__construct($request); } /** * @param string $message * @param array $items * @return JsonResponse */ private function response(string $message, array $items = []) { $itemString = implode(', ', $items); if (empty($itemString)) { $itemString = '[тестовое сообщение]'; } $tpl = [ '{{message}}' => $itemString, '{{subscriber}}' => $itemString, '{{count}}' => $itemString, '{{sum}}' => $itemString, ]; $fullMessage = strtr($message, $tpl); $name = str_replace($itemString, '', $fullMessage); return $this->success(compact( 'fullMessage', 'message', 'items', 'name' )); } /** * @param Request $request * @param User $user * @return JsonResponse */ public function lastMessage(Request $request, User $user) { Validator::make($request->all(), [ 'widget_type.message' => 'required|string', ])->validate(); $message = Transaction::whereUserId($user->id)->orderByDesc('id')->first(['message']); return $this->response($request->widget_type['message'], [$message->message ?? null]); } /** * @param User $user * @return JsonResponse */ public function mostExpensive(User $user) { $maxAmount = Transaction::whereUserId($user->id)->max('amount'); $message = 'Самое дорогое сообщение: ' . number_format($maxAmount) . 'руб.'; return $this->success($message); } /** * @param Request $request * @param User $user * @return JsonResponse */ public function lastDonater(Request $request, User $user) { Validator::make($request->all(), [ 'widget_type.message' => 'required|string', 'type' => 'nullable|in:free,paid,premium', 'widget_list_count' => 'nullable|min:1|max:100', ])->validate(); $ank = Transaction::with('paykeeper')->whereHas('paykeeper', function ($query) { return $query->whereStatus('paid'); })->whereUserId($user->id)->orderByDesc('id')->first(); return $this->response($ank->name ?? ''); } /** * @param Request $request * @param User $user * @return JsonResponse */ public function largestDonater(Request $request, User $user) { Validator::make($request->all(), [ 'widget_list_count' => 'nullable|min:1|max:100', 'widget_type.message' => 'required|string', 'options.sort' => 'in:id,sum', ])->validate(); $ankList = Transaction::with('paykeeper')->whereHas('paykeeper', function ($query) { return $query->whereStatus('paid'); })->whereUserId($user->id)->groupBy('name', 'id') ->selectRaw('sum(amount) as sum, name, id') ->orderByDesc($request->input('options.sort', 'sum')) ->take($request->input('widget_list_count', 1)) ->get()->pluck('name', 'sum'); $content = explode('||', $request->widget_type['message']); $users = []; foreach ($ankList as $sum => $name) { $tpl = [ '{{name}}' => $name, '{{sum}}' => number_format($sum), ]; $users[] = strtr(trim($content[1]), $tpl); } if (!count($users) && !$request->is_test) { $users = ['DS1', 'DS2', 'DS3']; } $tpl = [ '{{users}}' => implode(', ', $users), ]; $content = strtr(trim($content[0]), $tpl); return $this->response($content, $users); } /** * @param Request $request * @param User $user * @return JsonResponse */ public function lastSubscriber(Request $request, User $user) { Validator::make($request->all(), [ 'widget_type.message' => 'required|string', 'type' => 'nullable|in:free,paid,premium', 'widget_list_count' => 'nullable|min:1|max:100', ])->validate(); $subscriber = $user->subscribers()->when($request->type, function ($query) use ($request) { return $query->whereNotNull($request->type); })->orderByDesc('pivot_subscribers_id')->take($request->input('widget_list_count', 1))->get()->pluck('display_name'); if (!$subscriber->count() && $request->is_test) { $subscriber = collect(['DS1', 'DS2', 'DS3']); } $suffix = ''; if ($subscriber->count() && $request->type) { switch ($request->type) { case 'free': $suffix .= " (бесплатный)"; break; case 'paid': $suffix .= " (платный)"; break; case 'premium': $suffix .= " (премиум)"; break; } } return $this->response($request->widget_type['message'], $subscriber->toArray(), $suffix); } /** * @param Request $request * @param User $user * @return JsonResponse */ public function numberSubscribers(Request $request, User $user) { Validator::make($request->all(), [ 'widget_type.message' => 'required|string', 'period' => 'nullable|in:subDay,subWeek,subMonth,subQuarter,subYear', 'value' => 'nullable|integer', 'type' => 'nullable|in:free,paid,premium', ])->validate(); $count = SubscribeUser::whereUserId($user->id) ->when($request->type, function ($query) use ($request) { return $query->whereNotNull($request->type); }) ->when($request->period, function ($query) use ($request) { $value = $request->value ?? 1; return $query->where('created_at', '>=', Carbon::now()->{$request->period}($value)); })->count(); $type = ''; if ($request->type) { switch ($request->type) { case 'free': $type = "бесплатных"; break; case 'paid': $type = "платных"; break; case 'premium': $type = "премиумных"; break; } } $period = ''; if ($request->period) { switch ($request->period) { case 'subDay': $period = "день"; break; case 'subWeek': $period = "неделю"; break; case 'subMonth': $period = "месяц"; break; case 'subQuarter': $period = $request->value == 1 ? "квартал" : 'пол года'; break; case 'subYear': $period = " за год"; break; } } $tpl = [ '{{type}}' => $type, '{{period}}' => $period, ]; $content = strtr($request->widget_type['message'], $tpl); return $this->response($content, [number_format($count)]); } /** * @param Request $request * @param User $user * @return JsonResponse */ public function amountCollected(Request $request, User $user) { Validator::make($request->all(), [ 'widget_type.message' => 'required|string', ])->validate(); $sumAmount = Transaction::whereUserId($user->id)->sum('amount'); $sumAmount = number_format($sumAmount) . 'руб.'; return $this->response($request->widget_type['message'], [$sumAmount]); } } <file_sep> /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ import Vue from 'vue' import VueHead from 'vue-head' import VueCookies from 'vue-cookies' import App from './App' import VueClipboard from 'vue-clipboard2' import AnimateCss from 'v-animate-css'; import Swimlane from 'vue-swimlane' import Vuetify from 'vuetify' import 'vuetify/dist/vuetify.min.css' import 'material-design-icons-iconfont/dist/material-design-icons.scss' import router from './router' import { store } from './store/store.js'; import CxltToastr from 'cxlt-vue2-toastr' import 'cxlt-vue2-toastr/dist/css/cxlt-vue2-toastr.css' Vue.use(CxltToastr, { position: 'top right', timeOut: 3000, // progressBar: true, showMethod: 'slideInRight' // hideDuration: 1000 }) import ruLocale from 'vuetify/es5/locale/ru' Vue.use(Vuetify, { lang: { current: 'ru', locales: { ru: ruLocale } }, theme: { primary: "#6278f5", secondary: "#e57373", accent: "#9c27b0", error: "#f44336", warning: "#d09309", info: "#2196f3", success: "#4caf50" }, }) Vue.use(VueHead) Vue.use(VueCookies) Vue.use(VueClipboard) Vue.use(AnimateCss) Vue.use(Swimlane) import axios from 'axios' import { config } from './config' axios.defaults.baseURL = config.baseURL axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; // axios.defaults.headers.common['Authorization'] = 'Bearer fsdfsdfdsf' let token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; } else { console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); } /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ router.beforeEach((to, from, next) => { if (typeof to.meta.title !== 'undefined') { document.title = `Donation Support - ${to.meta.title}` } else { document.title = 'Donation Support' } next() }) const app = new Vue({ store, router, el: '#app', template: '<App/>', components: { App }, head: { meta: [ { name: 'viewport', content: 'width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover' } ] }, }); <file_sep><?php namespace App\Services\Subscribers\YouTube; class Subscriber { public $subscriber; public function __construct(\Google_Service_YouTube_Subscription $subscriber) { $this->subscriber = $subscriber->subscriberSnippet; } public function getData() { return [ '_id' => $this->subscriber->channelId, 'bio' => $this->subscriber->description, 'display_name' => $this->subscriber->title, 'logo' => $this->subscriber->thumbnails->medium->url, 'name' => $this->subscriber->title, 'service_id' => service('youtube'), ]; } }<file_sep><?php namespace App\Http\Controllers\Oauth; use App\Http\Controllers\Controller as ParentController; use Log; class Controller extends ParentController { protected function log(string $message, array $options = []) { $user_data = [ 'ip' => $_SERVER['REMOTE_ADDR'], 'user-agent' => $_SERVER['HTTP_USER_AGENT'], ]; $options = array_merge($options, $user_data); Log::channel('failed-auth')->error($message, $options); } } <file_sep><?php namespace App\Services; use App\Services\Setting; /** * Class Donate * @package App\Services */ class Donate { /** * @var \App\Services\Setting */ protected $donate; /** * @var array|bool */ public $settings; public function __construct() { $this->donate = settings('Donate'); $this->settings = $this->settings(); $this->settings['minAmount'] = $this->minDonate(); } /** * @param float $donate * @param bool $is_paid * @return array */ public function convert(float $donate, bool $is_paid = true): array { $amount = $total = $donate = $this->roundAmount($donate); $commission = 0; // если комиссии нету возвращаем то что пришло if (!$this->settings['commission']) { return compact('donate', 'amount', 'commission', 'total'); } // если комиссия в процентах, вычитываем в процентах if ($this->settings['percent']) { $commission = $this->roundAmount($amount / 100 * $this->settings['commission']); } else { $commission = $this->roundAmount($this->settings['commission']); } // если сумма денег с комиссии меньше чем указано для минимальной комиссии // устанавливаем это минимальное значение if ($this->settings['minCommissionAmount'] && $commission < $this->settings['minCommissionAmount']) { $commission = $this->settings['minCommissionAmount']; } // если донатер оплатил комиссию if ($is_paid) { $amount = $donate; // стример получает то, что донатер изначально ввёл для оплаты $total = $donate + $commission; // с донатера будет снято то что он ввёл + комиссия } else { // если донатер НЕ оплатил комиссию $amount = $donate - $commission; // стример получает то что ввёл донатер с вычетом комиссии $total = $donate; // донатер платит столько, сколько и вводил } return compact('donate', 'amount', 'commission', 'total', 'is_paid'); } /** * @return float */ public function minDonate(): float { $minDonate = $this->settings['minAmount']; // если комиссия не в % а фиксированая и, комиссия больше указанной минимальной суммы // за минимальную сумму считаем сумму комиссии + минимальная сумма if (!$this->settings['percent'] && $minDonate < $this->settings['commission']) { $minDonate = $this->settings['commission'] + $this->settings['minAmount']; } if ($this->settings['minCommissionAmount'] && $minDonate < $this->settings['minCommissionAmount']) { $minDonate = $this->settings['minCommissionAmount'] + $this->settings['minAmount']; } return $minDonate; } /** * @param float $amount * @return float */ protected function roundAmount(float $amount): float { return round($amount, 2, PHP_ROUND_HALF_UP); } /** * @param array $settings * @return bool */ public function save(array $settings) { return $this->donate->save($settings); } /** * @return array */ protected function settings(): array { $settings = $this->donate->settings ?? []; return [ 'percent' => $settings['percent'] ?? true, 'commission' => $settings['commission'] ?? 0, 'minCommissionAmount' => $settings['minCommissionAmount'] ?? 30, // указывется сумма в рублях 'minAmount' => $settings['minAmount'] ?? 1, ]; /** * minCommissionAmount - возможность установить минимальную комиссию, актуально если она указана в процентах. * к примеру установлено 10% комиссии, из суммы доната 1000руб. имеем 100руб дохода. * из суммы 10руб. имеем 1руб. Мы можем установить минимальную сумму комиссии 5руб. * теперь при донате в 1000руб, наш доход будет 100руб, при донате в 10руб. доход будет 5руб. а не 1руб. */ } } <file_sep>import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) import { store } from '../store/store.js'; const ifAuthenticated = (to, from, next) => { if (store.state.api_token) { next() return } next('/login') } const ifNotAuthenticated = (to, from, next) => { if (!store.state.api_token) { next() return } next('/') } import Home from '../pages/Home' import Login from '../pages/Login' import Logout from '../pages/Logout' // import Register from '../pages/Register' // import RecoverPassword from '../pages/RecoverPassword' import MyProfile from '../pages/MyProfile' import Profile from '../pages/Profile' import Follows from '../pages/Follows' // import Transaction from '../pages/Transaction' import Donate from '../pages/Donate' import UserSubscribe from '../pages/UserSubscribe' import MakePayment from '../pages/MakePayment' import StreamSettings from '../pages/StreamSettings/index' import ErrorPage from '../pages/Error' import Test from '../pages/Test' import Private from '../pages/Privacy/Private' import Services from '../pages/Privacy/Services' import Conditions from '../pages/Privacy/Conditions' import Privacy from '../pages/Privacy' import Help from '../pages/Help' import MySocial from '../pages/MySocial' // import TestImg from '../pages/TestImg' export default new Router({ // mode: 'history', routes: [ { path: '/', name: 'Home', component: Home, }, { path: '/testimg', name: 'TestImg', component: () => import('../pages/TestImg.vue'), }, { path: '/privacy', name: 'Privacy', component: Privacy, }, { path: '/help', name: 'Help', component: Help, }, { path: '/privacy/conditions', name: 'Conditions', component: Conditions, }, { path: '/privacy/services', name: 'Services', component: Services, }, { path: '/privacy/private', name: 'Private', component: Private, }, { path: '/make/payment/:orderId/:userId', name: 'MakePayment', component: MakePayment, }, { path: '/error/:message', name: 'ErrorPage', component: ErrorPage, }, { path: '/test', name: 'Test', component: Test, }, { path: '/stream/settings', name: 'StreamSettings', component: StreamSettings, beforeEnter: ifAuthenticated, }, { path: '/profile/social/:redirect?', name: 'MySocial', component: MySocial, beforeEnter: ifAuthenticated, }, { path: '/usersubscribe/:id', name: 'UserSubscribe', component: UserSubscribe }, { path: '/payment/:id', name: 'Payment', component: Donate, props: true, }, { path: '/login/:redirect?', name: 'Login', component: Login, beforeEnter: ifNotAuthenticated, meta: {title: 'Авторизация'} }, // { path: '/twitch/login/rollback', name: 'LoginTwitch', component: LoginTwitch, props: true,}, { path: '/logout', name: 'Logout', component: Logout, beforeEnter: ifAuthenticated, }, // { path: '/register', name: 'Register', component: Register, }, { path: '/profile', name: 'MyProfile', component: MyProfile, beforeEnter: ifAuthenticated, }, { path: '/profile/:id', name: 'Profile', component: Profile, props: true, }, { path: '/follows', name: 'Follows', component: Follows, beforeEnter: ifAuthenticated, }, { path: '/transaction', name: 'Transaction', component: () => import('../pages/Transaction.vue'), beforeEnter: ifAuthenticated, }, ] }) <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Badge; class BadgeGenerate extends Seeder { /** * Run the database seeds. * composer dump-autoload * php artisan db:seed --class=BadgeGenerate * * @return void */ public function run() { $badges = []; $files = glob(public_path('img/badges') . '/*'); for ($i = 0; $i < count($files); $i++) { $path = $files[$i]; $name = basename($path, '.png'); $size = getimagesize($path); $size = "{$size[0]}x{$size[1]}"; $badges[] = compact('path', 'name', 'size'); } Badge::whereNotNull('id')->delete(); Badge::insert($badges); } } <file_sep>import axios from 'axios' export const mutations = { rightDrawerToggle(state, val) { if (val === 'none') { state.settings.rightDrawer = !state.settings.rightDrawer } else { state.settings.rightDrawer = val } }, settingsDonatePage(state, settings) { state.settings.donate = settings console.log('update') state.settings.music = settings.music }, stopAll(state, execpt) { state.stopExecpt = execpt }, positionChangeMode(state, is_show) { state.positionChangeMode = is_show }, addMusic(state, music) { state.settings.music.push(music) }, setUser(state, user) { state.user = user }, setType(state, type) { state.type = type }, setPushId(state, push_id) { state.push_id = push_id }, setToken(state, token) { state.token = token }, } <file_sep><?php namespace App\Services\Subscribers\Twitch; use Carbon\Carbon; use App\Models\SubscribeUser; use App\Interfaces\Subscribers as SubscribersInterface; class Subscriber implements SubscribersInterface { public function getMethod(): string { return 'subscribers'; } public function getField(): string { return 'subscriptions'; } public function getType(): string { return 'paid'; } public function isReset(): bool { return true; } public function setDefaultValue(): array { return [ 'paid_counter' => 1 ]; } public function setAttributes($subscriber, $user): array { $currentSubscribe = $user->subscribers()->where('_id', $subscriber['user']['_id'])->first(); $paid_counter = $currentSubscribe->pivot->paid_counter ?? 1; try { $old_date = Carbon::parse($currentSubscribe->pivot->paid); $diff = Carbon::parse($subscriber['created_at'])->diffInDays($old_date); if ($diff) { $paid_counter = $diff < (31 + 4) ? ++$paid_counter : 1; } } catch (\Exception $e) { \Log::error('Ошибка при обновлении счётчика платых подписок подряд: ' . $e->getMessage() ); } return [ $this->getType() => $this->getValue($subscriber), 'paid_counter' => $paid_counter ]; } public function getValue($subscriber): ?string { try { return Carbon::parse($subscriber['created_at'])->format('Y-m-d H:i:s'); } catch (\Exception $e) { return null; } } }<file_sep>export const setSearchResult = (state, playload) => { state.searchResults = playload } export const setVideoResult = (state, playload) => { state.videoInfo = playload } export const setToken = (state, token) => { state.token = token } export const setUser = (state, user) => { state.user = user } export const setSelected = (state, video) => { state.selected = video } export const addToPlaylist = (state, video) => { state.playlists.push(video) } export const removeFromPlaylist = (state, index) => { state.playlists.splice(index, 1) } export const truncateFromPlaylist = (state) => { state.playlists = [] } export const showPlaylist = (state, is_show) => { state.showPlaylist = is_show } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddActiveEndPushNotificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('push_notifications', function (Blueprint $table) { $table->integer('activate_end')->after('activate')->nullale(); $table->boolean('active')->after('type')->default(true); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('push_notifications', function (Blueprint $table) { $table->dropColumn(['activate_end', 'active']); }); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\User; use App\Models\Setting; use Validator; use Illuminate\Filesystem\Filesystem; class SettingsController extends Controller { /** * @param $settings * @param $default */ private function mergeSettings($settings, &$default) { foreach (array_keys($default) as $value) { if (isset($settings[$value])) { foreach ($default[$value] as $key => $test) { if (is_array($test)) { $default[$value][$key] = array_merge($test, $settings[$value][$key]); } else { $default[$value] = array_merge($default[$value], $settings[$value]); } } } } } /** * @SWG\Get( * path="/api/mainsettings", * summary="Список настроек", * tags={"Settings"}, * @SWG\Response( * response=200, * description="Успешная операция", * @SWG\Schema( * type="array", * @SWG\Items(ref="#/definitions/MainSettings") * ), * ), * @SWG\Response( * response="404", * description="Настройки не найдены", * ) * ) */ /** * @return JsonResponse */ public function mainSettings() { $settings = Setting::pluck('settings', 'name'); $settings_default = config('settings_default'); $this->mergeSettings($settings, $settings_default); return $this->success($settings_default); } /** * @param Request $request * @return JsonResponse */ public function videoUpload(Request $request) { $validator = Validator::make($_FILES, [ 'filepond' => 'required|array', 'filepond.tmp_name' => 'required|string', 'filepond.name' => 'required|string', ])->validate(); $user = $request->user(); $file = $_FILES['filepond']; $path = "/storage/uploads/{$user->id}/formdonatevideo"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $system = new Filesystem; $system->cleanDirectory($dir); $fileinfo = pathinfo($file['name']); $filename = 'formbg_' . time() . '.' . $fileinfo['extension']; copy($file['tmp_name'], "{$dir}/{$filename}"); $settings = $user->settings; $settings['donate']['main']['bgVideo'] = "{$path}/{$filename}"; $settings['donate']['main']['bg'] = 'video'; $user->settings = $settings; $user->save(); return $this->success(['src' => "{$path}/{$filename}", 'name' => $filename]); } /** * @param Request $request * @return JsonResponse */ public function imageUpload(Request $request) { $validator = Validator::make($_FILES, [ 'file' => 'required|array', 'file.tmp_name' => 'required|string', 'file.name' => 'required|string', ])->validate(); $user = $request->user(); $file = $_FILES['file']; $path = "/storage/uploads/{$user->id}/formdonate"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $system = new Filesystem; $system->cleanDirectory($dir); $fileinfo = pathinfo($file['name']); $filename = 'formbg_' . time() . '.' . $fileinfo['extension']; copy($file['tmp_name'], "{$dir}/{$filename}"); return $this->success(['src' => "{$path}/{$filename}", 'name' => $filename]); } /** * @SWG\Put( * path="/api/donate/settings/{user}", * summary="Сброс настроек", * tags={"Settings"}, * description="Сброс настроек", * security={ * {"passport": {}}, * }, * @SWG\Parameter( * name="user", * in="path", * description="User id", * required=true, * type="integer", * ), * @SWG\Response( * response=200, * description="successful operation", * @SWG\Schema(ref="#/definitions/MainSettings"), * ), * @SWG\Response( * response="401", * description="Unauthorized user", * ), * @SWG\Response( * response="404", * description="User is not found", * ) * ) */ /** * @param Request $request * @param User $user * @return JsonResponse */ public function donateSettingsReset(Request $request, User $user) { if ($request->user()->id != $user->id) { return $this->fail('Доступ запрещён'); } $destinationPath = public_path("/storage/uploads/{$user->id}/"); $file = new Filesystem; $file->cleanDirectory($destinationPath); $settings = $user->settings; $settings['donate'] = []; $user->settings = $settings; $user->save(); $settings = settings('DonateForm')->settings; return $this->success(['message' =>'Настройки сброшены', 'settings' => $settings]); } /*** * @param Request $request * @param User $user * @return JsonResponse */ public function donateSettingsSave(Request $request, User $user) { $validator = Validator::make($request->all(), [ 'settings' => 'required|array', 'settings.*' => 'required|array', 'settings.main.bg' => 'required|in:image,color,default', 'settings.main.bgColor' => 'nullable|string', ])->validate(); if ($request->user()->id != $user->id) { return $this->fail('Доступ запрещён'); } $settings = $user->settings; $settings['donate'] = $request->settings; $user->settings = $settings; $user->save(); return $this->success('Настройки сохранены'); } /** * @return JsonResponse */ public function donateSettings() { $user = $this->user(); $settings = settings('DonateForm')->settings; $keys = array_keys($settings); for ($i = 0; $i < count($keys); $i++) { if (empty($user->settings['donate'][$keys[$i]])) { continue; } $mySettings = collect($user->settings['donate'][$keys[$i]]); $mySettings = $mySettings->filter(function ($value, $key) { return $value !== null; }); $mySettings->all(); $settings[$keys[$i]] = array_merge($settings[$keys[$i]], $mySettings->all()); } $settings['main']['bgImage'] = $user->bg_image; return $this->success($settings); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\{Animation, AnimationMilestone}; use Illuminate\Database\Eloquent\Relations\HasOne; /** * Class Notification * @package App\Models */ class Notification extends Model { /** * @var array */ protected $fillable = [ 'title', 'message', 'counter', 'user_id', 'type', 'image', 'animate_id', 'is_show', 'is_test' ]; /** * @var array */ protected $with = ['animate']; /** * @var array */ protected $casts = [ 'is_test' => 'boolean' ]; /** * @return HasOne */ public function animate() { return $this->hasOne(AnimationMilestone::class, 'id', 'animate_id'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Transaction extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('transactions', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id')->comment('Кому донат'); $table->unsignedInteger('who_id')->comment('Кто донатил'); $table->double('amount', 8, 2)->unsigned(); $table->string('platform'); $table->string('message')->nullable(); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users'); $table->foreign('who_id')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('transactions'); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\Badge; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class BadgesController extends Controller { /** * @param Request $request * @return JsonResponse */ public function add(Request $request) { $user = Auth::user(); $imageProps = getimagesize($request->path); $badge = Badge::create([ 'user_id' => $user->id, 'path' => $request->path, 'size' => $imageProps[0] . 'x' . $imageProps[1], 'name' => pathinfo($request->path,PATHINFO_FILENAME) ]); return $this->success($badge); } } <file_sep><?php namespace App\Models; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Database\Eloquent\Model; /** * Class Badge * @package App\Models */ class Badge extends Model { /** * @var array */ protected $fillable = ['name', 'size', 'path']; /** * @var array */ protected $hidden = ['path', 'updated_at', 'created_at']; /** * @var array */ protected $appends = ['src', 'disabled']; /** * @return UrlGenerator|string */ public function getSrcAttribute() { return url(str_replace(public_path(), '', $this->attributes['path'])); } /** * @return bool */ public function getDisabledAttribute(): Bool { return false; } } <file_sep>APP_NAME=Laravel APP_ENV=local APP_KEY= APP_DEBUG=true APP_URL=http://localhost TWITCH_CLIENT_ID= TWITCH_CLIENT_SECRET= TWITCH_REDIRECT= NOCAPTCHA_SECRET=secret-key NOCAPTCHA_SITEKEY=site-key LOG_CHANNEL=stack DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=<PASSWORD> BROADCAST_DRIVER=log CACHE_DRIVER=file SESSION_DRIVER=file SESSION_LIFETIME=120 QUEUE_DRIVER=sync REDIS_HOST=127.0.0.1 REDIS_PASSWORD=<PASSWORD> REDIS_PORT=6379 MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=<PASSWORD> MAIL_ENCRYPTION=null PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= PUSHER_APP_CLUSTER=mt1 MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" PAYKEEPER_USER= PAYKEEPER_PASSWORD= PAYKEEPER_SERVER= PAYKEEPER_SEED= YOUTUBE_CLIENT_ID= YOUTUBE_CLIENT_SECRET= YOUTUBE_REDIRECT=https://api.donatesupp.com/oauth2callback <file_sep><?php namespace App\Http\Controllers\Admin; use Config; use App\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller AS BaseController; class Controller extends BaseController { public function __construct(Request $request) { Config::set('auth.providers.users.model', Admin::class); } } <file_sep><?php namespace App\Interfaces; interface Subscribers { /** * Вызываемый метод twitch api */ public function getMethod(); /** * ключ поля в response твича с пользователями */ public function getField(); /** * тип подписки (free, paid, premium) */ public function getType(); /** * нужно ли обнулять значение поля value */ public function isReset(); /** * */ public function setDefaultValue(); /** * какие атрибуты, на какие значения нужно обновить в базе */ public function setAttributes($subscriber, $user); /** * значение которое будет зписываться в таблицу subscribers_user * для типа free: 0, 1 * paid: 1000, 2000m, 3000 * premium: дата в формате - 2018-11-10 22:05:16 */ public function getValue($subscriber); }<file_sep><?php namespace App\Http\Controllers\Admin; // use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Request; use Validator; use App\Admin; use JWTAuth; class AuthController extends Controller { // public function __construct() // { // \Config::set('auth.providers.users.model', \App\Admin::class); // } public function login2faQR() { $user = JWTAuth::parseToken()->authenticate(); if ($user->google2fa_code) { return $this->success(['image' => null, 'secretKey' => null]); } $google2fa = app('pragmarx.google2fa'); if (!$user->google2fa_secret) { $user->google2fa_secret = $google2fa->generateSecretKey(); $user->save(); } $QR_Image = $google2fa->getQRCodeInline( 'Admin StreamDonations', $user->email, $user->google2fa_secret ); return $this->success(['image' => $QR_Image, 'secretKey' => $user->google2fa_secret]); } public function login2fa(Request $request) { Validator::make($request->all(), [ 'secret' => 'required', ])->validate(); $google2fa = app('pragmarx.google2fa'); $secret = $request->secret; $user = JWTAuth::parseToken()->authenticate(); $valid = $google2fa->verifyKey($user->google2fa_secret, $secret); if ($valid) { $secret = sha1(md5($secret) . env('JWT_SECRET')); $user->google2fa_code = bcrypt($secret); $user->save(); return $this->success(['message' => 'Success', 'secret' => $secret]); } return $this->fail('Ошибка при вводе ключа'); } public function authenticate(Request $request) { Validator::make($request->all(), [ 'email' => 'required', 'password' => '<PASSWORD>', // 'recaptcha' => 'required|captcha', ])->validate(); $credentials = $request->only('email', 'password'); try { if (! $token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'Доступ запрещен'], 400); } } catch (JWTException $e) { return response()->json(['error' => 'could_not_create_token'], 500); } return response()->json(compact('token')); } // public function register(Request $request) // { // $validator = Validator::make($request->all(), [ // 'name' => 'required|string|max:255', // 'email' => 'required|string|email|max:255|unique:admins', // 'password' => '<PASSWORD>', // ]); // if($validator->fails()){ // return response()->json($validator->errors()->toJson(), 400); // } // $user = Admin::create([ // 'name' => $request->get('name'), // 'email' => $request->get('email'), // 'password' => <PASSWORD>('<PASSWORD>')), // ]); // $token = JWTAuth::fromUser($user); // return response()->json(compact('user','token'),201); // } public function getAuthenticatedUser() { if (! $user = JWTAuth::parseToken()->authenticate()) { return response()->json(['user_not_found'], 404); } return response()->json(compact('user')); } } <file_sep><?php namespace App\Services; use Illuminate\Config\Repository; use Illuminate\Http\Request; /** * Class Paykeeper * @package App\Services */ class Paykeeper { /** * @var Repository|mixed */ public $secret_seed; /** * @var array */ protected $headers = []; /** * @var Repository|mixed */ protected $user; /** * @var Repository|mixed */ protected $password; /** * @var Repository|mixed */ protected $server_paykeeper; /** * @var string */ protected $token; /** * @var mixed */ protected $response; public function __construct() { $this->user = config('paykeeper.user'); $this->password = config('<PASSWORD>'); $this->secret_seed = config('paykeeper.secret_seed'); $this->server_paykeeper = config('paykeeper.server_paykeeper'); $this->setHeader('Content-Type: application/x-www-form-urlencoded'); $this->auth(); } /** * @param string $header * @return $this */ protected function setHeader(string $header) { array_push($this->headers, $header); return $this; } /** * @param string $token * @return $this */ public function setToken(string $token) { $this->token = $token; return $this; } /** * @return $this */ public function auth() { $base64 = base64_encode("{$this->user}:{$this->password}"); $this->setHeader("Authorization: Basic {$base64}"); return $this; } /** * @param int $invoice_id * @return $this */ public function status(int $invoice_id) { return $this->request([], "/info/invoice/byid/?id={$invoice_id}"); } /** * @param array $options * @param string $uri * @return $this */ public function request(array $options, string $uri) { $method = count($options) ? 'POST' : 'GET'; if ($this->token) { $options = array_merge($options, ['token' => $this->token]); } # Для сетевых запросов в этом примере используется cURL $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_URL, $this->server_paykeeper . $uri); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($options)); # Инициируем запрос к API $response = curl_exec($curl); $this->response = json_decode($response, true); return $this; } /** * @param string $key * @return mixed */ public function fetch(string $key = '') { return $key ? $this->response[$key] : $this->response; } /** * @param int $invoice_id * @return string */ public function link(int $invoice_id): string { return "http://{$this->server_paykeeper}/bill/{$invoice_id}/"; } /** * @return string */ public function fetchLink(): string { return $this->link($this->fetch('invoice_id')); } } <file_sep><?php namespace App\Jobs\Subscribers; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Services\Subscribers\Twitch\SubscriberData; use App\Services\Subscribers\Subscriber; use TwitchApi; use App\User; class TwitchImport implements ShouldQueue { /** * Количество попыток задания. * * @var int */ public $tries = 3; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $user; protected $class; /** * TwitchImport constructor. * @param User $user * @param $subscribeClass * @throws \Exception */ public function __construct(User $user, $subscribeClass) { $this->checkDependence($subscribeClass); $this->user = $user; $this->class = $subscribeClass; } /** * Execute the job. * * @return void */ public function handle() { $options = [ 'limit' => 100, ]; TwitchApi::setToken($this->user->info['twitch']['token']); $followers = TwitchApi::{$this->class->getMethod()}($this->user->twitch_id, $options); // при ошибке выходим из ф-ции if (!empty($followers->error)) { return; } $subscribers = []; foreach ($followers[$this->class->getField()] as $follower) { $subscriberData = new SubscriberData($follower['user']); $subscriber = new Subscriber($subscriberData->getData()); if ($subscriber->_id) { $subscribers[] = $subscriber; } } (new \App\Services\Subscribers\Import($subscribers, $this->user))->startImport(); } private function checkDependence($class) { $interface = 'App\\Interfaces\\Subscribers'; $interfaces = array_values(class_implements($class)); if (!in_array($interface, $interfaces)) { $className = get_class($class); throw new \Exception("{$className} должен реализовывть интерфейс {$interface}"); } } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use JWTAuth; use App\User; use TwitchApi; use Illuminate\Http\Request; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; /** * @SWG\Swagger( * schemes={"http"}, * host="stream.local", * basePath="/", * @SWG\Info( * title="Donation Support API", * version="1.0.0" * ) * ) */ /** * @SWG\Definition( * definition="MainSettings", * @SWG\Property( * property="Donate", * type="object", * @SWG\Property(property="commission", type="integer"), * @SWG\Property(property="minAmount", type="integer"), * @SWG\Property(property="minCommissionAmount", type="integer"), * @SWG\Property(property="percent", type="integer"), * ), * @SWG\Property( * property="DonateForm", * type="object", * @SWG\Property( * property="btnBack", * type="object", * @SWG\Property(property="bgColor", type="string"), * @SWG\Property(property="flat", type="boolean"), * @SWG\Property(property="fontFamily", type="string"), * @SWG\Property(property="icon", type="string"), * @SWG\Property(property="light", type="boolean"), * @SWG\Property(property="size", type="integer"), * ), * @SWG\Property( * property="btnCanel", * type="object", * @SWG\Property(property="bgColor", type="string"), * @SWG\Property(property="flat", type="boolean"), * @SWG\Property(property="fontFamily", type="string"), * @SWG\Property(property="icon", type="string"), * @SWG\Property(property="light", type="boolean"), * @SWG\Property(property="size", type="integer"), * @SWG\Property(property="text", type="string"), * ), * @SWG\Property( * property="btnDonat", * type="object", * @SWG\Property(property="bgColor", type="string"), * @SWG\Property(property="color", type="string"), * @SWG\Property(property="flat", type="boolean"), * @SWG\Property(property="fontFamily", type="string"), * @SWG\Property(property="icon", type="string"), * @SWG\Property(property="light", type="boolean"), * @SWG\Property(property="size", type="integer"), * @SWG\Property(property="text", type="string"), * ), * @SWG\Property( * property="btnNext", * type="object", * @SWG\Property(property="bgColor", type="string"), * @SWG\Property(property="color", type="string"), * @SWG\Property(property="flat", type="boolean"), * @SWG\Property(property="fontFamily", type="string"), * @SWG\Property(property="icon", type="string"), * @SWG\Property(property="light", type="boolean"), * @SWG\Property(property="size", type="integer"), * @SWG\Property(property="text", type="string"), * ), * @SWG\Property( * property="header", * type="object", * @SWG\Property(property="bgColor", type="string"), * @SWG\Property(property="color", type="string"), * @SWG\Property(property="fontFamily", type="string"), * @SWG\Property(property="fontSize", type="integer"), * ), * @SWG\Property( * property="main", * type="object", * @SWG\Property(property="bg", type="string"), * @SWG\Property(property="bgColor", type="string"), * @SWG\Property(property="bgImage", type="string"), * @SWG\Property(property="bgVideo", type="string"), * @SWG\Property(property="justify", type="string"), * @SWG\Property(property="light", type="boolean"), * @SWG\Property(property="minDonate", type="integer"), * ), * @SWG\Property( * property="other", * type="object", * @SWG\Property(property="donatevideolimit", type="integer"), * ), * ), * @SWG\Property( * property="pushDonate", * type="object", * @SWG\Property( * property="amount", * type="object", * @SWG\Property(property="color", type="string"), * @SWG\Property(property="font", type="string"), * @SWG\Property(property="size", type="integer"), * ), * @SWG\Property( * property="attachment", * type="object", * @SWG\Property(property="src", type="string"), * ), * @SWG\Property( * property="image", * type="object", * @SWG\Property(property="color", type="string"), * @SWG\Property(property="size", type="integer"), * @SWG\Property(property="src", type="string"), * @SWG\Property(property="tile", type="boolean"), * ), * @SWG\Property( * property="main", * type="object", * @SWG\Property(property="bgColor", type="string"), * @SWG\Property(property="duration", type="integer"), * @SWG\Property( * property="grid", * type="object", * @SWG\Property(property="image", type="string"), * @SWG\Property(property="xs6", type="boolean"), * @SWG\Property(property="xs12", type="boolean"), * ), * @SWG\Property( * property="sound", * type="object", * @SWG\Property(property="src", type="string"), * @SWG\Property(property="volume", type="integer"), * ), * ), * @SWG\Property( * property="message", * type="object", * @SWG\Property(property="color", type="string"), * @SWG\Property(property="font", type="string"), * @SWG\Property(property="size", type="integer"), * ), * @SWG\Property( * property="name", * type="object", * @SWG\Property(property="color", type="string"), * @SWG\Property(property="font", type="string"), * @SWG\Property(property="size", type="integer"), * ), * @SWG\Property( * property="position", * type="object", * @SWG\Property( * property="attachment", * type="object", * @SWG\Property(property="angle", type="integer"), * @SWG\Property(property="classPrefix", type="string"), * @SWG\Property(property="height", type="integer"), * @SWG\Property(property="id", type="string"), * @SWG\Property(property="scaleX", type="integer"), * @SWG\Property(property="scaleY", type="integer"), * @SWG\Property(property="width", type="integer"), * @SWG\Property(property="x", type="integer"), * @SWG\Property(property="y", type="integer"), * ), * @SWG\Property( * property="counter", * type="object", * @SWG\Property(property="angle", type="integer"), * @SWG\Property(property="classPrefix", type="string"), * @SWG\Property(property="height", type="integer"), * @SWG\Property(property="id", type="string"), * @SWG\Property(property="scaleX", type="integer"), * @SWG\Property(property="scaleY", type="integer"), * @SWG\Property(property="width", type="integer"), * @SWG\Property(property="x", type="integer"), * @SWG\Property(property="y", type="integer"), * ), * @SWG\Property( * property="message", * type="object", * @SWG\Property(property="angle", type="integer"), * @SWG\Property(property="classPrefix", type="string"), * @SWG\Property(property="height", type="integer"), * @SWG\Property(property="id", type="string"), * @SWG\Property(property="scaleX", type="integer"), * @SWG\Property(property="scaleY", type="integer"), * @SWG\Property(property="width", type="integer"), * @SWG\Property(property="x", type="integer"), * @SWG\Property(property="y", type="integer"), * ), * @SWG\Property( * property="title", * type="object", * @SWG\Property(property="angle", type="integer"), * @SWG\Property(property="classPrefix", type="string"), * @SWG\Property(property="height", type="integer"), * @SWG\Property(property="id", type="string"), * @SWG\Property(property="scaleX", type="integer"), * @SWG\Property(property="scaleY", type="integer"), * @SWG\Property(property="width", type="integer"), * @SWG\Property(property="x", type="integer"), * @SWG\Property(property="y", type="integer"), * ), * ), * @SWG\Property( * property="video", * type="object", * @SWG\Property(property="src", type="string"), * ), * ), * @SWG\Property( * property="subscribers", * type="object", * @SWG\Property(property="costPremium", type="integer"), * ) * ), * ), * * @SWG\Definition( * definition="UserProfile", * @SWG\Property(property="accout_type", type="string"), * @SWG\Property(property="avatar", type="string"), * @SWG\Property(property="blocked_at", type="string"), * @SWG\Property(property="created_at", type="string"), * @SWG\Property(property="deleted_at", type="string"), * @SWG\Property(property="email", type="string"), * @SWG\Property(property="id", type="integer"), * @SWG\Property(property="is_vk", type="integer"), * @SWG\Property(property="login", type="string"), * @SWG\Property(property="name", type="string"), * @SWG\Property(property="profile_mode", type="string"), * @SWG\Property(property="settings", type="object"), * @SWG\Property(property="social_google", type="boolean"), * @SWG\Property(property="social_twitch", type="boolean"), * @SWG\Property(property="social_vkontakte", type="boolean"), * @SWG\Property(property="status", type="string"), * @SWG\Property(property="stream_hash_link", type="string"), * @SWG\Property(property="twitch_id", type="integer"), * @SWG\Property(property="type", type="object"), * @SWG\Property(property="updated_at", type="string"), * ), * * @SWG\Definition( * definition="FetchLinks", * @SWG\Property( * property="[]", * type="array", * @SWG\Items( * type="object", * @SWG\Property(property="link", type="string"), * @SWG\Property(property="name", type="string"), * @SWG\Property(property="types", type="string"), * ), * ), * ), */ class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; protected $request; /** * Controller constructor. * @param Request $request */ public function __construct(Request $request) { $this->request = $request; } /** * @param $data * @param int $check_numeric * @return JsonResponse */ public function success($data, $check_numeric = JSON_NUMERIC_CHECK) { return response()->json($data, 200, [], $check_numeric); } /** * @param $data * @return JsonResponse */ public function fail($data) { if (!is_array($data)) { $data = ['errors' => $data]; } return response()->json(['errors' => [$data]], 400); } /** * @return User|null */ protected function user(): ?User { static $user; if (!JWTAuth::getToken()) { return null; } if ($user) { return $user; } $user = JWTAuth::parseToken()->authenticate(); return $user; } /** * @return mixed */ protected function getUser() { $user = $this->request->user()->info['twitch']; TwitchApi::setToken($user['token']); return $user; } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Setting; class SettingPushDonate extends Seeder { /** * Run the database seeds. * composer dump-autoload * php artisan db:seed --class=SettingPushDonate * * @return void */ public function run() { Setting::whereName('PushDonate')->delete(); $set = new Setting; $set->name = 'PushDonate'; $settings = config('settings_default.pushDonate'); $set->settings = $settings; $set->save(); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Pivot; /** * Class BadgeMilestone * @package App\Models */ class BadgeMilestone extends Pivot { // } <file_sep><?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Request; use App\User; class TokenPushMessage { /** * @param Request $request * @param Closure $next * @return JsonResponse|mixed */ public function handle(Request $request, Closure $next) { $user = $request->route('user'); $token = base64_decode($request->route('token')); if (!Hash::check($user->streamlink, $token)) { return response()->json(['errors' => ['Access denied']], 403); } return $next($request); } } <file_sep><?php namespace App\Models; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Database\Eloquent\Model; use App\Models\Widget; use Illuminate\Database\Eloquent\Relations\HasMany; /** * Class WidgetCategory * @package App\Models */ class WidgetCategory extends Model { /** * @var array */ protected $fillable = ['title', 'message', 'slug']; /** * @var array */ protected $appends = ['active', 'link', 'method']; /** * @return bool */ public function getActiveAttribute() { return false; } /** * @return string */ public function getMethodAttribute() { switch ($this->attributes['title'] ?? $this->attributes['value'] ?? '') { case 'Последнее сообщение': return 'lastmessage'; case 'Самый крупный донатер': return 'largestdonater'; case 'Последний донатер': return 'lastdonater'; case 'Последний подписчик': return 'lastsubscriber'; case 'Количество подписчиков за период': return 'lastsubscriber'; case 'Сбор средств': return 'amountcollected'; } } /** * @return UrlGenerator|string */ public function getLinkAttribute() { return route('widget.view', $this); return url($this->attributes['slug']); } /** * @return string */ public function getRouteKeyName() { return 'slug'; } /** * @return HasMany */ public function collapseItem() { return $this->hasMany(Widget::class); } public static function boot() { parent::boot(); static::creating(function ($model) { $hash = static::slugGenerate(); while(WidgetCategory::whereSlug($hash)->first()) { $hash = static::slugGenerate(); } $model->slug = $hash; }); } /** * @return string */ public static function slugGenerate() { return md5(microtime()) . str_random(mt_rand(40, 80)); } } <file_sep><?php namespace App\Services; /** * Class Hash * @package App\Services */ class Hash { /** * @var false|string */ protected $secret_key; /** * @var string */ protected $secret_iv; /** * @var string */ protected $encrypt_method = 'AES-256-CBC'; public function __construct() { $this->secret_key = $this->getKeyContent(); $this->secret_iv = bin2hex(env('JWT_SECRET')); } /** * @param String $string * @return String */ public function decrypt(String $string): String { return openssl_decrypt(base64_decode($string), $this->encrypt_method, $this->key(), 0, $this->iv()); } /** * @param String $string * @return String */ public function encrypt(String $string): String { $output = openssl_encrypt($string, $this->encrypt_method, $this->key(), 0, $this->iv()); return base64_encode($output); } /** * @return false|string */ protected function key() { return $this->secret_key; } /** * @return false|string */ protected function iv() { return substr(hash('sha256', $this->secret_iv), 0, 16); } /** * @return false|string */ protected function getKeyContent() { $key_path = storage_path('keys/private.key'); return file_get_contents($key_path); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class PayKeeperDropForeginKey extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('paykeepers', function (Blueprint $table) { $table->dropForeign(['orderid']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('paykeepers', function (Blueprint $table) { $table->foreign('orderid')->references('id')->on('transactions'); }); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class SubscribersUserPaidToDate extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('subscribers_user', function (Blueprint $table) { $table->dropColumn('paid'); }); Schema::table('subscribers_user', function (Blueprint $table) { $table->dateTime('paid')->nullable()->after('free'); $table->integer('paid_counter')->default(0)->after('free'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('subscribers_user', function (Blueprint $table) { $table->dropColumn('paid'); }); Schema::table('subscribers_user', function (Blueprint $table) { $table->integer('paid')->nullable()->after('free'); $table->dropColumn('paid_counter'); }); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\View\View; use App\Models\{Widget, WidgetCategory}; use Validator; class WidgetController extends Controller { /*** * @return JsonResponse */ public function list() { $widgets = Widget::whereUserId($this->user()->id)->get(); return $this->success($widgets); } /** * @return JsonResponse */ public function listV2() { $widgets = WidgetCategory::with(['collapseItem' => function ($query) { return $query->whereUserId($this->user()->id); }])->whereHas('collapseItem', function ($query) { return $query->whereUserId($this->user()->id); })->select(['title', 'id', 'slug'])->get(); return $this->success($widgets); } /** * @param Widget $widget * @return Factory|View */ public function widget(Widget $widget) { $widget->stream_hash_link = $widget->user->stream_hash_link; return view('widget', compact('widget')); } /** * @param Request $request * @param Widget $widget * @return JsonResponse */ public function editWidget(Request $request, Widget $widget) { Validator::make($request->all(), [ 'name' => 'required|string', 'uri' => 'required|string', 'options' => 'nullable|array', 'options.type' => 'nullable|in:free,paid,premium', 'options.value' => 'nullable|integer|min:1', 'options.period' => 'nullable|in:subDay,subWeek,subMonth,subQuarter,subYear', 'settings' => 'nullable|array', 'settings.marquee' => 'nullable|boolean', 'settings.color' => 'nullable|array', 'settings.color.hex8' => 'nullable|string', 'settings.size' => 'nullable|integer', 'settings.speed' => 'nullable|integer', ])->validate(); $widget->uri = $request->uri; $widget->name = $request->name; $widget->options = $request->options; $widget->settings = $request->settings; $widget->save(); return $this->list(); } /** * @param Widget $widget * @return JsonResponse * @throws \Exception */ public function delete(Widget $widget) { if ($this->user()->id != $widget->user_id) { return $this->fail('Доступ запрещён!'); } $widget->delete(); return $this->success('Виджет успешно удалён'); } /** * @param Widget $widget * @return JsonResponse */ public function activate(Widget $widget) { if ($this->user()->id != $widget->user_id) { return $this->fail('Доступ запрещён!'); } Widget::whereUserId($this->user()->id) ->whereWidgetCategoryId($widget->widget_category_id) ->update(['active' => false]); $widget->active = true; $widget->save(); return $this->success(['success' => true]); } /** * @param Request $request * @param Widget $widget * @return JsonResponse */ public function editWidgetV2(Request $request, Widget $widget) { $count = $request->settings['widget_list_count']; $animation = $request->settings['widget_animation']['class_name']; $category = WidgetCategory::whereTitle($request->settings['widget_type']['value'])->first(); $data = [ 'count' => $count, 'animation' => $animation, 'widget_category_id' => $category->id, 'settings2' => $request->settings, ]; $widget->fill($data); $widget->save(); return $this->success(['success' => true]); } /** * @param Request $request * @return JsonResponse */ public function addV2(Request $request) { $count = $request->settings['widget_list_count']; $animation = $request->settings['widget_animation']['class_name']; $category = WidgetCategory::whereTitle($request->settings['widget_type']['value'])->first(); $widgetExists = Widget::whereUserId($this->user()->id)->whereWidgetCategoryId($category->id)->count(); $widget = Widget::create([ 'user_id' => $this->user()->id, 'widget_category_id' => $category->id, 'active' => !$widgetExists, 'count' => $count, 'uri' => str_random(16), 'animation' => $animation, 'settings2' => $request->settings, ]); return $this->success($widget); } /** * @param Request $request * @return JsonResponse */ public function add(Request $request) { Validator::make($request->all(), [ 'name' => 'required|string', 'uri' => 'required|string', 'options' => 'nullable|array', 'options.type' => 'nullable|in:free,paid,premium', 'options.value' => 'nullable|integer|min:1', 'options.period' => 'nullable|in:subDay,subWeek,subMonth,subQuarter,subYear', 'settings' => 'nullable|array', 'settings.marquee' => 'nullable|boolean', 'settings.color' => 'nullable|array', 'settings.color.hex8' => 'nullable|string', 'settings.size' => 'nullable|integer', 'settings.speed' => 'nullable|integer', ])->validate(); $widget = Widget::create([ 'user_id' => $this->user()->id, 'name' => $request->name, 'uri' => $request->uri, 'options' => $request->options, 'settings' => $request->settings, ]); return $this->success($widget); } } <file_sep><?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Models\Font; class FontGenerate extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'FontGenerate'; /** * The console command description. * * @var string */ protected $description = 'Сканирует шрифты в категории resources/assets/fonts, создает файл resources/assets/sass/_font.scss со стилями. Так же обновляет данные шрифтов в базе данных "fonts"'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->info('Старт'); $files = glob(base_path('resources/assets/fonts') . '/*'); $count = count($files); $bar = $this->output->createProgressBar($count); $this->info("Найдено {$count} шрифтов"); $text = ''; for ($i = 0; $i < count($files); $i++) { $file = basename($files[$i], '.ttf'); $name = mb_strtolower($file); $text .= <<<HTML @font-face { font-family: '{$name}'; src: url('../fonts/{$file}.ttf'); }\n HTML; } $fonts = []; for ($i = 0; $i < count($files); $i++) { $file = basename($files[$i], '.ttf'); $name = mb_strtolower($file); $fonts[] = [ 'name' => $name, 'class' => "font-{$name}", 'path' => base_path("resources/assets/fonts/{$file}.ttf"), ]; $text .= <<<HTML .font-{$name} { font-family: '{$name}'; }\n HTML; if ($count - $i <= 3) { sleep(1); } $bar->advance(); } $bar->finish(); $this->info(''); $f = fopen(base_path('resources/assets/sass/_font.scss'), 'w+'); fwrite($f, $text); fclose($f); // file_put_contents(base_path('resources/assets/sass/_font.scss'), $text); $this->info('Сохранен файл _font.scss'); Font::truncate(); $this->info('Очищена таблица fonts в базе данных'); Font::insert($fonts); $this->info('Данные записаны в базу данных'); $this->info('Готово'); } } <file_sep><?php namespace App\Jobs\Subscribers; use App\User; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Support\Collection; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Models\{SubscribeUser, Subscribers}; use App\Services\Subscribers\YouTube\Followers as FollowersYouTube; class Synchronization implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Количество попыток задания. * * @var int */ public $tries = 3; protected $user; protected $users; protected $class; /** * Synchronization constructor. * @param User $user * @param array $users * @param $class */ public function __construct(User $user, array $users, $class) { $this->user = $user; $this->users = $users; $this->class = $class; } /** * Execute the job. * * @return void */ public function handle() { $users = collect($this->users); $key = $this->class instanceof FollowersYouTube ? '_id' : 'user._id'; $subscribers = Subscribers::whereIn('_id', $users->pluck($key))->get(); foreach ($subscribers as $subscriber) { $who = $users->where($key, $subscriber->_id)->first(); subscribe( $this->user, $subscriber, $this->class->setAttributes($who, $this->user), 'YouTube' ); } // отписываем подписчиков которые уже отписались но еще числятся в нашей базе как подписанные if ($this->class->isReset()) { SubscribeUser::whereUserId($this->user->id) ->whereNotIn('subscribers_id', $subscribers->pluck('id')) ->when($this->class->getType() == 'paid', function ($query) { return $query->where('paid', '<=', Carbon::now()->subMonth(1)); }) ->update($this->class->setDefaultValue()); } } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'HomeController@index')->name('home'); // Route::get('/vkauth', 'HomeController@vkauth'); Route::get('/#/error/{message}', 'HomeController@index')->name('error'); Route::get('/testpush', function () { return view('push'); }); Route::get('/{user}/{token}/youtube', 'YoutubeController@playVideo')->middleware('TokenPushMessage'); Route::namespace('Oauth')->group(function () { # YouTube Route::get('/oauth2callback', 'YouTubeController@redirect'); # Socialite Route::prefix('oauth')->group(function () { Route::get('/{service}', 'SocialiteController@redirectToProvider'); Route::get('/{service}/rollback', 'SocialiteController@handleProviderCallback'); }); # Twitch Route::prefix('twitch')->group(function () { Route::get('/login', 'TwitchController@redirect'); Route::get('/login/rollback', 'TwitchController@rollback'); }); }); <file_sep><?php namespace App; use Illuminate\Support\Facades\Hash; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Foundation\Auth\User as Authenticatable; use App\Models\{ Transaction, Token, Subscribers, SubscribeUser, Badge, MilestoneBadge, Milestone }; class User extends Authenticatable implements JWTSubject { use Notifiable; use SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'api_token', 'info', 'avatar', 'is_vk', 'youtube_id', 'twitch_id' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', 'api_token', 'info' ]; protected $appends = [ 'status', 'type', 'social_youtube', 'social_twitch', 'social_vkontakte', 'currency', 'time_zone', 'language' ]; protected $casts = [ 'info' => 'Array', 'settings' => 'Array', ]; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['deleted_at']; // protected $with = ['transactions']; public function setSettingsAttribute(Array $settings) { $settings_old = $this->settings ?? []; $settings = array_merge($settings_old, $settings); $this->attributes['settings'] = json_encode($settings); } public function getStatusAttribute() { if ($this->deleted_at) return 'deleted'; if ($this->blocked_at) return 'draft'; return 'published'; } public function getCurrencyAttribute() { return $this->settings['currency'] ?? 'RUS'; } public function getTimeZoneAttribute() { return $this->settings['time_zone'] ?? '(UTC+3:00) Европа/Москва'; } public function getLanguageAttribute() { return $this->settings['language'] ?? 'Русский'; } public function getSocialTwitchAttribute() { return $this->isSocial('twitch'); } public function getSocialGoogleAttribute() { return $this->isSocial('google'); } public function getSocialYouTubeAttribute() { return $this->isSocial('youtube'); } public function getSocialVkontakteAttribute() { return $this->isSocial('vkontakte'); } protected function isSocial(string $social): Bool { return in_array($social, array_keys($this->info)); } public function getBgImageAttribute() { // return ''; $bgImagePath = "/storage/uploads/{$this->id}/formdonate/"; $files = glob(public_path($bgImagePath) . '*'); if (empty($files[0])) { return ''; } $bgImage = $bgImagePath . basename($files[0]); \Log::info($files); return $bgImage; } public function updateStatus($status) { switch ($status) { case 'draft': $this->blocked_at = \Carbon\Carbon::now(); $this->restore(); break; case 'published': $this->blocked_at = null; $this->restore(); break; case 'deleted': $this->delete(); break; } return $this->save(); } public function getTypeAttribute() { return collect($this->info)->keys(); return 'twitch'; } public function transactions() { return $this->hasMany(Transaction::class); } public function getStreamlinkAttribute() { return md5(env('SECRET_STREAM_LINK') . sha1($this->id) . $this->email) . env('SECRET_STREAM_LINK'); } public function getStreamHashLinkAttribute() { return base64_encode(Hash::make($this->streamlink)); } public function subscribers() { return $this->belongsToMany(Subscribers::class)->withPivot([ 'free', 'paid', 'paid_counter', 'premium', ]); } public function milestones() { return $this->hasMany(Milestone::class); } public function cards() { return $this->hasMany(Token::class); } /** * Get the identifier that will be stored in the subject claim of the JWT. * * @return mixed */ public function getJWTIdentifier() { return $this->getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ public function getJWTCustomClaims() { return []; } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Models\{PushNotification, Notification}; class AlertController extends Controller { /** * @return JsonResponse */ public function index() { $alerts = PushNotification::whereUserId($this->user()->id)->orderByDesc('id')->get(); return $this->success([ 'donate' => $alerts->where('type', 'donate'), 'subscribe' => $alerts->where('type', '!=', 'donate'), ]); } /** * @param Request $request * @return JsonResponse */ public function create(Request $request) { list($activate, $activate_end) = $request->range_value; if ($request->has('strick') && $request->type != 'donate') { $activate = $request->strick; $activate_end = $request->strick; } PushNotification::create([ 'activate' => $activate, 'activate_end' => $activate_end, 'type' => $request->type, 'user_id' => $this->user()->id, 'settings' => $request->all(), ]); return $this->success(['success' => true]); } /** * @param Request $request * @param string $type */ public function preview(Request $request, string $type) { Notification::create([ 'image' => $request->image, 'title' => $request->title, 'message' => $request->message, 'counter' => $request->counter, 'type' => $type, 'user_id' => $this->user()->id, ]); } public function image(Request $request) { $path = $request->file('file')->store('alerts', 'public'); return $this->success($path); } /** * @param Request $request * @param int $alert_id * @return JsonResponse */ public function update(Request $request, int $alert_id) { $request->merge([ 'image' => str_replace(\URL::to('/storage'), '', $request->image), 'sound' => str_replace(\URL::to('/storage'), '', $request->sound), ]); list($activate, $activate_end) = $request->range_value ?? $request->settings['range_value']; if ($request->has('strick') && $request->type != 'donate') { $activate = $request->strick; $activate_end = $request->strick; } $data = $request->only([ 'active', 'activate', 'activate_end', 'type' ]); $data['activate'] = $activate; $data['activate_end'] = $activate_end; $settings = $request->settings ?? $request->all(); $data['settings'] = json_encode($settings); PushNotification::whereUserId($this->user()->id)->whereId($alert_id)->update($data); return $this->success(['success' => true]); } /** * @param int $alert_id * @return JsonResponse */ public function destroy(int $alert_id) { PushNotification::whereUserId($this->user()->id)->whereId($alert_id)->delete(); return $this->success(['success' => true]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Relations\HasOne; use App\Models\{Transaction, Subscribers}; use Illuminate\Database\Eloquent\Model; /** * Class Paykeeper * @package App\Models */ class Paykeeper extends Model { /** * @var array */ protected $fillable = [ 'id', 'clientid', 'orderid', 'ps_id', 'service_name', 'client_email', 'batch_date', 'client_phone', 'fop_receipt_key', 'bank_id', 'card_number', 'card_holder', 'card_expiry', 'who_id', 'user_id' ]; /** * @var array */ protected $appends = ['payment_link']; /** * @return HasOne */ public function order() { $class = ''; switch ($this->service_name) { case 'subscription' : $class = Subscribers::class; break; case 'donate' : $class = Transaction::class; break; } if ($class) { return $this->hasOne($class, 'id', 'orderid'); } } /** * @return string */ public function getPaymentLinkAttribute() { return paykeeper()->link($this->id); } } <file_sep><?php namespace App\Http\Controllers\Admin; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Request; use Validator; use App\{Admin, User}; use JWTAuth; class UserController extends Controller { public function info() { $user = JWTAuth::parseToken()->toUser(); return $this->success($user); } public function update(Request $request) { Validator::make($request->all(), [ 'id' => 'required|integer|exists:users', 'name' => 'required|string', 'status' => 'required|string', 'is_vk' => 'nullable', ])->validate(); $profile = $request->only(['name', 'is_vk']); $profile['is_vk'] = $profile['is_vk'] ? 1 : 0; $user = User::withTrashed()->find($request->id); $user->update($profile); if ($request->status != $user->status) { $user->updateStatus($request->status); } return $this->success('Success'); } public function updateStatus(Request $request) { Validator::make($request->all(), [ 'status' => 'required|in:draft,published,deleted', 'user_id' => 'integer|exists:users,id' ])->validate(); $user = User::withTrashed()->find($request->user_id); if ($user->status != $request->status) { $user->updateStatus($request->status); } return $this->success($request->all()); } public function list() { $users = User::withTrashed()->get(); return $this->success([ 'items' => $users, 'total' => $users->count() ]); } } <file_sep><?php namespace App\Http\Controllers\Admin; // use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Request; use Validator; use App\Admin; use JWTAuth; class TransactionController extends Controller { // public function __construct() // { // \Config::set('auth.providers.users.model', \App\Admin::class); // } public function list() { return $this->success(['TransactionController']); } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\WidgetCategory; class WidgetsCategory extends Seeder { /** * Run the database seeds. * composer dump-autoload * php artisan db:seed --class=WidgetsCategory * * @return void */ public function run() { WidgetCategory::whereNotNull('id')->delete(); $items = [ [ 'title' => 'Последнее сообщение', 'message' => 'Последнее сообщение: {{message}}', 'slug' => WidgetCategory::slugGenerate(), ], [ 'title' => 'Самый крупный донатер', 'message' => 'Самый(-е) крупный(-е) донатер(-ы): {{users}} || {{name}} {{sum}}', 'slug' => WidgetCategory::slugGenerate(), ], [ 'title' => 'Последний донатер', 'message' => 'Последний(-е) донатер(-ы): {{users}} || {{name}} {{sum}}', 'slug' => WidgetCategory::slugGenerate(), ], [ 'title' => 'Последний подписчик', 'message' => 'Последний(-е) подписчик(-и): {{subscriber}}', 'slug' => WidgetCategory::slugGenerate(), ], [ 'title' => 'Количество подписчиков за период', 'message' => 'Количество подписчиков за период: {{count}} {{type}} {{period}}', 'slug' => WidgetCategory::slugGenerate(), ], [ 'title' => 'Сбор средств', 'message' => 'Сбор средств - 1', 'slug' => WidgetCategory::slugGenerate(), ], ]; WidgetCategory::insert($items); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\User; use Illuminate\Http\JsonResponse; use Validator; use App\Services\Hash; use App\Services\Setting; use Illuminate\Http\Request; use App\Models\{Transaction, Notification, Token, Badge, Paykeeper, YoutubePlaylist}; use JWTAuth; use DB; class TransactionController extends Controller { /** * @param Request $request * @return JsonResponse */ public function donateInfo(Request $request) { Validator::make($request->all(), [ 'amount' => 'required|numeric', ])->validate(); $donate = donate()->convert($request->amount, false); $settings = donate()->settings; return $this->success(compact('donate', 'settings')); } /** * @param Request $request * @return JsonResponse */ public function donate(Request $request) { Validator::make($request->all(), [ 'amount' => 'required|numeric', 'user_id' => 'required|exists:users,id', 'badge_id' => 'nullable|numeric|exists:badges,id', 'animate_id' => 'nullable|numeric|exists:animation_milestone,id', 'ank.login' => 'required', 'ank.message' => 'required', 'youtubeVideoID' => 'nullable|alpha_dash' ])->validate(); if ($user = $this->user()) { if ($request->ank['login'] != 'Аноним') { $user->login = $request->ank['login']; $user->save(); } } $commission = $request->commission ? true : false; $donate = donate()->convert($request->amount, $commission); $settings = donate()->settings; $info = compact('donate', 'settings'); $request->amount = $donate['amount']; DB::beginTransaction(); try { $transaction = Transaction::create([ 'user_id' => $request->user_id, 'who_id' => $user->id ?? null, 'amount' => $request->amount, 'info' => $info, 'commission' => $donate['commission'], 'message' => $request->ank['message'], 'name' => $request->ank['login'], ]); $token = paykeeper()->request([], '/info/settings/token/')->fetch('token'); $options = [ "pay_amount" => $request->amount + $donate['commission'], "clientid" => $request->ank['login'], "orderid" => $transaction->id, "service_name" => 'Донат', ]; $paykeeper = paykeeper()->setToken($token)->request($options, '/change/invoice/preview/'); $invoice_id = $paykeeper->fetch('invoice_id'); $link = $paykeeper->fetchLink(); $paykeeper = Paykeeper::create([ 'id' => $invoice_id, 'orderid' => $transaction->id, 'who_id' => $request->user_id, 'service_name' => 'donate', ]); if ($request->youtubeVideoID) { YoutubePlaylist::create([ 'paykeeper_id' => $paykeeper->id, 'video_id' => $request->youtubeVideoID, 'user_id' => $request->user_id, ]); } DB::commit(); } catch (\Exception $e) { \Log::info($e->getMessage()); DB::rollBack(); return $this->fail('Ошибка. Попробуйте позже.'); } $badge = Badge::find($request->badge_id); $path = "storage/google"; $dir = public_path($path); if (!is_dir($dir)) { mkdir($dir, 0777); } // $message = urlencode($request->ank['message']); // copy("https://translate.google.com.vn/translate_tts?ie=UTF-8&q={$message}&tl=ru&client=tw-ob", $dir . "/{$notification['id']}.mp3"); return $this->success([ 'message' => 'Выберите способ оплаты', 'order_id' => $invoice_id, ]); } /** * @param Request $request * @return JsonResponse */ public function transactionsStatistic (Request $request) { $user = $request->user(); $currentMonth = date('m'); $statistic = [ 'count' => $user->transactions()->count(), 'sum' => $user->transactions()->sum('amount'), 'current_mounth' => [ 'count' => $user->transactions()->whereRaw('MONTH(created_at) = ?',[$currentMonth])->count(), 'sum' => $user->transactions()->whereRaw('MONTH(created_at) = ?',[$currentMonth])->sum('amount'), ] ]; return $this->success($statistic); } /** * @param Request $request * @return JsonResponse */ public function transactions(Request $request) { Validator::make($request->all(), [ 'sortBy' => 'in:id,name,amount,created_at,platform', 'rowsPerPage' => 'integer', 'descending' => 'in:true,false', 'dateFrom' => 'nullable|date', 'dateTo' => 'nullable|date', ])->validate(); $user = $request->user(); $request->rowsPerPage = -1 == $request->rowsPerPage ? $user->transactions()->count() : $request->rowsPerPage; $request->descending = $request->descending == 'false' ? 'ASC' : 'DESC'; $transactions = $user->transactions() ->with('paykeeper') ->whereHas('paykeeper', function ($query) { return $query->whereStatus('paid'); }) ->when($request->sortBy, function ($query) use ($request) { if ('name' == $request->sortBy) { return $query->with(['who' => function ($query) use ($request) { return $query->orderBy($request->sortBy, $request->descending); }]); } return $query->orderBy($request->sortBy, $request->descending); }, function ($query) { return $query->orderBy('id', 'asc'); }) ->when($request->dateFrom, function ($query) use ($request) { return $query->where('created_at', '>=', $request->dateFrom); }) ->when($request->dateTo, function ($query) use ($request) { return $query->where('created_at', '<=', $request->dateTo); }); // ->paginate($request->rowsPerPage); if ($request->has('all')) { $transactions = $transactions->get(); } else { $transactions = $transactions->paginate($request->rowsPerPage); } return $this->success($transactions); } } <file_sep>const config = { API_KEY: '<KEY>' } export default config <file_sep><?php namespace App\Console; trait Helper { /** * @param $validator * @return bool */ public function showErrors($validator): Bool { if (!$validator->fails()) { return false; } $errors = $validator->errors()->all(); foreach ($errors as $error) { $this->error($error); } return true; } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class VideoYouTubePaykeepersAndStatus extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('youtube_playlists', function (Blueprint $table) { $table->unsignedBigInteger('paykeeper_id')->nullable()->after('title'); $table->enum('status', ['not_shown', 'shown'])->default('not_shown')->after('title'); $table->foreign('paykeeper_id')->references('id')->on('paykeepers'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('youtube_playlists', function (Blueprint $table) { $table->dropForeign(['paykeeper_id']); $table->dropColumn(['paykeeper_id']); }); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\Pivot; use App\Models\Animation; /** * Class AnimationMilestone * @package App\Models */ class AnimationMilestone extends Pivot { /** * @var array */ protected $fillable = ['duration']; /** * @var array */ protected $hidden = ['updated_at', 'created_at']; /** * @var array */ protected $with = ['animate']; /** * @return HasOne */ public function animate() { return $this->hasOne(Animation::class, 'id', 'animation_id'); } } <file_sep>import axios from 'axios' export const KEY_TOKEN = 'user-token' export const KEY_JWT = 'user-jwt' export const mutations = { loader(state, isLoader) { state.loader = isLoader }, mainSettings(state, settings) { state.mainSettings = settings }, setToken(state, api_token) { // axios.defaults.headers.common['Authorization'] = 'Bearer ' + api_token $cookies.set(KEY_TOKEN, api_token) // localStorage.setItem(KEY_TOKEN, api_token) state.api_token = api_token }, setJWTToken(state, jwt_token) { axios.defaults.headers.common['Authorization'] = 'Bearer ' + jwt_token $cookies.set(KEY_JWT, jwt_token) state.jwt_token = jwt_token }, setUser(state, user) { // localStorage.setItem(KEY_USER, JSON.stringify(user)) state.user = user }, setDesign(state, design) { state.settings.design = design switch (design) { case 'light': state.settings.logo = '/img/logo_light.png' break; case 'dark': state.settings.logo = '/img/logo.png' break; } }, errors(state, errors) { state.errors = Object.values(errors) }, rightDrawerToggle(state, val) { if (val === 'none') { state.settings.rightDrawer = !state.settings.rightDrawer } else { state.settings.rightDrawer = val } }, rightDrawerChange(state, val) { state.settings.menu = val }, settingsDonatePage(state, settings) { state.settings.donate = settings }, snackbar(state, snackbar) { state.snackbar.model = true state.snackbar.text = snackbar.text state.snackbar.color = snackbar.color || 'success' }, logout(state) { delete axios.defaults.headers.common['Authorization'] localStorage.clear() $cookies.remove(KEY_TOKEN); $cookies.remove(KEY_JWT); state.user = { id: null, profile_mode: null, } state.loader = null state.api_token = null state.jwt_token = null }, } <file_sep>export default { stopAll({ commit }, execpt) { commit('stopAll', execpt) }, positionChangeMode({ commit }, is_show) { commit('positionChangeMode', is_show) }, addMusic({ commit }, music) { commit('addMusic', music) }, setUser({ commit }, user) { commit('setUser', user) }, setToken({ commit }, token) { commit('setToken', token) }, setType({ commit }, type) { commit('setType', type) }, setPushId({ commit }, push_id) { commit('setPushId', push_id) }, rightDrawerToggle({ commit }, val = 'none') { commit('rightDrawerToggle', val) }, settingsDonatePage({ commit }, settings) { commit('settingsDonatePage', settings) }, }<file_sep><?php namespace App\Services\Subscribers\Twitch; use Carbon\Carbon; /** * Class SubscriberData * @package App\Services\Subscribers\Twitch */ class SubscriberData { public $subscriber; public function __construct($subscriber) { $this->subscriber = $subscriber; } /** * @return array */ public function getData() { return [ '_id' => $this->subscriber['_id'], 'bio' => $this->subscriber['bio'], 'logo' => $this->subscriber['logo'], 'name' => $this->subscriber['name'], 'created_at' => $this->converDate($this->subscriber['created_at']), 'updated_at' => $this->converDate($this->subscriber['updated_at']), 'service_id' => service('Twitch'), 'display_name' => $this->subscriber['display_name'], ]; } private function converDate(string $date) { return Carbon::parse($date)->format('Y-m-d H:i:s'); } } <file_sep><?php namespace App\Models; use App\User; use App\Models\{ Badge, Animation, BadgeMilestone, AnimationMilestone, MusicMilestone }; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; /** * Class Milestone * @package App\Models */ class Milestone extends Model { /** * @var array */ protected $fillable = ['donate', 'user_id']; /** * @var array */ protected $with = ['badges', 'animations', 'music']; /** * @param $donaterId * @param $streamerId * @return mixed */ public static function getClosestMilestone($donaterId, $streamerId) { $donater = User::find($donaterId); $streamer = User::find($streamerId); $myDonate = number_format( Transaction::whereWhoId($donater->id)->whereUserId($streamer->id)->sum('amount'), 2, '.', '' ); return self::where( [ ['user_id', $streamer->id], ['donate', '>=', $myDonate] ] )->orderBy('donate', 'desc'); } /** * @return BelongsToMany */ public function badges() { return $this->belongsToMany(Badge::class)->using(BadgeMilestone::class); } /** * @return BelongsToMany */ public function animations() { return $this->belongsToMany(Animation::class) ->using(AnimationMilestone::class) ->withPivot('id', 'duration'); } /** * @return HasMany */ public function music() { return $this->hasMany(MusicMilestone::class); } /** * @return BelongsTo */ public function user() { return $this->belongsTo(User::class); } } <file_sep>webpackJsonp([19],{ /***/ "./node_modules/babel-loader/lib/index.js?{\"cacheDirectory\":true,\"presets\":[[\"env\",{\"modules\":false,\"targets\":{\"browsers\":[\"> 2%\"],\"uglify\":true}}]],\"plugins\":[\"transform-object-rest-spread\",[\"transform-runtime\",{\"polyfill\":false,\"helpers\":false}],\"syntax-dynamic-import\"]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/App/pages/Profile.vue": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_axios__ = __webpack_require__("./node_modules/axios/index.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_axios___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_axios__); // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ data: function data() { return { user: null }; }, computed: { user_id: function user_id() { return this.$route.params.id; } }, methods: { goTransaction: function goTransaction() { this.$router.push({ name: 'Payment', params: { id: this.user_id } }); }, fetchUserInfo: function fetchUserInfo() { var _this = this; __WEBPACK_IMPORTED_MODULE_0_axios___default.a.get('/user/info/' + this.user_id).then(function (response) { _this.user = response.data; }).catch(function () { _this.$store.dispatch('snackbar', { text: 'Пользователь не найден', color: 'error' }); _this.$router.go(-1); }); } }, created: function created() { this.fetchUserInfo(); }, watch: { user_id: function user_id() { this.fetchUserInfo(); } } }); /***/ }), /***/ "./node_modules/vue-loader/lib/template-compiler/index.js?{\"id\":\"data-v-adb51224\",\"hasScoped\":false,\"buble\":{\"transforms\":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./resources/assets/js/App/pages/Profile.vue": /***/ (function(module, exports, __webpack_require__) { var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "v-container", [ _vm.user ? _c( "v-layout", { attrs: { row: "", wrap: "" } }, [ _c( "v-flex", { attrs: { xs12: "", "d-flex": "" } }, [ _c("v-flex", { attrs: { xs6: "" } }, [ _c("img", { staticClass: "img-circle elevation-7 mb-1", attrs: { src: _vm.user.avatar } }) ]), _vm._v(" "), _c("v-flex", { attrs: { xs6: "" } }, [ _c("div", { staticClass: "headline", domProps: { textContent: _vm._s(_vm.user.name) } }) ]) ], 1 ), _vm._v(" "), _c( "v-flex", { attrs: { xs12: "" } }, [ _c( "v-btn", { attrs: { color: "primary" }, on: { click: _vm.goTransaction } }, [_vm._v("Донатить")] ) ], 1 ) ], 1 ) : _vm._e() ], 1 ) } var staticRenderFns = [] render._withStripped = true module.exports = { render: render, staticRenderFns: staticRenderFns } if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api") .rerender("data-v-adb51224", module.exports) } } /***/ }), /***/ "./resources/assets/js/App/pages/Profile.vue": /***/ (function(module, exports, __webpack_require__) { var disposed = false var normalizeComponent = __webpack_require__("./node_modules/vue-loader/lib/component-normalizer.js") /* script */ var __vue_script__ = __webpack_require__("./node_modules/babel-loader/lib/index.js?{\"cacheDirectory\":true,\"presets\":[[\"env\",{\"modules\":false,\"targets\":{\"browsers\":[\"> 2%\"],\"uglify\":true}}]],\"plugins\":[\"transform-object-rest-spread\",[\"transform-runtime\",{\"polyfill\":false,\"helpers\":false}],\"syntax-dynamic-import\"]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/App/pages/Profile.vue") /* template */ var __vue_template__ = __webpack_require__("./node_modules/vue-loader/lib/template-compiler/index.js?{\"id\":\"data-v-adb51224\",\"hasScoped\":false,\"buble\":{\"transforms\":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./resources/assets/js/App/pages/Profile.vue") /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = null /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __vue_script__, __vue_template__, __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "resources/assets/js/App/pages/Profile.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-adb51224", Component.options) } else { hotAPI.reload("data-v-adb51224", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} module.exports = Component.exports /***/ }) });<file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\User; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use TwitchApi; class TwitchController extends Controller { /** * @param Request $request * @return mixed|string */ public function webhook(Request $request) { $body = file_get_contents('php://input'); \Log::info($body); try { $body = json_decode($body, true); $body = $body['data'][0] ?? []; $user_name = $body['user_name'] ?? null; $thumbnail_url = str_replace(['{width}', '{height}'], 128, $body['thumbnail_url']) ?? null; if ($user_name) { vk()->sendGroupMessage("{$user_name} начал стрим\nhttps://www.twitch.tv/{$user_name}", $thumbnail_url); } } catch(\Exception $e) { } return $request->hub_challenge ?? ''; } /** * @param Request $request * @return JsonResponse */ public function followsList(Request $request) { $user = $request->user()->info['twitch']; $options = [ 'limit' => 100, ]; TwitchApi::setToken($user['token']); return $this->success(TwitchApi::followers($user['_id'], $options)); } /** * @param Request $request * @return JsonResponse */ public function test(Request $request) { $user = $request->user()->info['twitch']; $options = [ 'limit' => 100, ]; TwitchApi::setToken('<KEY>'); return $this->success(TwitchApi::subscribers(138618207, $options)); } /** * @param Request $request * @param string $channel * @return JsonResponse */ public function channelInfoById(Request $request, string $channel) { return $this->success(TwitchApi::channel($channel)); } /** * @param User $user * @return JsonResponse */ public function getUserStreams(User $user) { if (!$user->twitch_id) { return $this->fail(['message' => 'Twitch не привязан к этом аккаунту']); } return $this->success( TwitchApi::sendRequest('GET', 'channels/' . $user->twitch_id . '/videos', false, [ 'limit' => 3 ] ) ); } } <file_sep><?php declare(strict_types=1); namespace App\Http\Controllers; use App\User; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Models\YoutubePlaylist; use Illuminate\View\View; class YoutubeController extends Controller { /** * @param User $user * @return JsonResponse */ public function index(User $user) { $list = YoutubePlaylist::with('paykeeper') ->whereStatus('not_shown') ->whereHas('paykeeper', function ($query) { return $query->whereStatus('paid'); }) ->whereUserId($user->id) ->get(); return $this->success($list); } /** * @param User $user * @param string $token * @param $id * @return JsonResponse */ public function destroy(User $user, string $token, $id) { YoutubePlaylist::whereStatus('not_shown') ->whereUserId($user->id) ->whereVideoId($id) ->limit(1) ->update(['status' => 'shown']); return $this->success(['message' => '=)']); } /** * @param User $user * @param string $token * @return Factory|View */ public function playVideo(User $user, string $token) { return view('playVideo', compact('user', 'token')); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePushNotificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('push_notifications', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->enum('type', ['donate', 'free', 'paid', 'premium'])->default('donate'); $table->json('settings')->nullable(); $table->integer('activate')->unsigned()->default(0)->comment('При каком значении доната/подписки будет активироваться это уведомление'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('push_notifications'); } } <file_sep><?php namespace App\Http\Controllers\Oauth; use Hash; use JWTAuth; use App\User; use Illuminate\Http\Request; use App\Jobs\Subscribers\YouTubeImport; class YouTubeController extends Controller { public function redirect(Request $request) { $is_streamer = $this->request->is_streamer ?? 0; setcookie('is_streamer', (int) $is_streamer, time() + 900, '/'); setcookie('redirect', $this->request->redirect, time() + 900, '/'); $client = new \Google_Client(); $client->setAuthConfig(config('youtube')); $client->addScope(\Google_Service_YouTube::YOUTUBE_READONLY); $client->addScope('https://www.googleapis.com/auth/userinfo.profile'); $client->addScope('https://www.googleapis.com/auth/userinfo.email'); $client->setRedirectUri(config('youtube.redirect')); $client->setAccessType('offline'); // offline access $client->setIncludeGrantedScopes(true); // incremental auth if ($request->code) { $response = $this->rollback($client, $request); list('user' => $user, 'token' => $token, 'redirect' => $redirect) = $response; if ($redirect) { return clientRedirect('/settings/account'); // return redirect($redirect); } return clientRedirect("/auth/?token={$token}"); // return view('home', compact('user', 'token', 'redirect')); } $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); exit; } public function rollback(\Google_Client $client, Request $request) { $client->authenticate($request->code); $access_token = $client->getAccessToken(); $userService = file_get_contents('https://www.googleapis.com/oauth2/v1/userinfo?access_token=' . $access_token['access_token']); $userService = \json_decode($userService); $client->setAccessToken($access_token); $user = User::withTrashed()->firstOrCreate(['email' => $userService->email], [ 'name' => $userService->name, 'password' => <PASSWORD>::<PASSWORD>(str_<PASSWORD>(128)), 'api_token' => str_random(128), 'avatar' => $userService->picture, 'info' => ['youtube' => $userService], ]); if ($user->trashed()) { return redirect('/#/login/?locked=error'); } $user->avatar = $userService->picture; $user->accout_type = 'youtube'; $user->profile_mode = !empty($_COOKIE['is_streamer']) && $_COOKIE['is_streamer'] ? 'streamer' : 'user'; $info = $user->info; $info['youtube'] = $userService; $info['youtube']->token = $access_token; $user->info = $info; $user->save(); dispatch(new YouTubeImport($user)); // dd(5); $token = JWTAuth::fromUser($user); $redirect = !empty($_COOKIE['redirect']) ? url('/', [], true) . '/' . $_COOKIE['redirect'] : null; // $redirect = !empty($_COOKIE['redirect']) ? env('FRONT_URL', 'http://localhost:8080') . $_COOKIE['redirect'] : null; return compact('user', 'token', 'redirect'); } }
7f92179fc57c4aef10c7c03c5e357439f167452f
[ "JavaScript", "Markdown", "PHP", "Shell" ]
117
PHP
freelaxdeveloper/laravel_vue_example
2fe79a1712c58c19fcc23ef47f29248053fffde4
c3947f09b521a889bfc3f3616f2423463c03d28b
refs/heads/master
<file_sep>using Prism.Commands; using Prism.Events; using System; using System.Threading.Tasks; using System.Windows.Input; using VetTracker2.UI.Event; using VetTracker2.UI.View.Services; namespace VetTracker2.UI.ViewModel { public class MainViewModel : ViewModelBase { private IEventAggregator _eventAggregator; private Func<IPetDetailViewModel> _petDetailViewModelCreator; private IMessageDialogService _messageDialogService; private IPetDetailViewModel _petDetailViewModel; public MainViewModel(INavigationViewModel navigationViewModel, Func<IPetDetailViewModel> petDetailViewModelCreator, IEventAggregator eventAggregator, IMessageDialogService messageDialogService) { _eventAggregator = eventAggregator; _petDetailViewModelCreator = petDetailViewModelCreator; _messageDialogService = messageDialogService; _eventAggregator.GetEvent<OpenPetDetailViewEvent>().Subscribe(OnOpenPetDetailView); _eventAggregator.GetEvent<AfterPetDeletedEvent>().Subscribe(AfterPetDeleted); CreateNewPetCommand = new DelegateCommand(OnCreatePetExecute); NavigationViewModel = navigationViewModel; } public async Task LoadAsync() { await NavigationViewModel.LoadAsync(); } public INavigationViewModel NavigationViewModel { get; } public ICommand CreateNewPetCommand { get; } public IPetDetailViewModel PetDetailViewModel { get { return _petDetailViewModel; } private set { _petDetailViewModel = value; OnPropertyChanged(); } } private async void OnOpenPetDetailView(int? petId) { if(PetDetailViewModel!=null && PetDetailViewModel.HasChanges) { var result = _messageDialogService.ShowOkCancelDialog("You have unsaved changes. Discard?", "Discard changes"); if(result == MessageDialogResult.Cancel) { return; } } PetDetailViewModel =_petDetailViewModelCreator(); await PetDetailViewModel.LoadAsync(petId); } private void OnCreatePetExecute() { OnOpenPetDetailView(null); } private void AfterPetDeleted(int petId) { PetDetailViewModel = null; } } } <file_sep>using System; using System.Collections.Generic; using VetTracker2.Model; namespace VetTracker2.UI.Wrapper { public class PetWrapper : ModelWrapper<Pet> { public PetWrapper(Pet model) : base(model) { } public int Id { get { return Model.Id; } } public string Name { get { return GetValue<string>(); } set { SetValue(value); } } public string Type { get { return GetValue<string>(); } set { SetValue(value); } } public string Illness { get { return GetValue<string>(); } set { SetValue(value); } } public string Owner { get { return GetValue<string>(); } set { SetValue(value); } } protected override IEnumerable<string> ValidateProperty(string propertyName) { switch (propertyName) { case nameof(Name): if (string.Equals(Name, "Fecker", StringComparison.OrdinalIgnoreCase)) { yield return "That's an aweful name for a pet."; } break; } } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using VetTracker2.DataAccess; using VetTracker2.Model; namespace VetTracker2.UI.Data.Repositories { public class PetRepository : IPetRepository { private readonly VetTrackerContext _context; public PetRepository(VetTrackerContext context) { _context = context; } public void Add(Pet pet) { _context.Pets.Add(pet); } public void Delete(Pet model) { _context.Pets.Remove(model); } public async Task<Pet> GetByIdAsync(int petId) { return await _context.Pets.SingleAsync(p => p.Id == petId); } public bool HasChanges() { return _context.ChangeTracker.HasChanges(); } public async Task SaveAsync() { await _context.SaveChangesAsync(); } } } <file_sep>using System.Collections.Generic; using System.Threading.Tasks; using VetTracker2.Model; namespace VetTracker2.UI.Data.Repositories { public interface IPetRepository { Task<Pet> GetByIdAsync(int petId); Task SaveAsync(); bool HasChanges(); void Add(Pet pet); void Delete(Pet model); } }<file_sep> using Autofac; using Prism.Events; using VetTracker2.DataAccess; using VetTracker2.UI.Data; using VetTracker2.UI.Data.Lookups; using VetTracker2.UI.Data.Repositories; using VetTracker2.UI.View.Services; using VetTracker2.UI.ViewModel; namespace VetTracker2.UI.Startup { public class Bootstrapper { // Bootstrapper class is responsible for creating the Autofac container public IContainer Bootstrap() { var builder = new ContainerBuilder(); builder.RegisterType<EventAggregator>().As<IEventAggregator>().SingleInstance(); builder.RegisterType<VetTrackerContext>().AsSelf(); builder.RegisterType<MessageDialogService>().As<IMessageDialogService>(); builder.RegisterType<MainWindow>().AsSelf(); builder.RegisterType<MainViewModel>().AsSelf(); builder.RegisterType<NavigationViewModel>().As<INavigationViewModel>(); builder.RegisterType<PetDetailViewModel>().As<IPetDetailViewModel>(); builder.RegisterType<LookupDataService>().AsImplementedInterfaces(); // Whenever a IPetDataService is required somewhere, it will create an instance of the PetDataService class builder.RegisterType<PetRepository>().As<IPetRepository>(); return builder.Build(); } } } <file_sep>using Prism.Events; using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using VetTracker2.Model; using VetTracker2.UI.Data; using VetTracker2.UI.Event; using System.Linq; using VetTracker2.UI.Data.Lookups; namespace VetTracker2.UI.ViewModel { public class NavigationViewModel : ViewModelBase, INavigationViewModel { private IPetLookupDataService _petLookupService; private IEventAggregator _eventAggregator; public NavigationViewModel(IPetLookupDataService petLookupService, IEventAggregator eventAggregator) { _petLookupService = petLookupService; _eventAggregator = eventAggregator; Pets = new ObservableCollection<NavigationItemViewModel>(); _eventAggregator.GetEvent<AfterPetSavedEvent>().Subscribe(AfterPetSaved); _eventAggregator.GetEvent<AfterPetDeletedEvent>().Subscribe(AfterPetDeleted); } public ObservableCollection<NavigationItemViewModel> Pets { get; } public async Task LoadAsync() { var lookup = await _petLookupService.GetPetLookupAsync(); Pets.Clear(); foreach (var item in lookup) { Pets.Add(new NavigationItemViewModel(item.Id, item.DisplayMember, _eventAggregator)); } } private void AfterPetDeleted(int petId) { var pet = Pets.SingleOrDefault(p => p.Id == petId); if(pet != null) { Pets.Remove(pet); } } private void AfterPetSaved(AfterPetSavedEventArgs obj) { var lookupItem = Pets.SingleOrDefault(l => l.Id == obj.Id); if (lookupItem == null) { Pets.Add(new NavigationItemViewModel(obj.Id, obj.DisplayMember, _eventAggregator)); } else { lookupItem.DisplayMember = obj.DisplayMember; } } } } <file_sep>using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using VetTracker2.Model; namespace VetTracker2.DataAccess { public class VetTrackerContext : DbContext { public VetTrackerContext() : base("VetTrackerDb") { } public DbSet<Pet> Pets { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } } <file_sep>using Prism.Events; namespace VetTracker2.UI.Event { public class OpenPetDetailViewEvent : PubSubEvent<int?> { } } <file_sep>using Prism.Events; namespace VetTracker2.UI.Event { public class AfterPetSavedEvent : PubSubEvent<AfterPetSavedEventArgs> { } public class AfterPetSavedEventArgs { public int Id { get; set; } public string DisplayMember { get; set; } } } <file_sep>using System.Collections.Generic; using System.Threading.Tasks; using VetTracker2.Model; namespace VetTracker2.UI.Data.Lookups { public interface IPetLookupDataService { Task<IEnumerable<LookupItem>> GetPetLookupAsync(); } }<file_sep>using System.Threading.Tasks; namespace VetTracker2.UI.ViewModel { public interface IPetDetailViewModel { Task LoadAsync(int? petId); bool HasChanges { get; } } }<file_sep>namespace VetTracker2.DataAccess.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using VetTracker2.Model; internal sealed class Configuration : DbMigrationsConfiguration<VetTracker2.DataAccess.VetTrackerContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(VetTracker2.DataAccess.VetTrackerContext context) { context.Pets.AddOrUpdate( p => p.Name, new Pet { Type = "Golden retriever", Name = "Doggo", Illness = "Broken tail", Owner = "<NAME>" }, new Pet { Type = "Llama", Name = "Max", Illness = "Influensa", Owner = "<NAME>" }, new Pet { Type = "Cat", Name = "BoatDude", Illness = "Blindness", Owner = "<NAME>" }, new Pet { Type = "Parrot", Name = "Francis", Illness = "Aspergillus", Owner = "<NAME>" }, new Pet { Type = "Chinchilla", Name = "Rocket", Illness = "Rabies", Owner = "Frank England" }, new Pet { Type = "Guinea pig", Name = "Sara", Illness = "Thorn in paw", Owner = "Leon<NAME>" }, new Pet { Type = "Horse", Name = "Stud", Illness = "Bruises on leg", Owner = "<NAME>" } ); } } } <file_sep>using Prism.Commands; using Prism.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using VetTracker2.Model; using VetTracker2.UI.Data; using VetTracker2.UI.Data.Repositories; using VetTracker2.UI.Event; using VetTracker2.UI.View.Services; using VetTracker2.UI.Wrapper; namespace VetTracker2.UI.ViewModel { public class PetDetailViewModel : ViewModelBase, IPetDetailViewModel { private IPetRepository _petRepository; private IEventAggregator _eventAggregator; private IMessageDialogService _messageDialogService; private PetWrapper _pet; private bool _hasChanges; public PetDetailViewModel(IPetRepository petRepository, IEventAggregator eventAggregator, IMessageDialogService messageDialogService) { _petRepository = petRepository; _eventAggregator = eventAggregator; _messageDialogService = messageDialogService; SaveCommand = new DelegateCommand(OnSaveExecute, OnSaveCanExecute); DeleteCommand = new DelegateCommand(OnDeleteExecute); } public async Task LoadAsync(int? petId) { var pet = petId.HasValue ? await _petRepository.GetByIdAsync(petId.Value) : CreateNewPet(); Pet = new PetWrapper(pet); Pet.PropertyChanged += (s, e) => { if (!HasChanges) { HasChanges = _petRepository.HasChanges(); } if (e.PropertyName == nameof(Pet.HasErrors)) { ((DelegateCommand)SaveCommand).RaiseCanExecuteChanged(); } }; ((DelegateCommand)SaveCommand).RaiseCanExecuteChanged(); if (Pet.Id == 0) { Pet.Name = ""; } } public PetWrapper Pet { get { return _pet; } private set { _pet = value; OnPropertyChanged(); } } public bool HasChanges { get { return _hasChanges; } set { if (_hasChanges != value) { _hasChanges = value; OnPropertyChanged(); ((DelegateCommand)SaveCommand).RaiseCanExecuteChanged(); } } } public ICommand SaveCommand { get; } public ICommand DeleteCommand { get; } private async void OnSaveExecute() { await _petRepository.SaveAsync(); HasChanges = _petRepository.HasChanges(); _eventAggregator.GetEvent<AfterPetSavedEvent>().Publish( new AfterPetSavedEventArgs { Id = Pet.Id, DisplayMember = $"{Pet.Name} the {Pet.Type}" }); } private bool OnSaveCanExecute() { return Pet != null && !Pet.HasErrors && HasChanges; } private async void OnDeleteExecute() { var result = _messageDialogService.ShowOkCancelDialog($"Are you sure you want to delete the client {Pet.Name}?", "Delete?"); if (result == MessageDialogResult.OK) { _petRepository.Delete(Pet.Model); await _petRepository.SaveAsync(); _eventAggregator.GetEvent<AfterPetDeletedEvent>().Publish(Pet.Id); } } private Pet CreateNewPet() { var pet = new Pet(); _petRepository.Add(pet); return pet; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using VetTracker2.DataAccess; using VetTracker2.Model; namespace VetTracker2.UI.Data.Lookups { public class LookupDataService : IPetLookupDataService { private readonly Func<VetTrackerContext> _contextCreator; public LookupDataService(Func<VetTrackerContext> contextCreator) { _contextCreator = contextCreator; } public async Task<IEnumerable<LookupItem>> GetPetLookupAsync() { using(var context = _contextCreator()) { return await context.Pets.AsNoTracking().Select(pet => new LookupItem { Id = pet.Id, DisplayMember = pet.Name + " the " + pet.Type }) .ToListAsync(); } } } } <file_sep>using Prism.Events; namespace VetTracker2.UI.Event { public class AfterPetDeletedEvent : PubSubEvent<int> { } }
564ba8ddbebeac81ac2c114027d5c6dd023a4fab
[ "C#" ]
15
C#
Simone1989/VetTracker2.0
2c9ccc302e7f776b506bbf101f2ddfd411e8218d
ab6a569c7394465c9b40ced0a268f3edb166c78a
refs/heads/master
<repo_name>wearelighthouse/react-redux<file_sep>/src/containers/App.js import React from 'react'; // Screens import ExamplesScreen from '../screens/Example/ExamplesScreen'; const App = () => ( <div> <h1>React Redux Example</h1> <ExamplesScreen /> </div> ); export default App; <file_sep>/tests/screens/Example/ExamplesScreen.test.js import React from 'react'; import { mount, shallow } from 'enzyme'; import { ExamplesScreen, mapStateToProps, mapDispatchToProps } from '../../../src/screens/Example/ExamplesScreen'; describe('ExamplesScreen', () => { const props = { examples: [{ id: 1, name: 'Lorem' }], fetchExamples: jest.fn(), isFetching: false }; it('render', () => { const wrapper = shallow(<ExamplesScreen {...props} />); const exampleListProps = wrapper.find('ExampleList').props(); expect(exampleListProps.examples).toEqual(props.examples); expect(exampleListProps.isFetching).toEqual(props.isFetching); }); it('componentDidMount', () => { expect(props.fetchExamples.mock.calls.length).toBe(0); mount(<ExamplesScreen {...props} />); expect(props.fetchExamples.mock.calls.length).toBe(1); }); }); describe('mapStateToProps', () => { it('shape', () => { const props = mapStateToProps({ entities: { examples: [] }, example: { ids: [], isFetching: false } }); expect(props.examples).toBeDefined(); expect(props.isFetching).toBeDefined(); }); }); describe('mapDispatchToProps', () => { it('shape', () => { const store = global.configureStore(); const props = mapDispatchToProps(store.dispatch); expect(props.fetchExamples).toBeDefined(); }); }); <file_sep>/src/store/configureStore.js import { applyMiddleware, compose, createStore } from 'redux'; import thunk from 'redux-thunk'; import * as api from './api'; import reducers from './reducers'; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const configureStore = initialState => { const store = createStore( reducers, initialState, composeEnhancers( applyMiddleware( thunk.withExtraArgument(api) ) ) ); if (module.hot) { module.hot.accept('./reducers', () => store.replaceReducer(reducers)); } return store; }; export default configureStore; <file_sep>/src/screens/Example/ExamplesScreen.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; // Actions import { fetchExamples } from '../../store/Example/actions'; // Components import ExampleList from '../../components/Example/ExampleList'; // Selectors import { getExamples, getIsFetching } from '../../store/Example/selectors'; export class ExamplesScreen extends Component { componentDidMount() { this.props.fetchExamples(); } render() { const { examples, isFetching } = this.props; return <ExampleList examples={examples} isFetching={isFetching} />; } } ExamplesScreen.propTypes = { examples: PropTypes.array.isRequired, fetchExamples: PropTypes.func.isRequired, isFetching: PropTypes.bool.isRequired }; export const mapStateToProps = state => ({ examples: getExamples(state), isFetching: getIsFetching(state) }); export const mapDispatchToProps = dispatch => ({ fetchExamples: () => dispatch(fetchExamples()) }); export default connect(mapStateToProps, mapDispatchToProps)(ExamplesScreen); <file_sep>/src/store/Example/actions.js import { normalize } from 'normalizr'; import { createAction } from 'redux-actions'; import { example as exampleSchema } from '../schema'; export const fetchExamplesRequest = createAction('FETCH_EXAMPLES_REQUEST'); export const fetchExamplesSuccess = createAction('FETCH_EXAMPLES_SUCCESS'); export const fetchExamplesFailure = createAction('FETCH_EXAMPLES_FAILURE'); export const fetchExamples = () => (dispatch, getState, api) => { dispatch(fetchExamplesRequest()); return api.fetchExamples() .then(api.checkStatus) .then(response => normalize(response.data.examples, [exampleSchema])) .then(normalizedData => dispatch(fetchExamplesSuccess(normalizedData))) .catch(api.handleError(dispatch, fetchExamplesFailure)); }; <file_sep>/src/store/reducers.js import { combineReducers } from 'redux'; // Reducers import entities from './Entities/reducers'; import example from './Example/reducers'; const reducers = combineReducers({ entities, example }); export default reducers; <file_sep>/src/store/Example/endpoints.js import { instance } from '../api'; export const fetchExamples = () => instance().get('/examples'); <file_sep>/src/store/Example/reducers.js import { combineReducers } from 'redux'; import * as actions from './actions'; const isFetching = (state = false, action) => { switch (action.type) { case actions.fetchExamplesRequest.toString(): return true; case actions.fetchExamplesSuccess.toString(): case actions.fetchExamplesFailure.toString(): return false; default: return state; } }; const ids = (state = [], action) => { switch (action.type) { case actions.fetchExamplesSuccess.toString(): return action.payload.result; default: return state; } }; const reducers = combineReducers({ ids, isFetching }); export default reducers; <file_sep>/src/store/schema.js import { schema } from 'normalizr'; export const example = new schema.Entity('examples'); <file_sep>/tests/store/Example/reducers.test.js import reducers from '../../../src/store/Example/reducers'; import * as actions from '../../../src/store/Example/actions'; describe('initial state', () => { it('shape', () => { const expected = { ids: [], isFetching: false }; expect(reducers(undefined, {})).toEqual(expected); }); }); describe('fetchExamples', () => { it(actions.fetchExamplesRequest.toString(), () => { const state = { ids: [], isFetching: false }; const expected = { ids: [], isFetching: true }; expect(reducers(state, actions.fetchExamplesRequest())).toEqual(expected); }); it(actions.fetchExamplesFailure.toString(), () => { const state = { ids: [], isFetching: true }; const expected = { ids: [], isFetching: false }; expect(reducers(state, actions.fetchExamplesFailure())).toEqual(expected); }); it(actions.fetchExamplesSuccess.toString(), () => { const state = { ids: [], isFetching: true }; const expected = { ids: [1], isFetching: false }; const payload = { entities: { examples: { 1: { id: 1, name: 'Lorem' } } }, result: [1] }; expect(reducers(state, actions.fetchExamplesSuccess(payload))).toEqual(expected); }); }); <file_sep>/tests/store/Entities/reducers.test.js import reducers from '../../../src/store/Entities/reducers'; describe('initial state', () => { it('shape', () => { const expected = { examples: {} }; expect(reducers(undefined, {})).toEqual(expected); }); }); describe('cache', () => { it('ANY_OLD_TYPE', () => { const state = { examples: {} }; const expected = { examples: { 1: { id: 1, name: 'Lorem' } } }; const action = { type: 'ANY_OLD_TYPE', payload: { entities: { examples: { 1: { id: 1, name: 'Lorem' } } }, result: [1] } }; expect(reducers(state, action)).toEqual(expected); }); }); <file_sep>/tests/store/Example/actions.test.js import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import * as actions from '../../../src/store/Example/actions'; describe('fetchExamples', () => { const mock = new MockAdapter(axios); afterEach(() => mock.reset()); it('failure', () => { mock .onGet('/examples') .reply(500); const store = global.configureStore(); return store.dispatch(actions.fetchExamples()) .then(() => { const expected = [ { type: actions.fetchExamplesRequest.toString() }, { type: actions.fetchExamplesFailure.toString() } ]; expect(store.getActions()).toEqual(expected); }); }); it('success', () => { mock .onGet('/examples') .reply(200, { examples: [{ id: 1, name: 'Lorem' }] }); const store = global.configureStore(); return store.dispatch(actions.fetchExamples()) .then(() => { const expected = [ { type: actions.fetchExamplesRequest.toString() }, { type: actions.fetchExamplesSuccess.toString(), payload: { entities: { examples: { 1: { id: 1, name: 'Lorem' } } }, result: [1] } } ]; expect(store.getActions()).toEqual(expected); }); }); });
13085c2dd40c9de5df8b5ec1da1ebd8784f9c7fc
[ "JavaScript" ]
12
JavaScript
wearelighthouse/react-redux
047ce005f2f294dc86533632be96bbc13acd3152
548fc57e6ba15d80357c3ae12c8453ec83c2f969
refs/heads/main
<file_sep>#Input employee data such as name, enrollment Nunber, age, work experience in years val = input("Enter your name: ") print(val) <file_sep>#hackathon Build an attendance tracker Level 1:The client --Develop a client of ur choice(Android, web app,...) --It should be able to interact with the REST API and mark the attendance Level 2: The Bridge --Allow employees to login with credentials --Enabled the employees to mark their attendance (punch in/ punch out time) Level 3: The backend --Should consisit a database of employees --Employees can be added or removed by the admin --Attendance record will be stored here --The admon should be able to generate a report of attendance
8ad609bd5b5319742f4657f0e150f081a1e0e4a5
[ "Markdown", "Python" ]
2
Python
binghaw/23456
462d59ce4898c606821e97fcf06888b3754876a0
28d8e8c7ddbd30b6007b3ce0043954d5833a55ab
refs/heads/master
<file_sep>const getters = { count: state => state.app.count, name: state => state.user.name, }; export default getters; <file_sep>const path = require('path'); const HTMLWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack') const VueLoaderPlugin = require('vue-loader/lib/plugin'); // const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const CopyWebpackPlugin = require('copy-webpack-plugin'); const config = require('./config'); // 多页面的配置项 let HTMLPlugins = []; let Entries = {}; config.HTMLDirs.forEach(item => { let filename = `${item.page}`; if (item.dir) filename = `${item.dir}/${item.page}`; const htmlPlugin = new HTMLWebpackPlugin({ title: item.title, // 生成的html页面的标题 filename: filename, // 生成到dist目录下的html文件名称,支持多级目录(eg: `${item.page}/index.html`) template: path.resolve(__dirname, `../src/template/index.html`), // 模板文件,不同入口可以根据需要设置不同模板 chunks: [item.page, 'vendor'], // html文件中需要要引入的js模块,这里的 vendor 是webpack默认配置下抽离的公共模块的名称 }); HTMLPlugins.push(htmlPlugin); Entries[item.page] = path.resolve(__dirname, `../src/pages/${item.page}/index.js`); // 根据配置设置入口js文件 }); const env = process.env.BUILD_MODE.trim(); let ASSET_PATH = '/'; // dev 环境 // if (env === 'prod') ASSET_PATH = '//abc.com/static/'; // build 时设置成实际使用的静态服务地址 if (env === 'prod') ASSET_PATH = ''; // build 时设置成实际使用的静态服务地址 module.exports = { // entry: Object.assign({},{app:path.resolve(process.cwd(), './app.js')}, Entries), entry: Entries, output: { publicPath: ASSET_PATH, filename: 'js/[name].[hash:8].js', path: path.resolve(__dirname, '../dist'), }, module: { rules: [ { test: /\.vue$/, // 处理vue模块 use: 'vue-loader', }, { test: /\.js$/, //处理es6语法 exclude: /node_modules/, use: ['babel-loader'], }, ] }, resolve: { // 设置模块如何被解析 alias: { '@components': path.resolve(__dirname, '../src/components'), '@styles': path.resolve(__dirname, '../src/styles'), '@assets': path.resolve(__dirname, '../src/assets'), '@commons': path.resolve(__dirname, '../src/commons'), '@mixins': path.resolve(__dirname, '../src/pages/page.js'), '@vuex': path.resolve(__dirname, '../src/store'), }, extensions:['*','.css','.js','.vue'] }, plugins: [ new VueLoaderPlugin(), new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../public'), to: path.resolve(__dirname, '../dist'), ignore: ['*.html'] }, { from: path.resolve(__dirname, '../src/scripts/lib'), to: path.resolve(__dirname, '../dist') } ]), ...HTMLPlugins, // 利用 HTMLWebpackPlugin 插件合成最终页面 new webpack.DefinePlugin({ 'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH) // 利用 process.env.ASSET_PATH 保证模板文件中引用正确的静态资源地址 }) ] }; <file_sep>const user = { state: { name: '<NAME>!', }, mutations: { CHANGE_NAME: state => { state.name = 'hello webpack4-vue2-vuex!'; } }, actions: { changeName: ({commit}) => { commit('CHANGE_NAME'); } } }; export default user; <file_sep>// package.json中通过 --BUILD_MODE 指定当前执行的配置文件 const env = process.env.BUILD_MODE.trim(); module.exports = require(`./build/webpack.${env}.js`); <file_sep>const path = require('path'); const webpackBase = require('./webpack.base'); const webpackMerge = require('webpack-merge'); const config = require('./config'); module.exports = webpackMerge(webpackBase, { mode: 'development', module: { rules: [ { test: /\.css$/, // exclude: /node_modules/, use: [ 'vue-style-loader', 'css-loader', 'postcss-loader', ] }, { test: /\.scss$/, exclude: /node_modules/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader', 'postcss-loader', { loader: 'sass-resources-loader', options: { resources: path.resolve(__dirname, '../src/styles/lib/main.scss'), } } ] }, { test: /\.(js|vue)$/, enforce: 'pre', // 强制先进行 ESLint 检查 exclude: /node_modules|lib/, loader: 'eslint-loader', options: { // 启用自动修复 fix: true, // 启用警告信息 emitWarning: true, } }, { test: /\.(png|svg|jpg|gif)$/, // 处理图片 use: { loader: 'file-loader', // 解决打包css文件中图片路径无法解析的问题 options: { // 打包生成图片的名字 name: '[name].[hash:8].[ext]', // 图片的生成路径 outputPath: config.imgOutputPath, } } }, { test: /\.(woff|woff2|eot|ttf|otf)$/, // 处理字体 use: { loader: 'file-loader', options: { outputPath: config.fontOutputPath, } } } ] }, devServer: { contentBase: config.devServerOutputPath, port: 8999, overlay: { errors: true, warnings: true, }, open: true // 服务启动后 打开浏览器 } }); <file_sep>module.exports = { HTMLDirs: [ { page: 'login', title: '登录' }, { page: 'index', title: '首页' }, { page: 'list', title: '列表页', // dir: 'content' // 支持设置多级目录 }, { page: 'detail', title: '详情页' } ], cssPublicPath: '../', imgOutputPath: 'img/', fontOutputPath: 'font', cssOutputPath: './css/styles.css', devServerOutputPath: '../dist', }; <file_sep># 基于webpack4搭建的Vue多页面应用 ## 背景 该项目是为公司内部使用vue开发而准备的基于webpack4搭建的vue2多页应用基础框架 ## 需要了解的相关技术知识 webpack + vue + vuex + ElementUI + Sass + ES6 ## 安装与运行 本项目运行需要本机安装Node6.0以上版本。 命令行到此目录下运行: ``` npm install ``` 安装完成后,工程内会生成node_modules等相关依赖目录,继续运行: ``` npm run dev ``` 进入开发模式,自动打开浏览器并访问[http://localhost:8999](http://localhost:8999),并随时响应代码修改。 使用国内cnpm ``` npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install cnpm run dev ``` ## 目录结构说明 ``` project │ README.md │ webpack.config.js // webpack配置基础文件 │ .gitignore // 标注git提交需忽略的内容 │ package.json // 项目所需要的各种模块及项目的配置信息等重要信息 │ └───build │ │ config.js // 多文件及路径配置 │ │ webpack.base.js // 打包基础配置 │ │ webpack.dev.js // 开发打包配置 │ │ webpack.prod.js // 产品打包配置 │ └───src // 源码目录 │ │ assets // 静态文件集合,如静态图片等 │ │ components // 模块和组件 │ │ └───common │ │ headerNav.vue // 页面公共header │ │ sideBar.vue // 页面公共sidebar │ │ pages // 项目模板文件,会根据需要持续扩充 │ │ store // vuex │ │ styles // 存放样式 │ │ template // 项目模板文件 ``` <file_sep>// 引入基础配置 const path = require('path'); const webpackBase = require('./webpack.base'); // 引入 webpack-merge 插件 const webpackMerge = require('webpack-merge'); // 清理 dist 文件夹 const CleanWebpackPlugin = require('clean-webpack-plugin'); // js压缩、优化插件 const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // 抽取css extract-text-webpack-plugin不再支持webpack4,官方出了mini-css-extract-plugin来处理css的抽取 const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const config = require('./config'); // 多页面的配置项 // const ASSET_PATH = '//abc.com/static/'; // 线上静态资地址 const ASSET_PATH = ''; // 线上静态资地址 // 合并配置文件 module.exports = webpackMerge(webpackBase, { mode: 'production', module: { rules: [ { test: /\.css$/, // exclude: /node_modules/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader' ] }, { test: /\.scss$/, exclude: /node_modules/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader', 'postcss-loader', { loader: 'sass-resources-loader', options: { resources: path.resolve(__dirname, '../src/styles/lib/main.scss'), }, } ] }, { test: /\.(png|svg|jpg|gif)$/, // 处理图片 use: { loader: 'file-loader', // 解决打包css文件中图片路径无法解析的问题 options: { // 打包生成图片的名字 name: '[name].[hash:8].[ext]', // 图片的生成路径 outputPath: config.imgOutputPath, publicPath: ASSET_PATH } } }, { test: /\.(woff|woff2|eot|ttf|otf)$/, // 处理字体 use: { loader: 'file-loader', options: { outputPath: config.fontOutputPath, publicPath: ASSET_PATH } } } ] }, optimization: { splitChunks: { cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, name: 'vendor', chunks: 'all' } } }, minimizer: [ new UglifyJsPlugin({ // 压缩js uglifyOptions: { compress: { warnings: false, drop_debugger: false, drop_console: true } } }), new OptimizeCSSAssetsPlugin({ // 压缩css cssProcessorOptions: { safe: true } }) ] }, plugins: [ // 自动清理 dist 文件夹 new CleanWebpackPlugin(['dist'], { root: path.resolve(__dirname, '..'), verbose: true, //开启在控制台输出信息 dry: false, }), new MiniCssExtractPlugin({ filename: 'css/[name].[chunkhash:8].css' }) ] });
f3cc0162a68a3318cf126e78950a3a18dac4c2d8
[ "JavaScript", "Markdown" ]
8
JavaScript
zhaoboy/basic-vue-frame
a86dba6c9c641aedd89f0b61b89576e22e03a5a6
7a4e945555e3c613242e44d6fa5111d06750131c
refs/heads/master
<file_sep>print "Hello Changed World!"
e71f101d0fb77902318414687aa5c2db2f43851c
[ "Python" ]
1
Python
smanuguri/HelloWorld
81600125deecc499b1153485c32049b85c363750
6ffb1232f1a28a644df494f2467faa7e4f42a55a
refs/heads/master
<file_sep>這是一篇共同編輯的文件 # maskandfacedetect <file_sep>import numpy as np from cv2 import cv2 as cv from matplotlib import pyplot as plt face_cascade = cv.CascadeClassifier('haarcascade_eye.xml') img = cv.imread('D:\\giwawa.jpg') imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) pathf = 'D:\\haarcascade_eye.xml' face_cascade.load(pathf) faces = face_cascade.detectMultiScale(imgGray, 1.3, 5) for (x,y,w,h) in faces: cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) cv.namedWindow('img', cv.WINDOW_NORMAL) cv.imshow('img', img) cv.waitKey(0) cv.destroyAllWindows() face_cascade.load(pathf)
b6f40fc83dabb9b39c4a0249226bb08ac548c30c
[ "Markdown", "Python" ]
2
Markdown
Flyingdolar/maskandfacedetect
3aa02b92d8522ed7d9fe341d888ba75b44f9e75a
74f56778fc042d7687fe7156feca23b41f866848
refs/heads/master
<repo_name>Kerwin-Lo/MVC5Course<file_sep>/MVC5Course/Controllers/Client1Controller.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using MVC5Course.Models; namespace MVC5Course.Controllers { public class Client1Controller : Controller { private FabricsEntities db = new FabricsEntities(); // GET: Client1 public ActionResult Index(int creditRatingFilter=-1, string lastNameFilter="") { var ratings = (from p in db.Client select p.CreditRating).Distinct().OrderBy(p => p).ToList(); ViewBag.CreditRatingFilter = new SelectList(ratings); var lastNames = (from p in db.Client select p.LastName).Distinct().OrderBy(p => p).ToList(); ViewBag.LastNameFilter = new SelectList(lastNames); var client = db.Client.AsQueryable(); if (creditRatingFilter>=0) { client = client.Where(c => c.CreditRating == creditRatingFilter); } if (!String.IsNullOrEmpty(lastNameFilter)) { client = client.Where(c => c.LastName == lastNameFilter); } return View(client.Take(10).ToList()); } // GET: Client1/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Client client = db.Client.Find(id); if (client == null) { return HttpNotFound(); } return View(client); } // GET: Client1/Create public ActionResult Create() { ViewBag.OccupationId = new SelectList(db.Occupation, "OccupationId", "OccupationName"); return View(); } // POST: Client1/Create // 若要免於過量張貼攻擊,請啟用想要繫結的特定屬性,如需 // 詳細資訊,請參閱 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ClientId,FirstName,MiddleName,LastName,Gender,DateOfBirth,CreditRating,XCode,OccupationId,TelephoneNumber,Street1,Street2,City,ZipCode,Longitude,Latitude,Notes")] Client client) { if (ModelState.IsValid) { db.Client.Add(client); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.OccupationId = new SelectList(db.Occupation, "OccupationId", "OccupationName", client.OccupationId); return View(client); } // GET: Client1/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Client client = db.Client.Find(id); if (client == null) { return HttpNotFound(); } var sli = new List<SelectListItem>(); int i = 0; while (i < 10) { sli.Add(new SelectListItem() { Text = i.ToString(), Value = i.ToString() }); i++; } ViewBag.CreditRating = new SelectList(sli, "Value", "Text"); ViewBag.ddlCreditRating = new SelectList(sli, "Value", "Text"); ViewBag.OccupationId = new SelectList(db.Occupation, "OccupationId", "OccupationName", client.OccupationId); return View(client); } // POST: Client1/Edit/5 // 若要免於過量張貼攻擊,請啟用想要繫結的特定屬性,如需 // 詳細資訊,請參閱 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ClientId,FirstName,MiddleName,LastName,Gender,DateOfBirth,CreditRating,XCode,OccupationId,TelephoneNumber,Street1,Street2,City,ZipCode,Longitude,Latitude,Notes")] Client client) { if (ModelState.IsValid) { db.Entry(client).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.OccupationId = new SelectList(db.Occupation, "OccupationId", "OccupationName", client.OccupationId); return View(client); } // GET: Client1/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Client client = db.Client.Find(id); if (client == null) { return HttpNotFound(); } return View(client); } // POST: Client1/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Client client = db.Client.Find(id); db.Client.Remove(client); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>/MVC5Course/Controllers/ClientController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC5Course.Models; using MVC5Course.Models.ViewModels; namespace MVC5Course.Controllers { public class ClientController : BaseController { // GET: Client public ActionResult BatchUpdate() { GetClients(); return View(); } private void GetClients() { var result = db.Client.OrderByDescending(c => c.ClientId).Take(10); ViewData.Model = result; } [HttpPost] public ActionResult BatchUpdate(ClientBatchUpdateVM[] items) { if (ModelState.IsValid) { foreach (var item in items) { var c = db.Client.Find(item.ClientId); c.FirstName = item.FirstName; c.MiddleName = item.MiddleName; c.LastName = item.LastName; } db.SaveChanges(); return RedirectToAction("BatchUpdate"); } GetClients(); return View(); } } }<file_sep>/MVC5Course/ActionFilter/SharedViewBagAttribute.cs using System; using System.Web.Mvc; namespace MVC5Course.Controllers { public class SharedViewBagAttribute : ActionFilterAttribute { public string MyProperty { get; set; } private DateTime dt { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { dt = DateTime.Now; filterContext.Controller.ViewBag.Message = "Your application description page."; } public override void OnActionExecuted(ActionExecutedContext filterContext) { //base.OnActionExecuted(filterContext); filterContext.Controller.ViewBag.Message +="S:"+ dt.ToString("mm:ss") + " E:" + DateTime.Now.ToString("mm:ss"); } } } <file_sep>/MVC5Course/Controllers/EFController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity.Validation; using MVC5Course.Models; namespace MVC5Course.Controllers { public class EFController : BaseController { // GET: EF public ActionResult Index() { var all = db.Product.AsQueryable(); var result = all.Where(p=>p.Active==true && p.Is刪除==false).OrderByDescending(p => p.ProductId).Take(10); return View(result); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Product product) { if (ModelState.IsValid) { db.Product.Add(product); db.SaveChanges(); return RedirectToAction("Index"); } return View(product); } public ActionResult Edit(int id) { var result = db.Product.Find(id); return View(result); } [HttpPost] public ActionResult Edit(int id, Product product) { if (ModelState.IsValid) { var item = db.Product.Find(id); item.ProductName = product.ProductName; item.Price = product.Price; item.Stock= product.Stock; item.Active = product.Active; db.SaveChanges(); return RedirectToAction("Index"); } return View(product); } public ActionResult Details(int id) { var result = db.Database.SqlQuery<Product>("SELECT * FROM dbo.Product WHERE ProductId=@p0", id).FirstOrDefault(); return View(result); } public ActionResult Delete(int id) { var product = db.Product.Find(id); //foreach (var p in product.OrderLine.ToList()) //{ // db.OrderLine.Remove(p); //} //db.OrderLine.RemoveRange(product.OrderLine); //db.Product.Remove(product); product.Is刪除 = true; try { db.SaveChanges(); } catch (DbEntityValidationException ex) { throw ex; } return RedirectToAction("Index"); } } }<file_sep>/MVC5Course/Models/ViewModels/ProductListSearchVM.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace MVC5Course.Models.ViewModels { /// <summary> /// ListProductQuery /// </summary> public class ProductListSearchVM : IValidatableObject { public ProductListSearchVM() { this.s1 = 0; this.s1 = 999; } public string q { get; set; } public int s1 { get; set; } public int s2 { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (this.s1 < this.s2) { yield return new ValidationResult("庫存資料篩選條件錯誤", new string[] { "s1", "s2" }); } } } }
3a23039476bd2a75c9a0493a54282c0b60488865
[ "C#" ]
5
C#
Kerwin-Lo/MVC5Course
3df20638d8693e5d6879000b37084af38f0d527b
9316a93b70347ec24ca23467ca4ac8bdc13c15ca
refs/heads/master
<repo_name>philou73/mybooks<file_sep>/src/app/services/auth.service.ts import { Injectable } from '@angular/core'; import * as firebase from 'firebase'; @Injectable() export class AuthService { constructor() { } //On crée un nouvel utilisateur à l'aide de firebase.auth(), et on retourne une Promise() car c'est en asynchrone createNewUser(email: string, password: string) { return new Promise( (resolve, reject) => { firebase.auth().createUserWithEmailAndPassword(email, password).then( () => { resolve(); }, (error) => { reject(error); } ); } ); } //Pour se connecter, on gère aussi une Promise en appelant la méthode asynchrone de firebase.auth() signInUser(email: string, password: string){ return new Promise( (resolve, reject) => { firebase.auth().signInWithEmailAndPassword(email, password).then( () => { resolve(); }, (error) => { reject(error); } ); } ); } // Déconnexion simple, on n'attend pas le retour de firebase.auth(), et on l'applique sur le user connecté uniquement signOutUser() { firebase.auth().signOut(); } } <file_sep>/src/app/services/book.service.ts import { Injectable } from '@angular/core'; import { Book } from '../models/book.model'; import { Subject } from 'rxjs/Subject'; import * as firebase from 'firebase'; import { DataSnapshot } from 'firebase/database'; @Injectable() export class BookService { // On crée notre tableau de livres books: Book[] = []; // On s'abonne à la mise à jour des livres bookSubject = new Subject<Book[]>(); // Fonction pour prévenir tous les abonnés que les livres ont été mis à jour emitBooks() { this.bookSubject.next(this.books); } // Fonction de mise à jour des livres saveBooks(){ firebase.database().ref('/books').set(this.books); } constructor() { //Il faut appeler une première fois la méthode getBooks pour déclencher l'écoute de FireBase this.getBooks(); } // Récupération de tous les livres, avec la méthode .on qui va s'exécuter à chaque fois que la base de données sera modifiée getBooks(){ console.log("On est dans BookService.getBooks()"); firebase.database().ref('/books') .on('value', (data: DataSnapshot) => { this.books = data.val ? data.val() : []; this.emitBooks(); console.log("On vient de récupérer la liste"); } ); } // Récupération d'un seul livre, avec une Promise() getSingleBook(id: number){ return new Promise( (resolve, reject) => { firebase.database().ref('/books/'+id).once('value').then( (data: DataSnapshot) => { resolve(data.val()); }, (error) => { reject(error); } ); } ); } // Création d'un nouveau livre createBook(book: Book) { this.books.push(book); this.saveBooks(); this.emitBooks(); } // Suppression d'un livre removeBook(book: Book) { // On traite l'existence d'une photo, qu'il faut supprimer if(book.photo){ const storageRef = firebase.storage().refFromURL(book.photo); storageRef.delete().then( () => { console.log("Photo removed : " + book.photo); }, (error) => { console.log("Erreur lors de la suppresion de " + book.photo + " : " + error); } ); } const bookIndexToRemove = this.books.findIndex( (bookEl) => { if(bookEl === book) { return true; } } ); this.books.splice(bookIndexToRemove, 1); this.saveBooks(); this.emitBooks(); } // Upload d'une image à partir d'un fichier uploadFile (file: File) { return new Promise( (resolve, reject) => { const almostUniqueFileName = Date.now().toString(); //On crée un identifiant "unique" basé sur l'heure en millisecondes const upload = firebase.storage().ref() .child('images/' + almostUniqueFileName + file.name).put(file); //On définit la cible de l'upload et on déclenche // Désormais, on écoute le changement d'état de l'upload upload.on(firebase.storage.TaskEvent.STATE_CHANGED, () => { console.log('Chargement...'); }, (error) => { console.log('Erreur pendant le chargement : ' + error); }, () => { resolve(upload.snapshot.downloadURL); // On récupére l'URL de l'image } ); } ); } }
b3bd0e5d9dd6f5504e66817a8a8890944f74d3ec
[ "TypeScript" ]
2
TypeScript
philou73/mybooks
7b3708b2f8abda76cf7751ea9130793376f7bab7
b3ad2770a034cfd68504357772ac33c4176c1d34
refs/heads/master
<file_sep># Rate It - Online Product Review Download MAMP Server (https://www.mamp.info/en/downloads/) Load the SQL dump file in MAMP. Register as a normal user. Give reviews to any of the product listed. You can add/remove any product to your wishlist. Register a user as an Admin by inserting an entry in USERS table with roleid as 2. Login as an admin. You can add/remove the Categories/Subcategories/Product listing. If the user add a particular product to the wishlist and an admin removes it in product listing, then the user can't see it in his/her Wishlist sections.<file_sep>-- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Dec 06, 2017 at 01:54 PM -- Server version: 5.6.34-log -- PHP Version: 7.1.5 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `productreview` -- -- -------------------------------------------------------- -- -- Table structure for table `brand` -- CREATE TABLE `brand` ( `id` int(11) NOT NULL, `name` varchar(60) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `brand` -- INSERT INTO `brand` (`id`, `name`) VALUES (20, 'ALCATEL'), (18, 'APPLE'), (30, 'aqewuriy'), (23, 'ASUS'), (28, 'aswin'), (1, 'AUDI'), (13, 'BEATS'), (21, 'BLU'), (2, 'BMW'), (6, 'BSA'), (9, 'CAMPAGNOLO'), (3, 'DODGE'), (10, 'GARMIN'), (8, 'HERCULES'), (24, 'INSIGNIA'), (14, 'JBL'), (31, 'krishna'), (5, 'LANCER'), (19, 'LG'), (4, 'MARUTI'), (16, 'MICROSOFT XBOX'), (15, 'MONSTER'), (22, 'MOTOROLA'), (26, 'PANASONIC'), (11, 'SAMSUNG'), (27, 'SHARP'), (12, 'SONY'), (17, 'SONY PLAYSTATION'), (25, 'TCL'), (7, 'THUNDERBIRD'), (29, 'xmvbakj'); -- -------------------------------------------------------- -- -- Table structure for table `category` -- CREATE TABLE `category` ( `id` int(11) NOT NULL, `name` varchar(60) NOT NULL, `deletedyn` varchar(1) NOT NULL, `image` varchar(64) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `category` -- INSERT INTO `category` (`id`, `name`, `deletedyn`, `image`) VALUES (1, 'Car', '', 'audia8.jpg'), (2, 'Cycle', '', ''), (3, 'TV', '', ''), (4, 'Electronics', '', ''), (5, 'Mobiles', '', ''); -- -------------------------------------------------------- -- -- Table structure for table `features` -- CREATE TABLE `features` ( `id` int(11) NOT NULL, `name` varchar(60) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `features` -- INSERT INTO `features` (`id`, `name`) VALUES (20, ' brake wires'), (5, 'A backup camera'), (16, 'a basket on the front '), (19, 'a covered chain'), (18, 'a lock and chain'), (17, 'adjustable seat '), (11, 'android'), (14, 'athletic'), (4, 'Automatic emergency braking'), (10, 'Automatic high beams'), (7, 'Blind-spot monitoring'), (8, 'Bluetooth connectivity'), (1, 'Comfortable seats'), (12, 'czxcvasidfyis'), (23, 'easy mount and dismount'), (3, 'Forward-collision warning'), (9, 'Head-up displays'), (2, 'Power driver seat '), (21, 'protect clothing'), (6, 'Rear cross-traffic alert'), (24, 'safety bell'), (22, 'step-through frame '), (15, 'three gears'), (13, 'vcamnsdfqwehriqwer'); -- -------------------------------------------------------- -- -- Table structure for table `product` -- CREATE TABLE `product` ( `id` int(11) NOT NULL, `name` varchar(1000) NOT NULL, `categoryid` int(11) NOT NULL, `subcategoryid` int(11) NOT NULL, `brandid` int(11) NOT NULL, `price` decimal(10,0) NOT NULL, `date` date NOT NULL, `content` longtext NOT NULL, `deletedyn` varchar(1) NOT NULL, `images` varchar(400) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `product` -- INSERT INTO `product` (`id`, `name`, `categoryid`, `subcategoryid`, `brandid`, `price`, `date`, `content`, `deletedyn`, `images`) VALUES (1, 'AUDI A8', 1, 1, 1, 2000, '2017-11-27', 'The Audi A8 is a four-door, full-size, luxury sedan manufactured and marketed by the German automaker Audi since 1994. Succeeding the Audi V8, and now in its third generation, the A8 has been offered with both front- or permanent all wheel drive and in short and long wheelbase variants. The first two generations employed the Volkswagen Group D platform, with the current generation deriving from the MLB platform. After the original models 1994 release, Audi released the second generation in late 2002, and the third and current iteration in late 2009.', '', 'audia8.jpg'), (2, 'BMW i8', 1, 1, 2, 2500, '2017-11-27', 'The BMW i8 is a plug-in hybrid sports car developed by BMW. The i8 is part of BMW electric fleet Project i being marketed as a new sub-brand, BMW i. The 2015 model year BMW i8 has a 7.1 kWh lithium-ion battery pack that delivers an all-electric range of 37 km (23 mi) under the New European Driving Cycle. Under the United States Environmental Protection Agency cycle, the range in EV mode is 24 km (15 mi) with a small amount of gasoline consumption. Its design is heavily influenced by the M1 Hommage Concept car, which in turn pays homage to BMW last production sports car prior to the i8: the BMW M1.', '', 'bmwi8.jpg'), (3, '<NAME>', 1, 2, 3, 1500, '2017-11-27', 'The Dodge Charger is a brand of automobile marketed by Dodge. The first Charger was a show car in 1964. There have been several different production Chargers, built on three different platforms and sizes. In the U.S., the Charger nameplate has been used on subcompact hatchbacks, full-sized sedans, and personal luxury coupes. The current version is a four-door sedan.', '', 'dodgecharger.jpg'), (4, '<NAME>', 1, 3, 4, 1000, '2017-11-27', 'The Suzuki Baleno is a compact car produced by the Japanese manufacturer Suzuki since 2015. Prior to this, the Baleno name had been applied to the Suzuki Cultus Crescent in numerous export markets.\r\nThe car was unveiled at the Frankfurt Motor Show in September 2015,[3][4] and was launched in India on October 24, 2015 and in Japan on March 9, 2016.[5] It became available in Europe in April 2016[5] and in Indonesia on August 10, 2017 at the 25th Gaikindo Indonesia International Auto Show.', '', 'marutibaleno.jpg'), (5, '<NAME>', 1, 4, 5, 2000, '2017-11-27', 'The Mitsubishi Lancer is a compact car produced by the Japanese manufacturer Mitsubishi since 1973. It has been marketed as the Colt Lancer, Dodge/Plymouth Colt, Chrysler Valiant Lancer, Chrysler Lancer, Eagle Summit, Hindustan Lancer, Soueast Lioncel, and Mitsubishi Mirage in various countries at different times, and has been sold as the Mitsubishi Galant Fortis in Japan since 2007. It has also been sold as Mitsubishi Lancer Fortis in Taiwan with a different facelift than the Galant Fortis. In Japan, it was sold at a specific retail chain called Car Plaza.', '', 'lancer.jpg'), (9, 'camnsdf', 1, 1, 30, 123, '2017-12-03', 'hkasjdfhk', 'y', ''), (10, 'kg', 1, 1, 31, 123, '2017-12-03', 'aswin', '', 'kg.jpg'), (11, 'MUKESH CYCLE', 2, 8, 6, 2000, '2017-12-19', '', '', ''), (12, 'Hercules 1.0', 2, 8, 8, 500, '2017-11-14', 'They have a light frame, medium gauge wheels, and derailleur gearing, and feature straight or curved-back, touring handlebars for more upright riding and a hybrid with all the accessories necessary for bicycle touring - mudguards, pannier rack, lights etc', '', 'hercules.jpg'), (13, 'BSA bicycle', 2, 8, 6, 300, '2017-12-04', 'It designed specifically for commuting over short or long distances. It typically features derailleur gearing, 700c wheels with fairly light 1.125-inch (28 mm) tires, a carrier rack, full fenders, and a frame with suitable mounting points for attachment of various load-carrying baskets or panniers. It sometimes, though not always, has an enclosed chainguard to allow a rider to pedal the bike in long pants without entangling them in the chain', '', 'bsa.jpg'), (14, 'Hercules 2.0', 2, 8, 6, 200, '2017-11-20', 'it optimized for the rough-and-tumble of urban commuting. The city bike differs from the familiar European city bike in its mountain bike heritage', '', 'bsa2.jpg'), (15, 'Hercules 3.0', 2, 8, 8, 600, '2017-12-04', 'It usually features mountain bike-sized (26-inch) wheels, a more upright seating position, and fairly wide 1.5 - 1.95-inch (38 – 50 mm) heavy belted tires designed to shrug off road hazards commonly found in the city,', '', 'her1.jpg'), (16, 'Hercules 4.0', 2, 8, 8, 1000, '2017-12-01', 'Using a sturdy welded chromoly or aluminum frame derived from the mountain bike, the city bike is more capable at handling urban hazards such as deep potholes, drainage grates, and jumps off city curbs.', '', 'her2.jpg'), (17, 'Hercules 5.0', 2, 8, 8, 800, '2017-12-05', 'City bikes are designed to have reasonably quick, yet solid and predictable handling, and are normally fitted with full fenders for use in all weather conditions.', '', 'her3.jpg'), (18, 'Hercules 6.0', 2, 8, 8, 1800, '2017-12-01', 'A few city bikes may have enclosed chainguards, while others may be equipped with suspension forks, similar to mountain bikes. City bikes may also come with front and rear lighting systems for use at night or in bad weather.', '', 'her4.jpg'), (19, 'BSA Bicycle 2.0', 2, 8, 6, 700, '2017-12-04', 'Comfort bikes typically incorporate such features as front suspension forks, seat post suspension with wide plush saddles, and drop-center, angled North Road style handlebars designed for easy reach while riding in an upright position.', '', 'bsa2.jpg'), (20, 'BSA bicycle 3.0', 2, 8, 6, 300, '2017-12-03', ' kind of cargo bicycle designed for carrying loads on a platform rack attached to the fork', '', 'bsa4.jpg'), (21, 'BSA bicycle 4.0', 2, 8, 6, 600, '2017-12-05', 'a type of bicycle (specifically a type of longbike) with a longer than usual frame wheelbase at the rear compared to a standard utility bicycle.', '', 'bsa5.jpg'), (22, 'BSA bicycle 6.0', 2, 8, 6, 200, '2017-11-13', 'designed for off-road cycling. All mountain bicycles feature sturdy, highly durable frames and wheels, wide-gauge treaded tires, and cross-wise handlebars to help the rider resist sudden jolts.', '', 'bsa7.jpg'), (23, 'Hercules 7.0', 2, 8, 8, 1500, '2017-12-08', 'Mountain bicycle gearing is often very wide-ranging, from very low ratios to mid ratios, typically with 16 to 28 gears, although some riders prefer the mechanical simplicity and ease of maintenance of single-speed mountain bikes.', '', 'her8.jpg'), (24, 'Hercules 8.0', 2, 8, 8, 800, '2017-12-04', 'heavy framed bicycles designed for comfort, with curved back handlebars, padded seats, and balloon tires. They are also called beach bikes or boulevardiers and are designed for comfortable travel', '', 'her9.jpg'), (25, 'Hercules 10.0', 2, 8, 6, 750, '2017-12-04', 'Cruisers were the bicycle standard in the United States from the 1930s until the 1950s. The traditional cruiser is single-speed with coaster brakes, but modern cruisers come with three to seven speeds. Aluminum frames have recently been used in Cruiser construction, lowering weight. Cruisers typically have minimal gearing and are often available for rental at beaches and parks which feature flat terrain.', '', 'her10.jpg'), (26, 'BSA bicycle 10.0', 2, 8, 6, 300, '2017-12-04', 'transmission used either to power the vehicle unassisted, or to assist with pedaling. Since it always retains both pedals and a discrete connected drive for rider-powered propulsion, the motorized bicycle is in technical terms a true bicycle, albeit a power-assisted one. However, for purposes of governmental licensing and registration requirements, the type may be legally defined as a motor vehicle, motorcycle, moped, or a separate class of hybrid vehicle. Powered by a variety of engine types and designs, the motorized bicycle formed the prototype for what would later become the motorcycle.', '', 'bsa11.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `product_features` -- CREATE TABLE `product_features` ( `id` int(11) NOT NULL, `productid` int(11) NOT NULL, `featureid` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `product_features` -- INSERT INTO `product_features` (`id`, `productid`, `featureid`) VALUES (1, 1, 1), (2, 1, 2), (3, 1, 3), (4, 2, 7), (5, 2, 8), (6, 2, 4), (7, 3, 3), (8, 3, 10), (9, 3, 9), (10, 4, 1), (11, 4, 2), (12, 4, 10), (13, 5, 6), (14, 5, 5), (15, 5, 9), (17, 9, 13), (18, 10, 14), (19, 11, 14), (20, 11, 11), (21, 13, 16), (22, 20, 17), (23, 13, 18), (24, 21, 18), (25, 12, 16), (26, 14, 23), (27, 15, 20), (28, 16, 10), (29, 17, 21), (30, 18, 24), (31, 24, 4), (32, 23, 22), (33, 19, 17), (34, 22, 20), (35, 26, 18), (36, 21, 15), (37, 15, 21), (38, 17, 19), (39, 25, 16), (40, 18, 17); -- -------------------------------------------------------- -- -- Table structure for table `review` -- CREATE TABLE `review` ( `id` int(11) NOT NULL, `productid` int(11) NOT NULL, `userid` int(11) NOT NULL, `rating` decimal(10,0) NOT NULL, `feedback` longtext NOT NULL, `datereviewed` datetime NOT NULL, `deletedyn` varchar(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `review` -- INSERT INTO `review` (`id`, `productid`, `userid`, `rating`, `feedback`, `datereviewed`, `deletedyn`) VALUES (1, 1, 1, 1, '0', '2017-11-05 00:00:00', ''), (2, 2, 1, 5, 'Very Good!', '2017-11-15 00:00:00', ''), (3, 3, 3, 1, 'Poor', '2017-11-29 00:00:00', ''), (4, 4, 3, 3, 'Okayish', '2017-11-11 00:00:00', ''), (5, 5, 4, 4, 'Good!', '2017-11-21 00:00:00', ''), (6, 1, 3, 1, '0', '2017-11-04 00:00:00', ''), (7, 1, 2, 3, 'Finally I got it workedddddddddd', '2017-12-06 02:58:27', ''), (9, 5, 3, 3, 'Looks good', '0000-00-00 00:00:00', ''), (10, 1, 15, 4, '<NAME>rrrrrrrrrrrqwasasasas', '2017-12-02 11:08:55', 'Y'), (11, 1, 14, 2, '<NAME>', '2017-12-02 10:35:18', ''), (12, 5, 14, 3, 'saassasa', '2017-12-02 00:00:00', ''), (13, 2, 14, 3, 'asasssssssssssssssssssss', '2017-12-02 00:00:00', ''), (14, 4, 14, 3, 'ssssssssssssssssssssssssssssssss', '0000-00-00 00:00:00', ''), (20, 1, 16, 2, 'nmbasdft435', '2017-12-03 09:36:31', ''), (21, 10, 16, 4, 'jhgjhgjgkjh', '2017-12-03 02:30:00', ''), (22, 11, 2, 4, 'CHeckingg it form me', '2017-12-04 00:00:00', ''), (24, 1, 5, 5, 'bu firsat icin tesekkurler\r\n', '2017-12-06 00:00:00', ''); -- -------------------------------------------------------- -- -- Table structure for table `roles` -- CREATE TABLE `roles` ( `id` int(11) NOT NULL, `rolename` varchar(400) NOT NULL, `adminrights` varchar(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `roles` -- INSERT INTO `roles` (`id`, `rolename`, `adminrights`) VALUES (1, 'user', 'N'), (2, 'admin', 'Y'); -- -------------------------------------------------------- -- -- Table structure for table `subcategory` -- CREATE TABLE `subcategory` ( `id` int(11) NOT NULL, `categoryid` int(11) NOT NULL, `name` varchar(60) NOT NULL, `deletedyn` varchar(1) NOT NULL, `image` varchar(64) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `subcategory` -- INSERT INTO `subcategory` (`id`, `categoryid`, `name`, `deletedyn`, `image`) VALUES (1, 1, 'Luxury car', '', ''), (2, 1, 'Compact car', '', ''), (3, 1, 'Economy car', '', ''), (4, 1, 'Roadster', '', ''), (5, 1, 'Cargo van', '', ''), (6, 2, 'Tandem', '', ''), (7, 2, 'GEAR CYCLE', '', ''), (8, 2, 'BICYCLE', '', ''), (9, 2, 'Tricycle', '', ''), (10, 3, 'LED TV', '', ''), (11, 3, 'LCD TV', '', ''), (12, 3, 'SMART TV', '', ''), (13, 3, 'Plasma Display Panels', '', ''), (14, 3, 'Digital Light Processing', '', ''), (15, 3, 'Cathode ray tube', '', ''), (16, 4, 'HEADPHONES', '', ''), (17, 4, 'EARPHONES', '', ''), (18, 4, 'SPEAKER', '', ''), (19, 4, 'SMARTWATCH', '', ''), (20, 4, 'MOUSE', '', ''), (31, 5, 'Camera Phones', '', ''), (32, 5, 'Smart Phones', '', ''), (33, 5, 'Music Phones', '', ''), (34, 5, '4G PHONES', '', ''), (35, 5, 'TABLET PHONE', '', ''), (41, 1, 'kg', '', 'kg.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(60) NOT NULL, `fname` varchar(400) NOT NULL, `lname` varchar(400) NOT NULL, `password` varchar(400) NOT NULL, `email` varchar(400) NOT NULL, `roleid` int(11) NOT NULL, `review_count` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `fname`, `lname`, `password`, `email`, `roleid`, `review_count`) VALUES (1, 'mukesh', 'mukesh', 'g s', '<PASSWORD>', '<EMAIL>', 1, 0), (2, 'mukesh1', 'm', 'm', '$2y$12$k3O7grv1quHyJ5mMbFCopexsWb5tIfBtthH8wb/EijgkoGhi6g9x.', 'a@a.c', 1, 0), (3, 'mukesh123', 'm', 'm', '$2y$12$T1HdZyuKir6ju4cyP5jrNuMzmQO6tZTn4SKETL8JSPykdljT/pV7y', '<EMAIL>', 1, 0), (4, 'mukeshabc', 'mukesh', 'kumar', '$2y$12$sW/2IDdSjxMws05CwTnBPeiCEvQIRkewfk706VBSXvnT1roWDzTqu', '<EMAIL>', 1, 0), (5, 'mukesh456', 'mukesh', 'kumar', '$2y$12$N11yTZuLDmi6e22xZaQ9OuA3cWBr.zksubZmECbziExhlw8ExwouC', '<EMAIL>', 1, 0), (6, '1234mukesh', 'mukesh', 'kumar', '$2y$12$35WCT6odyh5p5n4YOBBOvOCjL5je1DOR4QblkWIDQf8atxYn39VwG', '<EMAIL>', 1, 0), (7, 'jagsajgsasg', 'as', 'j', '$2y$12$OHX3H4/riK2Ah.Vel5Jecuicl0xu26g5IPR5E5n5As6iXce7LH3TK', '<EMAIL>', 1, 0), (8, 'Mukeshcheck', 'M', 'm', '$2y$12$lOFsWIx2TG8Q1XXcSIomeuISuiXNUeAkHyb.nkZpiO7JhWS8rY6fq', '<EMAIL>', 1, 0), (9, 'checking', 'm', 'm', '$2y$12$BOsAwvxilUpc5bkOmxwyku0FxWVmNiupFSvHCI1GmGtts1nnn94Zi', '<EMAIL>', 1, 0), (12, 'check123', 'm', 'm', '$2y$12$EDqjFyZyz1FOljpPPLb6BeoG0jP2aD0t3OIBsDf8DrNyubyY4aYwS', '<EMAIL>', 1, 0), (13, 'firstuuchecking', 'm', 'm', '$2y$12$ZpJYIgO8DplK28VtdE6aneOWhBzs43jrUQ05hm4T0JbGYdRzlBGZC', '<EMAIL>', 1, 0), (14, 'mukesh1234', 'm', 'm', '$2y$12$YGOYm18i7bKE9RqPeE80MO2WV.gxOFoqYprB3i58FpGOJ6sbIkiGi', '<EMAIL>', 1, 0), (15, 'kgaswin', 'm', 'm', '$2y$12$LSNpxjB8gpI1semE.Sj6OOZfaBkGegPmv9j2bcxfOMG3aa9ILU5LW', '<EMAIL>', 1, 0), (16, 'kgaswin93', 'aswin', 'asdjdfh', '$2y$12$zrA1zdHDZ2tZhoG2HJ6Tb.vAwUnrwy/2ALYwnB0ePXMDGqCEvNHnG', '<EMAIL>', 2, 0); -- -------------------------------------------------------- -- -- Table structure for table `wishlist` -- CREATE TABLE `wishlist` ( `id` int(11) NOT NULL, `userid` int(11) NOT NULL, `productid` int(11) NOT NULL, `deletedyn` varchar(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `wishlist` -- INSERT INTO `wishlist` (`id`, `userid`, `productid`, `deletedyn`) VALUES (3, 2, 3, ''), (4, 2, 4, ''), (5, 2, 5, ''), (9, 15, 1, ''), (14, 2, 1, ''); -- -- Indexes for dumped tables -- -- -- Indexes for table `brand` -- ALTER TABLE `brand` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- Indexes for table `category` -- ALTER TABLE `category` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- Indexes for table `features` -- ALTER TABLE `features` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- Indexes for table `product` -- ALTER TABLE `product` ADD PRIMARY KEY (`id`), ADD KEY `brandid` (`brandid`), ADD KEY `categoryid` (`categoryid`), ADD KEY `subcategoryid` (`subcategoryid`); -- -- Indexes for table `product_features` -- ALTER TABLE `product_features` ADD PRIMARY KEY (`id`), ADD KEY `featureid` (`featureid`), ADD KEY `productid` (`productid`); -- -- Indexes for table `review` -- ALTER TABLE `review` ADD PRIMARY KEY (`id`), ADD KEY `userid` (`userid`), ADD KEY `productid_2` (`productid`), ADD KEY `userid_2` (`userid`); -- -- Indexes for table `roles` -- ALTER TABLE `roles` ADD PRIMARY KEY (`id`); -- -- Indexes for table `subcategory` -- ALTER TABLE `subcategory` ADD PRIMARY KEY (`id`), ADD KEY `categoryid` (`categoryid`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD KEY `roleid` (`roleid`); -- -- Indexes for table `wishlist` -- ALTER TABLE `wishlist` ADD PRIMARY KEY (`id`), ADD KEY `productid` (`productid`), ADD KEY `userid` (`userid`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `brand` -- ALTER TABLE `brand` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=32; -- -- AUTO_INCREMENT for table `category` -- ALTER TABLE `category` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `features` -- ALTER TABLE `features` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; -- -- AUTO_INCREMENT for table `product` -- ALTER TABLE `product` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27; -- -- AUTO_INCREMENT for table `product_features` -- ALTER TABLE `product_features` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=41; -- -- AUTO_INCREMENT for table `review` -- ALTER TABLE `review` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; -- -- AUTO_INCREMENT for table `roles` -- ALTER TABLE `roles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `subcategory` -- ALTER TABLE `subcategory` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=42; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; -- -- AUTO_INCREMENT for table `wishlist` -- ALTER TABLE `wishlist` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- Constraints for dumped tables -- -- -- Constraints for table `product` -- ALTER TABLE `product` ADD CONSTRAINT `product_ibfk_1` FOREIGN KEY (`brandid`) REFERENCES `brand` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `product_ibfk_2` FOREIGN KEY (`categoryid`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `product_ibfk_3` FOREIGN KEY (`subcategoryid`) REFERENCES `subcategory` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `product_features` -- ALTER TABLE `product_features` ADD CONSTRAINT `product_features_ibfk_1` FOREIGN KEY (`featureid`) REFERENCES `features` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `product_features_ibfk_2` FOREIGN KEY (`productid`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `review` -- ALTER TABLE `review` ADD CONSTRAINT `review_ibfk_1` FOREIGN KEY (`productid`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `review_ibfk_2` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `subcategory` -- ALTER TABLE `subcategory` ADD CONSTRAINT `subcategory_ibfk_1` FOREIGN KEY (`categoryid`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `users` -- ALTER TABLE `users` ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`roleid`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `wishlist` -- ALTER TABLE `wishlist` ADD CONSTRAINT `wishlist_ibfk_1` FOREIGN KEY (`productid`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `wishlist_ibfk_2` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
ce69749399ad854b6d453d755be339f9e5750b54
[ "Markdown", "SQL" ]
2
Markdown
mukesh2249/Rate-It
ac2c124c014dbffb0f8ebb35adeff8729d76b5c8
eb84a9bc572135a9c7b950aa8d5dba77dd499e47
refs/heads/master
<file_sep>using InmoCRM.Models; using InmoCRM.Repositories.Config; using InmoCRM.Repositories.Crud; namespace InmoCRM.Repositories.Impl { public class AssetsRepositoryImpl : Repository<Asset, InmoCRMContext>, IAssetsRepository { public AssetsRepositoryImpl(InmoCRMContext context) : base(context) { } } } <file_sep>using InmoCRM.Models.Crud; using InmoCRM.Repositories.Crud; using System.Collections.Generic; using System.Threading.Tasks; namespace InmoCRM.Services.Crud { public abstract class CrudService<TEntity, TRepository> : ICrudService<TEntity> where TEntity : class, IEntity where TRepository : class, IRepository<TEntity> { public readonly IRepository<TEntity> repository; public CrudService(IRepository<TEntity> repository) { this.repository = repository; } public Task<TEntity> Add(TEntity entity) { return this.repository.Add(entity); } public Task<TEntity> Delete(int id) { return this.repository.Delete(id); } public Task<TEntity> Get(int id) { return this.repository.Get(id); } public Task<List<TEntity>> GetAll() { return this.repository.GetAll(); } public Task<TEntity> Update(TEntity entity) { return this.repository.Update(entity); } } } <file_sep>using System; namespace InmoCRM.Api.Dtos { public record AssetDto(int Id, string Reference, string Description, decimal Price, DateTimeOffset CreatedAt); } <file_sep>using InmoCRM.Models; using InmoCRM.Repositories; using InmoCRM.Services.Crud; namespace InmoCRM.Services.Impl { public class AssetsServiceImpl : CrudService<Asset, IAssetsRepository>, IAssetsService { public AssetsServiceImpl(IAssetsRepository repository) : base(repository) { } } } <file_sep>using InmoCRM.Models; using InmoCRM.Services; using Microsoft.AspNetCore.Mvc; namespace InmoCRM.Api.Controllers { [Route("api/[controller]")] [ApiController] public class AssetsController : CrudController<Asset, IAssetsService> { public AssetsController(IAssetsService service) : base(service) { } } } <file_sep>using InmoCRM.Models; using InmoCRM.Repositories.Crud; namespace InmoCRM.Repositories { public interface IAssetsRepository : IRepository<Asset> { } } <file_sep>using InmoCRM.Models; using Microsoft.EntityFrameworkCore; #nullable disable namespace InmoCRM.Repositories.Config { public partial class InmoCRMContext : DbContext { public InmoCRMContext() { } public InmoCRMContext(DbContextOptions<InmoCRMContext> options) : base(options) { } public virtual DbSet<Asset> Assets { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseSqlServer("Server=localhost; Database=InmoCRM; User=sa; Password=<PASSWORD>;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS"); modelBuilder.Entity<Asset>(entity => { entity.ToTable("Asset"); entity.Property(e => e.Id) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Description) .IsRequired() .HasColumnType("text"); entity.Property(e => e.Price).HasColumnType("decimal(18, 0)"); entity.Property(e => e.Reference) .IsRequired() .HasMaxLength(50) .IsUnicode(false); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } } <file_sep>using InmoCRM.Models; using InmoCRM.Services.Crud; namespace InmoCRM.Services { public interface IAssetsService : ICrudService<Asset> { } } <file_sep>using InmoCRM.Api.Dtos; using InmoCRM.Models; namespace InmoCRM.Api.Extensions { public static class AssetExtensions { public static AssetDto AsDto(this Asset asset) { return new AssetDto( asset.Id, asset.Reference, asset.Description, asset.Price, asset.CreatedAt ); } } }
0cfd2c44592da5081c857a1301f6fd0ac5f781b8
[ "C#" ]
9
C#
jordiDevel-dotnet/InmoCRM
7ee803c4d7fdb277e87a82b0c655a446d912495a
685f7eaeefbe6acf2c95cab90e3f5af7a9d3f18a
refs/heads/master
<repo_name>sergeyplis/Causality-Research<file_sep>/mytools.py #collection of helper functions from itertools import permutations,combinations from functools import wraps import random #helper function for checkconflict #if sublist is contained within superlist, return true def contained(sublist, superlist): temp = superlist[:] try: for v in sublist: temp.remove(v) return True except ValueError: return False def isedgesubset(g2star,g2): ''' check if g2star edges are a subset of those of g2 ''' for n in g2star: for h in g2star[n]: if h in g2[n]: #if not (0,1) in g2[n][h]: if not g2star[n][h].issubset(g2[n][h]): return False else: return False return True #it is assumed that G_test already has an edge added #H and G_test should have the same number of vertices #returns true if there is a conflict #returns false if there is not a conflict def checkconflict(H,G_test): allundersamples = all_undersamples(G_test) for graph in allundersamples: if isedgesubset(graph,H): return False return True #it is assumed that G_test already has an edge added #H and G_test should have the same number of vertices #returns true if there is equality #returns false if there is not equality def checkequality(H,G_test): allundersamples = all_undersamples(G_test) for graph in allundersamples: if graph == H: return True return False #helper function for checkconflict def all_undersamples(G_star,steps=5): glist = [G_star] while True: g = increment_u(G_star, glist[-1]) if isSclique(g): return glist # superclique convergence # this will (may be) capture DAGs and oscillations if g in glist: return glist glist.append(g) return glist #helper function for backtrack_more def memo(func): cache = {} # Stored subproblem solutions @wraps(func) # Make wrap look like func def wrap(*args): # The memoized wrapper s = signature(args[0],args[2])# Signature: g and edges if s not in cache: # Not already computed? cache[s] = func(*args) # Compute & cache the solution return cache[s] # Return the cached solution return wrap #helper function for backtrack_more def esig(l,n): ''' turns edge list into a hash string ''' z = len(str(n)) n = map(lambda x: ''.join(map(lambda y: y.zfill(z),x)), l) n.sort() n = ''.join(n[::-1]) return int('1'+n) #helper function for backtrack_more def gsig(g): ''' turns input graph g into a hash string using edges ''' return g2num(g) #helper function for backtrack_more def signature(g, edges): return (gsig(g),esig(edges,len(g))) #helper function for backtrack_more def isSclique(G): n = len(G) for v in G: if sum([(0,1) in G[v][w] for w in G[v]]) < n: return False if sum([(2,0) in G[v][w] for w in G[v]]) < n-1: return False return True #helper function for backtrack_more def ok2addaVpath(e,p,g,g2): mask = addaVpath(g,e,p) if not isedgesubset(undersample(g,2), g2): cleanVedges(g,e,p,mask) return False #l = [e[0]] + list(p) + [e[1]] #for i in range(len(l)-2): #if not edge_increment_ok(l[i],l[i+1],l[i+2],g,g2): # cleanVedges(g,e,p,mask) # return False #mask.extend(add2edges(g,(l[i],l[i+2]),l[i+1])) cleanVedges(g,e,p,mask) return True #helper function for backtrack_more def maskaVpath(g,e,p): mask = [] mask.extend([p[0] in g[e[0]], e[1] in g[p[-1]]]) for i in range(1,len(p)): mask.append(p[i] in g[p[i-1]]) return mask #helper function for backtrack_more def addaVpath(g,v,b): mask = maskaVpath(g,v,b) s = set([(0,1)]) l = [v[0]] + list(b) + [v[1]] for i in range(len(l)-1): g[l[i]][l[i+1]] = s return mask #helper function for backtrack_more def cleanVedges(g, e,p, mask): if mask: if not mask[0]: g[e[0]].pop(p[0], None) if not mask[1]: g[p[-1]].pop(e[1], None) i = 0 for m in mask[2:]: if not m: g[p[i]].pop(p[i+1], None) i += 1 #helper function for backtrack_more def delaVpath(g, v, b, mask): cleanVedges(g, v, b, mask) #helper function for backtrack_more def cloneempty(g): return {n:{} for n in g} # return a graph with no edges #helper function for backtrack_more def isedgesubset(g2star,g2): ''' check if g2star edges are a subset of those of g2 ''' for n in g2star: for h in g2star[n]: if h in g2[n]: #if not (0,1) in g2[n][h]: if not g2star[n][h].issubset(g2[n][h]): return False else: return False return True def backtrack_more(g2, rate=1, capsize=None): ''' computes all g1 that are in the equivalence class for g2 ''' if isSclique(g2): print 'Superclique - any SCC with GCD = 1 fits' return set([-1]) single_cache = {} if rate == 1: ln = [n for n in g2] else: ln = [x for x in permutations(g2.keys(),rate)] + [(n,n) for n in g2] @memo # memoize the search def nodesearch(g, g2, edges, s): if edges: if undersample(g,rate) == g2: s.add(g2num(g)) if capsize and len(s)>capsize: raise ValueError('Too many elements') return g e = edges[0] for n in ln: if (n,e) in single_cache: continue if not ok2addaVpath(e,n,g,g2): continue mask = addaVpath(g,e,n) r = nodesearch(g,g2,edges[1:],s) delaVpath(g,e,n,mask) elif undersample(g,rate)==g2: s.add(g2num(g)) if capsize and len(s)>capsize: raise ValueError('Too many elements in eqclass') return g # find all directed g1's not conflicting with g2 n = len(g2) edges = edgelist(g2) random.shuffle(edges) g = cloneempty(g2) for e in edges: for n in ln: mask = addaVpath(g,e,n) if not isedgesubset(undersample(g,rate), g2): single_cache[(n,e)] = False delaVpath(g,e,n,mask) s = set() try: nodesearch(g,g2,edges,s) except ValueError: s.add(0) return s #newEi consists of elements of the form # (e1,e2,...ei+1) where #every possible combination of size i #chosen from e1,e2...ei+1 is in oldEi #this version is for gu to g1 algorithm def createNextEi1(oldEi,i): newEi = [] oldEiset = set() for edgetuple in oldEi: oldEiset.add(edgetuple) set1 = set() for edgetuple in oldEiset: for k in range(0,i): set1.add(edgetuple[k]) #set1 consists of all the vertices involved in edges in oldEi set2 = set() combs = combinations(set1,i+1) for comb in combs: set2.add(comb) for object in set2: newEi.append(object) return newEi #for super and subgraph algorithm def createNextEi2(oldEi,i): newEi = [] oldEiset = set() for edgetuple in oldEi: oldEiset.add(edgetuple) set1 = set() for edgetuple in oldEiset: for k in range(0,i): set1.add(edgetuple[k]) set2 = set() combs = combinations(set1,i+1) for comb in combs: set2.add(comb) oldEisetOfsets = set(frozenset(edgetuple) for edgetuple in oldEiset) for comb in set2: smallercombsset = set() smallercombs = combinations(comb,i) set3 = set() for smallercomb in smallercombs: set3.add(smallercomb) set3Ofsets = set(frozenset(edgetuple) for edgetuple in set3) if set3Ofsets.issubset(oldEisetOfsets): newEi.append(comb) print newEi return newEi #returns all the edges of graph g in the form [('s','e'),('s','e'),....] def edgelist(g): l = [] for n in g: l.extend([(n,e) for e in g[n] if (0,1) in g[n][e]]) return l #helper function for undersample def directed_inc(G,D): G_un = {} for v in D: G_un[v] = {} for w in [el for el in D[v] if (0,1) in D[v][el]]: for e in G[w]: G_un[v][e] = set([(0,1)]) return G_un #helper function for undersample def bidirected_inc(G,D): for w in G: l = [e for e in D[w] if (2,0) in D[w][e]] for p in l: if p in G[w]: G[w][p].add((2,0)) else: G[w][p] = set([(2,0)]) l = [e for e in D[w] if (0,1) in D[w][e]] for pair in permutations(l,2): if pair[1] in G[pair[0]]: G[pair[0]][pair[1]].add((2,0)) else: G[pair[0]][pair[1]] = set([(2,0)]) return G #helper function for undersample def increment_u(G_star, G_u): # directed edges G_un = directed_inc(G_star,G_u) # bidirected edges G_un = bidirected_inc(G_un,G_u) return G_un #returns the undersampled graph of G #if G^U is desired the input u=U-1 def undersample(G, u): Gu = G for i in range(u): Gu = increment_u(G, Gu) return Gu #returns the superclique of g def superclique(n): g = {} for i in range(n): g[str(i+1)] = {str(j+1):set([(0,1),(2,0)]) for j in range(n) if j!=i} g[str(i+1)][str(i+1)] = set([(0,1)]) return g #returns the complement of graph g def complement(g): n = len(g) sq = superclique(n) for v in g: for w in g[v]: sq[v][w].difference_update(g[v][w]) if not sq[v][w]: sq[v].pop(w) return sq #helper function for addanedge def maskanedge(g,e): return [e[1] in g[e[0]]] #Slightly different from sergey's addanedge #adds an edge e to graph g #g itself is changed #e[0] is the starting vertex #e[1] is the ending vertex def addanedge(g,e): g[e[0]][e[1]] = set([(0,1)]) #Slightly different from sergey's delanedge #delete edge e in graph g #e[0] is the starting vertex #e[1] is the ending vertex def delanedge(g,e): g[e[0]].pop(e[1], None) #returns the number of vertices of graph g def numofvertices(g): return len(g) #concise way of notating a graph G def g2num(G): return int(graph2str(G),2) #helper function for g2num def graph2str(G): n = len(G) d = {((0,1),):'1', ((2,0),):'0',((2,0),(0,1),):'0',((0,1),(2,0),):'0'} A = ['0']*(n*n) for v in G: for w in G[v]: A[n*(int(v)-1)+int(w)-1] = d[tuple(G[v][w])] return ''.join(A) def superclique(n): g = {} for i in range(n): g[str(i+1)] = {str(j+1):set([(0,1),(2,0)]) for j in range(n) if j!=i} g[str(i+1)][str(i+1)] = set([(0,1)]) return g def complement(g): n = len(g) sq = superclique(n) for v in g: for w in g[v]: sq[v][w].difference_update(g[v][w]) if not sq[v][w]: sq[v].pop(w) return sq <file_sep>/supergraph_dfs.py #DFS implementation of Supergraph import itertools def directed_inc(G,D): G_un = {} # directed edges for v in D: G_un[v] = {} for w in [el for el in D[v] if (0,1) in D[v][el]]: for e in G[w]: G_un[v][e] = set([(0,1)]) return G_un def bidirected_inc(G,D): # bidirected edges for w in G: # transfer old bidirected edges l = [e for e in D[w] if (2,0) in D[w][e]] for p in l: if p in G[w]: G[w][p].add((2,0)) else: G[w][p] = set([(2,0)]) # new bidirected edges l = [e for e in D[w] if (0,1) in D[w][e]] for pair in itertools.permutations(l,2): if pair[1] in G[pair[0]]: G[pair[0]][pair[1]].add((2,0)) else: G[pair[0]][pair[1]] = set([(2,0)]) return G def increment_u(G_star, G_u): # directed edges G_un = directed_inc(G_star,G_u) # bidirected edges G_un = bidirected_inc(G_un,G_u) return G_un def undersample(G, u): Gu = G for i in range(u): Gu = increment_u(G, Gu) return Gu def ok2addanedge1(s, e, g, g2,rate=1): """ s - start, e - end """ # directed edges for u in g: if s in g[u] and not (e in g2[u] and (0,1) in g2[u][e]): return False for u in g[e]: # s -> Ch(e) if not (u in g2[s] and (0,1) in g2[s][u]):return False # bidirected edges for u in g[s]: # e <-> Ch(s) if u!=e and not (u in g2[e] and (2,0) in g2[e][u]):return False return True def ok2addanedge2(s, e, g, g2, rate=1): mask = addanedge(g,(s,e)) value = undersample(g,rate) == g2 delanedge(g,(s,e),mask) return value def ok2addanedge(s, e, g, g2, rate=1): f = [ok2addanedge1, ok2addanedge2] return f[min([1,rate-1])](s,e,g,g2,rate=rate) def addanedge(g,e): ''' add edge e[0] -> e[1] to g ''' mask = maskanedge(g,e) g[e[0]][e[1]] = set([(0,1)]) return mask def delanedge(g,e,mask): ''' delete edge e[0] -> e[1] from g if it was not there before ''' if not mask[0]: g[e[0]].pop(e[1], None) def edgelist(g): l = [] for n in g: l.extend([(n,e) for e in g[n] if (0,1) in g[n][e]]) return l def g2num(G): return int(graph2str(G),2) def complement(g): n = len(g) sq = superclique(n) for v in g: for w in g[v]: sq[v][w].difference_update(g[v][w]) if not sq[v][w]: sq[v].pop(w) return sq def superclique(n): g = {} for i in range(n): g[str(i+1)] = {str(j+1):set([(0,1),(2,0)]) for j in range(n) if j!=i} g[str(i+1)][str(i+1)] = set([(0,1)]) return g def maskanedge(g,e): return [e[1] in g[e[0]]] def graph2str(G): n = len(G) d = {((0,1),):'1', ((2,0),):'0',((2,0),(0,1),):'0',((0,1),(2,0),):'0'} A = ['0']*(n*n) for v in G: for w in G[v]: A[n*(int(v)-1)+int(w)-1] = d[tuple(G[v][w])] return ''.join(A) def supergraphs_in_eq(g, g2, rate): if undersample(g,rate) != g2: raise ValueError('g is not in equivalence class of g2') s = set() def addnodes(g,g2,edges): if edges: masks = [] for e in edges: if ok2addanedge(e[0],e[1],g,g2,rate=rate): masks.append(True) else: masks.append(False) nedges = [edges[i] for i in range(len(edges)) if masks[i]] n = len(nedges) if n: for i in range(n): mask = addanedge(g,nedges[i]) s.add(g2num(g)) addnodes(g,g2,nedges[:i]+nedges[i+1:]) delanedge(g,nedges[i],mask) edges = edgelist(complement(g)) addnodes(g,g2,edges) for graph in s: print graph return s def main(): #from page 3 of danks and plis paper #g = { #'1': {'1': set([(0, 1)]), '2': set([(0, 1)])}, #'2': {'3': set([(0, 1)])}, #'3': {'4': set([(0, 1)])}, #'4': {'1': set([(0, 1)])} #} #gu = undersample(g,1) #supergraphs_in_eq(g, gu, 1) #no supergraphs! #from email "a task for you" #g = { #'1': {'2': set([(0, 1)]), '4': set([(0, 1)]), '7': set([(0, 1)])}, #'2': {'3': set([(0, 1)]), '4': set([(0, 1)]), '7': set([(0, 1)])}, #'3': {'4': set([(0, 1)])}, #'4': {'1': set([(0, 1)]), '5': set([(0, 1)])}, #'5': {'1': set([(0, 1)]), '6': set([(0, 1)]), '8': set([(0, 1)])}, #'6': {'6': set([(0, 1)]), '7': set([(0, 1)])}, #'7': {'8': set([(0, 1)])}, #'8': {'1': set([(0, 1)]),'3': set([(0, 1)]),'4': set([(0, 1)]),'7': set([(0, 1)]),'8': set([(0, 1)])} #} #gu = undersample(g, 1) #h is a supergraph in the equivalence class of g with the extra edge (5,7) #h = { #'1': {'2': set([(0, 1)]), '4': set([(0, 1)]), '7': set([(0, 1)])}, #'2': {'3': set([(0, 1)]), '4': set([(0, 1)]), '7': set([(0, 1)])}, #'3': {'4': set([(0, 1)])}, #'4': {'1': set([(0, 1)]), '5': set([(0, 1)])}, #'5': {'1': set([(0, 1)]), '6': set([(0, 1)]), '7': set([(0, 1)]), '8': set([(0, 1)])}, #'6': {'6': set([(0, 1)]), '7': set([(0, 1)])}, #'7': {'8': set([(0, 1)])}, #'8': {'1': set([(0, 1)]),'3': set([(0, 1)]),'4': set([(0, 1)]),'7': set([(0, 1)]),'8': set([(0, 1)])} #} #supergraphs_in_eq(g, gu, 1) #contains h! yay! #from email g = { '1': {'2': set([(0, 1)])}, '2': {'3': set([(0, 1)]), '4': set([(0, 1)])}, '3': {'4': set([(0, 1)])}, '4': {'2': set([(0, 1)]), '4': set([(0, 1)]), '5': set([(0, 1)])}, '5': {'1': set([(0, 1)])} } g3 = undersample(g,2) #h1-h4 are ALL the supergraphs of g that lead to the same g3 #h1 = { #'1': {'2': set([(0, 1)]), '3': set([(0, 1)])}, #'2': {'3': set([(0, 1)]), '4': set([(0, 1)])}, #'3': {'4': set([(0, 1)])}, #'4': {'2': set([(0, 1)]), '4': set([(0, 1)]), '5': set([(0, 1)])}, #'5': {'1': set([(0, 1)])} #} #h2 = { #'1': {'2': set([(0, 1)])}, #'2': {'3': set([(0, 1)]), '4': set([(0, 1)])}, #'3': {'2': set([(0, 1)]), '4': set([(0, 1)])}, #'4': {'2': set([(0, 1)]), '4': set([(0, 1)]), '5': set([(0, 1)])}, #'5': {'1': set([(0, 1)])} #} #h3 = { #'1': {'2': set([(0, 1)])}, #'2': {'3': set([(0, 1)]), '4': set([(0, 1)])}, #'3': {'2': set([(0, 1)]), '4': set([(0, 1)]), '5': set([(0, 1)])}, #'4': {'2': set([(0, 1)]), '4': set([(0, 1)]), '5': set([(0, 1)])}, #'5': {'1': set([(0, 1)])} #} #h4 = { #'1': {'2': set([(0, 1)])}, #'2': {'3': set([(0, 1)]), '4': set([(0, 1)])}, #'3': {'4': set([(0, 1)]), '5': set([(0, 1)])}, #'4': {'2': set([(0, 1)]), '4': set([(0, 1)]), '5': set([(0, 1)])}, #'5': {'1': set([(0, 1)])} #} supergraphs_in_eq(g, g3, 2) #h1-h4 are all found! yay! if __name__ == "__main__": main()<file_sep>/research_func.py #BFS implementation of subgraph and supergraph #Gu to G1 algorithm from itertools import combinations from functools import wraps import copy import time import sys,os TOOLSPATH='../gunfolds/tools/' sys.path.append(os.path.expanduser(TOOLSPATH)) import bfutils as bfu import mytools as tool def memo(func): cache = {} # Stored subproblem solutions @wraps(func) # Make wrap look like func def wrap(*args): # The memoized wrapper s = tool.gsig(args[0]) # Signature: just the g #s = tool.signature(args[0],args[2])# Signature: g and edges if s not in cache: # Not already computed? cache[s] = func(*args) # Compute & cache the solution return cache[s] # Return the cached solution return wrap def prune_conflicts(H, g, elist): """checks if adding an edge from the list to graph g causes a conflict with respect to H and if it does removes the edge from the list Arguments: - `H`: the undersampled graph - `g`: a graph under construction - `elist`: list of edges to check """ masks = [] for e in elist: tool.addanedge(g,e) if tool.checkconflict(H,g): masks.append(False) else: masks.append(True) tool.delanedge(g,e) return [elist[i] for i in range(len(elist)) if masks[i]] def eqclass(H): ''' Find all graphs in the same equivalence class with respect to graph H and any undesampling rate. ''' g = {n:{} for n in H} s = set() @memo def addedges(g,H,edges): if edges: nedges = prune_conflicts(H, g, edges) n = len(nedges) if n == 0: return None for i in range(n): tool.addanedge(g,nedges[i]) if tool.checkequality(H,g): return tool.gsig(g) s.add(addedges(g,H,nedges[:i]+nedges[i+1:])) tool.delanedge(g,nedges[i]) edges = tool.edgelist(tool.complement(g)) addedges(g,H,edges) return s-set([None]) def main(): g = bfu.ringmore(4,2); H = bfu.undersample(g,2); ss = eqclass(H) print ss if __name__ == "__main__": main() <file_sep>/testEi.py from itertools import combinations import sys,os TOOLSPATH='~/Users/cynthia/Desktop/Causality/Causality-Research/mytools.py' sys.path.append(os.path.expanduser(TOOLSPATH)) import mytools as tool #for gu to g1 algorithm def createNextEi1(oldEi,i): newEi = [] oldEiset = set() for edgetuple in oldEi: oldEiset.add(edgetuple) set1 = set() for edgetuple in oldEiset: print edgetuple for k in range(0,i): set1.add(edgetuple[k]) #set1 consists of all the vertices involved in edges in oldEi set2 = set() combs = combinations(set1,i+1) for comb in combs: set2.add(comb) for object in set2: newEi.append(object) print newEi return newEi #for super and subgraph def createNextEi2(oldEi,i): newEi = [] oldEiset = set() for edgetuple in oldEi: oldEiset.add(edgetuple) set1 = set() for edgetuple in oldEiset: for k in range(0,i): set1.add(edgetuple[k]) set2 = set() combs = combinations(set1,i+1) for comb in combs: set2.add(comb) oldEisetOfsets = set(frozenset(edgetuple) for edgetuple in oldEiset) for comb in set2: smallercombsset = set() smallercombs = combinations(comb,i) set3 = set() for smallercomb in smallercombs: set3.add(smallercomb) set3Ofsets = set(frozenset(edgetuple) for edgetuple in set3) if set3Ofsets.issubset(oldEisetOfsets): newEi.append(comb) print newEi return newEi def main(): #oldEi = combinations(['e1','e2','e3','e4'],2) #oldEi = [('e1','e2'),('e1','e3'),('e1','e4'),('e2','e3'),('e2','e4')] print list(createNextEi2(oldEi,2)) #should contain [(e1,e2,e3),] if __name__ == "__main__": main()
83bfa8dd6beb8f19d2baf7b1c7ea16a9ae0174b0
[ "Python" ]
4
Python
sergeyplis/Causality-Research
9438bf4e4b4272ff00a7523500b749c1f3671f7d
a30ea0a207f5dacc5308a320eea818a74a496474
refs/heads/master
<file_sep># use employees; # # show tables; # # describe departments; # # describe dept_emp; # # describe dept_manager; # # describe employees; # # describe salaries; # # describe titles; use codeup_test_db; show tables; describe albums; # Add an index to make sure all album names combined with the artist are unique. Try to add duplicates to test the constraint. ALTER TABLE codeup_test_db.albums ADD UNIQUE `unique_album_artist` (artist, name); INSERT INTO albums (artist, name, release_date, genre, sales) VALUES ('Korn', 'Follow the Leader', 1998, 'Nu Metal', 14); INSERT INTO albums (artist, name, release_date, genre, sales) VALUES ('Korn', 'Follow the Leader', 1998, 'Nu Metal', 14); # shows you the list of indexes show index from albums; # drop the index alter table albums drop index name; select * from albums;<file_sep>use employees; select * from employees where birth_date like '%-02-01' order by birth_date desc; select birth_date, count(birth_date) as "number of birthday's on 5/3/61" from employees where birth_date = '1961-05-03' group by birth_date; select count(birth_date) from employees where birth_date = '1961-05-03' group by birth_date; select birth_date, count(birth_date) as 'number of birthday\'s on the selected day' from employees where birth_date = '1961-05-03' or birth_date = '1958-05-03' group by birth_date; select * from employees where birth_date = '1958-05-03'; # where birth_date = '1961-05-03'; select count(*) as 'counted birthdays' from employees where birth_date = '1961-05-03' or birth_date = '1958-05-03'; select count(emp_no) from employees where first_name = 'Kokou' and gender = 'm'; <file_sep>use employees; # the list of employees that were hired in 1987-02-23 # where show tables; # what describe employees; # what do I want to see select * # from where I get the info from from employees # conditions where hire_date = '1987-02-23'; select * from employees where first_name = 'fer'; select * from employees where first_name like 'fer%'; select * from employees where last_name like '%ing' && gender = 'F' || first_name like 'fer%'; # all employees whose last name ends with -in select * from employees where first_name like '%in'; # all employees whose employee number is in between a range select * from employees where emp_no between 12434 and 12440; select * from employees # where hire_date between '1990-10-22' and '1990-11-22'; where hire_date like '%-10-%'; select * from employees where hire_date > '1991-02-07'; select * from employees where hire_date between '1991-02-01' and '1991-02-29'; select * from employees where first_name in ('Elvis', 'Magy', 'Brendon'); select * from employees where first_name = 'Elvis' or first_name = 'Magy' or first_name = 'Brendon'; describe titles; select * from titles where emp_no = 10005; select emp_no, first_name, last_name from employees where emp_no < 20000 and last_name in ('Herber', 'Baek') or first_name = 'Shridhar'; <file_sep>use employees; show tables; describe employees; select * from employees # order by emp_no; order by first_name; select first_name, last_name from employees order by last_name; select first_name, last_name from employees order by last_name desc; # Ordering by multiple columns a-z select first_name, last_name from employees order by first_name, last_name; # Ordering by multiple columns first a-z last z-a select first_name, last_name from employees order by first_name, last_name desc; # First women who were hired select * from employees order by gender desc, hire_date, emp_no; # Find the highest/lowest current salary select * from salaries # order by to_date desc, salary desc; order by to_date desc, salary; <file_sep>CREATE TABLE IF NOT EXISTS users ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, email VARCHAR(45) NOT NULL, password VARCHAR(24) NOT NULL, first_name VARCHAR(45) NOT NULL, last_name VARCHAR(45) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE IF NOT EXISTS ads ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, user_id INTEGER UNSIGNED NOT NULL, title VARCHAR(50), description VARCHAR(255), p_date date NOT NULL, PRIMARY KEY (id), FOREIGN KEY (user_id) REFERENCES users (id) ); CREATE TABLE IF NOT EXISTS categories ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, category VARCHAR (20), PRIMARY KEY (id) ); CREATE TABLE IF NOT EXISTS ad_category ( ad_id INTEGER UNSIGNED NOT NULL, category_id INTEGER UNSIGNED NOT NULL, FOREIGN KEY (ad_id) REFERENCES ads(id), FOREIGN KEY (category_id) REFERENCES categories(id) ); -- ============= POPULATING TABLES INSERT INTO categories (category) VALUES ('antiques'), ('appliances'), ('arts+crafts'), ('atv/utv/sno'), ('auto parts'), ('aviation'), ('baby+kid'), ('barter'), ('beauty+hlth'), ('bike parts'), ('bikes'), ('boat parts'), ('boats'), ('books'), ('business'), ('cars+trucks'), ('cds/dvd/vhs'), ('cell phones'), ('clothes+acc'), ('collectibles'), ('computer parts'), ('computers'), ('electronics'), ('farm+garden'), ('free'), ('furniture'), ('garage sale'), ('general'), ('heavy equip'), ('household'), ('jewelry'), ('materials'), ('motorcycle parts'), ('motorcycles'), ('music instr'), ('photo+video'), ('rvs+camp'), ('sporting'), ('tickets'), ('tools'), ('toys+games'), ('trailers'), ('video gaming'), ('wanted'), ('wheels+tires'); INSERT INTO users (email, password, first_name, last_name) VALUES ('<EMAIL>', 'codeup', 'TJ', 'English'), ('<EMAIL>', 'codeup', 'Graham', 'Davis'), ('<EMAIL>', 'codeup', 'Mykel', 'Kovar'), ('<EMAIL>', 'codeup', 'Test', 'User'); INSERT INTO ads(user_id, title, description, p_date) VALUES (1, 'Post Title Test1', 'Post Description 1', '2018-08-11'), (2, 'Post Title Test2', 'Post Description 2', '2018-08-10'), (3, 'Post Title Test3', 'Post Description 3', '2018-08-09'), (3, 'Post Title Test4', 'Post Description 4', '2018-08-10'), (1, 'Post Title Test5', 'Post Description 5', '2018-08-11'); INSERT INTO ad_category(ad_id, category_id) VALUES (6,5), (6,7), (7,2), (8,9), (9,2), (9,3); -- ============= 'SELECT' QUERIES select * from users; select * from ads; select * from categories; select * from ad_category; -- For a given ad, what is the email address of the user that created it? SELECT a.title as Ad, u.email as 'Posted By' FROM ads as a JOIN users as u on u.id = a.user_id order by a.p_date; -- For a given ad, what category, or categories, does it belong to? select a.title as Ad, c.category as Category from ads as a join ad_category as ac on ac.ad_id = a.id join categories as c on c.id = ac.category_id; -- For a given category, show all the ads that are in that category. select c.category as Category, a.title as Ad from ads as a right join ad_category as ac on ac.ad_id = a.id right join categories as c on c.id = ac.category_id; -- For a given user, show all the ads they have posted. select concat(u.first_name, ' ', u.last_name) as Name, u.email as Email, a.title as Ad from users as u join ads as a on a.user_id = u.id order by Name;
fd942fafa470608afec3e5bd3198ae3d640dc091
[ "SQL" ]
5
SQL
Graham-Davis-SATX/database-exercises
17768de831a42267b26bb3af61d36379e246bc39
c529f3f8f9c2b6a3889c72f28feeb61d44f3e8a4
refs/heads/master
<file_sep>@main("Testing") { <link rel="stylesheet" href="@routes.Assets.versioned("stylesheets/practice.css")"> <link href="http://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet" type="text/css" /> <script src="//use.typekit.net/wmv4bzh.js"></script> <script>try{Typekit.load();}catch(e){}</script> <div class="navbar-fixed-top"> <div class="row header"> <img src="/assets/images/icon.png" height="45px" class="panel-logo hidden-xs" /> <img src="/assets/images/icon.png" height="25px" class="panel-logo-xs visible-xs-inline-block" /> <span class="panel-heading-heading">Practice Dojo - Section 1</span> <span data-toggle="modal" data-target="#exit-dialog"><div class="exit-icon" data-toggle="tooltip" data-placement="bottom" title="Exit"></div></span> <img src="assets/images/stopwatch.png" height="36px" class="panel-stopwatch hidden-xs" /> <!--<img src="/images/stopwatch.png" height="30px" class="panel-stopwatch visible-xs-inline-block" />--> <span class="globaltimer"></span> </div> </div> <div class="modal exit-modal fade" id="exit-dialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <div class="modal-header"> <h3 class="modal-title" id="myModalLabel">Wait! Are you sure?</h3> </div> <div class="modal-body"> <hr> If you really must leave without finishing, click 'Submit Completed' below and we'll mark the questions you completed and show you their solutions. <br><br>Alternatively, click 'Quit' to leave without these questions being marked. <hr> </div> <div class="modal-footer"> <button type="button" class="btn btn-default btn-cancel" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-submit-completed" data-dismiss="modal">Submit Completed</button> <a href="/"><button type="button" class="btn btn-danger">Quit</button></a> </div> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-12"> <form method="POST" action="https://bmat.ninja/questionbank/practice/review" accept-charset="UTF-8" id="practice_form" name="practice_form"><input name="_token" type="hidden" value="<KEY>"> <input name="mode" type="hidden" value="standard"> <input name="freeSolutions" type="hidden" value=""> <input name="section" type="hidden" value="1"> <div class="panel panel-default"> <div class="panel-body"> <div class="panel-body-inner"> <div class="row question" data-questionnumber="1" data-questionid="444" style="display:none;"> <div class="col-md-12"> <div class="question-number"> <span class="number">1</span> <span class="total">/5</span> <span class="pull-right timer" id="watchdisplay-1"></span> </div> </div> <div class="col-md-6 question2wrapper"> <div class="question2"><p><!--StartFragment--><p>“Is cannabis really as dangerous as some people have claimed? This is an important question, since the use of cannabis has increased, and even children under 15 are known to use it. It is said that smoking cannabis is just as dangerous as smoking tobacco, in that it is equally likely to lead to death from heart disease. A number of recent studies have suggested that smoking cannabis may increase the risk of developing schizophrenia, and that those who start smoking it before age 15 have a much higher risk of becoming schizophrenic in later life. Yet since the incidence of schizophrenia in the population has remained stable whilst the use of cannabis has been increasing, it cannot be true that smoking cannabis causes schizophrenia.” </p><!--EndFragment--></p></div> </div> <br class="visible-xs"> <div class="col-md-6 questioncontainer"> <div class="actualquestion"><p><!--StartFragment--><p>Which <strong>one</strong> of the following, if true, weakens the above argument? </p><!--EndFragment--></p></div> <div class="option-items" onclick=""> <div class="question_answer" onclick="" data-question-id="question_444_answer" data-answer-value="a"> <div class="abcde">A</div> <div class="question-option"><p><!--StartFragment--><p>Most people who use cannabis do not develop schizophrenia. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_444_answer" data-answer-value="b"> <div class="abcde">B</div> <div class="question-option"><p><!--StartFragment--><p>Cannabis smoke contains high levels of substances that cause cancer. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_444_answer" data-answer-value="c"> <div class="abcde">C</div> <div class="question-option"><p><!--StartFragment--><p>Drugs that alter one’s mood cause chemical changes in the brain. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_444_answer" data-answer-value="d"> <div class="abcde">D</div> <div class="question-option"><p><!--StartFragment--><p>Cannabis smokers have higher amounts of tar in the lungs than tobacco smokers. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_444_answer" data-answer-value="e"> <div class="abcde">E</div> <div class="question-option"><p><!--StartFragment--><p>The use of cannabis by those aged under 15 is a recent development. </p><!--EndFragment--></p></div> </div> <ol type="A" style="display:none"> <li><input type="radio" name="question_444_answer" value="a"><!--StartFragment--><p>Most people who use cannabis do not develop schizophrenia. </p><!--EndFragment--></li> <li><input type="radio" name="question_444_answer" value="b"><!--StartFragment--><p>Cannabis smoke contains high levels of substances that cause cancer. </p><!--EndFragment--></li> <li><input type="radio" name="question_444_answer" value="c"><!--StartFragment--><p>Drugs that alter one’s mood cause chemical changes in the brain. </p><!--EndFragment--></li> <li><input type="radio" name="question_444_answer" value="d"><!--StartFragment--><p>Cannabis smokers have higher amounts of tar in the lungs than tobacco smokers. </p><!--EndFragment--></li> <li><input type="radio" name="question_444_answer" value="e"><!--StartFragment--><p>The use of cannabis by those aged under 15 is a recent development. </p><!--EndFragment--></li> </ol> </div> </div> <!--<input class="submitButton btn-primary btn" type="submit" value="Submit">--> </div> <div class="row question" data-questionnumber="2" data-questionid="261" style="display:none;"> <div class="col-md-12"> <div class="question-number"> <span class="number">2</span> <span class="total">/5</span> <span class="pull-right timer" id="watchdisplay-2"></span> </div> </div> <div class="col-md-6 question2wrapper"> <div class="question2"><p><p>One in ten adults in the UK has had a body piercing somewhere other than the ear lobe. 28% of these experienced complications and 1% were admitted to hospital, according to a survey of 10,000 adults. Body piercing is three times more common in women than men. Navel piercings are most common amongst women, whereas men are more likely to have a nipple piercing. Swelling, infection and bleeding are common side effects and tongue piercings are the most risky. Serious complications resulting in hospital admission mostly occur with piercings performed by non specialists rather than those carried out in a tattoo parlour or specialist piercing shop. In the other countries, people have been infected with hepatitis B and C and HIV.&nbsp;</p></p></div> </div> <br class="visible-xs"> <div class="col-md-6 questioncontainer"> <div class="actualquestion"><p><p>Which one of the following can reliably be concluded from the information above?</p></p></div> <div class="option-items" onclick=""> <div class="question_answer" onclick="" data-question-id="question_261_answer" data-answer-value="a"> <div class="abcde">A</div> <div class="question-option"><p><p>Good piercers give their clients advice about how to care for a piercing and minimise the risk of infection.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_261_answer" data-answer-value="b"> <div class="abcde">B</div> <div class="question-option"><p><p>No one should ever get a body piercing because the risk outweighs the benefit.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_261_answer" data-answer-value="c"> <div class="abcde">C</div> <div class="question-option"><p><p>Nothing can reliably be concluded because the survey sample was too small to be representative.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_261_answer" data-answer-value="d"> <div class="abcde">D</div> <div class="question-option"><p><p>People who want a body piercing would be well advised to go to a reputable piercer.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_261_answer" data-answer-value="e"> <div class="abcde">E</div> <div class="question-option"><p><p>The Government should regulate body piercers more strictly to reduce complications.</p></p></div> </div> <ol type="A" style="display:none"> <li><input type="radio" name="question_261_answer" value="a"><p>Good piercers give their clients advice about how to care for a piercing and minimise the risk of infection.</p></li> <li><input type="radio" name="question_261_answer" value="b"><p>No one should ever get a body piercing because the risk outweighs the benefit.</p></li> <li><input type="radio" name="question_261_answer" value="c"><p>Nothing can reliably be concluded because the survey sample was too small to be representative.</p></li> <li><input type="radio" name="question_261_answer" value="d"><p>People who want a body piercing would be well advised to go to a reputable piercer.</p></li> <li><input type="radio" name="question_261_answer" value="e"><p>The Government should regulate body piercers more strictly to reduce complications.</p></li> </ol> </div> </div> <!--<input class="submitButton btn-primary btn" type="submit" value="Submit">--> </div> <div class="row question" data-questionnumber="3" data-questionid="779" style="display:none;"> <div class="col-md-12"> <div class="question-number"> <span class="number">3</span> <span class="total">/5</span> <span class="pull-right timer" id="watchdisplay-3"></span> </div> </div> <div class="col-md-6 question2wrapper"> <div class="question2"><p><h3 style="text-align: center;"><strong>Comparing cannabis with tobacco</strong></h3><p style="text-align: center;"><em>Smoking cannabis, like smoking tobacco, can be a major public health hazard</em></p><p><img class="fr-fin fr-dib" alt="Image title" src="https://bmatninja.s3-eu-west-1.amazonaws.com/questions%2F1436877864198-Q32-35.png" width="574"></p><h6 style="text-align: center;"><!--StartFragment--><NAME>, Oldfield WLG &amp; Kon OM. Comparing cannabis with tobacco. BMJ, 2003; 326: 942-3.</h6><h6 style="text-align: center;">Reproduced with permission from the BMJ Publishing Group. <!--EndFragment--></h6><p><em> </em><!--EndFragment--></p><h3><strong></strong> <!--EndFragment--></h3><p style="text-align: center;"><strong>Answer the following questions, assuming that the information above is accurate. </strong><!--EndFragment--></p></p></div> </div> <br class="visible-xs"> <div class="col-md-6 questioncontainer"> <div class="actualquestion"><p><!--StartFragment--><p>Which of the following statements may we safely conclude to be accurate? </p><!--EndFragment--></p></div> <div class="option-items" onclick=""> <div class="question_answer" onclick="" data-question-id="question_779_answer" data-answer-value="a"> <div class="abcde">A</div> <div class="question-option"><p><!--StartFragment--><p>Smoking cannabis is less harmful than smoking tobacco because it occurs less frequently. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_779_answer" data-answer-value="b"> <div class="abcde">B</div> <div class="question-option"><p><!--StartFragment--><p>Smoking cannabis is equally harmful to smoking tobacco because largely identical chemicals are produced. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_779_answer" data-answer-value="c"> <div class="abcde">C</div> <div class="question-option"><p><!--StartFragment--><p>Smoking cannabis is more harmful than smoking tobacco because the products of combustion are retained to a higher degree. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_779_answer" data-answer-value="d"> <div class="abcde">D</div> <div class="question-option"><p><!--StartFragment--><p>Cannabis smokers often smoke tobacco, incurring harm produced by both. </p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_779_answer" data-answer-value="e"> <div class="abcde">E</div> <div class="question-option"><p><p>-</p></p></div> </div> <ol type="A" style="display:none"> <li><input type="radio" name="question_779_answer" value="a"><!--StartFragment--><p>Smoking cannabis is less harmful than smoking tobacco because it occurs less frequently. </p><!--EndFragment--></li> <li><input type="radio" name="question_779_answer" value="b"><!--StartFragment--><p>Smoking cannabis is equally harmful to smoking tobacco because largely identical chemicals are produced. </p><!--EndFragment--></li> <li><input type="radio" name="question_779_answer" value="c"><!--StartFragment--><p>Smoking cannabis is more harmful than smoking tobacco because the products of combustion are retained to a higher degree. </p><!--EndFragment--></li> <li><input type="radio" name="question_779_answer" value="d"><!--StartFragment--><p>Cannabis smokers often smoke tobacco, incurring harm produced by both. </p><!--EndFragment--></li> <li><input type="radio" name="question_779_answer" value="e"><p>-</p></li> </ol> </div> </div> <!--<input class="submitButton btn-primary btn" type="submit" value="Submit">--> </div> <div class="row question" data-questionnumber="4" data-questionid="498" style="display:none;"> <div class="col-md-12"> <div class="question-number"> <span class="number">4</span> <span class="total">/5</span> <span class="pull-right timer" id="watchdisplay-4"></span> </div> </div> <div class="col-md-6 question2wrapper"> <div class="question2"><p><p><img alt="Image title" class="fr-fin fr-dib" src="https://bmatninja.s3-eu-west-1.amazonaws.com/questions%2F1436637202354-Q31-35.png" width="300"></p><p><!--StartFragment-->Internet companies are discovering, as billions of people have before them, that whilegrowing up brings problems, maturity brings more.</p><p>For e-Bay, Google, Yahoo! and Microsoft, the internet’s commercial potential is provingbigger than even most early dreamers imagined. To keep expanding at sensational rates,however, players are encroaching on each other’s territory. Competition, which was oncesharks against minnows, is becoming a battle of the giants. Corporate manoeuvring isreaching soap opera intensity.</p><p>Google, now the dominant online search engine, is making the pace. It snatched a longtermlink with AOL Time Warner from under the nose of Microsoft. In the first quarter of2006 it boosted revenue by 80% to more than $2 billion (£1.2 billion). That represents a lotof advertising, the common revenue all are chasing.</p><p>Yahoo! and Microsoft fret at losing market share. E-Bay, the auction and trading site, fearsthat Google is pushing its own new consumer trading facility and also threatening e-Bay’sPayPal online payments system with a rival system.</p><p>The three, who recently looked down on Google, wonder if they can forge alliances tocombat it. Microsoft does not want anyone repeating on the internet what it achieved incomputer systems. The jockeying offers rich entertainment and opportunities forconsumers, so long as the players do not gang up against them.<!--EndFragment--></p><p style="text-align: right; font-size: 11px"><!--StartFragment-->© The Times, 22 April 2006<!--EndFragment--></p></p></div> </div> <br class="visible-xs"> <div class="col-md-6 questioncontainer"> <div class="actualquestion"><p><!--StartFragment--><p>Which of the following can reliably be inferred from the passage, especially from the lastparagraph? </p><!--EndFragment--></p></div> <div class="option-items" onclick=""> <div class="question_answer" onclick="" data-question-id="question_498_answer" data-answer-value="a"> <div class="abcde">A</div> <div class="question-option"><p><!--StartFragment--><p>Google is achieving on the internet what Microsoft achieved in computer systems.</p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_498_answer" data-answer-value="b"> <div class="abcde">B</div> <div class="question-option"><p><!--StartFragment--><p>The former giants of IT no longer look down on Google.</p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_498_answer" data-answer-value="c"> <div class="abcde">C</div> <div class="question-option"><p><!--StartFragment--><p>The only way for Microsoft to stop Google is to merge with its former rivals.</p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_498_answer" data-answer-value="d"> <div class="abcde">D</div> <div class="question-option"><p><!--StartFragment--><p>Consumers will lose out if the big IT companies merge.</p><!--EndFragment--></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_498_answer" data-answer-value="e"> <div class="abcde">E</div> <div class="question-option"><p><p>-</p></p></div> </div> <ol type="A" style="display:none"> <li><input type="radio" name="question_498_answer" value="a"><!--StartFragment--><p>Google is achieving on the internet what Microsoft achieved in computer systems.</p><!--EndFragment--></li> <li><input type="radio" name="question_498_answer" value="b"><!--StartFragment--><p>The former giants of IT no longer look down on Google.</p><!--EndFragment--></li> <li><input type="radio" name="question_498_answer" value="c"><!--StartFragment--><p>The only way for Microsoft to stop Google is to merge with its former rivals.</p><!--EndFragment--></li> <li><input type="radio" name="question_498_answer" value="d"><!--StartFragment--><p>Consumers will lose out if the big IT companies merge.</p><!--EndFragment--></li> <li><input type="radio" name="question_498_answer" value="e"><p>-</p></li> </ol> </div> </div> <!--<input class="submitButton btn-primary btn" type="submit" value="Submit">--> </div> <div class="row question" data-questionnumber="5" data-questionid="61" style="display:none;"> <div class="col-md-12"> <div class="question-number"> <span class="number">5</span> <span class="total">/5</span> <span class="pull-right timer" id="watchdisplay-5"></span> </div> </div> <div class="col-md-6 question2wrapper"> <div class="question2"><p><p>Socialist politicians are often taunted by their opponents for leading lifestyles similar to those of their capitalist counterparts. The theme of the taunts runs like this; 'You object on socialist principles to gross inequalities in the distribution of wealth; yet you enjoy a higher personal standard of living than the majority of the population. Therefore you are not really a socialist'. But the jibe can easily be answered, for there is no hypocrisy in arguing, even from a privileged position, for a fairer and more equal society.</p></p></div> </div> <br class="visible-xs"> <div class="col-md-6 questioncontainer"> <div class="actualquestion"><p><p>Which of the following is a conclusion which can be reliably drawn from the passage as a whole?</p></p></div> <div class="option-items" onclick=""> <div class="question_answer" onclick="" data-question-id="question_61_answer" data-answer-value="a"> <div class="abcde">A</div> <div class="question-option"><p><p>Socialists who enjoy personal wealth cannot object to others who amass even greater wealth.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_61_answer" data-answer-value="b"> <div class="abcde">B</div> <div class="question-option"><p><p>Someone can be a genuine socialist whilst enjoying a high standard of living.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_61_answer" data-answer-value="c"> <div class="abcde">C</div> <div class="question-option"><p><p>Calls for reform are more effective if they come from the more privileged classes of society.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_61_answer" data-answer-value="d"> <div class="abcde">D</div> <div class="question-option"><p><p>There is nothing immoral about inequalities in the distribution of wealth.</p></p></div> </div> <div class="question_answer" onclick="" data-question-id="question_61_answer" data-answer-value="e"> <div class="abcde">E</div> <div class="question-option"><p><p>It is hypocritical to claim to be a socialist if one enjoys a standard of living above the average.</p></p></div> </div> <ol type="A" style="display:none"> <li><input type="radio" name="question_61_answer" value="a"><p>Socialists who enjoy personal wealth cannot object to others who amass even greater wealth.</p></li> <li><input type="radio" name="question_61_answer" value="b"><p>Someone can be a genuine socialist whilst enjoying a high standard of living.</p></li> <li><input type="radio" name="question_61_answer" value="c"><p>Calls for reform are more effective if they come from the more privileged classes of society.</p></li> <li><input type="radio" name="question_61_answer" value="d"><p>There is nothing immoral about inequalities in the distribution of wealth.</p></li> <li><input type="radio" name="question_61_answer" value="e"><p>It is hypocritical to claim to be a socialist if one enjoys a standard of living above the average.</p></li> </ol> </div> </div> <!--<input class="submitButton btn-primary btn" type="submit" value="Submit">--> </div> </div> </div> </div> </div> <div class="visible-xs-block 50pxspacer"> </div> </div> </div> <div class="container-fluid"> <div class="navbar-fixed-bottom normal-row"> <div class="panel-footer bottombar row"> <div class="col-xs-6 col-sm-2 nopadding"> <div class="previousButton" style="display:none;">Previous</div> </div> <div class="col-xs-6 col-sm-2 col-sm-push-8 nopadding"> <div class="nextButton">Next</div> <span style="display:none"><input class="submitButton" type="submit" value="Finish"></span> <div class="fakeSubmitButton"><span class="glyphicon glyphicon-ok" style="margin-right: 10px;margin-left: -10px;"></span> Finish</div> </div> <div class="pagination-wrapper col-xs-12 col-sm-8 col-sm-pull-2 nopadding"> <div class="backscroll hidden-xs"></div> <ul class="pagination"> <li class="bottombar-questions" data-questionid="" data-questionnumber="1"onclick="showOnlyQuestion(1)">1</li> <li class="bottombar-questions" data-questionid="" data-questionnumber="2"onclick="showOnlyQuestion(2)">2</li> <li class="bottombar-questions" data-questionid="" data-questionnumber="3"onclick="showOnlyQuestion(3)">3</li> <li class="bottombar-questions" data-questionid="" data-questionnumber="4"onclick="showOnlyQuestion(4)">4</li> <li class="bottombar-questions" data-questionid="" data-questionnumber="5"onclick="showOnlyQuestion(5)">5</li> </ul> <div class="forwardscroll hidden-xs"></div> </div> </div> </div> </div> <div class="loadingModal"><!-- Place at bottom of page --></div> <!-- Scripts --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js"></script> <script src="@routes.Assets.versioned("javascripts/practice.js")"></script> } <file_sep>import models.Question; import models.QuestionSet; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import static play.test.Helpers.fakeApplication; import static play.test.Helpers.running; public class ModelTest { @Test public void loadGateCsSet1() { running(fakeApplication(), () -> { loadFile("questionsets/gate-cs-set-1"); }); } @Test public void loadDsQuiz() { running(fakeApplication(), () -> { loadFile("questionsets/datastructure"); }); } private void loadFile(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(fileName).getFile()); try { Scanner scanner = new Scanner(file); QuestionSet questionSet = new QuestionSet(); questionSet.name = scanner.nextLine(); List<Question> questionList = new ArrayList<Question>(); while(scanner.hasNextLine()) { Question question = new Question(); question.statement = scanner.nextLine(); question.options = new ArrayList<String>(); for(int i=0;i<4;i++) question.options.add(scanner.nextLine()); question.correctOptionIndex = Integer.parseInt(scanner.nextLine()); question.answerExplanation = scanner.nextLine(); questionList.add(question); question.save(); if(scanner.hasNextLine()) scanner.nextLine(); } questionSet.setQuestionList(questionList); questionSet.save(); } catch (FileNotFoundException e) { e.printStackTrace(); } } @Test public void save() { running(fakeApplication(), () -> { Question question1 = new Question(); question1.statement = "Question 1"; question1.correctOptionIndex = 1; question1.options = Arrays.asList("Option 1", "Option 2", "Option 3", "Option 4"); Question question2 = new Question(); question2.statement = "Question 2"; question2.correctOptionIndex = 2; question2.options = Arrays.asList("Option 1", "Option 2", "Option 3", "Option 4"); QuestionSet questionSet = new QuestionSet(); questionSet.name = "Question Set 1"; questionSet.setQuestionList(Arrays.asList(question1, question2)); question1.save(); question2.save(); questionSet.save(); }); } }<file_sep>package controllers; import controllers.pojo.Menu; import org.apache.commons.lang3.StringUtils; import play.mvc.Result; import play.mvc.Results; import java.io.*; import java.util.Objects; import java.util.Scanner; import static play.mvc.Results.ok; /** * Created by kartik on 27/12/16. */ public class TrainingController { public Result index() { return ok(views.html.training_index.render("Training")); } public Result copy() { return ok(views.html.training_copy.render("Training copy")); } public Result displayTraining(String topic) { System.out.println("Received training display request for " + topic ); try { InputStream in = TrainingController.class.getResourceAsStream("/data/" + topic + "/content.html"); String content = getString(in); Menu menu = parseAndGetMenu(getString(TrainingController.class.getResourceAsStream("/data/" + topic + "/menu"))); //menu.printMenu(); return ok(views.html.training_display.render("Training " + topic, menu.getHtml(), content)); } catch (Exception e) { e.printStackTrace(); return Results.internalServerError(); } } private Menu parseAndGetMenu(String menuFile) { Scanner sc = new Scanner(menuFile); Menu rootMenu = new Menu("root","/"); Menu menu = rootMenu; int currentDepth = 0; while(sc.hasNextLine()) { String line = sc.nextLine(); String link = sc.nextLine(); int depth = 0; for(int i=0;i<line.length();i++) { if(line.charAt(i) != '.') break; depth++; } while(true) { String prev = line; line = StringUtils.removeStart(line, "."); if (Objects.equals(line, prev)) break; } if(depth > currentDepth) { menu.subMenu.add(new Menu(line,link, menu )); menu = menu.subMenu.get(menu.subMenu.size()-1); } else if(depth == currentDepth){ menu = menu.parentMenu; menu.subMenu.add(new Menu(line, link,menu)); menu = menu.subMenu.get(menu.subMenu.size()-1); } else if(depth < currentDepth){ for(int i=0;i< currentDepth-depth+1;i++) { menu = menu.parentMenu; } menu.subMenu.add(new Menu(line,link, menu)); menu = menu.subMenu.get(menu.subMenu.size()-1); } currentDepth = depth; } return rootMenu; } private String getString(InputStream in) throws IOException { BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int result = bis.read(); while (result != -1) { buf.write((byte) result); result = bis.read(); } return buf.toString(); } } <file_sep>package controllers.pojo; import java.util.ArrayList; import java.util.List; /** * Created by kartik on 27/12/16. */ public class Menu { public Menu parentMenu = null; public String title; public String link; public List<Menu> subMenu = new ArrayList<>(); public Menu(String title, String link) { this.title = title; this.link = link; } public Menu(String title, String link, Menu parentMenu) { this.title = title; this.parentMenu = parentMenu; this.link = link; } private void printMenu(Menu menu,int depth) { if(menu == null) { return; } System.out.println(depth + " " + menu.title); for(Menu menu1: menu.subMenu) { printMenu(menu1,depth+1); } } public void printMenu() { printMenu(this, 0); } public void getHtml(StringBuilder sb, Menu menu) { sb.append("<li>"); sb.append("<a href='" + menu.link +"'>" + menu.title + "</a>"); if(menu.subMenu.size() >0 ) { sb.append("<ul class=\"list-style-none sub-menu\">"); for(int i=0;i<menu.subMenu.size();i++) { getHtml(sb, menu.subMenu.get(i)); } sb.append("</ul>"); } sb.append("</li>"); } public String getHtml() { StringBuilder sb = new StringBuilder(); for(Menu menu: subMenu) { getHtml(sb, menu); } return sb.toString(); } } <file_sep>/* Let's start by applying the class of 'img-responsive' to all images. */ var numberOfQuestionsAttempted = 0; $(".container img").addClass('img-responsive'); /* Let's now make all tables responsive. */ $("table").addClass('table table-hover').wrap("<div class='table-responsive'></div>"); /* * Javascript Stopwatch class * http://www.seph.dk * * Copyright 2009 <NAME> * Released under the MIT license (do whatever you want - just leave my name on it) * http://opensource.org/licenses/MIT */ // * Stopwatch class {{{ Stopwatch = function(listener, resolution) { this.startTime = 0; this.stopTime = 0; this.totalElapsed = 0; // * elapsed number of ms in total this.started = false; this.listener = (listener != undefined ? listener : null); // * function to receive onTick events this.tickResolution = (resolution != undefined ? resolution : 500); // * how long between each tick in milliseconds this.tickInterval = null; // * pretty static vars this.onehour = 1000 * 60 * 60; this.onemin = 1000 * 60; this.onesec = 1000; } Stopwatch.prototype.start = function() { var delegate = function(that, method) { return function() { return method.call(that) } }; if(!this.started) { this.startTime = new Date().getTime(); this.stopTime = 0; this.started = true; this.tickInterval = setInterval(delegate(this, this.onTick), this.tickResolution); } } Stopwatch.prototype.stop = function() { if(this.started) { this.stopTime = new Date().getTime(); this.started = false; var elapsed = this.stopTime - this.startTime; this.totalElapsed += elapsed; if(this.tickInterval != null) clearInterval(this.tickInterval); } return this.getElapsed(); } Stopwatch.prototype.reset = function() { this.totalElapsed = 0; // * if watch is running, reset it to current time this.startTime = new Date().getTime(); this.stopTime = this.startTime; } Stopwatch.prototype.restart = function() { this.stop(); this.reset(); this.start(); } Stopwatch.prototype.getElapsed = function() { // * if watch is stopped, use that date, else use now var elapsed = 0; if(this.started) elapsed = new Date().getTime() - this.startTime; elapsed += this.totalElapsed; var hours = parseInt(elapsed / this.onehour); elapsed %= this.onehour; var mins = parseInt(elapsed / this.onemin); elapsed %= this.onemin; var secs = parseInt(elapsed / this.onesec); var ms = elapsed % this.onesec; return { hours: hours, minutes: mins, seconds: secs, milliseconds: ms }; } Stopwatch.prototype.setElapsed = function(hours, mins, secs) { this.reset(); this.totalElapsed = 0; this.totalElapsed += hours * this.onehour; this.totalElapsed += mins * this.onemin; this.totalElapsed += secs * this.onesec; this.totalElapsed = Math.max(this.totalElapsed, 0); // * No negative numbers } Stopwatch.prototype.toString = function() { var zpad = function(no, digits) { no = no.toString(); while(no.length < digits) no = '0' + no; return no; } var e = this.getElapsed(); //return zpad(e.hours,2) + ":" + zpad(e.minutes,2) + ":" + zpad(e.seconds,2); return zpad(e.hours*60 + e.minutes,2) + ":" + zpad(e.seconds,2); } Stopwatch.prototype.setListener = function(listener) { this.listener = listener; } // * triggered every <resolution> ms Stopwatch.prototype.onTick = function() { if(this.listener != null) { this.listener(this); } } // }}} var allquestions = $(".question"); var totalQuestions = allquestions.size(); var myWatch = []; var globalWatch = new Stopwatch(); for (i = 1; i <= totalQuestions; i++) { //Shove the stopwatches for each question into an array. myWatch[i] = new Stopwatch(); thisquestion = $(".question[data-questionnumber='" + i + "']"); thisquestion.find(".timer").text(myWatch[i].toString()); } function updateClock(watch) { var number = $(".question.active").data("questionnumber"); thisquestion.find(".timer").text(myWatch[number].toString()); $(".globaltimer").text(globalWatch.toString()); } function showOnlyQuestion(number) { //Stop all the stopwatches. for (i = 1; i <= totalQuestions; i++) { myWatch[i].stop(); } thisquestion = $(".question[data-questionnumber='" + number + "']"); allquestions.hide(); allquestions.removeClass("active"); thisquestion.show(); thisquestion.addClass("active"); $('.bottombar-highlight').removeClass('bottombar-highlight'); $(".bottombar-questions[data-questionnumber='" + number + "']").addClass('bottombar-highlight'); //Start/resume the appropriate watch and set its listener to update //every second. myWatch[number].start(); myWatch[number].setListener(updateClock); updateButtons(); } function initialiseQuestions() { firstquestion = $(".question").first().data("questionnumber"); showOnlyQuestion(firstquestion); myWatch[1].start(); globalWatch.start(); } function nextQuestion() { var activeQuestion = $(".question.active").data("questionnumber"); var newQuestion = activeQuestion + 1; if (newQuestion <= totalQuestions) { showOnlyQuestion(newQuestion); }; } function previousQuestion() { var activeQuestion = $(".question.active").data("questionnumber"); var newQuestion = activeQuestion - 1; if (newQuestion >= 1) { showOnlyQuestion(newQuestion); } } function updateButtons() { var activeQuestion = $(".question.active").data("questionnumber"); $(".nextButton").show(); $(".previousButton").hide(); $(".fakeSubmitButton").hide(); if (activeQuestion == totalQuestions) { $(".nextButton").hide(); $(".fakeSubmitButton").show(); } if (activeQuestion == 1) { $(".previousButton").hide(); } else { $(".previousButton").show(); } } $(window).resize(function() { if(34*$('.bottombar-questions').length > $(window).width() - 2*$('.nextButton').width()){ $('.pagination').width($(window).width() - 2*$('.nextButton').width() - 2*$('.backscroll').width()); } else { $('.forwardscroll').hide(); $('.backscroll').hide(); } }); $(document).ready(function() { if(34*$('.bottombar-questions').length > $(window).width() - 2*$('.nextButton').width()){ $('.pagination').width($(window).width() - 2*$('.nextButton').width() - 2*$('.backscroll').width()); } else { $('.forwardscroll').hide(); $('.backscroll').hide(); }; $('body').on('click touchstart tap','.forwardscroll',function(){ $('.pagination').animate({ scrollLeft: '+=150' },350); }); $('body').on('click touchstart tap','.backscroll',function(){ $('.pagination').animate({ scrollLeft: '-=150' },350); }); initialiseQuestions(); $('.exit-icon').tooltip(); $('body').on('click touchstart tap', '.question_answer', function(){ var qname = $(this).attr('data-question-id'); var value = $(this).attr('data-answer-value'); $('input[type="radio"][name="'+qname+'"][value="'+value+'"]').prop('checked', true); $(this).prop('checked', false); $('.selected-answer[data-question-id="'+qname+'"]').removeClass('selected-answer'); $(this).addClass('selected-answer'); numberOfQuestionsAttempted++; }); $('body').keydown(function(event) { if (event.which == 37) { event.preventDefault(); $(".previousButton").click(); } if (event.which == 39) { event.preventDefault(); $('.nextButton').click(); } }); $(".nextButton").click(function(e) { nextQuestion(); e.preventDefault(); }); $(".previousButton").click(function(e) { previousQuestion(); e.preventDefault(); }); $('.btn-submit-completed').click(function(){ $('.submitButton').click(); }); $(".fakeSubmitButton").click(function(e) { // Check to see if there are any blank questions if (numberOfQuestionsAttempted < $(".question").length) { // If so, confirm with them. swal({ title: "Submit Answers", text: "Looks like you've left some questions blank. Our system will not regard those questions as having been attempted, and they will be excluded from your score. Obviously this won't happen in the real BMAT, so make sure you mark an answer for everything you want marked.", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Relax, I know what I'm doing. Just mark my answers please :)", closeOnConfirm: true }, function(){ $('.submitButton').click(); }); } else { $('.submitButton').click(); } }); $(".solutionButton").click(function(e) { $(this).parent().parent().find(".solution").slideToggle(); e.preventDefault(); }); var submitted = 0; console.log(submitted); if (submitted == 0) { $("#practice_form").on('submit', function(e) { var form = this; e.preventDefault(); $("body").addClass("loading"); var questions = []; $(".question").each(function() { // Make an object for each question // This should have the question ID, the user Answer and the time taken. questionObj = {}; var question_id = $(this).data('questionid'); var user_answer = $(this).find("input:checked").val(); var time_taken = $(this).find(".timer").text(); if (user_answer == undefined) { var user_answer = "0"; } questionObj['question_id'] = question_id; questionObj['user_answer'] = user_answer; questionObj['time_taken'] = time_taken; // Now we want to put that object within the array of questions questions.push(questionObj); console.log('Logged a question'); }); //Now we want to send this array of questions to the server. //questions.push(token); console.log(questions); console.log($('input[name=_token]').val()); var input = $("<input>") .attr("type", "hidden") .attr("name", "questiondata").val(JSON.stringify(questions)); $('#practice_form').append($(input)); submitted = 1; console.log(submitted); // $("#practice_form").submit(); // form.submit(); /* $.ajax({ url:'/questionbank/practice/processing', data: { questions:questions, _token: $('input[name=_token]').val() }, type:'POST', success:function(data){ console.log("The server has returned usable data! This is good.") console.log(data); // Show the containers containing correct answer + solution + stats $(".solution-container").slideDown(); $(".review-row").slideDown(); $(".timer").hide(); $(".timer-label").hide(); $('.normal-row').hide(); $(".submitButton").remove(); $('.panel-heading-heading').append(': Review'); data.forEach(function(question) { if (question.was_user_correct == true) { backgroundClass = "btn-success"; } else if (question.user_answer == "0") { backgroundClass = "btn-default"; } else if (question.was_user_correct == false) { backgroundClass = "btn-danger"; } // Colorise the review buttons appropriately. $(".review").find('.review-questions[data-questionid='+question.question_id+']').addClass(backgroundClass); // Show the time taken for the user to complete the question. $(".solution-container").find('.user-time-taken[data-questionid='+question.question_id+']').text(question.time_taken); }); }, error:function(data) { alert('failed'); console.log(data); } }); e.preventDefault(); */ }); } });<file_sep>$(document).ready(function () { console.log("Dom loaded"); var isReview = $('.root').data('is-review'); console.log("isReview: " + isReview); console.log("type isReview: " + typeof isReview); $("#questions-div").steps({ headerTag: "h3", bodyTag: "section", transitionEffect: "slideLeft", autoFocus: true, enableAllSteps: true, onFinished: function (event, currentIndex) { if(!isReview) { $("body").addClass("loading"); var questions = []; $(".question").each(function () { // Make an object for each question // This should have the question ID, the user Answer and the time taken. questionObj = {}; var question_id = $(this).data('question-id'); var user_answer = $(this).find("input:checked").val(); if (user_answer == undefined) { var user_answer = "-1"; } questionObj['question_id'] = question_id; questionObj['user_answer'] = user_answer; // Now we want to put that object within the array of questions questions.push(questionObj); console.log('Logged a question'); }); var question_set_id = $('.root').attr('data-question-set-id'); console.log("Question set id: " + question_set_id); var jsonQuestions = JSON.stringify(questions); console.log(jsonQuestions); $("#json_form_data").val(jsonQuestions); console.log($("#submit")); $("#submit").click(); } } }); if (isReview) { $(".question").each(function () { var qid = $(this).data('question-id'); var was_correct = $(this).data('was-correct'); var user_answer = $(this).data('user-answer'); var correct_answer = $(this).data('correct-answer'); console.log("qid: " + qid); console.log("user_answer: " + user_answer); console.log("correct answer: " + correct_answer); // if (was_correct) { // $(this).addClass("light-green"); // } else { // $(this).addClass("light-red"); // } if (user_answer != -1) { $('.question-answer[data-question-id="' + qid + '"][data-answer-value="' + user_answer + '"]').addClass('selected-answer bg-info text-white'); } }); } if (!isReview) { $('body').on('click touchstart tap', '.question-answer', function () { console.log("Clicked: " + this); var qid = $(this).attr('data-question-id'); var value = $(this).attr('data-answer-value'); $('input[type="radio"][name="' + qid + '"][value="' + value + '"]').prop('checked', true); $('.selected-answer[data-question-id="' + qid + '"]').removeClass('selected-answer bg-info text-white'); $(this).addClass('selected-answer'); $(this).addClass('bg-info text-white'); }); } }); <file_sep># --- Created by Ebean DDL # To stop Ebean DDL generation, remove this comment and start using Evolutions # --- !Ups create table question ( id bigserial not null, statement TEXT, options json, correct_option_index integer, answer_explanation TEXT, constraint pk_question primary key (id) ); create table question_set ( id bigserial not null, name varchar(255), constraint pk_question_set primary key (id) ); create table question_set_question ( question_set_id bigint not null, question_id bigint not null, constraint pk_question_set_question primary key (question_set_id,question_id) ); alter table question_set_question add constraint fk_question_set_question_question_set foreign key (question_set_id) references question_set (id) on delete restrict on update restrict; create index ix_question_set_question_question_set on question_set_question (question_set_id); alter table question_set_question add constraint fk_question_set_question_question foreign key (question_id) references question (id) on delete restrict on update restrict; create index ix_question_set_question_question on question_set_question (question_id); # --- !Downs alter table if exists question_set_question drop constraint if exists fk_question_set_question_question_set; drop index if exists ix_question_set_question_question_set; alter table if exists question_set_question drop constraint if exists fk_question_set_question_question; drop index if exists ix_question_set_question_question; drop table if exists question cascade; drop table if exists question_set cascade; drop table if exists question_set_question cascade; <file_sep>package controllers.pojo; import models.Question; public class Review { public Question question; public long userAnswer; public boolean wasCorrect; } <file_sep>package controllers; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import controllers.pojo.QuestionAnswer; import controllers.pojo.Review; import models.Question; import models.QuestionSet; import play.Logger; import play.mvc.Controller; import play.mvc.Result; import views.html.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class QuestionSetController extends Controller { private ObjectMapper mapper = new ObjectMapper(); public Result index() { List<QuestionSet> questionSets = QuestionSet.find.all(); return ok(QuestionSetsIndex.render("Question Sets", questionSets)); } public Result questionSet(Long id) { QuestionSet questionSet = QuestionSet.find.byId(id); return ok(QuestionSetDisplay.render("Question Set " + id, questionSet)); } public Result questionSetFlow() { return ok(QuestionSetFlow.render()); } public Result questionSetReview(Long id) throws IOException { QuestionSet questionSet = QuestionSet.find.byId(id); Map<String, String[]> map = request().body().asFormUrlEncoded(); String json = map.get("json_form_data")[0]; Logger.debug("Json received: " + json); List<QuestionAnswer> questionAnswers = mapper.readValue(json, new TypeReference<List<QuestionAnswer>>() { }); List<Review> reviews = new ArrayList<>(); for(QuestionAnswer questionAnswer: questionAnswers) { Question question = questionSet.getQuestionList(). stream().filter(q -> q.getId().equals(questionAnswer.questionId)) .collect(Collectors.toList()).get(0); Review review = new Review(); review.wasCorrect = question.correctOptionIndex == questionAnswer.userAnswer; review.userAnswer = questionAnswer.userAnswer; review.question = question; reviews.add(review); } String responseJson = mapper.writeValueAsString(reviews); Logger.info("Review: " + responseJson); return ok(QuestionSetReview.render("Question Set Review " + id, questionSet, reviews)); } } <file_sep>@(title: String)(questionSet: QuestionSet) @import java.math.BigInteger; var index=0 @main(title) { <div data-is-review=false data-question-set-id="@questionSet.id" class="root container"> <div class="container mt-1"> <h3>@questionSet.name</h3> </div> <div class="container mt-2"> <form id=practice_form" method="post" action="/questionsets/review/@questionSet.id"> <input type="hidden" name="json_form_data" id="json_form_data"> <div id="questions-div"> @for(question <- questionSet.getQuestionList) { @(index += 1) <h3>@index</h3> <section> <div class="row mt-1"> <div class="col-md-12"> <div> <span>@index</span> <span>/@questionSet.questionList.size()</span> </div> </div> </div> <div class="row bg-faded question" data-question-id="@question.id"> <div class="col-md-6"> <p>@Html(question.statement)</p> </div> <div class="col-md-6 "> <div> @for(option <- question.getOptions) { <div data-question-id="@question.id" data-answer-value="@question.getOptions.indexOf(option)" class="question-answer clickable"><span>@{ (question.getOptions.indexOf(option) + 'A').toChar } </span> @option </div> <input style="display:none" class="hidden-xl-up" type="radio" name="@question.id" value="@question.getOptions.indexOf(option)"> } </div> </div> </div> </section> } </div> <input id ="submit" class="btn-success btn-lg" type="submit" value="Submit Test"> </form> </div> </div> <script src="@routes.Assets.versioned("javascripts/app.js")"></script> }
d51f8bf4ff86eb62bcc868c675e7b38c1285e21e
[ "JavaScript", "Java", "HTML", "SQL" ]
10
HTML
ka4tik/play-java
4d4bcd313d66075a55f5ec8591bfefb07cd2451e
10169d0b2618198a6d5e3d70e83409c1148ea051
refs/heads/master
<repo_name>RiyamGithub/Udacity-Projects---FEND<file_sep>/project9/neighborhood-map-p9-fend/README.md ## Udacity - Student RIYAM | Front End Web Developer - FEND - P9 - Neighborhood Map Date: April 21, 2019 Udacity Front End Web Developer Nanodegree project Welcome and have a great time .... :) ## Table of Contents - [Project Overview](#Project Overview) - [How to use](#How to use) - [How run on your local machine](#How run on your local machine) - [Create React App](#Create React App) - [How to run the projet in developer mode](#How to run the projet in developer mode) - [Service Worker](#Service Worker) - [Dependencies](#dependencies) - [ What I Use To built the Feed Reader Project](# What I Use To built the Feed Reader Project) - [Resources](#resources) - [Notes](#notes) - [License](#license) ### Project Overview This is Project 9 (Maps) is the end for the Udacity FEND course. This Project is single page app uses the Google Maps API to insert a map and the map location markers. It also uses the Foursquare Developer API, Wikipedia API to fetch the location information, Flickr.com provides photos of the historical places in Jordan where available, In this map, I am locating some historical places . ### How to use The user can click on marker to display an infowindow containing the name of the place, a link to pictures coming from Flickr taken around that place (if avaialble) and a tip coming from Foursquare (if avaialble). He also can show a sidebar with a text input at the top and a list of the places. In sideBar You will get a list of historical places and you can type into the text input in some text to filter the location. The user can click on Item Nav to display a information coming from Wikipedia.com shown in accordance of the places matching the query. Clicking anywhere outside the infowindow closes the infowindow and clicking anywhere on the map closes any active infowindow display. This project uses React along with some APIs and other external dependencies. Namely: * Google Maps * FourSquare * Flickr * Wikipedia * Font Awesome icon * google-maps-react for primary map display The purpose of the project is to demonstrate a good understanding of: reactJS, javascript, API usage, HTML, CSS, responsive design, and front-end web development overall. ### How run on your local machine * To run this file, download the GitHub zip file or clone the repository. * Open the root folder of the repository in a terminal * Get started by intalling npm, please follow this tutorial - http://blog.npmjs.org/post/85484771375/how-to-install-npm * install all project dependencies with `npm install` * start the development server with `npm start` ### Create React App This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). You can find more information on how to perform common tasks [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). ### How to run the projet in developer mode: 1. Download this repo 2. Run: npm install in working directory 3. Install Dependances (see Dependances) 4. Run npm start to initialize. A new browser window will initialize and display the app. In case it doesn't, navigate to http://localhost:3000/ in your browser ### Service Worker The service worker will cashe the app in Production mode. Take the folowing steps: 1. npm run build 2. npm install -g serve 3. In build directory: serve -s The app will be hosted at http://localhost:5000 ### Dependencies: React NPM Dependencies 1. react-google-map ([follow this link](https://tomchentw.github.io/react-google-maps/#introduction) for documentation) 2. prop-types 3. sort-by 4. jquery --save 5. react-detect-offline 6. escape-string-regexp 7. fetch-jsonp 8. @fortawesome/react-fontawesome 9. @fortawesome/fontawesome-svg-core 10. @fortawesome/free-solid-svg-icons ### What I Use To built the Feed Reader Project * Font Awesome Library ## https://fontawesome.com/start * Fonts - Google Fonts ## https://fonts.google.com/ * WEB Accessibility in mind - color ## https://webaim.org/resources/contrastchecker/ * HTML5/CSS3 * DOM * Object Oriented JavaScript ES6 * jQuery * HTML5 * React.js * Foursquare * Flickr * Wikipedia * Google Maps ### Resources: Udacity - Udacity teaching material * W3Schools * MDN Web Docs * Stack Overflow * YouTube: - Elharony's YouTube walkthrough: [Udacity | Neighborhood Map - Intro and Creating our React App](https://www.youtube.com/watch?v=ywdxLNjhBYw&t=1s) - <NAME>'s YouTube walkthrough: [Neighborhood Map - Setup Project](https://www.youtube.com/watch?v=ktc8Gp9jD1k&list=PL4rQq4MQP1crXuPtruu_eijgOUUXhcUCP) ### Notes This app was scaffolded using `create-react-app`. By default, this application runs in a development build which does come with a Service Worker. The Service Worker will only work in the production build. You can download and create a production build by running the following commands. ``` npm run build ``` ### License This is a project for Udacity and is believed to use a [MIT License](https://opensource.org/licenses/MIT). This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.<br> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.<br> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting ### Analyzing the Bundle Size This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size ### Making a Progressive Web App This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app ### Advanced Configuration This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration ### Deployment This section has moved here: https://facebook.github.io/create-react-app/docs/deployment ### `npm run build` fails to minify This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify <file_sep>/MyReads P8 - FEND/src/components/SearchBooks.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import * as BooksAPI from '../BooksAPI'; import Book from './Book'; class SearchBooks extends Component { // Set types for properties static propTypes = { books: PropTypes.array.isRequired, onMoveBook: PropTypes.func.isRequired } state = { query: '', searchedBooks: [] } updateQuery = query => { if(query.length > 0) { this.setState(() => ({ searchedBooks: [], query: query })) this.updateSearch(query) } else{ this.clearQuery() } } clearQuery =() => { this.setState({ query: '', searchedBooks: [] }) } updateSearch = query => { if (query.length > 0) { BooksAPI.search(query).then(searchedBooks => { if (searchedBooks.error) { this.setState({ searchedBooks: [] }) } else { this.setState({ searchedBooks }) } }) } else { this.setState({ searchedBooks: [] }) } } render() { const {books, onMoveBook} = this.props const {query, searchedBooks} = this.state return ( <div className="search-books"> <div className="search-books-bar"> <Link className="close-search" onClick={this.clearQuery} to="/"> Close </Link> <div className="search-books-input-wrapper"> <input type="text" placeholder="Search by title or author" value={query } onChange={(e) => this.updateQuery(e.target.value)} /> </div> </div> <div className="search-books-results"> <ol className="books-grid"> {searchedBooks.map(searchedBook => { let shelf= 'none' books.map(book => ( (book.id === searchedBook.id) && (shelf = book.shelf) )) return ( <li key={searchedBook.id}> <Book book={searchedBook} moveBook={onMoveBook} currentShelf= {shelf} /> </li> ) })} </ol> <Link to='/' className="return-home"></Link> </div> </div> ); } } export default SearchBooks;<file_sep>/Arcade Game P3- FEND/README.md # Udacity - Student RIYAM | Front End Web Developer - FEND - P3 Classic Arcade Game Project Welcome and have a great time .... # Classic Arcade Game Clone Project This is an arcade game, made for Udacity Frontend Nanodegree project ## Table of Contents - [What is the Classic Arcade Game](#What is the Classic Arcade Game) - [How The Game Works](#How The Game Works) - [Game Rules](#Game Rules) - [How I built the Classic Arcade Game](#How I built the Classic Arcade Game) - [What I Use To built the Classic Arcade Game](#What I Use To built the Classic Arcade Game) - [Contribution and Resources](#Contribution and Resources) - [How You Can Get The Game To Play](#How You Can Get The Game To Play) ## What is the Classic Arcade Game A fun and simple game, the story of Challenge between player and enemies(bugs). The player should cross the road to reach the water and get 50 points but the player should be carefull and do not touch the bugs unless that the player will lose one heart. Along the way, there is many gifts help to get 100 points from collect star, gem and key and also there is a haert to help the player to get one heart each time collect it to be strong. IF the player lose all hearts then the player can play again. ## How The Game Works User can use left, right, up, and down arrow keys to move the player each time in the canvas. User can use Enter key to start / restart. User can use Space key to pause / continue. ## Game Rules 1- You have 3 Hearts, by touching any bugs, you will lose one Heart. 2. Reaching the water increase your score by +50 points , collect the items to get +100 points 3. Increase player score until reach the final is 1000 points to win. 4. Have fun and challenge the bugs ... ## How I built the Classic Arcade Game To build this game, I had the following files project was provided by Udacity to start: 1- The HTML structure. 2- The game engine 3- The resources and images. * create popup modal at the begin of the game to read rules of the game. * add a points counte score, Heart, star, gem, key counter and create start/restart - pause/continue buttons. * create the classes, the new objects and add their methods * Game should have the ability to render the tiles, enemies, player, items. * Set the length of each tile for the player character to move. * Keep enemies and the player inside the canvas during move. * Game should be able to control the movement of the player only inside the canvas when use the keys and the enemies to move out and back into the canvas from beginning with randomizing it's speed. * Return the player to the starting position any time it collide with an enemy, start or restart the Game. * Create list of players in case to change default player. * Something happens when player wins or lose Game. ## What I Use To built the Classic Arcade Game * Font Awesome Library #### https://fontawesome.com/start * normalize.css - Very Nice Rest #### https://necolas.github.io/normalize.css/ * HTML5 * CSS3 * Object Oriented JavaScript * DOM * canvas ( optional) ## Contribution and Resources * Udacity - Udacity teaching material * W3Schools * MDN Web Docs * Stack Overflow ## How You Can Get The Game To Play If you want to play it locally on your computer: - clone the game from repo or download as Zip - Extract zip - open the folder then You will find (index.html ) open it in any of your favourit browser. - play the game and challenge the enemies(bugs). <file_sep>/Feed Reader Testing P4- FEND/jasmine/spec/feedreader.js /* jshint esnext: true */ /* jshint browser: true */ /* esnext": true */ /* jscs:esnext */ /* global, console */ /* alert, prompt */ /* start with letters, underscore, $ */ /* feedreader.js /* * This is the spec file that Jasmine will read and contains * all of the tests that will be run against your application. */ /* We're placing all of our tests within the $() function, * since some of these tests may require DOM elements. We want * to ensure they don't run until the DOM is ready. */ $(function () { /* This is our first test suite - a test suite just contains * a related set of tests. This suite is all about the RSS * feeds definitions, the allFeeds variable in our application. */ /******************************************************************************* TODO: Start Test suite 1 *******************************************************************************/ describe('RSS Feeds', function () { /* This is our first test - it tests to make sure that the * allFeeds variable has been defined and that it is not * empty. Experiment with this before you get started on * the rest of this project. What happens when you change * allFeeds in app.js to be an empty array and refresh the * page? */ /* TEST 1.1 * Determines If allfeeds Has Been Defined And That It Is Not Empty */ it('Each Feeds Are Defined', function () { expect(allFeeds).toBeDefined(); expect(allFeeds.length).not.toBe(0); }); /* TODO: Write a test that loops through each feed * in the allFeeds object and ensures it has a URL defined * and that the URL is not empty. */ /* TEST 1.2 * Determines If allFeeds Have A Url And That The Url Is Not Empty */ it('Each Has URL And Urls Are Defined', function () { for (var feed of allFeeds) { expect(feed.url).not.toBeUndefined(); expect(feed.url.length).toBeGreaterThan(0); } }); /* TODO: Write a test that loops through each feed * in the allFeeds object and ensures it has a name defined * and that the name is not empty. */ /* TEST 1.3 * Determines if allFeeds Have A Name And That The Name Is Not Empty */ it('Each Has Name And Names Are Defined', function () { for (var feed of allFeeds) { expect(feed.name).not.toBeUndefined(); expect(feed.name.length).toBeGreaterThan(0); } }); }); /******************************************************************************* TODO: End Test suite 1 *******************************************************************************/ /******************************************************************************* TODO: Start Test suite 2 *******************************************************************************/ /* TODO: Write a new test suite named "The menu" */ describe('The Menu', function () { var body, menuIconLink; beforeEach(function () { body = document.querySelector('body'); menuIconLink = document.getElementsByClassName('menu-icon-link')[0]; }); afterEach(function () { body = null; menuIconLink = null; }); /* TODO: Write a test that ensures the menu element is * hidden by default. You'll have to analyze the HTML and * the CSS to determine how we're performing the * hiding/showing of the menu element. */ /* TEST 2.1 * This Ensures The body Tag Has The Class menu-hidden * This Test to Ensure The Menu Element Is Hidden By Default */ it('Menu Is Hidden By Default', function () { expect(body.classList.contains('menu-hidden')).toBeTruthy(); }); /* TODO: Write a test that ensures the menu changes * visibility when the menu icon is clicked. This test * should have two expectations: does the menu display when * clicked and does it hide when clicked again. */ /* TEST 2.2 * This Simulates : * The Click On Menu Icon And Checks The Presence * Of menu-hidden Tag After Clicks */ it('Menu Is Visible(on) Or Hidden(off) When Menu Icon Link Is Clicked', function () { /* When The menu icon Is Clicked, The Class Name "menu-hidden" * Has To Be Exactly */ menuIconLink.click(); expect(body.classList.contains('menu-hidden')).toBeFalsy(); /* When The menu icon Is Clicked Again, The Class Name "menu-hidden" * Should Be Removed. */ menuIconLink.click(); expect(body.classList.contains('menu-hidden')).toBeTruthy(); }); }); /******************************************************************************* TODO: End Test suite 2 *******************************************************************************/ /******************************************************************************* TODO: Start Test suite 3 *******************************************************************************/ /* TODO: Write a new test suite named "Initial Entries" */ describe('Initial Entries', function () { /* TODO: Write a test that ensures when the loadFeed * function is called and completes its work, there is at least * a single .entry element within the .feed container. * Remember, loadFeed() is asynchronous so this test will require * the use of Jasmine's beforeEach and asynchronous done() function. */ /* * The beforeEach-function With The Parameter done Is Run * Before All Of The Asynchronous Tests. * It Is Called Within The Async * Tests To Tell The Tests When They Should Stop. * loadFeed(0) Loads The First Feed. * After That Is done, The Tests Can Begin. */ //Load First Feed Before Execute Our Test beforeEach(function (done) { //Load The First Feed , Then Call Done loadFeed(0, function () { done(); }); }); /* TEST 3.1 * Pass done As A Parameter To The Funciton To Tell It That * It Has To Rely On The Asynchronous Testing. * Call The done()-function When The Test Is Done. */ it('Feed Container Has At Least 1 Or More Entries Avaliable After LoadFeed Is Called ', function (done) { //Grabe The Number Of Articals let contents = document.querySelectorAll('.feed .entry'); //Make Sure There Is One Entry Or More Than Zero Entries expect(contents.length).toBeGreaterThan(0); done(); }); /* TEST 3.2 * Make Sure Each Entry Link Start With http:// or https:// * Resources expression: * https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */ it("Each Entry Link Starting With 'http(s)://'", function (done) { let entries = document.querySelector('.feed').getElementsByClassName('entry-link'); var expression = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/; var regex = new RegExp(expression); console.log(entries); for (var i = 0; i < entries.length; i++) { let entry = entries[i]; expect(entry.href).toMatch(regex); } done(); setTimeout(done, 1000); }); }); /******************************************************************************* TODO: End Test suite 3 *******************************************************************************/ /******************************************************************************* TODO: Start Test suite 4 *******************************************************************************/ /* TODO: Write a new test suite named "New Feed Selection" */ describe('New Feed Selection', function () { var firstFeed, secondFeed; /* TODO: Write a test that ensures when a new feed is loaded * by the loadFeed function that the content actually changes. * Remember, loadFeed() is asynchronous. */ /* Before The Tests Are Started, The First Feed Load, * Its Content Is Stored In firstFeed Variable So That It * Can Be Later Compared To The New Feed (second feed). * After This Is Finished, The New Feed load(1) Is Loaded. */ //Start Loading Two Different Feeds beforeEach(function (done) { loadFeed(0, function () { var feed = document.querySelector('.feed').innerHTML; firstFeed = feed; loadFeed(1, function () { done(); }); }); }); afterEach(function () { feed = null; firstFeed = null; secondFeed = null; }); /* This Test Ensures That When A New Feed Is Loaded * By The loadFeed function That The Content Actually Changes. * Remember, loadFeed() Is Asynchronous. * The innerHTML Of The First Feed Is Compared To That Of * The New Feed(seconf feed). * When They ASre Different, The Feed's Content Has Changed * Properly. */ it('Change Content With Load New Feeds', function (done) { var feed = document.querySelector('.feed').innerHTML; var secondFeed = feed; expect(firstFeed).not.toBe(secondFeed); done(); setTimeout(done, 1000); }); }); /******************************************************************************* TODO: End Test suite 4 *******************************************************************************/ }()); <file_sep>/project9/neighborhood-map-p9-fend/src/Modals/ModalFlickr.js import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faWindowClose } from '@fortawesome/free-solid-svg-icons'; class Modal extends React.Component { constructor(props) { super(props); this.state = { } } render() { return ( <div> {this.props.isVisible ?( <div id="modal" tabIndex={0}> <span className="close" tabIndex="0" role="button" onClick={this.props.closeModal}> <FontAwesomeIcon icon={faWindowClose} /> </span> <h1>{this.props.modalTitle}</h1> <p className="attributionFlickr">Provided by Flickr.com</p> <div className="modal-body-flickr"> <div id="images"></div> </div> </div> ):null} </div> ) } } export default Modal;<file_sep>/Memory Game P2- FEND/js/script.js /*jshint esnext: true*/ /* jshint browser: true */ /*esnext": true*/ /* jscs:esnext */ /* global, console*/ /* alert, prompt */ /* start with letters, underscore, $ */ /* * Create a list that holds all of your cards */ /* * set up the event listener for a card. If a card is clicked: * - display the card's symbol (put this functionality in another function that you call from this one) * - add the card to a *list* of "open" cards (put this functionality in another function that you call from this one) * - if the list already has another card, check to see if the two cards match * + if the cards do match, lock the cards in the open position (put this functionality in another function that you *call from this one) * + if the cards do not match, remove the cards from the list and hide the card's symbol (put this functionality in *another function that you call from this one) * + increment the move counter and display it on the page (put this functionality in another function that you call *from this one) * + if all cards have matched, display a message with the final score (put this functionality in another function that *you call from this one) */ /* * info Function To Read Instruction */ /*function info(){ alert('Grading System :\n\n (0<moves<12): Moves = Great!\n\ (13<moves<24): Moves = Average \n\ (25>moves) moves = Poor :( \ '); }*/ /* * Create a list that holds all of your cards */ /*const cards = ['far fa-gem', 'far fa-gem', 'far fa-paper-plane', 'far fa-paper-plane', 'fas fa-anchor', 'fas fa-anchor', 'fas fa-bolt', 'fas fa-bolt', 'fas fa-cubes', 'fas fa-cubes', 'fas fa-leaf', 'fas fa-leaf', 'fas fa-bicycle', 'fas fa-bicycle', 'far fa-envelope', 'far fa-envelope'];*/ /* Read Me : I use This Method But Happened To Me Many Errors And Stop Created Cards, I lost many Time const symbols = [ "far fa-gem", "far fa-paper-plane", "fas fa-anchor", "fas fa-bolt", "fas fa-cubes", "fas fa-leaf", "fas fa-bicycle", "far fa-envelope" ];// save all the initial symbols into one array. //Diplicate Cards const cards = [...symbols, ...symbols];// will have the same effect as the spread syntax. or let cards =symbols.concat(symbols); */ /* * Display the cards on the page * - shuffle the list of cards using the provided "shuffle" method below * - loop through each card and create its HTML * - add each card's HTML to the page */ // Shuffle function from http://stackoverflow.com/a/2450976 function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } //Select the Parent To Put the Cards Inside const deckCards = document.getElementById("deckCard"); // Array To Collect 2 Cards Each Time To Compare Them let memoryCard = []; // Array To Contains All Cards That Are Matched To Compre With original Cards array Length To Over Game let matchCards = []; //Select All Cards By Class Name let card = document.getElementsByClassName("card"); //Array Collect All Cards let cards = [...card]; /* * Initialize the Game */ function init() { // Shuffle function cards = shuffle(cards); //Initiliaze Deck for (var i = 0; i < cards.length; i++) { deckCards.innerHTML = ""; [].forEach.call(cards, function (item) { deckCards.appendChild(item); }); //Restart All Card From Classes cards[i].classList.remove("show", "open", "match", "disable"); } //Restart All The Variables To Start Game Correctly restartContent(); } //Add Event Listener To Each Card for (var i = 0; i < cards.length; i++) { cards[i].addEventListener("click", display); } let firstCard, secondCard; let firstCardFlip = false; function display(evt) { if (evt.target.nodeName === "LI") { //prevent To Click On First Card Twice if (this === firstCard) { return; } // Give To First And Second Cards Classes To Open - Show - Disable this.classList.add("open", "show", "disable"); //Check If this Is First card To store It In MemeoryCard Array To Compare First And Second if (!firstCardFlip) { firstCardFlip = true; firstCard = this; memoryCard.push(firstCard); return; } // This For Second Card and Store It In memoryCard To Compare First And Second firstCardFlip = false; secondCard = this; memoryCard.push(this); // Check If MemoryCard Contain 2 Cards if (memoryCard.length === 2) { // start Count Move addMove(); // Compare Two cards if (memoryCard[0].type === memoryCard[1].type) { // Do This Function If Two Cards Are Match sameCards(); } else { //Do This Function If Two Cards Are Not Match differentCards(); } } } } /* * sameCards Function To Check If Two Cards Are Matcher */ function sameCards() { memoryCard[0].classList.add("match", "disable"); memoryCard[1].classList.add("match", "disable"); memoryCard[0].classList.remove("show", "open"); memoryCard[1].classList.remove("show", "open"); matchCards.push(memoryCard[0], memoryCard[1]); memoryCard = []; //Check If The Game Is Over endGame(); } /* * different Function To Check If Two Cards Are Not Match */ function differentCards() { disbling(); setTimeout(function () { disbling(); memoryCard[0].classList.remove("show", "open"); memoryCard[1].classList.remove("show", "open"); enable(); memoryCard = []; }, 1100); } //select Only Two Cards and Prevent Selected The Others Cards Until Check If The Two Cards Are Match Or Not function disbling() { cards.map(function (card) { card.classList.add('disable'); }); } // Let The Two Cards Are Match Disable And The Others Cards Enable To Select let CardMatched = document.getElementsByClassName("match"); function enable() { cards.map(function(card) { card.classList.remove('disable'); for (var i = 0; i < CardMatched.length; i++) { CardMatched[i].classList.add("disable"); } }); } /* * MovesContainer Function to Count Move And Then Rating Stars */ const movesContainer = document.querySelector('.moves'); let moves = 0; movesContainer.innerHTML = 0; function addMove() { moves++; if (moves === 1) { startTimer(); } movesContainer.innerHTML = moves; // Set the Rating rating(); } /* * Rating Function To Rate Player */ const ratingStars = document.querySelector('.stars'); function rating() { switch (moves) { case 15: ratingStars.innerHTML = `<li><i class="fas fa-star"></i></li> <li><i class="fas fa-star"></i></li>`; break; case 25: ratingStars.innerHTML = `<li><i class="fas fa-star"></i></li>`; } } let minutes = 0; let seconds = 0; let hours = 0; let interval; let myTimer = document.querySelector(".timer"); /* * startTimer Function To Collect Time That Player take */ function startTimer() { interval = setInterval(function () { myTimer.innerHTML = `<i class="far fa-clock"></i>&nbsp;&nbsp;` + hours + ':' + minutes + ':' + seconds; seconds++; if (seconds === 60) { minutes++; seconds = 0; } else if (minutes === 60) { hours++; minutes = 0; } }, 1000); } /* * Restart Game By Using Button restart On The Top Of Deck */ const restartBtn = document.querySelector('.restart'); restartBtn.addEventListener('click', function () { //Delete All Cards deckCards.innerHTML = ''; //Restart Any Related Variable restartContent(); //Call Init To Initilize Cards init(); }); /* * Restart All The Variables To Start Game Correctly */ function restartContent() { //Restart Any Related Variable memoryCard = []; matchCards = []; [firstCard, secondCard] = [null, null]; firstCardFlip = false; moves = 0; movesContainer.innerHTML = moves; ratingStars.innerHTML = `<li><i class="fas fa-star"></i></li> <li><i class="fas fa-star"></i></li> <li><i class="fas fa-star"></i></li>`; minutes = 0; seconds = 0; hours = 0; let myTimer = document.querySelector(".timer"); myTimer.innerHTML = `<i class="far fa-clock"></i>&nbsp;&nbsp;` + hours + ':' + minutes + ':' + seconds; clearInterval(interval); } /* * Show Or Hide Modal Info Screen */ var modal = document.getElementById("myInfoModal"); var btn1 = document.getElementById("info-Btn"); var span = document.getElementsByClassName("info-modal-close")[0]; btn1.onclick = function (event) { if (event.target === btn1) { modal.style.display = 'block'; } }; span.onclick = function () { modal.style.display = "none"; }; window.onclick = function (event) { if (event.target === modal) { modal.style.display = 'none'; } }; /* * endGame Function to Show Modal Winner If the Game Is Over To See The Result Then Close Or Play Again */ let modalWinner = document.getElementById("myWinnerModal"); span = document.getElementsByClassName("winner-modal-close")[0]; let button = document.getElementsByClassName("winner-Btn")[0]; function endGame() { //Compaier Between memoryCards length and cards length To Check If The Game Is Over if (matchCards.length === cards.length) { // Restart Timer let lastTime = myTimer.innerHTML; minutes = 0; seconds = 0; hours = 0; myTimer.innerHTML = `<i class="far fa-clock"></i>&nbsp;&nbsp;` + hours + ':' + minutes + ':' + seconds; clearInterval(interval); //Store Star rating In A Variable To Use It to Show The Result let starsWinner = document.querySelector('.stars').innerHTML; // Stor All Info Need To Show It In A winner Result on Modal document.getElementById('result-moves').innerHTML = moves; document.getElementById('result-stars').innerHTML = starsWinner; document.getElementById('result-timer').innerHTML = lastTime; // Show Congratulation Modal modalWinner.style.display = 'block'; // Close Winner Modal span.onclick = function () { modalWinner.style.display = "none"; clearInterval(interval); //Delete All Cards deckCards.innerHTML = ''; //Restart Variable restartContent(); //Call Init To Create Cards init(); }; window.onclick = function (event) { if (event.target === modalWinner) { modalWinner.style.display = 'none'; clearInterval(interval); //Delete All Cards deckCards.innerHTML = ''; //Restart Variable restartContent(); //Call Init To Create Cards init(); } }; //Play Again button.onclick = function () { modalWinner.style.display = "none"; clearInterval(interval); //Delete All Cards deckCards.innerHTML = ''; //Restart Variable restartContent(); //Call Init To Create Cards init(); }; } } //Start The game for the First Time document.body.onload = init(); <file_sep>/Feed Reader Testing P4- FEND/README.md # Udacity - Student RIYAM | Front End Web Developer - FEND - P4 Feed Reader Project # ================================================================================= Welcome and have a great time .... # Feed Reader Clone Project This is a feed reader, made for Udacity Front-End Developer Nanodegree project Project provided by Udacity via GitHub Clone it or download from: https://github.com/udacity/frontend-nanodegree-feedreader ## Table of Contents - [Project Overview Given By Udacity](#Project Overview Given By Udacity) - [Feed Reader Testing in Jasmine.js](#Feed Reader Testing in Jasmine.js) - [How You Can Run The Project](#How You Can Run The Project) - [Notes On Running Project](#Notes On Running Project) - [About Tests In This Project](#About Tests In This Project) - [What I Use To built the Feed Reader Project](#What I Use To built the Feed Reader Project) - [Contribution and Resources](#Contribution and Resources) ## Project Overview Given By Udacity The Udacity overview for this project states: "In this project you are given a web-based application that reads RSS feeds. The original developer of this application clearly saw the value in testing, they've already included [Jasmine](http://jasmine.github.io/) and even started writing their first test suite! Unfortunately, they decided to move on to start their own company and we're now left with an application with an incomplete test suite. That's where you come in." ## Feed Reader Testing in Jasmine.js ## About the Project In this project given to me by Udacity for my Nanodegree Course which has contained to test a feedReader code in Jasmine.js with jQuery to select DOM elements. These will test the application as well as the event handling and DOM manipulation. And must pass the required tests, So I implemented the [Jasmine](http://jasmine.github.io/) testing framework to write a number of test suites and attendant _specs_ were written for a series of issues so the application could be tested to determine if the Javascript is working properly. ## How You Can Run The Project If you want to run it locally on your computer: - clone the project from repo or download as Zip - Extract zip - open the folder then You will find (index.html ) open it in any of your favourit ES6 compatible browser. - There should be acble to see the feeds load with 8 specs, 0 failures at the bottom of the html page. ## Notes On Running project After open the index.html file in the browser.Jasmine will automatically execute the test suites and their results will show at the bottom of the html page. Just under the words (Jasmine) each test will have either a red X or a green dot. A red X signifies a failing test, while a green dot signifies a test passing. Just under the green dots and/or red x's there is state of the number of tests, followed by the number of tests that failed. Just right of the state you will see the words (finished in x.xxxs) that the time it took to run all the tests. ## About Tests In This Project 1- Tests that allfeeds has been defined and that it is not empty. 2- Tests that loops through each feed in the allFeeds have a url and that the url is not empty. 3- Tests that loops through each feed in the allFeeds have a name and that the name is not empty. 4- Tests that the menu element is hidden by default. 5- Test that the menu changes visibility when the menu icon is clicked showing/hiding menu. 6- Test that there is at least a single entry element within the feed container. 7- Test that the entry-links start with "http://" or "https://". 8- Test that content actually changes when a new feed is loaded by the loadFeed function to see if two entries are not equal. Finally all tests are happy ## What I Use To built the Feed Reader Project * Font Awesome Library ## https://fontawesome.com/start * normalize.css - Very Nice Rest ## https://necolas.github.io/normalize.css/ * Icomoon - Pixel Perfect Icon Solutions ## https://icomoon.io/ * Fonts - Google Fonts ## https://fonts.google.com/ * HTML5/CSS3 * DOM * Object Oriented JavaScript ES6 * jsapi by Google * HandlebarsJS * Jasmine * Bootstrap * jQuery ## Contribution and Resources * Udacity - Udacity teaching material * W3Schools * MDN Web Docs * Stack Overflow * YouTube QAShahin: https://www.youtube.com/watch?v=Ac2sBrkSK-c&list=PL_noPv5wmuO9op-OQ22SbHcqFGGHA6iIZ * Jest Web Site: https://jest-bot.github.io/jest/docs/using-matchers.html * npmjs Web site: https://docs.npmjs.com/cli-documentation/ <file_sep>/project9/neighborhood-map-p9-fend/src/Data/Places.js export const Locations = [ { name: 'Al-Khazneh', position: {lat: 30.32224844024984, lng: 35.451722145080566}, venue_id: '4ecd1f3cd3e377110d4a76a8', }, { name: '<NAME>', position: { lat:30.337814021849717, lng: 35.43045076606644}, venue_id: '4ece18ec29c223f9263956b7', }, { name: 'Petra', position: { lat: 30.324841521406704, lng: 35.44843912124634}, venue_id: '4ba4a248f964a520bba838e3', }, { name: "<NAME>", position: {lat: 31.95412853252949, lng: 35.93651533126831}, venue_id: '4ba75d44f964a520608e39e3', }, { name: '<NAME>', position: {lat: 31.182049925844357, lng: 35.702266265580064}, venue_id: '4db93cd18154ce84dc22f589', }, { name: '<NAME>', position: {lat: 32.32540886251235, lng: 35.72786092758179}, venue_id: '4c37226d3849c928e41cbdb1', }, { name: '<NAME> (Amman)', position: {lat: 31.952368259346624, lng: 35.93911998478296}, venue_id: '4ba76ec2f964a5207b9339e3', }, { name: 'Siq', position: {lat: 30.321877994481145, lng: 35.46090602874756}, venue_id: '50af750be4b03c6b1d7df618', }, { name: '<NAME> (Amman)', position: {lat: 31.953754429661394, lng: 35.935705489328356}, venue_id: '4e27c40d6284ab5e8acfa575', }, { name: 'Jarash', position: {lat: 32.28190818349021, lng: 35.90087413787842}, venue_id: '4be275751dd22d7fa12d94bd', }, { name: '<NAME>', position: {lat: 31.80183583374716, lng: 36.58738961900393}, venue_id: '4be51537bcef2d7fa07903e5', }, { name: '<NAME>', position: {lat: 31.913071944259567, lng: 35.75207335462714}, venue_id: '4d6e2832fbb8a1cdff746f0f', }, ]; <file_sep>/project9/neighborhood-map-p9-fend/src/App.js import React, { Component } from 'react'; //import styles for the app import './Styles/App.css'; import Map from './Components/mapContainer'; //import when online, offline to display a message when offline import {Online, Offline} from 'react-detect-offline'; class App extends Component { render() { return ( <div className="App" role="main"> <header className="header" aria-label="Application Header - Historical Sites In Jordan " tabIndex={0}> <div className="container-header-nav"> <div className="header-nav"> <h1>Historical Sites In Jordan</h1> </div> </div> </header> <Online> <Map google={this.props.google} tabIndex={0} /> </Online> <Offline> <div className={'offline-map'} aria-label={'Offline Map of Land Between the Lakes'} tabIndex={0}> <div className={'offline-div'} tabIndex={0}> <h3>Your interactive map is not available in off-line mode</h3> <p> Please check your internet connection </p> </div> </div> </Offline> </div> ); } } export default App;<file_sep>/project9/neighborhood-map-p9-fend/src/API/FlickrAPI.js /**FLICKR * const key= '86b17d5f53fd3e75776a75af1e98c247' * const secret= '<KEY>' */ //key,results per request=10 //let tag = this.props.modalTitle export const fetchFlickrImages = (tag) => { let target = document.getElementById('images') let h = document.createElement("H1") let h2 = document.createElement("H2") const request = `https://api.flickr.com/services/rest/?&api_key=86b17d5f53fd3e75776a75af1e98c247&method=flickr.photos.search&format=json&nojsoncallback=1&per_page=10&tag_mode=all&tags=jordan%2C+${tag}` fetch(request) .then(response => response.json()) .then((data) => { if(data.photos.total<1){ h2.innerHTML+='No Image from Flickr<br>We hope to fix this in the future'; target.appendChild(h2); console.log('no photo')} data.photos.photo.forEach(({ farm, server, id, secret, title }) => { let a = document.createElement("a") let img = document.createElement("img"); img.src = `https://farm${farm}.staticflickr.com/${server}/${id}_${secret}.jpg` img.setAttribute("alt", `Image tile:${title}`) a.setAttribute("href", img.src) a.appendChild(img) target.appendChild(a) }); }) .catch(error => { h.innerHTML+='No Network, <br> or no response from Flickr'; target.appendChild(h); console.warn(error) }) } <file_sep>/README.md ## NANODEGREE PROGRAM Become a Front End Developer In the Front End Developer Nanodegree program, you will complete nine projects and build a resume-worthy portfolio. https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001 Welcome and have a great time .... ## Table of Contents - [Advance your Career](#Advance your Career) - [Front End Developer](#Front End Developer) - [Front End Web Developer Concepts covered](#Front End Web Developer Concepts covered) - [Time](#Time) - [IN COLLABORATION WITH](#IN COLLABORATION WITH) - [PREREQUISITE KNOWLEDGE](#PREREQUISITE KNOWLEDGE) ## Advance your Career The Front End Developer Nanodegree program is designed to ensure your long-term success in the field. The skills you learn will prepare you for jobs in front end web development, and you’ll be ready to deliver immediate value to any organization. We will support you throughout your learning journey; from gaining valuable technical and career skills, to landing your dream job. ## Front End Developer The Front End Developer Nanodegree program is composed of nine projects. With each project, you'll create something that demonstrates your mastery of in-demand skills. Projects range in complexity, and each builds upon the previous. In the end, you will have a resume-worthy portfolio that you can showcase to prospective employers. ## Front End Web Developer Concepts covered JavaScript, jQuery, HTML5, HTML, CSS, Python, Object-Oriented Programming ## Time Study 10 hrs/week and complete in 4 4 Months. ## IN COLLABORATION WITH AT&T Google Github ## PREREQUISITE KNOWLEDGE You must be comfortable using basic HTML, CSS, and JavaScript (or another programming language).See detailed requirements. ### Web Foundations Learn the building blocks of the web - HTML and CSS! Learning how to effectively create the structure of a website using semantic HTML. Then style a website with CSS and responsive design. #### PROJECT : Build a Portfolio Site You will be provided with a design mockup as a PDF-file and must replicate that design in HTML and CSS. You will develop a responsive website that will display images, descriptions and links to each of the portfolio projects you will complete throughout the course of the Front-End Web Developer Nanodegree. ### JavaScript and the DOM Use JavaScript to control a webpage! Learn what the Document Object Model (DOM) is. Use JavaScript and the DOM to control page content and interactions. #### PROJECT : Memory Game In this project, you’ll demonstrate your mastery of HTML, CSS, and JavaScript by building a complete browser-based card matching game (also known as Concentration). From building a grid of cards, adding functionality to handle user input, and implementing gameplay logic -- you'll combine all your web development skills to create a fully interactive experience for your users. ## Web Accessibility Get hands-on experience making accessible web apps. You'll learn when and why users need accessibility. Then you'll dive into the "how" of building out accessible website components. ## Object-Oriented JavaScript Learn how to build professional applications using object-oriented JavaScript techniques. Then you'll learn how JavaScript has improved with the major language improvements made in ES6. #### PROJECT : Classic Arcade Game Clone You will be provided with visual assets and a game loop engine; using these tools you must add a number of entities to the game including the player characters and enemies to recreate the classic arcade game Frogger. ## JavaScript Tools & Testing Professional developers use tools to help them build maintainable applications. Learn how to use Grunt and Gulp to speed up app development. Learn to use testing to help build app features. #### PROJECT: Feed Reader Testing In this project, you will learn about testing with JavaScript. Many organizations practice a standard known as "test-driven development" or TDD, in which developers write tests first, before developing their application. You'll use TDD to add new features to a Feed Reader application. ## Front-End Applications Most professional websites are built as single-page applications. You'll learn about Angular, Ember, how to fetch data asynchronously, and offline apps with Service Worker. #### PROJECT : Restaurant Reviews - stage 1,2,3 In this project, you’ll build a Restaurant Reviews App that meets accessibility standards and provides a responsive user experience. You will take a static design that lacks accessibility, and convert the design to be responsive on different sized displays and accessible for screen reader use. <file_sep>/MyReads P8 - FEND/src/components/WrongUrl.js import React from 'react'; import { Link } from 'react-router-dom'; const WrongUrl = () => { return ( <div className="list-books"> <div className="list-books-title"> <h1>MyReads</h1> </div> <div style={{ width: '100%', textAlign: "center" }} > <h1 style={{ fontSize: '80pt', marginBottom: '0px'}}>404</h1> <h3 style={{ fontSize: '25pt' , fontFamily: 'Franklin Gothic Medium' , color: '#004d99'}}>There is no page with this url.</h3> <h4 style={{ fontSize: '20pt', fontFamily: 'Franklin Gothic Medium' , color: '#004d99'}}>Please, press the button below to return to your Home Screen Page.</h4> <Link to="/" className="redirectHome">Return to Home Page</Link> <Link to='/' className="return-home btn-404"></Link> </div> </div> ); } export default WrongUrl;<file_sep>/MyReads P8 - FEND/README.md ## Udacity - Student RIYAM | Front End Web Developer - FEND - P8 MyReads Project Welcome and have a great time .... # MyReads Project This is the repository that contains the code for The MyReads app. This app is built as the out of class project for Udacity's React nanodegree program part 1: React Fundimentals. This app which allows to add books and move them into different shelves, depending on the user action. There are 3 shelves available[ Currently Reading, Want To Read, Read ]. Each book has a control that lets you select the shelf for that book and comes with a drop-down menu which contains the shelves. Clicking on the desired option moves the book to the corresponding shelf. There is also a fourth option, "none", which simply removes the book from the page. ### Table of Contents * [Steps to complete the project](#Steps to complete the project) * [Installing](#installing) * [Requirements](#Requirements) * [User Instructions](#User Instructions) * [License](#License) * [Author](#author) ## Steps to complete the project To get started developing right away: 1. Clone the repository or download the zip-file of the master branch [Udacity repo is available here]( https://github.com/facebookincubator/create-react-app). 2. open the terminal 3. cd into the project folder 4. install all project dependencies with `npm install` 5. start the development server with `npm start` ### Installing * [npm](https://www.npmjs.com/) If you have Node installed, you have NPM, if not install node: * [Node](https://nodejs.org/en/) Run: ``` npm install ``` Once that finishes: ``` npm start ``` Which will open a new browser window pointed to [localhost:3000](http://localhost:3000/) where you can start interacting with the app. ## Requirements: Create a bookshelf app that allows the user to: 1. Search for and select books to be added to the Library 2. Categorize books as "read, currently reading, or want to read" 3. Place books on appropriate bookshelf 4. Move books between shelves 5. Remove books from the Library ## User Instructions - Once you run `npm start`, the server opens a browser window to the application home page. - Click on the down arrow on any book to open a menu from which you can change the shelf the book is on - Click on the plus icon on the bottom right of the window to search for and add new books to your Library. ## License This app is released under a MIT license. ### Author <NAME> <file_sep>/MyReads P8 - FEND/src/components/Book.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import WithoutCover from '../icons/without_cover.png'; class Book extends Component { // Set types for properties static propTypes = { book: PropTypes.object.isRequired , currentShelf: PropTypes.string.isRequired, moveBook: PropTypes.func.isRequired } render() { const {book,currentShelf, moveBook} = this.props let handleImage = book.imageLinks ? /* With thumbnail cover */ book.imageLinks.thumbnail : /* Without thumbnail cover */ WithoutCover; return ( <div key={book.id} className="book"> <div className="book-top"> <div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url("${handleImage}")`, backgroundSize: 'cover' }}> </div> <div className="book-shelf-changer"> <select value={currentShelf} onChange={(e) => moveBook(book, e.target.value)}> <option value="move" disabled>Move to...</option> <option value="currentlyReading">Currently Reading</option> <option value="wantToRead">Want to Read</option> <option value="read">Read</option> <option value="none">None</option> </select> </div> </div> <div className="book-title">{book.title}</div> {book.authors ? (book.authors.length > 1 ? /* Has author */ (book.authors.map((author) => ( <div key={author} className="book-authors">{author}</div> ))) : (<div className="book-authors">{book.authors}</div>) ): /* No Authors Avaliable */ (<div className="book-authors">Author Unknown</div>)} </div> ) } } export default Book;<file_sep>/Memory Game P2- FEND/README.md # Udacity - Student RIYAM | Front End Web Developer - FEND - P2 Memory Game Project ## What is the Memory Game Fun and simple memory game, many people from different age like to play it because it build to test your memory and make Challenge. There's a deck of cards with different icons. ## Instructions - Click on a card - Keep revealing cards and working your memory to remember each unveiled card. - Match cards properly with less moves and in faster time ## How I built the Memory Game I manipulated the DOM with JS, and part of the HTML and also styled the game. - created a deck of cards that shuffles when game is refreshed. - created a counter to count the number of moves made by player and timer to know the duration of a play. - added effects to cards when they match and are unmatched. - create a pop-up modal when player wins game. - Display 16 cards. - Create Cards Array To Holds All 16 Cards. - Shuffle to Randomize the display of cards. - Add styles for selected cards. - Only allow two cards to be selected at a time. - Add delay to selections. - Determine if two selected cards are a match then appear them. - Else flip initially unmatch cards selected. - Continue until finished game! but the trick is how to take 3 stars with less moves. - You can Reset game if you like on the button above the deck. - You can read information on button info under of paragraph The header Called( HOW THE GAME WORKS.) - Modal Screen appear when the game is over and display all moves, time, rating you did. - I hope to enjoy with game. ## What I Use To built the Memory Game - Font Awesome Library ## https://fontawesome.com/start - normalize.css - Very Nice Rest ## https://necolas.github.io/normalize.css/ - materialize (Compiled and minified CSS ) ## https://materializecss.com/ - animate.css ## https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css - Html5shiv.js Symentic Library ## https://cdnjs.com/libraries/html5shiv ## https://github.com/aFarkas/html5shiv - BootStrap Library ## https://www.bootstrapcdn.com/ - jQuery ## https://jquery.com/download/ - CSS3 - HTML5 ## How You Can Get The Game To Play - clone the game from repo or download as Zip - Extract zip - open the folder then You will find (index.html ) open it in any of your favourit browser. - play the game and challenge your working memory. <file_sep>/MyReads P8 - FEND/src/components/ListBooks.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import Book from './Book'; import '../App.css'; const shelves = [ { key: 'currentlyReading', name: 'Currently Reading' }, { key: 'wantToRead', name: 'Want To Read' }, { key: 'read', name: 'Read' } ]; class ListBooks extends Component { // Set types for properties static propTypes = { books: PropTypes.array.isRequired, onMoveBook: PropTypes.func.isRequired } render() { const { books, onMoveBook} = this.props function addBooksOnShelf(shelfKey) { return books.filter(book => book.shelf === shelfKey); } return( <div className="app"> <div className="list-books"> <div className="list-books-title"> <h1> My Reads</h1> </div> <div className="list-books-content"> <div> { shelves.map((shelf) => ( <div key={shelf.key} className="bookshelf"> <h2 className="bookshelf-title">{shelf.name}</h2> { addBooksOnShelf(shelf.key).length === 0 ? ( <div> <h4>No Authors Avaliable</h4> </div> ) : ( <div className="bookshelf-books"> <ol className="books-grid"> <li> { addBooksOnShelf(shelf.key).map((book) => ( <div key={book.id} className="book"> <Book currentShelf={book.shelf} book={book} moveBook={onMoveBook} /> </div> ))} </li> </ol> </div> )} </div> )) } </div> </div> <Link to='/search' className="open-search"></Link> </div> </div> ); } } export default ListBooks;
c795c754cb96aef9f736127094a7d1dfc8071763
[ "Markdown", "JavaScript" ]
16
Markdown
RiyamGithub/Udacity-Projects---FEND
96c8a4cf5e2dcaca48efad15016251932662c582
9224863bdbcd72eac375f0b8f563a89cd556ed6c
refs/heads/master
<repo_name>aashishsingh99/Darkweb-Crawling-Framework<file_sep>/tor session.py import requests session=requests.session() session.proxies={} r = session.get("http://httpbin.org/ip") print("original ip") print(r.text) session.proxies['http'] = 'socks5h://localhost:9150' session.proxies['https'] = 'socks5h://localhost:9150' r = session.get("http://httpbin.org/ip") print("after connected to tor") print(r.text) r = session.get("https://www.facebookcorewwwi.onion/") print(r.headers)<file_sep>/myfile.sh #!/bin/bash clear cd mkdir logs echo "The script starts now." sudo systemctl start zookeeper >> ~/logs/zookeper.log sudo systemctl start redis.service export KAFKA_HOME="/opt/Kafka/kafka_2.12-2.2.1" sudo $KAFKA_HOME/bin/kafka-server-start.sh $KAFKA_HOME/config/server.properties >> ~/logs/kafka.log & cd Downloads/scrapy-cluster/kafka-monitor/ python kafka_monitor.py run >> ~/logs/kafkamonitor.log cd .. cd redis-monitor python redis_monitor.py >> ~/logs/redislog.log cd .. cd crawler scrapy runspider crawling/spiders/link_spider.py cd .. cd rest python rest_service.py cd kafka-monitor python kafkadump.py dump -t demo.crawled_firehose >> ~/logs/crawled python kafkadump.py dump -t demo.outbound_firehose >> ~/logs/kafkaoutput <file_sep>/crawling with titles.py from collections import deque from bs4 import BeautifulSoup import urllib.request from urllib.parse import urljoin import requests session=requests.session() session.proxies={} session.proxies['http'] = 'socks5h://localhost:9150' session.proxies['https'] = 'socks5h://localhost:9150' url="http://facebookcorewwwi.onion" b = session.get(url) print ("Page to be crawled:", url) queue = deque([]) visited_list = [] def crawl(url): visited_list.append(url) if len(queue) > 99: return # urlfg=session.get("http://xmh57jrzrnw6insl.onion/4a1f6b371c/search.cgi?s=DRP&q=cyber&cmd=Search%21") #urlf = urllib.request.urlopen(b) #urlf=session.urlopen(url) #print("\n\n\n\n") #print(urlf) soup = BeautifulSoup(b.content) urls = soup.findAll("a", href=True) #urls = soup.findAll("a href^=http://www.mkyong.com/page/") for i in urls: flag = 0 complete_url = urljoin(url, i["href"]).rstrip('/') for j in queue: if j == complete_url: flag = 1 break if flag == 0: if len(queue) > 99: return if (visited_list.count(complete_url)) == 0: queue.append(complete_url) current = queue.popleft() crawl(current) crawl(url) #print queue for i in queue: print(i) print("\n\n-----") r = session.get(i) text=r.content html=text soup=BeautifulSoup(html,"html5lib") type(soup) print(soup.title) with open(r'C:\Users\A<NAME>\Desktop\webcrawl\crawled.txt', 'w') as f: for item in queue: f.write("%s\n" % item) print ("Pages crawled:")
e23ec9bbe963a6fc434967cfb9e87923c592a7d3
[ "Python", "Shell" ]
3
Python
aashishsingh99/Darkweb-Crawling-Framework
183a4cf6131b0af7ea0820973d43f84315d43f74
5c59cfb5223cf4812a6c43237c8bb665c3394dbe
refs/heads/main
<repo_name>iampratapbabu/react-redux-basics<file_sep>/src/store.js import {createStore} from "redux"; import rootReducer from "./reducers/index"; const store = createStore(rootReducer); //yhi store centrealized state ho gya hai yhi se koi component store call krke data le skta hai export default store;
06726e7b42a4cacc3256acd7de03624296ef4532
[ "JavaScript" ]
1
JavaScript
iampratapbabu/react-redux-basics
fadd8982a5e296fa8d425f0f3fa1384b10c0127f
25ae9bc3f6c6b4bd05f0f1b869272ed85e4a2121
refs/heads/master
<repo_name>bhavy-jain/Algorithms<file_sep>/Algorithms/AVL_trees.cpp //AVL trees are self balancing binary trees capable of performing insertion,deletion and other such opertions in O(log(n)) #include<bits/stdc++.h> using namespace std; struct Node { int data,height,count; Node *left,*right; }; int height(Node *root) { if(root==NULL) return 0; return root->height; } int count(Node *root) { if(root==NULL) return 0; return root->count; } int f(Node *root) { if(root==NULL) return 0; return height(root->left)-height(root->right); } void inorder(Node *root) { if(root==NULL) return; inorder(root->left); cout<<root->data<<" "; inorder(root->right); } int k_element(Node *root,int k) { if(root==NULL||k<=0) return -1; if(count(root->left)==k-1) return root->data; else if(count(root->left)>=k) return k_element(root->left,k); else return k_element(root->right,k-(1+count(root->left))); } int index(Node *root,int k) { if(root==NULL) return -1; if(k==root->data) return count(root->left)+1; else if(k<root->data) return index(root->left,k); else return 1+count(root->left)+index(root->right,k); } Node* lrotate(Node *x) { Node *y=x->right; Node *T2=y->left; y->left=x; x->right=T2; x->height=1+max(height(x->left),height(x->right)); y->height=1+max(height(y->left),height(y->right)); x->count=1+count(x->left)+count(x->right); y->count=1+count(y->left)+count(y->right); return y; } Node* rrotate(Node *y) { Node *x=y->left; Node *T2=x->right; x->right=y; y->left=T2; y->height=1+max(height(y->left),height(y->right)); x->height=1+max(height(x->left),height(x->right)); y->count=1+count(y->left)+count(y->right); x->count=1+count(x->left)+count(x->right); return x; } Node* insert( Node* root, int data) { if(root==NULL) { Node *p=new Node; p->data=data; p->left=NULL; p->right=NULL; p->height=1; p->count=1; return p; } if(root->data<data) root->right=insert(root->right,data); else if(root->data>data) root->left=insert(root->left,data); else return root; root->height=1+max(height(root->left),height(root->right)); root->count=1+count(root->left)+count(root->right); int g=f(root); if(g>1&&data<root->left->data) return rrotate(root); else if(g<-1&&data>root->right->data) return lrotate(root); else if(g>1&&data>root->left->data) { root->left=lrotate(root->left); return rrotate(root); } else if(g<-1&&data<root->right->data) { root->right=rrotate(root->right); return lrotate(root); } return root; } Node* deleteroot(Node* root, int data) { if(root==NULL) return NULL; if(root->data<data) root->right=deleteroot(root->right,data); else if(root->data>data) root->left=deleteroot(root->left,data); else { if(root->left==NULL&&root->right==NULL) return NULL; else if(root->left==NULL) return root->right; else if(root->right==NULL) return root->left; else { Node *p=root->right; while(p->left) p=p->left; root->data=p->data; root->right=deleteroot(root->right,root->data); } } root->height=1+max(height(root->left),height(root->right)); root->count=1+count(root->left)+count(root->right); int g=f(root); if(g>1&&f(root->left)>=0) return rrotate(root); else if(g<-1&&f(root->right)<=0) return lrotate(root); else if(g>1&&f(root->left)<0) { root->left=lrotate(root->left); return rrotate(root); } else if(g<-1&&f(root->right)>0) { root->right=rrotate(root->right); return lrotate(root); } return root; } int main() { Node* root=NULL; root=insert(root,5); root=insert(root,4); root=insert(root,8); root=insert(root,12); root=insert(root,18); root=insert(root,1); root=insert(root,9); root=deleteroot(root,5); root=deleteroot(root,1); inorder(root); cout<<"\n"; cout<<k_element(root,4)<<"\n"; cout<<index(root,12)<<"\n"; } <file_sep>/Algorithms/fft.cpp #include<bits/stdc++.h> using namespace std; void fft(vector<complex<long double>> &a,bool invert) { int n=(int)a.size(); for(int i=0;i<n;i++) { int reverse=0; for(int j=1;j<n;j<<=1) { if(i&j) reverse+=((n>>1)/j); } if(i<reverse) swap(a[i],a[reverse]); } for(int l=2;l<=n;l<<=1) { long double angle=(2*acos(-1)*(invert?-1:1))/l; complex<long double>w(cos(angle),sin(angle)); for(int i=0;i<n;i+=l) { complex<long double>wi(1); for(int j=0;j<l/2;j++) { complex<long double>p=a[i+j],q=a[i+j+l/2]*wi; a[i+j]=p+q; a[i+j+l/2]=p-q; wi*=w; } } } if(invert) { for(int i=0;i<n;i++) a[i]/=n; } } void multiply(vector<int> &a,vector<int> &b,vector<int> &c) { int n=1; while(n<max((int)a.size(),(int)b.size())) n<<=1; n<<=1; vector<complex<long double>>aa(a.begin(),a.end()),bb(b.begin(),b.end()); aa.resize(n); bb.resize(n); fft(aa,0); fft(bb,0); for(int i=0;i<n;i++) aa[i]*=bb[i]; fft(aa,1); c.resize(n); for(int i=0;i<n;i++) c[i]=(int)(aa[i].real()+0.5); } int main() { vector<int>a={1,2,1},b={1,1,0},c; multiply(a,b,c); for(auto i:c) cout<<i<<" "; } <file_sep>/Algorithms/Convex hull.cpp #include<bits/stdc++.h> using namespace std; #define X real() #define Y imag() complex<int>g={0,0}; bool cmp(complex<int>a,complex<int>b) { int cross=(conj(a-g)*(b-g)).Y; if(cross==0) return a.Y<b.Y; return cross>0; } void convex_hull(vector<pair<int,int>>&p,vector<pair<int,int>>&hull) { int n=(int)p.size(),idx=0; vector<complex<int>>v; for(auto i:p) { v.push_back({0,0}); v.back().real(i.first); v.back().imag(i.second); } int ans=0; for(int i=1;i<n-1;i++) { int cross=(conj(v[i]-v[0])*(v[i+1]-v[0])).Y; if(cross) { ans=1; break; } } if(ans==0) { hull.push_back({-1,-1}); return; } for(int i=1;i<n;i++) { if(v[i].Y<v[idx].Y) idx=i; else if(v[i].Y==v[idx].Y&&v[i].X<v[idx].X) idx=i; } swap(v[0],v[idx]); g=v[0]; sort(v.begin()+1,v.end(),cmp); vector<complex<int>>s; s.push_back(v[0]); s.push_back(v[1]); s.push_back(v[2]); for(int i=3;i<n;i++) { while((conj(s[(int)s.size()-1]-s[(int)s.size()-2])*(v[i]-s[(int)s.size()-1])).Y<=0) s.pop_back(); s.push_back(v[i]); } for(auto i:s) hull.push_back({i.X,i.Y}); } int main() { vector<pair<int,int>>a={{1,0},{2,0},{2,2},{0,4},{5,5}},b; convex_hull(a,b); for(auto i:b) cout<<i.first<<" "<<i.second<<"\n"; }<file_sep>/README.md # Algorithms Implementation of some useful algorithms <file_sep>/Algorithms/Karatsuba.cpp #include<bits/stdc++.h> using namespace std; void f(vector<int> &a,vector<int> &b,vector<int> &c) { int n=(int)a.size(); if(n==1) { c.push_back(a[0]*b[0]); c.push_back(0); return; } vector<int>al,ar,bl,br; for(int i=0;i<n/2;i++) { al.push_back(a[i]); bl.push_back(b[i]); ar.push_back(a[i+n/2]); br.push_back(b[i+n/2]); } vector<int> ans1,ans2; f(al,bl,ans1); f(ar,br,ans2); for(int i=0;i<n/2;i++) { al[i]+=ar[i]; bl[i]+=br[i]; } ar.clear(); f(al,bl,ar); for(int i=0;i<n;i++) ar[i]-=(ans1[i]+ans2[i]); c.resize(n<<1); for(int i=0;i<n;i++) { c[i]+=ans1[i]; c[i+n/2]+=ar[i]; c[i+n]+=ans2[i]; } } void multiply(vector<int> &a,vector<int> &b,vector<int> &c) { int n=1; while(n<max((int)a.size(),(int)b.size())) n<<=1; vector<int>aa=a,bb=b; aa.resize(n); bb.resize(n); f(aa,bb,c); } int main() { vector<int>a={1,2,1},b={1,1,0},c; multiply(a,b,c); for(auto i:c) cout<<i<<" "; }
bd5588cc1b56ba0c6cda67076315363cb4127a28
[ "Markdown", "C++" ]
5
C++
bhavy-jain/Algorithms
7a1fc55b781c102c5be6f84bec3c1cf81b268f5a
7f6dac33accde6ccb8c4b656c2e341f10a2c16df
refs/heads/master
<file_sep>FROM jupyter/datascience-notebook WORKDIR /usr/src/app COPY requirements.txt /usr/src/app RUN pip install --no-cache-dir -r requirements.txt COPY analysis.ipynb /usr/src/app EXPOSE 8888 CMD [ "jupyter", "notebook","--allow-root" ]<file_sep>pandas numpy feedparser nltk psycopg2 SQLAlchemy<file_sep>pandas numpy feedparser nltk beautifulsoup4 psycopg2<file_sep>FROM python:3 WORKDIR /usr/src/app COPY requirements.txt /usr/src/app RUN pip install --no-cache-dir -r requirements.txt COPY dataProcessor.py /usr/src/app CMD [ "python", "dataProcessor.py" ,"10"]<file_sep>import pandas as pd from dateutil import parser import re from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import nltk import feedparser import time import psycopg2 import sys from sqlalchemy import create_engine, MetaData, Table, Column, TEXT, VARCHAR, DateTime nltk.download('punkt') nltk.download('stopwords') #Common Variables for the Script stop_words = stopwords.words('english') engine = create_engine('postgresql://postgres:example@db:5432/postgres') #Connection to the Postgres Working in different container repeat_time_seconds = int(float(sys.argv[1])*60) #Time interval for the checking the feed after Nth hour def push_postgres_table(df, table, engine): ''' This Function will push data in the Postgres it takes 3 variables. df = Pandas DataFrame, Table = Table name in String, Engine = Sqlalchemy create_engine ''' try: engineCon = engine.connect() df = df.to_sql(table, engineCon, index=False, if_exists='append') finally: engineCon.close() return df def get_max_date_postgre(): ''' This Function will max date from the Postgres table. df = Pandas DataFrame, Table = Table name in String, Engine = Sqlalchemy create_engine It return Date or Emty string if nothing found ''' query = 'Select max("Pipeline_Update") from "Data_Pipeline"' try: engineCon = engine.connect() df = pd.read_sql_query(query, engineCon) finally: engineCon.close() return df['max'].iloc[0] def push_feed_database(engine,rss_feed,papers): ''' This Function will push feeds to database. ''' for paper in rss_feed.entries: if 'CROSS LISTED' in paper.title or 'UPDATED' in paper.title: #Filter New Submissions from the feed leaving crosslisted and replc pass else: title = re.sub(r'\(arXiv:.+\)','',paper.title).rstrip() title = re.sub('[^A-Za-z0-9]+', ' ', title) description = re.sub('<[^<]+?>', '', paper.summary) #removes HTML tags from the Description of the paper tokens = word_tokenize(description) #create Word tokens for removal of stop words, punctuations and making every word to lower words = [word.lower() for word in tokens if word.isalpha()] words = [w for w in words if not w in stop_words] description = " ".join(words) papers.append((title,paper.link,description,parser.parse(rss_feed.feed.updated).replace(tzinfo=None))) #creating tuples which will we passed to Pandas Dataframe new_df = pd.DataFrame(papers,columns=['Title','Link','Description','Pipeline_Update']) print(new_df.head()) push_postgres_table(new_df, 'Data_Pipeline', engine) print('Data has been Pushed') if not engine.dialect.has_table(engine, 'Data_Pipeline'): # If table don't exist, Create. metadata = MetaData(engine) # Create a table with the appropriate Columns meta = MetaData(engine) t1 = Table('Data_Pipeline', meta,Column('Title', VARCHAR(500)),Column('Link',VARCHAR(50)),Column('Description',TEXT),Column('Pipeline_Update',DateTime)) # Implement the creation t1.create() while True: print('Started') papers = [] #intialize empty list to hold required information from the feed rss_feed = feedparser.parse('http://export.arxiv.org/rss/cs') #Request Feed using feedparser max_date = get_max_date_postgre() #check for the Date from the Pipeline_Update for maximum date to make desicion logic to process feed or not. print(parser.parse(rss_feed.feed.updated)) if len(rss_feed.entries) > 0: # If Feed Length is greater than 0 then only it is feasible to process data if max_date is None: push_feed_database(engine,rss_feed,papers) else: if parser.parse(rss_feed.feed.updated).replace(tzinfo=None) > max_date: #This will Update the records in Table when Feed is new print('Working') push_feed_database(engine,rss_feed,papers) elif parser.parse(rss_feed.feed.updated).replace(tzinfo=None) == max_date: # This Condition will work when the Date in the Database and Feed in the Feed is Similar print('Feed and Database is upto date') else: #This condition should run when Database is Empty push_feed_database(engine,rss_feed,papers) else: print("Nothing to Update") time.sleep(repeat_time_seconds) <file_sep># dataprocessor-docker Simple Data Processor built using Docker Dataprocessor is checking for new feed after **Nth Minute** which can be changed in the **Dockerfile of part1 cmd section** after filename third arugment is minutes for eg: **CMD [ "python", "dataProcessor.py" ,"put the number here"]** ## Note *_RSS Feed(http://export.arxiv.org/rss/cs) is not controlled by us. There might be somedays when univesrity don't announce new papers and feed will be empty. Please leave the dataprocessor running. It will automatically fetch the result once the data is available in the feed. Python script checks for the length of feed entries - if len(feed.enteries)> 0 only then it will process the data otherwise skip and print "Nothing to Update"_* ## Build Setup ``` bash # Clone the repo git clone https://github.com/rishabh-90/dataprocessor-docker.git # navigate to project folder cd <project-folder> #Run the docker compose docker-compose up #To make changes to app and rebuild the docker docker-compose up --build
413e4bf3a6b5fcb5e9c103707a1cfbec71eb962f
[ "Markdown", "Python", "Text", "Dockerfile" ]
6
Dockerfile
Batmobil/dataprocessor-docker
1d3da7bf9a5b8fcc4cf528ff66623339cfa79c6e
b3c6f125ccd228e090b1362d45a6963e208fef2f
refs/heads/master
<repo_name>small-coding/commnutiy<file_sep>/src/main/java/life/qyh/community/controller/QuestionController.java package life.qyh.community.controller; import life.qyh.community.dto.QuestionDTO; import life.qyh.community.service.QuestionService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Controller public class QuestionController { @Resource private QuestionService questionService; @GetMapping("/question/{id}") public String question (@PathVariable("id") int id, HttpServletRequest request) { QuestionDTO questionDTO = questionService.getById (id); if (questionDTO != null) { questionService.setView_Count(questionDTO); } request.setAttribute("question", questionDTO); return "question"; } } <file_sep>/src/main/java/life/qyh/community/mapper/QuestionMapper.java package life.qyh.community.mapper; import com.sun.scenario.effect.Offset; import life.qyh.community.model.Question; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface QuestionMapper { @Insert("insert into question (id, title, description, gmt_create, gmt_modified, creator, tag) values (default, #{title}, #{description}, #{gmt_create}, #{gmt_modified}, #{creator}, #{tag})") void insertQuestion (Question question); @Select("select * from question") List<Question> selList(); @Select("select * from question limit #{offset}, #{size}") List<Question> selByPage(@Param("offset") int offset, @Param("size") int size); @Select("select count(1) from question") int selCount (); @Select("select count(1) from question where creator=#{creator}") int selById(@Param("creator") String creator); @Select("select * from question where creator=#{creator} limit #{offset}, #{size}") List<Question> selByIdPage(@Param("creator") String creator, @Param("offset") int offset, @Param("size") int size); @Select("select * from question where id=#{id}") Question getById (@Param("id") int id); @Select("select * from question where id=#{id}") Question selByQuestionId(@Param("id") int id); @Update("update question set title=#{title}, description=#{description}, tag=#{tag}, gmt_modified=#{gmt_modified} where id=#{id}") void updateQuestion(Question question); @Update("update question set view_count=#{view_count} where id=#{id}") void setViewCount(@Param("view_count") int view_count, @Param("id") int id); } <file_sep>/src/main/resources/application.properties server.port=8888 github.client.id=52ef534d8128684749ab github.client.secret=<KEY> github.redirect.uri=http://localhost:8888/callback spring.datasource.url=jdbc:mysql://localhost:3306/mysql?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<file_sep>/src/main/java/life/qyh/community/service/QuestionService.java package life.qyh.community.service; import life.qyh.community.dto.PageInfo; import life.qyh.community.dto.QuestionDTO; import life.qyh.community.mapper.QuestionMapper; import life.qyh.community.mapper.UserMapper; import life.qyh.community.model.Question; import life.qyh.community.model.User; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Service public class QuestionService { public PageInfo pageInfo = new PageInfo(); @Resource private UserMapper userMapper; @Resource private QuestionMapper questionMapper; public List<QuestionDTO> selList (int currentPage, int size) { int totalCount = questionMapper.selCount(); int totalPage = totalPageCalc(totalCount, size); if (currentPage < 1) { currentPage = 1; } else if (currentPage > totalPage) { currentPage = totalPage; } int offset = (currentPage - 1) * size; List<Question> questionList = questionMapper.selByPage(offset, size); List<QuestionDTO> questionDTOList = new ArrayList<>(); for (Question question : questionList) { User user = userMapper.findById(question.getCreator()); QuestionDTO questionDTO = new QuestionDTO(); BeanUtils.copyProperties(question, questionDTO); questionDTO.setUser(user); questionDTOList.add(questionDTO); } pageInfo.setQuestionDTOList(questionDTOList); pageInfo.setPage(currentPage); setPage(totalCount, size, currentPage, totalPage); return questionDTOList; } public void setPage (int totalCount, int size, int currentPage, int totalPage) { pageInfo.setTotalPage(totalPage); if (currentPage < 1) { currentPage = 1; } else if (currentPage > totalPage) { currentPage = totalPage; } List<Integer> list = new ArrayList<>(); list.add(currentPage); for (int i = 1; i <= 3; i ++) { if (currentPage - i > 0) { list.add(0, currentPage - i); } if (currentPage + i <= totalPage) { list.add(currentPage + i); } } pageInfo.setPages(list); if (currentPage == 1) { pageInfo.setAfterPage(true); pageInfo.setFirstPage(false); pageInfo.setPreviousPage(false); } else { pageInfo.setPreviousPage(true); } if (currentPage == totalPage) { if (currentPage != 1) { pageInfo.setPreviousPage(true); } else { pageInfo.setPreviousPage(false); } pageInfo.setEndPage(false); pageInfo.setAfterPage(false); } else { pageInfo.setAfterPage(true); } if (!pageInfo.getPages().contains(1)) { pageInfo.setFirstPage(true); } else { pageInfo.setFirstPage(false); } if (!pageInfo.getPages().contains(totalPage)) { pageInfo.setEndPage(true); } else { pageInfo.setEndPage(false); } } public List<QuestionDTO> selList(User user, int currentPage, int size) { int totalCount = questionMapper.selById (user.getAccount_id()); int totalPage = totalPageCalc(totalCount, size); if (currentPage < 1) { currentPage = 1; } else if (currentPage > totalPage) { currentPage = totalPage; } int offset = (currentPage - 1) * size; List<Question> questionList = questionMapper.selByIdPage(user.getAccount_id(), offset, size); List<QuestionDTO> questionDTOList = new ArrayList<>(); for (Question question : questionList) { QuestionDTO questionDTO = new QuestionDTO(); BeanUtils.copyProperties(question, questionDTO); questionDTO.setUser(user); questionDTOList.add(questionDTO); } pageInfo.setQuestionDTOList(questionDTOList); pageInfo.setPage(currentPage); setPage(totalCount, size, currentPage, totalPage); return questionDTOList; } public int totalPageCalc (int totalCount, int size) { return totalCount % size == 0 ? totalCount / size : totalCount / size + 1; } public QuestionDTO getById(int id) { Question question = questionMapper.getById(id); QuestionDTO questionDTO = new QuestionDTO(); BeanUtils.copyProperties(question, questionDTO); User user = userMapper.findById(question.getCreator()); questionDTO.setUser(user); return questionDTO; } public void createOrUpdateQuestion (int id, Question question) { if (id == 0) { questionMapper.insertQuestion(question); } else { Question resultQuestion = questionMapper.selByQuestionId(id); if (resultQuestion != null) { resultQuestion.setGmt_modified(System.currentTimeMillis()); resultQuestion.setTag(question.getTag()); resultQuestion.setDescription(question.getDescription()); resultQuestion.setTitle(question.getTitle()); questionMapper.updateQuestion(resultQuestion); } } } public void setView_Count(QuestionDTO questionDTO) { questionDTO.setView_count(questionDTO.getView_count() + 1); questionMapper.setViewCount(questionDTO.getView_count(), questionDTO.getId()); } } <file_sep>/src/main/java/life/qyh/community/interceptor/WebConfig.java package life.qyh.community.interceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.annotation.Resource; @Configuration public class WebConfig implements WebMvcConfigurer { @Resource private SessionInterceptor sessionInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(sessionInterceptor).addPathPatterns("/**").excludePathPatterns("/index").excludePathPatterns("/") .excludePathPatterns("/css/**").excludePathPatterns("/js/**").excludePathPatterns("/fonts/**").excludePathPatterns("/callback/**"); } } <file_sep>/src/main/java/life/qyh/community/controller/PublishController.java package life.qyh.community.controller; import life.qyh.community.dto.QuestionDTO; import life.qyh.community.mapper.QuestionMapper; import life.qyh.community.mapper.UserMapper; import life.qyh.community.model.Question; import life.qyh.community.model.User; import life.qyh.community.service.QuestionService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @Controller public class PublishController { @Resource private UserMapper userMapper; @Resource private QuestionMapper questionMapper; @Resource private QuestionService questionService; @GetMapping("/publish") public String publish () { return "publish"; } @GetMapping("/publish/{id}") public String updateQuestion (@PathVariable("id") int id, HttpServletRequest request) { QuestionDTO question = questionService.getById(id); request.setAttribute("title", question.getTitle()); request.setAttribute("description", question.getDescription()); request.setAttribute("tag", question.getTag()); request.setAttribute("id", id); return "publish"; } @PostMapping("/publish") public String doPublish (@RequestParam("title") String title, @RequestParam("description") String description, @RequestParam("tag") String tag, @RequestParam(value = "id") String id, HttpServletRequest request) { request.setAttribute("title", title); request.setAttribute("description", description); request.setAttribute("tag", tag); if (title == null || title == "") { request.setAttribute("error", "标题不能为空"); return "publish"; } if (description == null || description == "") { request.setAttribute("error", "描述内容不能为空"); return "publish"; } if (tag == null || tag == "") { request.setAttribute("error", "标签不能为空"); return "publish"; } User user = (User) request.getSession().getAttribute("user"); if (user == null) { request.setAttribute("error", "用户未登录"); return "publish"; } Question question = new Question(); question.setTitle(title); question.setDescription(description); question.setTag(tag); question.setCreator(user.getAccount_id()); question.setGmt_create(System.currentTimeMillis()); question.setGmt_modified(question.getGmt_create()); if (id == null || "".equals(id)) { questionService.createOrUpdateQuestion(0, question); } else { questionService.createOrUpdateQuestion(Integer.parseInt(id), question); } // questionMapper.insertQuestion(question); return "redirect:/"; } }
611058e484661b4872f021e312c7500c80e55ae6
[ "Java", "INI" ]
6
Java
small-coding/commnutiy
ee7edb2a3597b753cc6d05fcaff3b6910f06d351
eb499930502a0c9a3f6df18fbbb479320c6d5961
refs/heads/master
<file_sep>//***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //Wiegand_Code.ino //Compiled using arduino uno software found at //http://arduino.cc/en/Main/Software //On Windows 7 64 bits //IMPORTANT //ARDUINO UNO MUST BE //COMPILED USING A DLINE Mode and //RUN USING UART Mode //Created by <NAME> on May 13 2012. //using Luis Ricardo Salgado example for academic purposes //***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //Libraries used #include "pins_arduino.h" //Declaration for the PINS that the Arduino UNO used for the card reader wiegand const int WiegandData1 = 4; const int WiegandData0 = 5; //Declaration for the PINS the ARDUINO UNO used to tell if a door opened or closed const int greenLed = 8; const int redLed = 9; const int tunerBip = 10; //Used for recieving a complete string from the serial communication String inputString = ""; boolean stringComplete = false; //Variables used for the wiegand so it can read the card bits volatile long readerBits = 0; volatile int readerBitCount = 0; //Used for getting the user ID from the card. //userIdB * 256 + userIdA = userId as we know it char userIdA; char userIdB; //***************** vv Code for managing interruptions vv ******************** /* All terminals can generate interrupts on ATmega168 transition. The bit corresponding to the terminal to be the source of the event should be enabled in the registry correspond PCInt and a service routine (ISR). Because the registration PCInt operates port, not terminal, the routine ISR must use some algorithm to implement an interrupt service routine by terminal Correspondenicas terminal and to interrupt masking registers: D0-D7 => 16-23 = PCIR2 PCInt = PD = PCIE2 = pcmsk2 D8-D13 => 0-5 = PCIR0 PCInt = PB = PCIE0 = pcmsk0 A0-A5 (D14-D19) => 8-13 = PCIR1 PCInt = PC = PCIE1 = pcmsk1 */ volatile uint8_t *port_to_pcmask[] = { &PCMSK0, &PCMSK1, &PCMSK2 }; typedef void (*voidFuncPtr)(void); volatile static voidFuncPtr PCintFunc[24] = { NULL }; volatile static uint8_t PCintLast[3]; void PCattachInterrupt(uint8_t pin, void (*userFunc)(void), int mode) { uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); uint8_t slot; volatile uint8_t *pcmask; if (mode != CHANGE) { return; } // Modify the registry ("Interrupt Control Register") ICR // As requested terminal, validating that is between 0 and 13 if (port == NOT_A_PORT) { return; } else { port -= 2; pcmask = port_to_pcmask[port]; } slot = port * 8 + (pin % 8); PCintFunc[slot] = userFunc; // Set the interrupt mask *pcmask |= bit; // Interrupt Enable PCICR |= 0x01 << port; } static void PCint(uint8_t port) { uint8_t bit; uint8_t curr; uint8_t mask; uint8_t pin; // get the pin states for the indicated port. curr = *portInputRegister(port+2); mask = curr ^ PCintLast[port]; PCintLast[port] = curr; // mask is pins that have changed. screen out non pcint pins. if ((mask &= *port_to_pcmask[port]) == 0) { return; } // mask is pcint pins that have changed. for (uint8_t i=0; i < 8; i++) { bit = 0x01 << i; if (bit & mask) { pin = port * 8 + i; if (PCintFunc[pin] != NULL) { PCintFunc[pin](); } } } } SIGNAL(PCINT0_vect) { PCint(0); } SIGNAL(PCINT1_vect) { PCint(1); } SIGNAL(PCINT2_vect) { PCint(2); } //***************** ^^ Code for managing interruptions ^^ ******************** //*********** vv Code for counting and storing bits vv ********** void readerOne(void) { if(digitalRead(4) == LOW){ readerBitCount++; readerBits = readerBits << 1; //Move the bits ... readerBits |= 1; // ... add a bit to '1 'in the least significant bit } } void readerZero(void) { if(digitalRead(5) == LOW){ readerBitCount++; readerBits = readerBits << 1; //Move the bits ... } } //*********** ^^ Code for counting and storing bits ^^ ********** void setup() { //Serial transfer speed Serial.begin(9600); // Attach pin change interrupt service routines from the Wiegand RFID readers PCattachInterrupt(WiegandData1, readerOne, CHANGE); PCattachInterrupt(WiegandData0, readerZero, CHANGE); delay(10); // the interrupt in the Atmel processor misses out the first negative pulse as the inputs are already high, // so this gives a pulse to each reader input line to get the interrupts working properly. // Then clear out the reader variables. // The readers are open collector sitting normally at a one so this is OK for(int i = WiegandData1; i<=WiegandData0; i++){ pinMode(i, OUTPUT); digitalWrite(i, HIGH); // enable internal pull up causing a one digitalWrite(i, LOW); // disable internal pull up causing zero and thus an interrupt pinMode(i, INPUT); digitalWrite(i, HIGH); // enable internal pull up } delay(10); // put the reader input variables to zero readerBits=0; readerBitCount = 0; // enable pins of the LEDs pinMode(greenLed, OUTPUT); pinMode(redLed, OUTPUT); digitalWrite(13, HIGH); // show Arduino has finished initilisation } void loop() { //If the card is slided in the card reader enters the condition if(readerBitCount >= 26){ //Protocol to write on serial Serial.write("3"); Serial.write(":"); Serial.write("1"); Serial.write("-"); //Gets the user id int userID = readerBits >> 1 & 0xffff; int a,b; a = userID & 0xff; b = userID >> 8 & 0xff; userIdA = (char)a; userIdB = (char)b; //Sends the user id in 1 Byte. //Serial.write can only send 1 byte at a time Serial.write(userIdB); Serial.write("+"); Serial.write(userIdA); readerBits = 0; readerBitCount = 0; } //String complete received from serial communication if(stringComplete){ //Protocol to turn on led on on green or red and making a sound or not if(inputString[0] == '3' && inputString[1] == ':' && inputString[2] == '1' && inputString[3] == '-' && inputString[4] == 's'){ digitalWrite(greenLed, HIGH); tone(tunerBip, 2000); delay(1000); digitalWrite(greenLed, LOW); noTone(tunerBip); } else if(inputString[0] == '3' && inputString[1] == ':' && inputString[2] == '1' && inputString[3] == '-' && inputString[4] == 'n'){ digitalWrite(redLed, HIGH); delay(1000); digitalWrite(redLed, LOW); } inputString=""; //inputString reset to null stringComplete=false; } } //Sets serial communication, always ready to receive void serialEvent(){ while(Serial.available()){ char inChar = (char)Serial.read(); //read char from serial inputString += inChar; //Creating string if(inChar == '\n'){ //if string is an "enter" the string is complete stringComplete = true; } } }<file_sep>//***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //C_Program_Administrate_Employees.c //Compiled using Microsoft Visual Studio 11 found at //http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express //Connection with the database with ODBC (x86, 64-bit) found at //http://dev.mysql.com/downloads/connector/odbc/ //On Windows 7 64 bits //Created by <NAME> on May 13 2012. //***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //Libraries used #include <windows.h> #include <conio.h> #include <stdio.h> #include <sql.h> #include <sqlext.h> #include <time.h> //Variables used for the database HENV henv; //Reference ("handle") to memory for environment variables / / ("Handle to environment") HDBC hdbc; //Reference ("handle") to data connection (session) with the database ("Handle Conection to DataBase") RETCODE retcode; //Return code for SQL operations ... actually 32-bit integer. HSTMT hstmt; //Reference ("handle") to a statute ... actually is a STRING HSTMT hstmt2; //Reference ("handle") to a statute ... actually is a STRING //Chars to handle transfer of Serial Port char option; char query[300]; char query2[300]; char optionUser[5]; //Read string from keyboard char year[5]; char month[3]; char day[3]; char optionKeyboard[5]; //For payroll char countablePeriod[5]; char initialYear[5]; char initialMonth[3]; char initialDay[3]; int workedHoursIncome,extraHoursIncome, netIncome; float ISPT, IMSS, grossIncome; char finalYear[5]; char finalMonth[3]; char finalDay[3]; int sumOfWorkedHoursPayroll,sumOfExtraHoursPayroll; //For query int workedHours; int extraHours; int wage,extraWage; char completeDate[14]; char initialDate[14]; char finalDate[14]; //Not exit program variable int cycle = 1; //Variables for methods int checkTheExit,checkTheTime,dayOfWeek; //Variables that uses SQL to get data from tables char door; //door number char name[51]; //array of 51 chars int hours,sumOfHours,payroll,badge; SDWORD bufferForSql,secondBufferForSql,fourthBufferForSql,fifthBufferForSql; //SQLINTEGER thirdBufferForSql; //SQL_TIMESTAMP_STRUCT StatusTime; //Get time from SQL //Method for calculating the daily asistance and insert it on the database void dailyAsistance(){ printf( "(Ejemplo 2012) Escribe ano: " ); /* notice stdin being passed in */ fgets ( year, 5, stdin ); getchar(); printf( "(Ejemplo 05) Escribe mes: " ); /* notice stdin being passed in */ fgets ( month, 3, stdin ); getchar(); printf( "(Ejemplo 03) Escribe dia: " ); /* notice stdin being passed in */ fgets ( day, 3, stdin ); getchar(); //Query for getting the id of the employee the sum of worked hours and the employee badge sprintf(query, "SELECT E.IDGaffete, E.NominaEmpleado, Sum(LA.HorasTrabajadas) AS SumOfHorasTrabajadas FROM LogAsistencia AS LA, Empleado AS E WHERE (((E.IDGaffete)=[LA].[IDGaffete]) AND ((DatePart('yyyy',[Salida]))=%s) AND ((DatePart('m',[Salida]))=%s) AND ((DatePart('d',[Salida]))=%s)) GROUP BY E.IDGaffete, E.NominaEmpleado;", year,month,day); //REMOVE printf(query); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &badge, 0, &fifthBufferForSql); SQLBindCol(hstmt, 2, SQL_C_LONG, &payroll, 0, &fifthBufferForSql); SQLBindCol(hstmt, 3, SQL_C_LONG, &sumOfHours, 0, &fifthBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { //Calculate worked hours and extra hours from the total of hours worked in one day if(sumOfHours >= 8){ workedHours = 8; extraHours = sumOfHours - workedHours; } else{ extraHours = 0; workedHours = sumOfHours; } //Put the day month and year asked to the used previously in one string sprintf(completeDate,"%s/%s/%s",day,month,year); //Query for inserting the daily asistance sprintf(query2, "INSERT INTO AsistenciaDiaria (Fecha, HorasDeTrabajo, HorasExtra, NominaEmpleado) VALUES ('%s', %d, %d, %d)",completeDate,workedHours,extraHours,payroll); //REMOVE printf(query2); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt2); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt2, query2 ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt2); // Execute statement with // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt2); // Fetch next row from result set retcode = SQLFetch (hstmt); } printf("\nSe ejecuto exitosamente!\n\n"); //Print that everything went successfull } //method for generating payroll void generatePayroll(){ printf( "(Ejemplo 8) Periodo contable: " ); /* notice stdin being passed in */ fgets ( countablePeriod, 3, stdin ); getchar(); printf( "(Ejemplo 2012) Escribe ano inicio: " ); /* notice stdin being passed in */ fgets (initialYear, 5, stdin ); getchar(); printf( "(Ejemplo 05) Escribe mes inicio: " ); /* notice stdin being passed in */ fgets ( initialMonth, 3, stdin ); getchar(); printf( "(Ejemplo 03) Escribe dia inicio: " ); fgets ( initialDay, 3, stdin ); getchar(); printf( "(Ejemplo 2012) Escribe ano fin: " ); /* notice stdin being passed in */ fgets ( finalYear, 5, stdin ); getchar(); printf( "(Ejemplo 05) Escribe mes fin: " ); /* notice stdin being passed in */ fgets ( finalMonth, 3, stdin ); getchar(); printf( "(Ejemplo 03) Escribe dia fin: " ); /* notice stdin being passed in */ fgets ( finalDay, 3, stdin ); getchar(); //Query for getting the sum of hours worked, the sum of extra hours, the employee badge, salary and extra salary sprintf(query, "SELECT SUM(HorasDeTrabajo) AS HorasDeTrabajoAcum, SUM(HorasExtra) AS HorasExtraAcum, AsistenciaDiaria.NominaEmpleado, Salario, SalarioExtra FROM AsistenciaDiaria, Empleado WHERE Empleado.NominaEmpleado = AsistenciaDiaria.NominaEmpleado AND ((DatePart('yyyy',[Fecha])) >= %s) AND ((DatePart('yyyy',[Fecha])) <= %s) AND ((DatePart('m',[Fecha])) >=%s) AND ((DatePart('m',[Fecha])) <=%s) AND ((DatePart('d',[Fecha])) >=%s) AND ((DatePart('d',[Fecha])) <=%s) GROUP BY AsistenciaDiaria.NominaEmpleado, Salario, SalarioExtra", initialYear,finalYear,initialMonth,finalMonth,initialDay,finalDay); //REMOVE printf(query); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &sumOfWorkedHoursPayroll, 0, &fifthBufferForSql); SQLBindCol(hstmt, 2, SQL_C_LONG, &sumOfExtraHoursPayroll, 0, &fifthBufferForSql); SQLBindCol(hstmt, 3, SQL_C_LONG, &badge, 0, &fifthBufferForSql); SQLBindCol(hstmt, 4, SQL_C_LONG, &wage, 0, &fifthBufferForSql); SQLBindCol(hstmt, 5, SQL_C_LONG, &extraWage, 0, &fifthBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { //Put the day month and year asked to the used previously in one string sprintf(initialDate,"'%s/%s/%s'",initialMonth,initialDay,initialYear); sprintf(finalDate,"'%s/%s/%s'",finalMonth,finalDay,finalYear); //Calculates the worked income, extra hours income, netincome, ISPT, IMSS and grossIncome workedHoursIncome = wage * sumOfWorkedHoursPayroll; extraHoursIncome = extraWage * sumOfExtraHoursPayroll; netIncome = workedHoursIncome + extraHoursIncome; ISPT = (float) netIncome * .105; IMSS = (float) netIncome * .0282; grossIncome = (float) netIncome - ISPT - IMSS; //Insert the data to the badge table sprintf(query2, "INSERT INTO Nomina (NominaEmpleado, PeriodoContable, InicioPeriodoContable, FinPeriodoContable, IngresoHorasDeTrabajo, IngresoHorasExtra, IngresoNeto, ISPT, IMSS, PagoTotal) VALUES (%d,%s,%s,%s,%d,%d,%d,%.2f,%.2f,%.2f)", badge, countablePeriod, initialDate, finalDate, workedHoursIncome, extraHoursIncome, netIncome, ISPT, IMSS, grossIncome); //REMOVE printf(query2); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt2); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt2, query2 ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt2); // Execute statement with // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt2); // Fetch next row from result set retcode = SQLFetch (hstmt); } printf("\nSe ejecuto exitosamente!\n\n"); //Prints that everything went successfull } void main() { retcode = SQLAllocEnv(&henv); //Reference ("handle") memory space environment variables if (retcode == SQL_SUCCESS) { retcode = SQLAllocConnect(henv, &hdbc); //Reference to session data if (retcode == SQL_SUCCESS) { retcode = SQLConnect(hdbc, "dbPieci", SQL_NTS, NULL, 0, NULL, 0); //Connect to database with ODBC if (retcode == SQL_SUCCESS) { printf("Se conecto exitosamente con la base de datos\n"); retcode = SQLAllocStmt(hdbc, &hstmt); //Reference to the SQL statement if (retcode == SQL_SUCCESS) { //The program is always running while(cycle == 1) { printf( "(Asistencia diaria = 1)\n(Genera Nomina = 2)\nElige opcion: " ); /* notice stdin being passed in */ fgets ( optionKeyboard, 2, stdin ); getchar(); //Put the char read in an array sprintf(optionUser,"%s",optionKeyboard); //If it reads a 1 it enters this funcion if(optionUser[0] == 49){ //Calculate daily asistace from a given date dailyAsistance(); } //If it reads a 2 it enters this funcion else if (optionUser[0] == 50){ //Generate payroll of every employee from a given date generatePayroll(); } else { //Type something again printf("\nEhhh?\n"); } } } } } } }<file_sep>//***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //C_Program_Register_SerialData_AccessDB.c //Compiled using Microsoft Visual Studio 11 found at //http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express //Connection with the database with ODBC (x86, 64-bit) found at //http://dev.mysql.com/downloads/connector/odbc/ //On Windows 7 64 bits //Created by <NAME> on May 13 2012. //using <NAME> example for academic purposes //***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //Libraries used #include <windows.h> #include <conio.h> #include <stdio.h> #include <sql.h> #include <sqlext.h> #include <time.h> //Variables used for the database HENV henv; //Reference ("handle") to memory for environment variables / / ("Handle to environment") HDBC hdbc; //Reference ("handle") to data connection (session) with the database ("Handle Conection to DataBase") RETCODE retcode; //Return code for SQL operations ... actually 32-bit integer. HSTMT hstmt; //Reference ("handle") to a statute ... actually is a STRING //It keeps all the query in this chain of chars char query[300]; //Variables for Serial port interaction HANDLE serialPort; DCB protocol; //Chars to handle transfer of Serial Port char oneLetter; char multipleLetters[30]; int readFromSerial,writedToSerial; //Variables for sync the serial data int sync=0; //Sync data int syncronizedForTwoPoints = 0; //Sync for protocol used int counterForSync = 0; //Sincroniza los datos int addForId; //Variable para guardar el id del usuario //Variables for methods int checkTheExit,checkTheTime,dayOfWeek; //Variables that uses SQL to get data from tables char door; //door number char name[51]; //array of 51 chars int hours,theDate,countDoors,validateTime; SDWORD bufferForSql,secondBufferForSql,fourthBufferForSql,fifthBufferForSql; SQLINTEGER thirdBufferForSql; SQL_TIMESTAMP_STRUCT StatusTime; //Get time from SQL //Funcion para checar la salida int checkExit(int addForId, int door){ //REMOVE - it only prints data printf("\n\n"); //REMOVE //If the count is more than cero, it means the employee is inside the building sprintf(query,"SELECT Count(*) AS Salida FROM LogAsistencia WHERE (((LogAsistencia.[IDGaffete])=%d) AND ((LogAsistencia.[Entrada]) Is Not Null) AND ((LogAsistencia.[Salida]) Is Null))", addForId); //REMOVE - it only prints data printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &hours, 0, &secondBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { //Prints the exit hour printf("Salida es 1 Entrada es 0 \nEntrada/Salida: %d \n",hours); // Fetch next row from result set retcode = SQLFetch (hstmt); } //If the count was more than cero, it means the employee tries to exit. Enter this function if true. if(hours != 0){ //Protocol to send the message to open door multipleLetters[0] = '3'; multipleLetters[1] = ':'; multipleLetters[2] = door; multipleLetters[3] = '-'; multipleLetters[4] = 's'; multipleLetters[5] = '\n'; WriteFile(serialPort,&multipleLetters,6,(LPDWORD)&writedToSerial,NULL); //Sends the message //REMOVE printf("\n\n"); //REMOVE //Registers the user in the access log and puts a 3 in autorizacion. 3 means exit sprintf(query,"INSERT INTO LogAccesos (IDGaffete, Puerta,Hora,Autorizado) VALUES ('%d','%d',NOW(),'3');",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with //REMOVE printf("\n\n"); //REMOVE //Set the time when the employee exit the building sprintf(query,"UPDATE LogAsistencia SET Salida=NOW() WHERE LogAsistencia.IDGaffete = %d ;" ,addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with //REMOVE printf("\n\n"); //REMOVE //Set the hours work when the employee entered and get out of the building sprintf(query,"UPDATE LogAsistencia SET HorasTrabajadas=DateDiff('h',Entrada,NOW()) WHERE IDGaffete=%d;",addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with return 1; } else { return 0; } } int checkDoor(int addForId, int door){ //REMOVE printf("\n\n"); //REMOVE //Check if the user have access to the door. If count is more than 0 it means it does have access sprintf(query,"SELECT Count(*) AS Puertas FROM Puertas WHERE IDGaffete=%d AND Puerta=%d",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &countDoors, 0, &fourthBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); //If count is more than cero, it means it does have access. Enter the function if true. if(countDoors != 0){ return 1; } else { return 0; } } void checkTime(int addForId,int door){ //Day of week format /* 1 = Sunday 2 = Monday 3 = Tuesday 4 = Wednesday 5 = Thurday 6 = Friday 7 = Saturday */ //REMOVE printf("\n\n"); //REMOVE //Returns the day of week sprintf(query,"SELECT Weekday (NOW());"); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &validateTime, 0, &fifthBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { //Prints the exit hour printf("Domingo es igual a 1\nDia de la semana: %d \n",validateTime); // Fetch next row from result set retcode = SQLFetch (hstmt); } //If its Monday - Friday if(validateTime >= 2 && validateTime <= 6){ //REMOVE printf("\n\n"); //REMOVE //Check if employee can enter between his access hours from Monday to friday sprintf(query,"SELECT Count(*) As Valido FROM Restricciones WHERE time()>=Lu_ViMin AND time()<=Lu_ViMax AND IDGaffete=%d;",addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &validateTime, 0, &fifthBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); //Check if employee is on selected hours. Enter function if(validateTime != 0){ //REMOVE printf("\n\n"); //REMOVE //Insert into access log that the employee has access to the door. 1 means autorization is valid. sprintf(query,"INSERT INTO LogAccesos (IDGaffete, Puerta,Hora,Autorizado) VALUES ('%d','%d',NOW(),'1');",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with //REMOVE printf("\n\n"); //REMOVE //Insert the time the employee entered the building sprintf(query,"INSERT INTO LogAsistencia (IDGaffete, Entrada) VALUES ('%d',NOW());",addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with } else { //Protocol to send the message to close door multipleLetters[0] = '3'; multipleLetters[1] = ':'; multipleLetters[2] = door; multipleLetters[3] = '-'; multipleLetters[4] = 'n'; multipleLetters[5] = '\n'; WriteFile(serialPort,&multipleLetters,6,(LPDWORD)&writedToSerial,NULL); //Sends the message //REMOVE printf("\n\n"); //REMOVE //Register in the access log that the employee tried to get in, but was not autorized. 2 is for not autorized. sprintf(query,"INSERT INTO LogAccesos (IDGaffete, Puerta,Hora,Autorizado) VALUES ('%d','%d',NOW(),'2');",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with } } //If its Sunday else if (validateTime == 1){ //REMOVE printf("\n\n"); //REMOVE //Check if employee can enter between his access hours on Sunday sprintf(query,"SELECT Count(*) As Valido FROM Restricciones WHERE time()>=DomingoMin AND time()<=DomingoMax AND IDGaffete=%d;",addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &validateTime, 0, &fifthBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); if(validateTime != 0){ //REMOVE printf("\n\n"); //REMOVE //Insert into access log that the employee has access to the door. 1 means autorization is valid. sprintf(query,"INSERT INTO LogAccesos (IDGaffete, Puerta,Hora,Autorizado) VALUES ('%d','%d',NOW(),'1');",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with //REMOVE printf("\n\n"); //REMOVE //Insert the time the employee entered the building sprintf(query,"INSERT INTO LogAsistencia (IDGaffete, Entrada) VALUES ('%d',NOW());",addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with } else { //Protocol to send the message to close door multipleLetters[0] = '3'; multipleLetters[1] = ':'; multipleLetters[2] = door; multipleLetters[3] = '-'; multipleLetters[4] = 'n'; multipleLetters[5] = '\n'; WriteFile(serialPort,&multipleLetters,6,(LPDWORD)&writedToSerial,NULL); //Sends the message //REMOVE printf("\n\n"); //REMOVE //Register in the access log that the employee tried to get in, but was not autorized. 2 is for not autorized. sprintf(query,"INSERT INTO LogAccesos (IDGaffete, Puerta,Hora,Autorizado) VALUES ('%d','%d',NOW(),'2');",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with } } //If its Saturday else if(validateTime == 7){ //REMOVE printf("\n\n"); //REMOVE //Check if employee can enter between his access hours on Saturday sprintf(query,"SELECT Count(*) As Valido FROM Restricciones WHERE time()>=SabadoMin AND time()<=SabadoMax AND IDGaffete=%d;",addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with // Takes SQL numbers SQLBindCol(hstmt, 1, SQL_C_LONG, &validateTime, 0, &fifthBufferForSql); // Get row of data from the result set defined above in the statement retcode = SQLFetch(hstmt); if(validateTime != 0){ //REMOVE printf("\n\n"); //REMOVE //Insert into access log that the employee has access to the door. 1 means autorization is valid. sprintf(query,"INSERT INTO LogAccesos (IDGaffete, Puerta,Hora,Autorizado) VALUES ('%d','%d',NOW(),'1');",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with //REMOVE printf("\n\n"); //REMOVE //Insert the time the employee entered the building sprintf(query,"INSERT INTO LogAsistencia (IDGaffete, Entrada) VALUES ('%d',NOW());",addForId); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with } else { //Protocol to send the message to close door multipleLetters[0] = '3'; multipleLetters[1] = ':'; multipleLetters[2] = door; multipleLetters[3] = '-'; multipleLetters[4] = 'n'; multipleLetters[5] = '\n'; WriteFile(serialPort,&multipleLetters,6,(LPDWORD)&writedToSerial,NULL); //Sends the message //REMOVE printf("\n\n"); //REMOVE //Register in the access log that the employee tried to get in, but was not autorized. 2 is for not autorized. sprintf(query,"INSERT INTO LogAccesos (IDGaffete, Puerta,Hora,Autorizado) VALUES ('%d','%d',NOW(),'2');",addForId,door-48); //REMOVE printf(query); printf("\n\n"); //REMOVE // Allocate memory for the statement handle retcode = SQLAllocStmt (hdbc, &hstmt); // Prepare the SQL statement by assigning it to the statement handle retcode = SQLPrepare(hstmt, query ,SQL_NTS); // Execute the SQL statement handle retcode = SQLExecute(hstmt); // Execute statement with } } } void main() { serialPort = CreateFile("COM3",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); //opens the communication port for READ and WRITE //If it can conect to the serial port, it enter t if (serialPort != INVALID_HANDLE_VALUE) { //Initialize the serial protocol GetCommState(serialPort,&protocol); protocol.BaudRate = CBR_9600; protocol.fBinary = TRUE; protocol.fParity = FALSE; protocol.ByteSize = 8; protocol.Parity = NOPARITY; protocol.StopBits = ONESTOPBIT; SetCommState(serialPort,&protocol); retcode = SQLAllocEnv(&henv); //Reference ("handle") memory space environment variables if (retcode == SQL_SUCCESS) { retcode = SQLAllocConnect(henv, &hdbc); //Reference to session data if (retcode == SQL_SUCCESS) { retcode = SQLConnect(hdbc, "dbPieci", SQL_NTS, NULL, 0, NULL, 0); //Connect to database with ODBC if (retcode == SQL_SUCCESS) { printf("Se conecto exitosamente con la base de datos\n"); retcode = SQLAllocStmt(hdbc, &hstmt); //Reference to the SQL statement if (retcode == SQL_SUCCESS) { //The program is always running while(0 == 0) { ReadFile(serialPort,&oneLetter,1,(LPDWORD)&readFromSerial,NULL); //Serial data read and stored in the variable char: letter //If it read something it enters the function if (readFromSerial!=0) { //Protocol to receive data by initializing the number 3 if (oneLetter == '3') { syncronizedForTwoPoints = 1; printf("%c",oneLetter); //Prints number in screen } //Is protocol "3:" is read it enters this function if (sync) { if(counterForSync == 0 ){ printf("%c",oneLetter); //Prints in screen door = oneLetter; //Saves door number } else if(counterForSync == 1 ){ printf("%c",oneLetter); //Prints in screen } else if(counterForSync == 2 ){ addForId = oneLetter * 256; //Saves user ID part of it } //Not do anything because of protocol char in 3 position doesnt have anything useful else if(counterForSync == 3 ){ } else if(counterForSync == 4 ){ addForId += oneLetter; //Saves user ID correctly printf("%d\n",addForId); //Prints user ID //CheckExit return 1 if its an exit checkTheExit = checkExit(addForId,door); //If its not an exit, validates door. if (checkTheExit == 0){ checkTheTime = checkDoor(addForId,door); //If the employee is registered in the door, then check the time to know if the employee can enter if(checkTheTime == 1){ checkTime(addForId,door); } else { //Protocol to send the message to close door multipleLetters[0] = '3'; multipleLetters[1] = ':'; multipleLetters[2] = door; multipleLetters[3] = '-'; multipleLetters[4] = 'n'; multipleLetters[5] = '\n'; WriteFile(serialPort,&multipleLetters,6,(LPDWORD)&writedToSerial,NULL); //Sends the message } } /* //Get SQL Data con given Format //Get string SQLBindCol(hstmt, 1, SQL_C_CHAR, name, 51, &bufferForSql); //Get Numbers SQLBindCol(hstmt, 2, SQL_C_LONG, &hours, 0, &secondBufferForSql); //Get Date SQLBindCol(hstmt, 3, SQL_C_TIMESTAMP, &StatusTime, 0, &thirdBufferForSql); //Date is dislayed this way: printf("Los dias : %d-%d-%d %d:%d:%d\n",StatusTime.year,StatusTime.day,StatusTime.month,StatusTime.hour,StatusTime.minute,StatusTime.second); */ } //Add Sync Counter counterForSync++; //Resets the syncF if(counterForSync == 5 ){ sync = 0; counterForSync = 0; } } //If the letter 3 was previosly read, it enters this function if(oneLetter == ':' && syncronizedForTwoPoints == 1){ printf("%c",oneLetter); //Prints number in screen syncronizedForTwoPoints = 0; sync = 1; //Syncs } } } } } } } // Free the allocated statement handle SQLFreeStmt (hstmt, SQL_DROP); CloseHandle(serialPort); } }<file_sep>//***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //Serial_Code.ino //Compiled using arduino uno software found at //http://arduino.cc/en/Main/Software //On Windows 7 64 bits //IMPORTANT //ARDUINO UNO MUST BE //COMPILED USING A DLINE Mode and //RUN USING DLINE Mode //Created by <NAME> on May 13 2012. //using <NAME> and <NAME> example which is on a public domain //***************** vv DOCUMENTING AND HELPFUL STUFF vv ******************** //Libraries used #include <SoftwareSerial.h> //PINS used to receive and transfer bytes const int pinRX = 2; const int pinTX = 3; SoftwareSerial XBee(pinRX, pinTX); // Initialized RX and TX void setup() { // Set data rates Serial.begin(9600); // set the data rate for the SoftwareSerial port XBee.begin(9600); } void loop() // run over and over { if (XBee.available()) //If read from Serial hardware then writes to serial software Serial.write(XBee.read()); if (Serial.available()) //If read from Serial software writes to serial hardware XBee.write(Serial.read()); }
ea436a30bce113913157caa0edbd6f228be7850e
[ "C", "C++" ]
4
C++
samuelviana/Arduino_C_AccessDB
66d0472649ea48fc5867f182c56cb5f36e002814
d7b3a73c4e431576b5ef664ec95a4dc444356272
refs/heads/master
<file_sep># StudyScraper An application that hits various API endpoints to pull and store data on studies related to nootropics and neuroscience. Also utilizes a web scraper to pull data from the newest posts in the nootropics Reddit community if they are related to scientific studies. <file_sep>(function () { "use strict"; angular.module("app") .controller("savedController", SavedController); SavedController.$inject = ["$scope"]; function SavedController($scope) { var vm = this; vm.$scope = $scope; vm.$onInit = _onInit; function _onInit() { console.log("init saved study controller"); } } })();<file_sep>(function () { "use strict"; angular.module("app") .controller("loginController", LoginController); LoginController.$inject = ["$scope", "$location"]; function LoginController($scope, $location) { var vm = this; vm.$scope = $scope; vm.$location = $location; vm.$onInit = _onInit; vm.email = ""; vm.password = ""; vm.login = _login; function _onInit() { console.log("init login controller"); } function _login() { vm.$location.path("home"); } } })();<file_sep>(function () { "use strict"; angular.module("app") .controller("scraperController", ScraperController); ScraperController.$inject = ["$scope", "scraperService"]; function ScraperController($scope, ScraperService) { var vm = this; vm.$scope = $scope; vm.scraperService = ScraperService; vm.posts = []; vm.$onInit = _onInit; vm.loaded = false; vm.savePost = _savePost; vm.savePostSuccess = _savePostSuccess; vm.savePostError = _savePostError; vm.getAll = _getAll; vm.getAllSuccess = _getAllSuccess; vm.getAllError = _getAllError; function _onInit() { console.log("init scraper controller"); vm.getAll(); } function _savePost(title, url) { var data = { "title": title, "url": url } vm.scraperService.savePost(data) .then(vm.savePostSuccess).catch(vm.savePostError); } function _savePostSuccess(res) { alert("Post saved!"); console.log(res); } function _savePostError(err) { alert("Failed to save post!"); console.log(err); } function _getAll() { vm.scraperService.getAll() .then(vm.getAllSuccess) .catch(vm.getAllError); } function _getAllSuccess(res) { vm.posts = res.data.item.posts; vm.loaded = true; } function _getAllError(err) { console.log(err); } } })();<file_sep>(function () { "use strict"; angular.module("app") .controller("studyController", StudyController); StudyController.$inject = ["$scope"]; function StudyController($scope) { var vm = this; vm.$scope = $scope; vm.$onInit = _onInit; function _onInit() { console.log("init study API controller"); } } })();<file_sep>(function () { "use strict"; angular.module("app") .controller("registerController", RegisterController); RegisterController.$inject = ["$scope"]; function RegisterController($scope) { var vm = this; vm.$scope = $scope; vm.$onInit = _onInit; function _onInit() { console.log("init register controller"); } } })();<file_sep>(function () { "use strict"; angular.module("app") .factory("loginService", LoginService); LoginService.$inject = ["$http", "$q"]; function LoginService($http, $q) { return { } } })();
543d04d71ab5066dd65d56d6db655bf6a08b3e54
[ "Markdown", "JavaScript" ]
7
Markdown
Kinarki/StudyScraper
1c781c175a3f53fc1d3f03a27f391354b55b6556
3bf36694c56c0b7dc2135241a5f236cd72848739
refs/heads/master
<repo_name>checksound/TryJavaRMI<file_sep>/src/TopicServer.java import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.List; import java.util.ArrayList; public class TopicServer implements Topic { private List<MessageRecipient> subscribers; public TopicServer() { subscribers = new ArrayList<MessageRecipient>(); } public synchronized void receive(String message) throws RemoteException { List<MessageRecipient> successes = new ArrayList<MessageRecipient>(); for (MessageRecipient subscriber : subscribers) { try { subscriber.receive(message); successes.add(subscriber); } catch (Exception e) { // silently drop any subscriber that fails } } subscribers = successes; } public synchronized void addSubscriber(MessageRecipient subscriber) throws RemoteException { subscribers.add(subscriber); } public static void main(String args[]) { try { TopicServer obj = new TopicServer(); Topic stub = (Topic) UnicastRemoteObject.exportObject(obj, 0); Registry registry = LocateRegistry.getRegistry(); registry.rebind("topic.1", stub); System.err.println("Server ready"); } catch (Exception e) { System.err.println("Server exception: " + e.toString()); e.printStackTrace(); } } } <file_sep>/README.md # Try Java RMI Prima utilizzare lo script `compile.bat` per compilare i sorgenti. ## ESECUZIONE Prima far partire l'`rmiregistry`, utilizzando lo script `startRmiRegistry.bat`, e il [TopicServer](./src/TopicServer.java) con lo script `startServer.bat`. Per eseguire un [Subscriber](./src/Subscriber.java) si puņ utilizzare lo script `startSubscriber.bat`. Per inviare un messaggio tramite il client [Publisher](./src/Publisher.java) ulilizzando lo script `runClient.bat <messaggio>`.
f09c020d1a45e2b3badf05aa4d17ab784fed21da
[ "Markdown", "Java" ]
2
Java
checksound/TryJavaRMI
95c8278f2e7e328da4ab0fe346907095349624e9
db2ea7e337a96edc4861678373f017df6845836b
refs/heads/master
<file_sep>class User < ActiveRecord::Base has_many :casks validates :login, presence: true scope :using_cask_for_configuration, -> { where('casks.configuration' => true).joins(:casks).uniq(:id) } end <file_sep>FactoryGirl.define do factory :user do sequence(:login) { |n| "login#{n}" } sequence(:name) { |n| "name#{n}" } sequence(:url) { |n| "http://example.com/user#{n}" } sequence(:avatar_url) { |n| "http://example.com/avatar/#{n}" } followers 0 following 0 end end <file_sep>require 'github_code_search' module CaskUpdater module_function DEFAULT_QUERY = "filename:cask depends-on size:<100000" SEARCH_BEST_MATCH = GithubCodeSearch.new(DEFAULT_QUERY) SEARCH_RECENTLY_INDEXED = GithubCodeSearch.new(DEFAULT_QUERY, sort: :indexed) INTERVAL = 10 def update(page_count, search: nil) search ||= SEARCH_BEST_MATCH (1..page_count).each do |page| save_search_result!(search, page) sleep INTERVAL unless page == page_count end end def save_search_result!(search, page) search.result(page).each do |item| if item[:code][:url].end_with? '/Cask' # Save Cask file only save_item! item end end end def save_item!(item) user = User.find_or_create_by!(url: item[:user][:url]) do |user| user.attributes = item[:user] end url = item[:code][:url] unless Cask.exists?(url: url) old_casks = Cask.where("url LIKE ?", url.sub(%r{/blob/\S{40}/}, '/blob/%/')) old_casks.destroy_all cask = Cask.create!(item[:code]) user.casks << cask end end def delete_outdated_casks Cask.where(configuration: [false, nil]).where("updated_at < ?", 1.month.ago).destroy_all end end <file_sep>require 'open-uri' require 'json' class MelpaFetcher def initialize @recipes = JSON(read_text('http://melpa.org/recipes.json')) @archive = JSON(read_text('http://melpa.org/archive.json')) end def packages Enumerator.new do |yielder| package_names.each do |name| yielder << create_package(name) end end end def package_names @recipes.keys end def create_package(name) recipe = @recipes[name] package = Package.new package.name = name package.repo_type = recipe['fetcher'] package.url = source_url(name, recipe) package.description = @archive[name]['desc'] rescue nil package end def source_url(name, recipe) if recipe['fetcher'] == 'github' (recipe['repo'].match('/') ? "https://github.com/" : "https://gist.github.com/") + recipe['repo'] elsif recipe['fetcher'] == "wiki" && !recipe['files'] "http://www.emacswiki.org/emacs/" + name + ".el" elsif recipe['url'] url_match = lambda do |re, prefix| m = recipe['url'].match(re) prefix + m[1] if m end url_match.call(/(bitbucket\.org\/[^\/]+\/[^\/\?]+)/, "https://") || url_match.call(/(gitorious\.org\/[^\/]+\/[^.]+)/, "https://") || url_match.call(/\Alp:(.*)/, "https://launchpad.net/") || url_match.call(/\A(https?:\/\/code\.google\.com\/p\/[^\/]+\/)/, '') || url_match.call(/\A(https?:\/\/[^.]+\.googlecode\.com\/)/, '') else nil end end def read_text(url) open(url) { |f| f.read } end def inspect "#<#{self.class}>" end end <file_sep>require 'rails_helper' RSpec.describe Cask, :type => :model do it { should belong_to(:user) } it { should have_many(:cask_packages).dependent(:delete_all) } it { should have_many(:packages).through(:cask_packages) } it { should validate_presence_of(:url) } it { should validate_presence_of(:raw_url) } describe "#path" do it "returns path" do cask = create(:cask, url: 'https://github.com/username/.emacs.d/blob/53da80c63c467fac27d79e8c9c8653c81d4bb0a1/Cask') expect(cask.path).to eq '.emacs.d/Cask' end end end <file_sep>require 'stats' describe Stats do describe "roundrobin" do it "returns a Enumerator" do expect(Stats.roundrobin([1])).to be_instance_of Enumerator end it "enumerates all combination of elements" do combinations = Stats.roundrobin([1, 2, 3, 4]) expect(combinations.to_a).to eq [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] end end describe "jaccard_index" do context "empty set(s)" do it { expect(Stats.jaccard_index([], [])).to be 0.0 } it { expect(Stats.jaccard_index([1, 2, 3], [])).to be 0.0 } it { expect(Stats.jaccard_index([], [1, 2, 3])).to be 0.0 } end context "disjoint sets" do it { expect(Stats.jaccard_index([1, 2, 3], [4, 5, 6])).to be 0.0 } it { expect(Stats.jaccard_index([1, 3, 5], [2, 4, 6])).to be 0.0 } end context "intersecting sets" do it { expect(Stats.jaccard_index([1, 2, 3], [1, 2, 4])).to be (2.0 / 4.0) } it { expect(Stats.jaccard_index([1, 2, 3], [1, 4, 5])).to be (1.0 / 5.0) } it { expect(Stats.jaccard_index([1, 2, 3], [2, 3])).to be (2.0 / 3.0) } it { expect(Stats.jaccard_index([1, 2, 3], [3])).to be (1.0 / 3.0) } end context "equivalent sets" do it { expect(Stats.jaccard_index([1, 2, 3], [1, 2, 3])).to be 1.0 } it { expect(Stats.jaccard_index([1, 2, 3], [3, 1, 2])).to be 1.0 } end end end <file_sep>FactoryGirl.define do factory :package do sequence(:name) { |n| "package#{n}" } sequence(:url) { |n| "http://example.com/package#{n}" } repo_type 'github' end end <file_sep>require 'open-uri' require 'json' module UserAttributesUpdater module_function GITHUB_API_URL = 'https://api.github.com' def update(users, access_token) users.each do |user| begin update_user!(user, access_token: access_token) rescue => e # TODO: Retry warn "Update failed. #{user.inspect} #{e}" end sleep 10 unless access_token end end def update_user!(user, access_token: nil) url = "#{GITHUB_API_URL}/users/#{user.login}" url << "?access_token=#{access_token}" if access_token attr = JSON(open(url) { |f| f.read }) user.update_attributes!(name: attr['name'], url: attr['html_url'], avatar_url: attr['avatar_url'], followers: attr['followers'], following: attr['following']) end end <file_sep>FactoryGirl.define do factory :cask do user nil sequence(:url) { |n| "http://example.com/cask#{n}" } sequence(:raw_url) { |n| "http://example.com/raw/cask#{n}" } read false configuration false end end <file_sep>require 'melpa_fetcher' module PackageUpdater module_function def update cols = %w(url repo_type description) MelpaFetcher.new.packages.each do |package| old_package = Package.find_by(name: package.name) if old_package new_attr = package.attributes.slice(*cols) old_package.update_attributes!(new_attr) else package.save! end end end end <file_sep>require 'rails_helper' RSpec.describe User, :type => :model do it { should have_many(:casks) } it { should validate_presence_of(:login) } end <file_sep>class Package < ActiveRecord::Base include Redis::Objects belongs_to :cask has_many :cask_packages, dependent: :delete_all has_many :casks, through: :cask_packages validates :name, presence: true validates :repo_type, presence: true sorted_set :similarity scope :popular, -> { select('packages.*, COUNT(packages.id) AS count_packages') .joins(:cask_packages) .group('packages.id') .order('count_packages DESC') } scope :added_after, ->(time) { popular .where('packages.created_at > ?', time) .having('COUNT(packages.id) > ?', 1) .reorder('created_at DESC') } def similar_packages(limit: nil) end_index = limit.nil? ? -1 : limit - 1 id_scores = similarity.revrange(0, end_index, withscores: true) ids = id_scores.map { |a, b| a.to_i } scores = id_scores.map(&:last) packages = Package.find(ids).index_by(&:id).slice(*ids).values packages.zip(scores) end end <file_sep>module PackageSimilarityUpdater module_function def update cask_ids_dict = Hash[Package.includes(:casks).map { |p| [p, p.casks.map(&:id)] }] Package.redis.pipelined do Stats.roundrobin(Package.all).each do |p1, p2| similarity = Stats.jaccard_index cask_ids_dict[p1], cask_ids_dict[p2] if similarity > 0 p1.similarity[p2.id] = similarity p2.similarity[p1.id] = similarity end end end end def delete_all Package.redis.flushdb end end <file_sep>require 'rails_helper' RSpec.describe Package, :type => :model do it { should have_many(:cask_packages).dependent(:delete_all) } it { should have_many(:casks).through(:cask_packages) } it { should validate_presence_of(:name) } it { should validate_presence_of(:repo_type) } describe '#similar_packages' do before :each do @package_a = create(:package) @package_b = create(:package) @package_c = create(:package) @package_d = create(:package) @package_a.similarity[@package_b.id] = 0.4 @package_a.similarity[@package_c.id] = 0.9 @package_a.similarity[@package_d.id] = 0.8 end it { expect(@package_a.similar_packages(limit: 1)).to eq [[@package_c, 0.9]] } it { expect(@package_a.similar_packages(limit: 2)).to eq [[@package_c, 0.9], [@package_d, 0.8]] } it { expect(@package_a.similar_packages(limit: 10)).to eq [[@package_c, 0.9], [@package_d, 0.8], [@package_b, 0.4]] } it { expect(@package_a.similar_packages()).to eq [[@package_c, 0.9], [@package_d, 0.8], [@package_b, 0.4]] } end end <file_sep>class CaskPackage < ActiveRecord::Base belongs_to :cask belongs_to :package end <file_sep>class HomeController < ApplicationController def index @packages = Package.page(params[:page]).per(10).popular @new_packages = Package.added_after(1.month.ago).limit(10) end end <file_sep>if Rails.env.test? Redis.current = Redis.new(db: 1) end if ENV["REDISCLOUD_URL"] $redis = Redis.new(:url => ENV["REDISCLOUD_URL"]) end <file_sep>require 'rails_helper' require 'package_similarity_updater' RSpec.describe PackageSimilarityUpdater do before :each do @package_a = create(:package) @package_b = create(:package) @package_c = create(:package) @cask_a = create(:cask) @cask_b = create(:cask) @cask_c = create(:cask) @cask_d = create(:cask) @package_a.casks = [@cask_a, @cask_b, @cask_c, @cask_d] @package_b.casks = [@cask_a, @cask_b] @package_c.casks = [@cask_c] end describe "update" do it "updates similarities" do PackageSimilarityUpdater.update expect(@package_a.similar_packages).to eq [[@package_b, 2.0 / 4.0], [@package_c, 1.0 / 4.0]] expect(@package_b.similar_packages).to eq [[@package_a, 2.0 / 4.0]] expect(@package_c.similar_packages).to eq [[@package_a, 1.0 / 4.0]] end end describe "delete_all" do it "deletes all similarities" do PackageSimilarityUpdater.update PackageSimilarityUpdater.delete_all expect(@package_a.similar_packages).to eq [] expect(@package_b.similar_packages).to eq [] expect(@package_c.similar_packages).to eq [] end end end <file_sep>class UsersController < ApplicationController PER = 10 def index @users = User.page(params[:page]).per(PER).using_cask_for_configuration.order(followers: :desc) end def show @user = User.find(params[:id]) @casks = @user.casks.where(configuration: true) @packages = Package.uniq.joins(:casks).where('casks.id' => @casks).order(:name) end end <file_sep>class CaskParser def self.remove_comments(str) str.gsub(/;.+$/, '') end def initialize(text) @text = self.class.remove_comments(text) end def configuration? !@text.match(/\(\s*(?:package|development)/) end def dependencies @text.scan(/\(\s*depends-on\s+"(.+?)"/).flatten.uniq end end <file_sep># el-more ## License [MIT License](http://www.opensource.org/licenses/MIT) <file_sep>require 'open-uri' require 'cask_parser' module CaskDependencyUpdater module_function def update(limit, reader: nil) reader ||= ->(cask) { sleep 1; open(cask.raw_url) { |f| f.read } } casks = Cask.joins(:user).order("users.followers DESC") casks.lazy.select do |cask| begin save_package_dependencies! cask, reader unless cask.read cask.configuration rescue => e warn "#{e} : Cask id = #{cask.id}" false end end.take(limit).force end def save_package_dependencies!(cask, reader) Cask.transaction do text = reader.call(cask) content = CaskParser.new text config = content.configuration? cask.configuration = config if config cask.packages = Package.where(name: content.dependencies) end cask.read = true cask.save! end end def delete_all Cask.transaction do Cask.update_all(read: false, configuration: nil) CaskPackage.delete_all end end end <file_sep>require 'nokogiri' require 'open-uri' class GithubCodeSearch SEARCH_URL = 'https://github.com/search' def initialize(query, sort: nil, order: :desc) @params = { q: query, s: sort, o: order, type: 'Code' } end def result(page) params = @params.merge(p: page) uri = URI(SEARCH_URL) uri.query = params.to_param doc = Nokogiri::HTML(open uri) doc.css("div.code-list-item").map do |item| user_path = item.css('a').attribute('href').value user = user_path.split('/').last code_path = item.css('p.title a').last.attribute('href').value code_raw_path = code_path.sub(%r{(\A/[^/]+/[^/]+/)blob}, '\1raw') { user: { login: user, url: (uri + user_path).to_s }, code: { url: (uri + code_path).to_s, raw_url: (uri + code_raw_path).to_s } } end end end <file_sep>class PackagesController < ApplicationController PER = 20 WORD_LIMIT = 5 def index @packages = Package.page(params[:page]).per(PER).popular if params[:q] words = tokenize(params[:q]).uniq.take(WORD_LIMIT) @packages = @packages.search(contains_all(words)).result end end def show @package = Package.find(params[:id]) @similar_packages = @package.similar_packages(limit: 20) @users = @package.casks.select('users.*').uniq.joins(:user) .order('users.followers DESC').to_a end private def tokenize(str) str.scan /\w+/ end def contains_all(values) alist = values.map.with_index do |x, i| [i.to_s, { m: 'or', name_cont: x, description_cont: x }] end { m: 'and', g: Hash[alist] } end end <file_sep>class Cask < ActiveRecord::Base belongs_to :user has_many :cask_packages, dependent: :delete_all has_many :packages, through: :cask_packages validates :url, presence: true validates :raw_url, presence: true def path URI(url).path.split('/').values_at(2, 5..-1).join('/') end end <file_sep>namespace :data do def ensure_github_access_token ENV['GITHUB_ACCESS_TOKEN'] or raise "Environment variable GITHUB_ACCESS_TOKEN is not defined." end namespace :package do desc "Fetch MELPA package information" task :update => :environment do PackageUpdater.update end end namespace :package_similarity do desc "Calculate package similarity" task :update => :environment do PackageSimilarityUpdater.delete_all PackageSimilarityUpdater.update end end namespace :cask do desc "Search on GitHub for Cask files" task :initial_import => :environment do CaskUpdater.update(80) end desc "Search on GitHub for recently updated Cask files" task :update => :environment do require 'cask_updater' CaskUpdater.update(5, search: CaskUpdater::SEARCH_RECENTLY_INDEXED) end end namespace :cask_dependency do desc "Update package dependencies of Cask" task :update => :environment do CaskDependencyUpdater.update(100) end desc "Delete package dependencies of all Cask" task :delete => :environment do CaskDependencyUpdater.delete_all end end namespace :user_attributes do desc "Update user attributes" task :update => :environment do access_token = ensure_github_access_token UserAttributesUpdater.update User.all, access_token end end namespace :all do desc "Update all data" task :update => :environment do tasks = %w(data:package:update data:cask:update data:user_attributes:update data:cask_dependency:update data:package_similarity:update) ensure_github_access_token tasks.each do |task| puts "Task: #{task}" Rake::Task[task].invoke end end end end <file_sep>require 'rails_helper' Dir.glob(Rails.root.join('lib', '*.rb')).each { |x| require x } <file_sep>module Stats module_function def roundrobin(l) Enumerator.new do |yielder| l.each_with_index do |row, i| l.drop(i + 1).each do |col| yielder << [row, col] end end end end def jaccard_index(set1, set2) n_or = (set1 | set2).length n_and = (set1 & set2).length if n_or == 0 || n_and == 0 0.0 else n_and.to_f() / n_or.to_f() end end end <file_sep>require 'rails_helper' RSpec.describe PackagesController, :type => :controller do describe "GET index" do before :each do @package_a = create(:package, name: 'foo', description: 'bar') @package_b = create(:package, name: 'bar', description: 'baz') @package_c = create(:package, name: 'baz', description: 'foo') @package_d = create(:package, name: 'foobar', description: 'baz') @package_a.casks << create(:cask) @package_b.casks << create(:cask) @package_c.casks << create(:cask) @package_d.casks << create(:cask) end context 'without params[:q]' do it "returns http success" do get :index expect(response).to have_http_status(:success) end it "assigns all packages to @packages" do get :index expect(assigns(:packages)).to contain_exactly(@package_a, @package_b, @package_c, @package_d) end end context 'with params[:q]' do specify "q: 'foo'" do get :index, q: 'foo' expect(assigns(:packages)).to contain_exactly(@package_a, @package_c, @package_d) end specify "q: 'bar'" do get :index, q: 'bar' expect(assigns(:packages)).to contain_exactly(@package_a, @package_b, @package_d) end specify "q: 'baz'" do get :index, q: 'baz' expect(assigns(:packages)).to contain_exactly(@package_b, @package_c, @package_d) end specify "q: 'foo bar'" do get :index, q: 'foo bar' expect(assigns(:packages)).to contain_exactly(@package_a, @package_d) end specify "q: 'zoo'" do get :index, q: 'zoo' expect(assigns(:packages)).to contain_exactly() end end end describe "GET show" do let(:package) { create(:package) } it "returns http success" do get :show, id: package expect(response).to have_http_status(:success) end it "assigns the requested package to @package" do get :show, id: package expect(assigns(:package)).to eq package end end end
057f654feb40b4f62eb2180b206f0e366099fe88
[ "Markdown", "Ruby" ]
29
Ruby
igjit/el-more
c174a6d52e66cc46ba7849a0c823c22e770180f9
62b1bc1dce06c39ba769c46ba33779f76b9e9f06
refs/heads/master
<file_sep><?php use yii\db\Migration; class m161217_165316_create_tbl_tr_travel extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('{{%tr_travel}}', [ 'id' => $this->primaryKey(), 'kota_asal' => $this->integer(), 'kota_tujuan' => $this->integer(), 'jam' => $this->integer(), 'company_id' => $this->integer(), 'status' => $this->smallInteger()->notNull()->defaultValue(10), 'created_at' => $this->integer()->notNull(), 'updated_at' => $this->integer()->notNull(), ], $tableOptions); $this->addForeignKey ('fk_kota_asal_travel', 'tr_travel', 'kota_asal', 'kota', 'id', 'NO ACTION', 'NO ACTION'); $this->addForeignKey ('fk_kota_tujuan_travel', 'tr_travel', 'kota_tujuan', 'kota', 'id', 'NO ACTION', 'NO ACTION'); $this->addForeignKey ('fk_company_travel', 'tr_travel', 'company_id', 'company', 'id', 'NO ACTION', 'NO ACTION'); } public function down() { $this->dropTable('{{%tr_travel}}'); } } <file_sep><?php /* @var $this yii\web\View */ use yii\helpers\Html; ?> <footer> <div class="subscribe"> <div class="container"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <div class="form-group has-feedback"> <?php echo Html::label('Subscribe to get more of us!', 'subscribe') ?> <div class="input-group"> <?php echo Html::input('text', 'subscribe', '', ['id' => 'subscribe','class' => 'form-control', 'placeholder' => 'Masukkan email Anda']) ?> <span class="fa fa-envelope form-control-feedback" aria-hidden="true"></span> <div class="input-group-btn"> <?php echo Html::button('SUBSCRIBE', ['class' => 'btn btn-primary']) ?> </div> </div> </div> </div> </div> </div> </div> <div class="container"> <div class="row"> <?php for ($a = 0; $a < 3; $a++): ?> <div class="col-md-2 col-sm-3 col-xs-4"> <ul class="quick-links"> <li><?php echo Html::a('Some link 1', '#') ?></li> <li><?php echo Html::a('Some link 2', '#') ?></li> <li><?php echo Html::a('Some link 3', '#') ?></li> <li><?php echo Html::a('Some link 4', '#') ?></li> <li><?php echo Html::a('Some link 5', '#') ?></li> </ul> </div> <?php endfor; ?> <div class="col-md-offset-3 col-sm-3 text-center hidden-xs"> <span class="fa-stack fa-5x text-primary"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-map-marker fa-inverse fa-stack-1x"></i> </span> </div> </div> <p>&copy; 2016&mdash;<?php echo date('Y') ?> TravelMarket.com. All rights reserved.</p> <div class="separator"></div> <p class="text-center">TravelMarket.com is supported by Transuperindo.</p> </div> </footer><file_sep><?php use yii\db\Migration; class m161228_131523_create_table_tr_paket_wisata extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('{{%tr_paketwisata}}', [ 'id' => $this->primaryKey(), 'kode' => $this->string(), 'nama_pemesan' => $this->string(225), 'telp1' => $this->string(15), 'telp2' => $this->string(15), 'alamat_jemput' => $this->string(225), 'detail_jemput' => $this->text(), 'harga' => $this->integer(), 'metode_bayar' => $this->integer(), 'paket_id' => $this->integer(), 'keterangan' => $this->text(), 'status' => $this->smallInteger()->notNull()->defaultValue(10), 'created_at' => $this->integer()->notNull(), 'updated_at' => $this->integer()->notNull(), ], $tableOptions); $this->addForeignKey ('fk_paket_tr_paket', 'tr_paketwisata', 'paket_id', 'pw_paket', 'id', 'NO ACTION', 'NO ACTION'); } public function down() { $this->dropTable('{{%tr_paketwisata}}'); } } <file_sep><?php use yii\db\Migration; class m161217_142921_add_id_kota_tbl_company extends Migration { public function up() { $this->addColumn('company','id_kota',$this->integer()->after('alamat')); $this->addForeignKey ('fk_kota_company', 'company', 'id_kota', 'kota', 'id', 'NO ACTION', 'NO ACTION'); } public function down() { $this->dropColumn('company','id_kota'); return false; } } <file_sep><?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; use yii\helpers\Url; use yii\widgets\LinkPager; $this->title = 'Daftar Tempat Wisata'; $this->params['breadcrumbs'][] = $this->title; ?> <!-- banner start --> <!-- ================ --> <div class="banner dark-translucent-bg" style="background-image:url('../images/shop-banner.jpg'); background-position:50% 32%;"> <!-- breadcrumb start --> <!-- ================ --> <div class="breadcrumb-container"> <div class="container"> <ol class="breadcrumb"> <li><i class="fa fa-home pr-10"></i><a class="link-dark" href="/">Home</a></li> <li class="active"><?php echo $this->title;?></li> </ol> </div> </div> <!-- breadcrumb end --> <div class="container"> <div class="row"> <div class="col-md-8 text-center col-md-offset-2 pv-20"> <h2 class="title object-non-visible" data-animation-effect="fadeIn" data-effect-delay="100"><?php echo $this->title;?></h2> <div class="separator object-non-visible mt-10" data-animation-effect="fadeIn" data-effect-delay="100"></div> </div> </div> </div> </div> <!-- banner end --> <!-- section start --> <!-- ================ --> <div class="light-gray-bg section"> <div class="container"> <!-- filters start --> <div class="sorting-filters text-center mb-20"> <?php $form = ActiveForm::begin(['id' => 'frmFilterPwWisata','options' => ['class'=>'form-inline']]); ?> <?= $form->field($model, 'id_kota')->dropDownList(ArrayHelper::map($kota, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control']) ?> <div class="form-group"> <label class="control-label">&nbsp;</label> <?= Html::submitButton('Cari', ['class' => 'btn btn-default margin-clear']) ?> <div class="mt-5 mb-10"></div> </div> <?php ActiveForm::end(); ?> </div> <!-- filters end --> </div> </div> <!-- section end --> <!-- main-container start --> <!-- ================ --> <section class="main-container"> <div class="container"> <div class="row"> <!-- main start --> <!-- ================ --> <div class="main col-md-12"> <!-- pills start --> <!-- ================ --> <!-- Tab panes --> <?php if(empty($DataPaket)):?> <div class="row"> <!-- main start --> <!-- ================ --> <div class="main col-md-6 col-md-offset-3 pv-40"> <h1 class="page-title"><span class="text-default">Maaf</span></h1> <p>Data layanan umroh tidak ada</p> <a href="/umroh" class="btn btn-default btn-animated btn-lg">Return Umroh <i class="fa fa-home"></i></a> </div> <!-- main end --> </div> <?php else:?> <?php foreach($DataPaket as $dtpaket):?> <div class="listing-item mb-20"> <div class="row grid-space-0"> <div class="col-sm-6 col-md-4 col-lg-3"> <div class="overlay-container"> <img src="../images/danau.jpg" alt=""> <a class="overlay-link" href="shop-product.html"><i class="fa fa-plus"></i></a> </div> </div> <div class="col-sm-6 col-md-8 col-lg-9"> <div class="body"> <h3 class="margin-clear"><a href="<?php echo Url::to(['detail-paket-umroh', 'id' => $dtpaket->id])?>"><?php echo $dtpaket->nama;?></a></h3> <p> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star"></i> <a href="<?php echo Url::to(['my-wishlist', 'id' => $dtpaket->id])?>" class="btn-sm-link"><i class="icon-heart pr-5"></i>Add to Wishlist</a> <a href="<?php echo Url::to(['detail-agen', 'id' => $dtpaket->id])?>" class="btn-sm-link"><i class="icon-link pr-5"></i><?php echo $dtpaket->company->nama?></a> </p> <p><?php echo $dtpaket->deskripsi;?></p> <div class="elements-list clearfix"> <span class="price">IDR <?php echo number_format($dtpaket->harga);?></span> <a href="<?php echo Url::to(['detail-paket-umroh', 'id' => $dtpaket->id])?>" class="pull-right btn btn-sm btn-default-transparent">More Detail</a> </div> </div> </div> </div> </div> <?php endforeach;?> <!-- pills end --> <!-- pagination start --> <nav class="text-center"> <?php echo LinkPager::widget([ 'pagination' => $pages, 'options' => ['class'=>'pagination','firstPageLabel'=>false], ]); ?> </nav> <!-- pagination end --> <?php endif;?> </div> <!-- main end --> </div> </div> </section> <!-- main-container end --> <file_sep><?php namespace common\models; use Yii; /** * This is the model class for table "pw_paket". * * @property integer $id * @property string $nama * @property string $deskripsi * @property integer $harga * @property integer $kategori_id * @property integer $company_id * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property Company $company * @property PwKategori $kategori */ class PwPaket extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'pw_paket'; } /** * @inheritdoc */ public function rules() { return [ [['harga', 'kategori_id', 'company_id', 'status', 'created_at', 'updated_at'], 'integer'], [['created_at', 'updated_at'], 'required'], [['nama', 'deskripsi'], 'string', 'max' => 255], [['company_id'], 'exist', 'skipOnError' => true, 'targetClass' => Company::className(), 'targetAttribute' => ['company_id' => 'id']], [['kategori_id'], 'exist', 'skipOnError' => true, 'targetClass' => PwKategori::className(), 'targetAttribute' => ['kategori_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'nama' => Yii::t('app', 'Nama'), 'deskripsi' => Yii::t('app', 'Deskripsi'), 'harga' => Yii::t('app', 'Harga'), 'kategori_id' => Yii::t('app', 'Kategori ID'), 'company_id' => Yii::t('app', 'Company ID'), 'status' => Yii::t('app', 'Status'), 'created_at' => Yii::t('app', 'Created At'), 'updated_at' => Yii::t('app', 'Updated At'), ]; } /** * @return \yii\db\ActiveQuery */ public function getCompany() { return $this->hasOne(Company::className(), ['id' => 'company_id']); } /** * @return \yii\db\ActiveQuery */ public function getKategori() { return $this->hasOne(PwKategori::className(), ['id' => 'kategori_id']); } public static function GetListPaket($id_kategori) { $data = PwPaket::find()->where(['=', 'kategori_id', $id_kategori])->andWhere(['=', 'pw_paket.status_wisata', 1]); return $data; } public static function GetListUmroh($id_kota) { $data = PwPaket::find()->joinWith('company')->where(['=', 'company.id_kota', $id_kota])->andWhere(['=', 'pw_paket.status_wisata', 2]); return $data; } public static function GetPaketById($id) { $data = PwPaket::find()->where(['=', 'id', $id])->one(); return $data; } } <file_sep><?php namespace common\models; use Yii; /** * This is the model class for table "kota". * * @property integer $id * @property string $nama * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property Company[] $companies * @property Overarea[] $overareas * @property TrTravel[] $trTravels * @property TrTravel[] $trTravels0 */ class Kota extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'kota'; } /** * @inheritdoc */ public function rules() { return [ [['status', 'created_at', 'updated_at'], 'integer'], [['created_at', 'updated_at'], 'required'], [['nama'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'nama' => Yii::t('app', 'Nama'), 'status' => Yii::t('app', 'Status'), 'created_at' => Yii::t('app', 'Created At'), 'updated_at' => Yii::t('app', 'Updated At'), ]; } /** * @return \yii\db\ActiveQuery */ public function getCompanies() { return $this->hasMany(Company::className(), ['id_kota' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getOverareas() { return $this->hasMany(Overarea::className(), ['kota_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTrTravels() { return $this->hasMany(TrTravel::className(), ['kota_asal' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTrTravels0() { return $this->hasMany(TrTravel::className(), ['kota_tujuan' => 'id']); } } <file_sep><?php namespace common\assets; use yii\web\AssetBundle; /** * Asset bundle for common css files. * */ class CommonCssAsset extends AssetBundle { public $sourcePath = '@common/shared-assets'; public $css = [ 'https://fonts.googleapis.com/css?family=Roboto:300,400,700', 'css/bootstrap-custom.css', 'css/nprogress.css', ]; public $depends = [ 'yii\bootstrap\BootstrapAsset', ]; public $publishOptions = [ 'forceCopy' => YII_DEBUG, ]; } <file_sep><?php namespace frontend\models; use Yii; use yii\base\Model; /** * SimpanTravelForm is the model behind the paket wisata form. */ class SimpanTravelForm extends Model { public $id_kota_berangkat; public $id_kota_tujuan; public $tgl_berangkat; public $jam_berangkat; /** * @inheritdoc */ public function rules() { return [ [['nama_pemesan', 'telp1','alamat_jemput','detail_jemput','harga','metode_bayar','id'], 'required'], [['nama_pemesan', 'telp1','telp2','alamat_jemput','detail_jemput','harga','metode_bayar','paket_id','keterangan'], 'string'], [['metode_bayar','paket_id'], 'integer'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'nama_pemesan' => 'Nama Pemesan', 'telp1' => 'Telp 1', 'telp2' => 'Telp 2', 'alamat_jemput' => 'Alamat Penjemputan', 'detail_jemput' => 'Detail penjemputan', 'metode_bayar' => 'Metode pembayaran', 'keterangan' => 'Keterangan Tambahan', ]; } } <file_sep><?php namespace common\assets; use yii\web\AssetBundle; /** * Asset bundle for Font Awesome css files & friends. * */ class FontAwesomeAsset extends AssetBundle { // public $sourcePath = '@vendor/fortawesome/font-awesome'; public $css = [ 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', ]; /** * Menentukan publishOptions property untuk menggabungkan nilai namespace. * * @return void */ public function init() { $this->publishOptions = [ 'forceCopy' => YII_DEBUG, 'beforeCopy' => __NAMESPACE__ . '\FontAwesomeAsset::filterFolders', ]; parent::init(); } public static function filterFolders($from, $to) { $validFilesAndFolders = [ 'css/', 'fonts/', 'font-awesome.css', 'font-awesome.min.css', 'FontAwesome.otf', 'fontawesome-webfont.eot', 'fontawesome-webfont.svg', 'fontawesome-webfont.ttf', 'fontawesome-webfont.woff', 'fontawesome-webfont.woff2', ]; $pathItems = array_reverse(explode(DIRECTORY_SEPARATOR, $from)); if (in_array($pathItems[0], $validFilesAndFolders)) return true; else return false; } /*Code dibawah, yang di-publish hanya foldernya saja T-T public $publishOptions = [ 'only' => [ 'css/', 'fonts/', ], ];*/ } <file_sep><?php namespace common\models; use Yii; /** * This is the model class for table "tr_jadwal". * * @property integer $id * @property string $jam * @property integer $tr_travel_id * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property TrTravel $trTravel */ class TrJadwal extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'tr_jadwal'; } /** * @inheritdoc */ public function rules() { return [ [['tr_travel_id', 'status', 'created_at', 'updated_at'], 'integer'], [['created_at', 'updated_at'], 'required'], [['jam'], 'string', 'max' => 20], [['tr_travel_id'], 'exist', 'skipOnError' => true, 'targetClass' => TrTravel::className(), 'targetAttribute' => ['tr_travel_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'jam' => Yii::t('app', 'Jam'), 'tr_travel_id' => Yii::t('app', 'Tr Travel ID'), 'status' => Yii::t('app', 'Status'), 'created_at' => Yii::t('app', 'Created At'), 'updated_at' => Yii::t('app', 'Updated At'), ]; } /** * @return \yii\db\ActiveQuery */ public function getTrTravel() { return $this->hasOne(TrTravel::className(), ['id' => 'tr_travel_id']); } public static function GetListTravel($id_kota_berangkat,$id_kota_tujuan,$tgl_berangkat,$jam_berangkat) { $data = Trjadwal::find() ->joinWith('trTravel'); // ->where(['=', 'company.id_kota', $id_kota]); return $data; } } <file_sep><?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; use yii\helpers\Url; $this->title = 'Detail Paket Wisata'; $this->params['breadcrumbs'][] = $this->title; ?> <!-- breadcrumb start --> <!-- ================ --> <div class="breadcrumb-container"> <div class="container"> <ol class="breadcrumb"> <li><i class="fa fa-home pr-10"></i><a class="link-dark" href="/">Home</a></li> <li class="active"><?php echo $this->title;?></li> </ol> </div> </div> <!-- breadcrumb end --> <!-- main-container start --> <!-- ================ --> <section class="main-container"> <div class="container"> <div class="row"> <!-- main start --> <!-- ================ --> <div class="main col-md-12"> <!-- page-title start --> <!-- ================ --> <h1 class="page-title"><?php echo $DataPaket->nama;?></h1> <div class="separator-2"></div> <!-- page-title end --> <div class="row"> <div class="col-md-4"> <!-- pills start --> <!-- ================ --> <!-- Nav tabs --> <ul class="nav nav-pills" role="tablist"> <li class="active"><a href="#pill-1" role="tab" data-toggle="tab" title="images"><i class="fa fa-camera pr-5"></i> Photo</a></li> <li><a href="#pill-2" role="tab" data-toggle="tab" title="video"><i class="fa fa-video-camera pr-5"></i> Video</a></li> </ul> <!-- Tab panes --> <div class="tab-content clear-style"> <div class="tab-pane active" id="pill-1"> <div class="owl-carousel content-slider-with-large-controls"> <div class="overlay-container overlay-visible"> <img src="../images/product-1.jpg" alt=""> <a href="../images/product-1.jpg" class="popup-img overlay-link" title="image title"><i class="icon-plus-1"></i></a> </div> <div class="overlay-container overlay-visible"> <img src="../images/product-1-2.jpg" alt=""> <a href="../images/product-1-2.jpg" class="popup-img overlay-link" title="image title"><i class="icon-plus-1"></i></a> </div> </div> </div> <div class="tab-pane" id="pill-2"> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="http://player.vimeo.com/video/29198414?byline=0&amp;portrait=0"></iframe> <p><a href="http://vimeo.com/29198414">Introducing Vimeo Music Store</a> from <a href="http://vimeo.com/staff">Vimeo Staff</a> on <a href="https://vimeo.com/">Vimeo</a>.</p> </div> </div> </div> <!-- pills end --> </div> <div class="col-md-8 pv-30"> <h2>Deskripsi</h2> <?php echo $DataPaket->deskripsi;?> <hr class="mb-10"> <div class="clearfix mb-20"> <span> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star"></i> </span> <a href="<?php echo Url::to(['my-wishlist', 'id' => $DataPaket->id])?>" class="wishlist"><i class="fa fa-heart-o pl-10 pr-5"></i>Wishlist</a> <ul class="pl-20 pull-right social-links circle small clearfix margin-clear animated-effect-1"> <li class="twitter"><a target="_blank" href="http://www.twitter.com/"><i class="fa fa-twitter"></i></a></li> <li class="googleplus"><a target="_blank" href="http://plus.google.com/"><i class="fa fa-google-plus"></i></a></li> <li class="facebook"><a target="_blank" href="http://www.facebook.com/"><i class="fa fa-facebook"></i></a></li> </ul> </div> <div class="light-gray-bg p-20 bordered clearfix"> <span class="product price"><i class="icon-tag pr-10"></i>IDR <?php echo number_format($DataPaket->harga);?></span> <div class="product elements-list pull-right clearfix"> <a href="<?php echo Url::to(['pesan-paket-umroh', 'id' => $DataPaket->id])?>" class="margin-clear btn btn-default">Pesan</a> </div> </div> </div> </div> </div> <!-- main end --> </div> </div> </section> <!-- main-container end --> <!-- section start --> <!-- ================ --> <section class="pv-30 light-gray-bg"> <div class="container"> <div class="row"> <div class="col-md-12"> <!-- Nav tabs --> <ul class="nav nav-tabs style-4" role="tablist"> <li class="active"><a href="#h2tab2" role="tab" data-toggle="tab"><i class="fa fa-files-o pr-5"></i>Specifications</a></li> <li><a href="#h2tab3" role="tab" data-toggle="tab"><i class="fa fa-star pr-5"></i>(3) Reviews</a></li> </ul> <!-- Tab panes --> <div class="tab-content padding-top-clear padding-bottom-clear"> <div class="tab-pane fade in active" id="h2tab2"> <h4 class="space-top">Specifications</h4> <hr> <dl class="dl-horizontal"> <dt>Consectetur</dt> <dd>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</dd> <dt>Culla</dt> <dd>Adipisci autem illo hic itaque nulla velit quod laboriosam ipsum in illum!</dd> <dt>Quas</dt> <dd>Velit mollitia vel nemo, repudiandae quas nisi consectetur maiores beatae.</dd> <dt>Sapiente</dt> <dd>Dolor, architecto, accusamus. Explicabo, culpa hic sapiente amet libero, recusandae laudantium consequatur velit possimus ratione quo. Ipsum maxime officia quasi quos magni!</dd> <dt>Dignissimos</dt> <dd>Odio cum deleniti mollitia, quisquam dignissimos voluptatem, unde rem alias.</dd> <dt>Adipisicing</dt> <dd>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</dd> <dd>Tempora rerum veritatis nam blanditiis.</dd> <dt>Werspiciatis</dt> <dd>Rem nostrum sit magnam debitis quidem perspiciatis fuga fugit.</dd> </dl> <hr> </div> <div class="tab-pane fade" id="h2tab3"> <!-- comments start --> <div class="comments margin-clear space-top"> <!-- comment start --> <div class="comment clearfix"> <div class="comment-avatar"> <img class="img-circle" src="../images/avatar.jpg" alt="avatar"> </div> <header> <h3>Amazing!</h3> <div class="comment-meta"> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star"></i> | Today, 12:31</div> </header> <div class="comment-content"> <div class="comment-body clearfix"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <a href="blog-post.html" class="btn-sm-link link-dark pull-right"><i class="fa fa-reply"></i> Reply</a> </div> </div> </div> <!-- comment end --> <!-- comment start --> <div class="comment clearfix"> <div class="comment-avatar"> <img class="img-circle" src="../images/avatar.jpg" alt="avatar"> </div> <header> <h3>Really Nice!</h3> <div class="comment-meta"> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star"></i> | Today, 10:31</div> </header> <div class="comment-content"> <div class="comment-body clearfix"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <a href="blog-post.html" class="btn-sm-link link-dark pull-right"><i class="fa fa-reply"></i> Reply</a> </div> </div> </div> <!-- comment end --> <!-- comment start --> <div class="comment clearfix"> <div class="comment-avatar"> <img class="img-circle" src="../images/avatar.jpg" alt="avatar"> </div> <header> <h3>Worth to Buy!</h3> <div class="comment-meta"> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star"></i> | Today, 09:31</div> </header> <div class="comment-content"> <div class="comment-body clearfix"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <a href="blog-post.html" class="btn-sm-link link-dark pull-right"><i class="fa fa-reply"></i> Reply</a> </div> </div> </div> <!-- comment end --> </div> <!-- comments end --> <!-- comments form start --> <div class="comments-form"> <h2 class="title">Add your Review</h2> <form role="form" id="comment-form"> <div class="form-group has-feedback"> <label for="name4">Name</label> <input type="text" class="form-control" id="name4" placeholder="" name="name4" required> <i class="fa fa-user form-control-feedback"></i> </div> <div class="form-group has-feedback"> <label for="subject4">Subject</label> <input type="text" class="form-control" id="subject4" placeholder="" name="subject4" required> <i class="fa fa-pencil form-control-feedback"></i> </div> <div class="form-group"> <label>Rating</label> <select class="form-control" id="review"> <option value="five">5</option> <option value="four">4</option> <option value="three">3</option> <option value="two">2</option> <option value="one">1</option> </select> </div> <div class="form-group has-feedback"> <label for="message4">Message</label> <textarea class="form-control" rows="8" id="message4" placeholder="" name="message4" required></textarea> <i class="fa fa-envelope-o form-control-feedback"></i> </div> <input type="submit" value="Submit" class="btn btn-default"> </form> </div> <!-- comments form end --> </div> </div> </div> </div> </div> </section> <!-- section end --><file_sep><?php /* @var $this yii\web\View */ use yii\helpers\Html; ?> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <i class="fa fa-lg fa-fw fa-bars"></i> <!-- <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> --> </button> <a class="navbar-brand" href="<?php echo Yii::$app->homeUrl ?>"><i class="fa fa-fw fa-map-marker"></i> TRAVELMARKET</a> </div> <div id="navbar-collapse" class="collapse navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Dead link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-hover="dropdown" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Single page <span class="caret"></span></a> <ul class="dropdown-menu"> <li><?php echo Html::a('Search page', '@web/test/search') ?></li> <li><?php echo Html::a('Single page 1', '@web/single') ?></li> <li><?php echo Html::a('Single page 2', '@web/single/index2') ?></li> <li class="divider" role="separator"></li> <li><a href="#">Dead link</a></li> </ul> </li> </ul> </div> </div> </nav> <div class="nav-pack"> <div class="container"> <?php // echo Html::a(Html::img('@web/images/transuperindo-white.png'), Yii::$app->homeUrl, ['class' => 'navbar-brand big']) ?> <?php // echo Html::a(Html::img('@web/images/transuperindo-logo.png'), Yii::$app->homeUrl, ['class' => 'navbar-brand small']) ?> <?php echo Html::a('<i class="fa fa-lg fa-fw fa-map-marker"></i> <b>TRAVELMARKET</b>', Yii::$app->homeUrl, ['class' => 'navbar-brand big']) ?> <?php echo Html::a('<i class="fa fa-lg fa-fw fa-map-marker"></i>', Yii::$app->homeUrl, ['class' => 'navbar-brand small']) ?> <ul class="nav nav-pills"> <li class="active"><a href="#">Paket wisata</a></li> <li> <a href="/umroh">Umroh</a></li> <li> <a href="travel">Travel</a></li> <li> <a href="drop">Drop</a></li> <li> <a href="rental">Rental</a></li> </ul> </div> </div> <div class="nav-pack-clear"></div> <file_sep><?php /* @var $this yii\web\View */ use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\ActiveForm; $this->title = 'Single page'; // $this->params['breadcrumbs'][] = $this->title; ?> <div class="container"> <div class="page-heading"> <h2> <?php echo $DataPaket->nama ?> <small><?php echo Html::a('<i class="fa fa-fw fa-heart"></i>', Url::to(['my-wishlist', 'id' => $DataPaket->id])) ?></small> </h2> </div> <div class="flat-panel"> <div class="row"> <div class="col-sm-4"> <div class="row"> <div class="col-sm-12 col-sm-offset-0 col-xs-10 col-xs-offset-1"> <div class="preview"> <div class="preview-image"> <?php for ($a = 0; $a < 10; $a++): ?> <?php $number[] = mt_rand(1, 4) ?> <?php echo Html::img('@web/images/sample'.$number[$a].'.jpg', ['class' => 'img-responsive']) ?> <?php endfor ?> </div> <div class="preview-thumbnail"> <?php for ($a = 0; $a < 10; $a++): ?> <?php echo Html::img('@web/images/sample'.$number[$a].'.jpg', ['class' => 'img-responsive']) ?> <?php endfor ?> </div> </div> </div> </div> </div> <div class="col-sm-8"> <div class="rating"> <?php $rate = mt_rand(1, 5) ?> <?php for ($b = 0; $b < 5; $b++): ?> <i class="fa fa-star <?php echo $b < $rate ? 'text-warning' : '' ?>"></i> <?php endfor ?> </div> <p>Single item vendor</p> <p><?php echo $DataPaket->deskripsi ?></p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed enim nulla, euismod nec vehicula in, iaculis vitae diam. Nulla lacinia, est non feugiat eleifend, lorem felis fringilla tellus, eu consectetur ante orci et eros. Nullam feugiat tempus elit id bibendum. Duis pellentesque vestibulum quam a elementum. Etiam id dolor euismod, fermentum purus ac, ornare dolor. Morbi ac quam quis ante porta luctus nec eu lectus. Ut sit amet dolor aliquet, commodo libero eget, ornare nulla. Proin quis lobortis ex.</p> <div class="price"><?php echo number_format($DataPaket->harga) ?></div> <div class="row"> <div class="col-md-4 col-md-offset-8 col-xs-6 col-xs-offset-6"> <?php echo Html::a('PESAN', Url::to(['pesan-paket-wisata', 'id' => $DataPaket->id]), ['class' => 'btn btn-lg btn-block btn-warning']) ?> </div> </div> </div> </div> </div> </div><file_sep><?php namespace frontend\assets; use yii\web\AssetBundle; /** * Main frontend application asset bundle. */ class AllAsset extends AssetBundle {} <file_sep><?php use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\ActiveForm; ?> <!-- banner start --> <!-- ================ --> <div class="banner banner-big-height dark-translucent-bg padding-bottom-clear" style="background-image:url('images/hotel-banner.jpg');background-position: 50% 32%;"> <div class="container"> <div class="row"> <div class="col-md-8 text-center col-md-offset-2 pv-20"> <h1 class="title">Travel</h1> <div class="separator mt-10"></div> <p class="text-center">Cari dan temukan layanan travel di kota anda.</p> </div> </div> </div> <!-- section start --> <!-- ================ --> <div class="dark-translucent-bg section"> <div class="container"> <!-- filters start --> <div class="sorting-filters text-center mb-20"> <?php $form = ActiveForm::begin(['id' => 'frmPwWisata','options' => ['class'=>'form-inline','role'=>'form']]); ?> <?= $form->field($model, 'id_kota_berangkat')->dropDownList(ArrayHelper::map($kota, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control']) ?> <?= $form->field($model, 'id_kota_tujuan')->dropDownList(ArrayHelper::map($kota, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control']) ?> <?= $form->field($model, 'tgl_berangkat')->TextInput(['maxlength' => 255, 'class' => 'form-control datepicker']) ?> <?= $form->field($model, 'jam_berangkat',['template' => '{label}<div class="clockpicker" data-autoclose="true">{input}</div>{error}{hint}','labelOptions' => [ 'class' => 'control-label' ]]) ?> <div class="form-group"> <label class="control-label">&nbsp;</label> <?= Html::submitButton('Cari', ['class' => 'btn btn-gray-transparent btn-animated margin-clear']) ?> <div class="mt-5 mb-10"></div> </div> <?php ActiveForm::end(); ?> </div> <!-- filters end --> </div> </div> <!-- section end --> </div> <!-- banner end --> <!-- section start --> <!-- ================ --> <section class="light-gray-bg pv-40 border-clear"> <div class="container"> <div class="col-md-8 col-md-offset-2"> <h2 class="text-center title">Layanan Travel Terbaru</h2> <div class="separator"></div> </div> </div> <div class="container-fluid"> <div class="row"> </div> </div> </section> <!-- section end --> <!-- section start --> <!-- ================ --> <section class="dark-translucent-bg background-img-9 pv-40" style="background-position: 50% 50%;"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="testimonial text-center"> <div class="testimonial-image"> <img src="../images/testimonial-1.jpg" alt="<NAME>" title="<NAME>" class="img-circle"> </div> <h3>Just Perfect!</h3> <div class="separator"></div> <div class="testimonial-body"> <blockquote> <p>Sed ut perspiciatis unde omnis iste natu error sit voluptatem accusan tium dolore laud antium.</p> </blockquote> <div class="testimonial-info-1">- Jane Doe</div> <div class="testimonial-info-2">By Company</div> </div> </div> </div> <div class="col-md-4"> <div class="testimonial text-center"> <div class="testimonial-image"> <img src="images/testimonial-2.jpg" alt="<NAME>" title="<NAME>" class="img-circle"> </div> <h3>Amazing!</h3> <div class="separator"></div> <div class="testimonial-body"> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et cupiditate deleniti ratione.</p> </blockquote> <div class="testimonial-info-1">- <NAME></div> <div class="testimonial-info-2">By Company</div> </div> </div> </div> <div class="col-md-4"> <div class="testimonial text-center"> <div class="testimonial-image"> <img src="images/testimonial-3.jpg" alt="<NAME>" title="<NAME>" class="img-circle"> </div> <h3>Amazing!</h3> <div class="separator"></div> <div class="testimonial-body"> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et cupiditate deleniti ratione.</p> </blockquote> <div class="testimonial-info-1">- <NAME></div> <div class="testimonial-info-2">By Company</div> </div> </div> </div> </div> </div> </section> <!-- section end --> <?php $this->registerJsFile('@web/js/travel.js', ['depends' => [\frontend\assets\AppAsset::className()]]); ?> <file_sep><?php /* @var $this yii\web\View */ use yii\widgets\Breadcrumbs; use yii\helpers\Html; $this->title = 'Single item heading 2'; ?> <div class="container"> <div class="page-heading media"> <div class="media-left"> <?php echo Html::img('@web/images/default-64.png', ['class' => 'media-object']) ?> </div> <div class="media-body"> <h4 class="media-heading">Single item heading 2</h4> <p>Single item vendor</p> </div> <div class="media-right media-middle"> <?php echo Html::button('PESAN', ['class' => 'btn btn-lg btn-warning']) ?> </div> </div> <div class="form-horizontal"> <div class="row"> <div class="col-md-9"> <div class="flat-panel"> <div class="flat-title"> <h4>Single item body title 2</h4> </div> <div class="row"> <?php $no = 1; ?> <?php for ($a = 0; $a < 2; $a++): ?> <div class="col-md-6"> <?php for ($b = 0; $b < 3; $b++): ?> <div class="form-group"> <?php echo Html::label('Form '.$no, 'form'.$no, ['class' => 'control-label col-sm-3']) ?> <div class="col-sm-9"> <?php echo Html::input('text', 'form'.$no, '', ['class' => 'form-control']) ?> </div> </div> <?php $no++ ?> <?php endfor ?> </div> <?php endfor ?> </div> </div> </div> <div class="col-md-3 text-right"> <?php $value = mt_rand(1, 10) ?> <div class="price">Rp <span class="value"><?php echo $value ?>,000,000</span></div> <small>* Lorem ipsum dolor sit amet, consectetur adipiscing elit.</small> </div> </div> </div> </div><file_sep><?php /* @var $this yii\web\View */ use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\widgets\ActiveForm; use yii\widgets\LinkPager; $this->title = 'Paket wisata'; ?> <div class="container"> <div class="page-heading"> <h2>Search item heading</h2> </div> <div class="row"> <div class="col-md-3"> <div class="flat-panel sidenav"> <div class="flat-title"> <h4><a class="close visible-xs visible-sm"><i class="fa fa-close"></i></a>Search form</h4> </div> <?php $form = ActiveForm::begin([ 'id' => 'frmFilterPwWisata', 'options' => ['role' => 'form'], 'fieldConfig' => ['options' => ['class' => 'form-group has-feedback']], ]) ?> <?= $form ->field( $model, 'id_kategori', ['template' => "{label}\n{input}\n".'<span class="fa fa-tags form-control-feedback" aria-hidden="true"></span>'."\n{hint}\n{error}"] ) ->dropDownList( ArrayHelper::map($kategori, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control'] ) ?> <?= $form ->field( $model, 'id_kota', ['template' => "{label}\n{input}\n".'<span class="fa fa-map-marker form-control-feedback" aria-hidden="true"></span>'."\n{hint}\n{error}"] ) ->dropDownList( ArrayHelper::map($kota, 'id', 'nama'), ['id' => 'idKota', 'class' => 'form-control'] ) ?> <?= Html::submitButton('CARI', ['class' => 'btn btn-block btn-primary']) ?> <?php ActiveForm::end(); ?> </div> <div class="hidden-xs hidden-sm"> <h3>Ads</h3> <div class="separator left"></div> <?php for ($a = 0; $a < 4; $a++): ?> <div style="margin:15px 0"> <?php echo Html::img('@web/images/sample'.($a+1).'.jpg', ['class' => 'img-responsive']) ?> </div> <?php endfor; ?> </div> </div> <div class="col-md-9"> <div class="flat-panel"> <div class="flat-title"> <h4>Search result</h4> </div> <div class="row"> <div class="col-md-4 col-md-offset-8"> <!-- <div class="form-horizontal"> --> <div class="form-group"> <?php // echo Html::label('Sort by', 'sort', ['class' => 'control-label col-sm-4']) ?> <!-- <div class="col-sm-8"> --> <?php echo Html::dropDownList('sort', null, ['Paket termurah', 'Paket termahal'], ['class' => 'form-control']) ?> <!-- </div> --> </div> <!-- </div> --> </div> </div> <?php foreach ($DataPaket as $dtpaket): ?> <div class="search-item media"> <div class="media-left"> <?php echo Html::img('@web/images/default-96.png', ['class' => 'media-object']) ?> </div> <div class="media-body"> <div class="row"> <div class="col-lg-9 col-sm-8"> <h4 class="media-heading"> <?php echo Html::a($dtpaket->nama, Url::to(['detail-paket-wisata', 'id' => $dtpaket->id])) ?> <small><?php echo Html::a('<i class="fa fa-fw fa-heart"></i>', Url::to(['my-wishlist', 'id' => $dtpaket->id])) ?></small> </h4> <div class="rating"> <?php $rate = mt_rand(1, 5) ?> <?php for ($b = 0; $b < 5; $b++): ?> <i class="fa fa-star <?php echo $b < $rate ? 'text-warning' : '' ?>"></i> <?php endfor ?> </div> <p><?php echo Html::a($dtpaket->company->nama, Url::to(['detail-agen', 'id' => $dtpaket->id])) ?></p> <!-- <p><?php echo $dtpaket->deskripsi ?></p> --> </div> <div class="col-lg-3 col-sm-4"> <div class="row deal"> <div class="col-sm-12 col-xs-7"> <div class="price">Rp <span class="value"><?php echo number_format($dtpaket->harga) ?></span></div> </div> <div class="col-sm-12 col-xs-5"> <?php echo Html::a('DETAIL &nbsp;<i class="fa fa-angle-double-right"></i>', Url::to(['detail-paket-wisata', 'id' => $dtpaket->id]), ['class' => 'btn btn-block btn-warning']) ?> </div> </div> </div> </div> </div> </div> <?php endforeach ?> </div> <div class="text-center"> <?php echo LinkPager::widget([ 'pagination' => $pages, 'options' => ['class' => 'pagination', 'firstPageLabel' => false] ]) ?> </div> </div> </div> <div id="view-filter" class="floating-container bottom left visible-sm visible-xs"> <a class="btn btn-circle btn-warning"><i class="fa fa-lg fa-fw fa-search"></i></a> </div> <div id="go-top" class="floating-container bottom right"> <a class="btn btn-circle btn-primary"><i class="fa fa-lg fa-fw fa-long-arrow-up"></i></a> </div> </div> <?php /* ?> <!-- banner start --> <!-- ================ --> <div class="banner dark-translucent-bg" style="background-image:url('../images/shop-banner.jpg'); background-position:50% 32%;"> <!-- breadcrumb start --> <!-- ================ --> <div class="breadcrumb-container"> <div class="container"> <ol class="breadcrumb"> <li><i class="fa fa-home pr-10"></i><a class="link-dark" href="/">Home</a></li> <li class="active"><?php echo $this->title;?></li> </ol> </div> </div> <!-- breadcrumb end --> <div class="container"> <div class="row"> <div class="col-md-8 text-center col-md-offset-2 pv-20"> <h2 class="title object-non-visible" data-animation-effect="fadeIn" data-effect-delay="100"><?php echo $this->title;?></h2> <div class="separator object-non-visible mt-10" data-animation-effect="fadeIn" data-effect-delay="100"></div> </div> </div> </div> </div> <!-- banner end --> <!-- section start --> <!-- ================ --> <div class="light-gray-bg section"> <div class="container"> <!-- filters start --> <div class="sorting-filters text-center mb-20"> <?php $form = ActiveForm::begin(['id' => 'frmFilterPwWisata','options' => ['class'=>'form-inline']]); ?> <?= $form->field($model, 'id_kategori')->dropDownList(ArrayHelper::map($kategori, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control']) ?> <?= $form->field($model, 'id_kota')->dropDownList(ArrayHelper::map($kota, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control']) ?> <div class="form-group"> <label class="control-label">&nbsp;</label> <?= Html::submitButton('Cari', ['class' => 'btn btn-default margin-clear']) ?> <div class="mt-5 mb-10"></div> </div> <?php ActiveForm::end(); ?> </div> <!-- filters end --> </div> </div> <!-- section end --> <!-- main-container start --> <!-- ================ --> <section class="main-container"> <div class="container"> <div class="row"> <!-- main start --> <!-- ================ --> <div class="main col-md-12"> <!-- pills start --> <!-- ================ --> <!-- Tab panes --> <?php foreach($DataPaket as $dtpaket):?> <div class="listing-item mb-20"> <div class="row grid-space-0"> <div class="col-sm-6 col-md-4 col-lg-3"> <div class="overlay-container"> <img src="../images/danau.jpg" alt=""> <a class="overlay-link" href="shop-product.html"><i class="fa fa-plus"></i></a> </div> </div> <div class="col-sm-6 col-md-8 col-lg-9"> <div class="body"> <h3 class="margin-clear"><a href="<?php echo Url::to(['detail-paket-wisata', 'id' => $dtpaket->id])?>"><?php echo $dtpaket->nama;?></a></h3> <p> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star text-default"></i> <i class="fa fa-star"></i> <a href="<?php echo Url::to(['my-wishlist', 'id' => $dtpaket->id])?>" class="btn-sm-link"><i class="icon-heart pr-5"></i>Add to Wishlist</a> <a href="<?php echo Url::to(['detail-agen', 'id' => $dtpaket->id])?>" class="btn-sm-link"><i class="icon-link pr-5"></i><?php echo $dtpaket->company->nama?></a> </p> <p><?php echo $dtpaket->deskripsi;?></p> <div class="elements-list clearfix"> <span class="price">IDR <?php echo number_format($dtpaket->harga);?></span> <a href="<?php echo Url::to(['detail-paket-wisata', 'id' => $dtpaket->id])?>" class="pull-right btn btn-sm btn-default-transparent">More Detail</a> </div> </div> </div> </div> </div> <?php endforeach;?> <!-- pills end --> <!-- pagination start --> <nav class="text-center"> <?php echo LinkPager::widget([ 'pagination' => $pages, 'options' => ['class'=>'pagination','firstPageLabel'=>false], ]); ?> </nav> <!-- pagination end --> </div> <!-- main end --> </div> </div> </section> <!-- main-container end --> <?php */ ?> <file_sep><?php namespace frontend\controllers; use Yii; use yii\base\InvalidParamException; use yii\web\BadRequestHttpException; use yii\web\Controller; use yii\filters\VerbFilter; use yii\filters\AccessControl; use yii\filters\Cors; use yii\data\Pagination; use yii\helpers\Url; //---model use common\models\LoginForm; use frontend\models\PasswordResetRequestForm; use frontend\models\ResetPasswordForm; use frontend\models\SignupForm; use frontend\models\ContactForm; use frontend\models\WisataForm; use frontend\models\UmrohForm; use frontend\models\TravelForm; use frontend\models\SimpanWisataForm; //---active record use common\models\PwKategori; use common\models\PwPaket; use common\models\Kota; use common\models\TrPaketwisata; use common\models\TrTravel; use common\models\TrJadwal; /** * Site controller */ class SiteController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['logout', 'signup'], 'rules' => [ [ 'actions' => ['signup'], 'allow' => true, 'roles' => ['?'], ], [ 'actions' => ['logout'], 'allow' => true, 'roles' => ['@'], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'logout' => ['post'], ], ], 'corsFilter' => [ 'class' => Cors::className(), 'cors' => [ // restrict access to 'Origin' => ['*'], ], ], ]; } /** * @inheritdoc */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], ]; } /** * Displays homepage. * * @return mixed */ public function actionIndex() { $model = new WisataForm(); $kategori = PwKategori::find()->all(); $pwWisataNew = PwPaket::find()->with('company')->where(['=', 'pw_paket.status_wisata', 1])->limit(4)->all(); $kota = Kota::find()->all(); if ($model->load(Yii::$app->request->post())) { return $this->redirect(Url::to(['list-paket-wisata', 'kategori' => $model->id_kategori])); } else{ return $this->render('index' ,[ 'newest_wisata' => $pwWisataNew,'kategori' => $kategori,'kota' => $kota,'model'=>$model ]); } } /** * Logs in a user. * * @return mixed */ public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } else { return $this->render('login', [ 'model' => $model, ]); } } /** * Logs out the current user. * * @return mixed */ public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } /** * Displays contact page. * * @return mixed */ public function actionContact() { $model = new ContactForm(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->sendEmail(Yii::$app->params['adminEmail'])) { Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.'); } else { Yii::$app->session->setFlash('error', 'There was an error sending email.'); } return $this->refresh(); } else { return $this->render('contact', [ 'model' => $model, ]); } } /** * Displays about page. * * @return mixed */ public function actionAbout() { return $this->render('about'); } /** * Signs user up. * * @return mixed */ public function actionSignup() { $model = new SignupForm(); if ($model->load(Yii::$app->request->post())) { if ($user = $model->signup()) { if (Yii::$app->getUser()->login($user)) { return $this->goHome(); } } } return $this->render('signup', [ 'model' => $model, ]); } /** * Requests password reset. * * @return mixed */ public function actionRequestPasswordReset() { $model = new PasswordResetRequestForm(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->sendEmail()) { Yii::$app->session->setFlash('success', 'Check your email for further instructions.'); return $this->goHome(); } else { Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.'); } } return $this->render('requestPasswordResetToken', [ 'model' => $model, ]); } /** * Resets password. * * @param string $token * @return mixed * @throws BadRequestHttpException */ public function actionResetPassword($token) { try { $model = new ResetPasswordForm($token); } catch (InvalidParamException $e) { throw new BadRequestHttpException($e->getMessage()); } if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) { Yii::$app->session->setFlash('success', 'New password was saved.'); return $this->goHome(); } return $this->render('resetPassword', [ 'model' => $model, ]); } /** * Displays daftar paket wisata. * * @return mixed */ public function actionListPaketWisata($kategori) { $model = new WisataForm(); $dtkategori = PwKategori::find()->all(); $kota = Kota::find()->all(); $PwPaket = new PwPaket(); $query = $PwPaket->GetListPaket($kategori); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->params = (['kategori'=>$kategori,'page'=>$pages->offset,'per-page'=>$pages->limit]); $pages->route = 'site/list-paket-wisata/'; $pages->setPageSize(10); $DataPaket = $query->offset($pages->offset) ->limit($pages->limit) ->all(); return $this->render('list-paket',['pages' => $pages,'model'=>$model,'DataPaket'=>$DataPaket,'kategori' => $dtkategori,'kota' => $kota]); } /** * Displays detail paket wisata. * * @return mixed */ public function actionDetailPaketWisata($id) { $PwPaket = new PwPaket(); $DataPaket = $PwPaket->GetPaketById($id); return $this->render('detail-paket',['DataPaket'=>$DataPaket]); } /** * Displays detail paket wisata. * * @return mixed */ public function actionPesanPaketWisata($id) { $model = new SimpanWisataForm(); $PwPaket = new PwPaket(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { $TrPaketwisata = new TrPaketwisata(); $TrPaketwisata->kode = "PW-".time(); $TrPaketwisata->nama_pemesan = $model->nama_pemesan; $TrPaketwisata->telp1 = $model->telp1; $TrPaketwisata->telp2 = $model->telp2; $TrPaketwisata->alamat_jemput = $model->alamat_jemput; $TrPaketwisata->detail_jemput = $model->detail_jemput; $TrPaketwisata->harga = $model->harga; $TrPaketwisata->metode_bayar = $model->metode_bayar; $TrPaketwisata->paket_id = $model->paket_id; $TrPaketwisata->keterangan = $model->keterangan; $TrPaketwisata->created_at = time(); $TrPaketwisata->save(); Yii::$app->getSession()->setFlash('no_order', $TrPaketwisata->kode); $this->redirect(array("/site/pemesanan-paket-sukses?by=".$TrPaketwisata->metode_bayar)); } else{ $DataPaket = $PwPaket->GetPaketById($id); return $this->render('pesan-paket-1',['DataPaket'=>$DataPaket,'model'=>$model]); } } /** * Displays pemesanan paket wista sukses. * * @return mixed */ public function actionPemesananPaketSukses($by) { return $this->render('pemesanan-paket-sukses',['by'=>$by]); } /** * Displays umroh. * * @return mixed */ public function actionUmroh() { $model = new UmrohForm(); $kota = Kota::find()->all(); $pwUmrohNew = PwPaket::find()->with('company')->where(['=', 'pw_paket.status_wisata', 2])->limit(4)->all(); if ($model->load(Yii::$app->request->post())) { return $this->redirect(Url::to(['list-paket-umroh', 'kota' => $model->id_kota])); } else{ return $this->render('umroh' ,[ 'newest_umroh' => $pwUmrohNew,'kota' => $kota,'model'=>$model ]); } } /** * Displays daftar layanan umroh. * * @return mixed */ public function actionListPaketUmroh($kota) { $model = new UmrohForm(); $dtkategori = PwKategori::find()->all(); $listkota = Kota::find()->all(); $PwPaket = new PwPaket(); $query = $PwPaket->GetListUmroh($kota); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->params = (['kota'=>$listkota,'page'=>$pages->offset,'per-page'=>$pages->limit]); $pages->route = 'site/list-paket-umroh/'; $pages->setPageSize(2); $DataPaket = $query->offset($pages->offset) ->limit($pages->limit) ->all(); return $this->render('list-umroh',['pages' => $pages,'model'=>$model,'DataPaket'=>$DataPaket,'kota' => $listkota]); } /** * Displays detail paket umroh. * * @return mixed */ public function actionDetailPaketUmroh($id) { $PwPaket = new PwPaket(); $DataPaket = $PwPaket->GetPaketById($id); return $this->render('detail-umroh',['DataPaket'=>$DataPaket]); } /* * Displays detail paket umroh. * * @return mixed */ public function actionPesanPaketUmroh($id) { $model = new SimpanWisataForm(); $PwPaket = new PwPaket(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { $TrPaketwisata = new TrPaketwisata(); $TrPaketwisata->kode = "PU-".time(); $TrPaketwisata->nama_pemesan = $model->nama_pemesan; $TrPaketwisata->telp1 = $model->telp1; $TrPaketwisata->telp2 = $model->telp2; $TrPaketwisata->alamat_jemput = $model->alamat_jemput; $TrPaketwisata->detail_jemput = $model->detail_jemput; $TrPaketwisata->harga = $model->harga; $TrPaketwisata->metode_bayar = $model->metode_bayar; $TrPaketwisata->paket_id = $model->paket_id; $TrPaketwisata->keterangan = $model->keterangan; $TrPaketwisata->created_at = time(); $TrPaketwisata->save(); Yii::$app->getSession()->setFlash('no_order', $TrPaketwisata->kode); $this->redirect(array("/site/pemesanan-umroh-sukses?by=".$TrPaketwisata->metode_bayar)); } else{ $DataPaket = $PwPaket->GetPaketById($id); return $this->render('pesan-umroh-1',['DataPaket'=>$DataPaket,'model'=>$model]); } } /** * Displays pemesanan paket umroh sukses. * * @return mixed */ public function actionPemesananUmrohSukses($by) { return $this->render('pemesanan-umroh-sukses',['by'=>$by]); } /** * Displays umroh. * * @return mixed */ public function actionTravel() { $model = new TravelForm(); $kota = Kota::find()->all(); // $pwUmrohNew = PwPaket::find()->with('company')->where(['=', 'pw_paket.status_wisata', 2])->limit(4)->all(); if ($model->load(Yii::$app->request->post())) { return $this->redirect(Url::to(['list-travel', 'id_kota_berangkat' => $model->id_kota_berangkat, 'id_kota_tujuan' => $model->id_kota_tujuan,'tgl_berangkat' => $model->tgl_berangkat, 'jam_berangkat' => $model->jam_berangkat])); } else{ return $this->render('travel' ,[ 'kota' => $kota,'model'=>$model ]); } } /** * Displays daftar travel. * * @return mixed */ public function actionListTravel($id_kota_berangkat,$id_kota_tujuan,$tgl_berangkat,$jam_berangkat) { $model = new TravelForm(); $listkota = Kota::find()->all(); $TrJadwal = new TrJadwal(); $query = $TrJadwal->GetListTravel($id_kota_berangkat,$id_kota_tujuan,$tgl_berangkat,$jam_berangkat); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->params = (['kota'=>$listkota,'page'=>$pages->offset,'per-page'=>$pages->limit]); $pages->route = 'site/list-travel/'; $pages->setPageSize(10); $DataPaket = $query->offset($pages->offset) ->limit($pages->limit) ->all(); return $this->render('list-travel',['pages' => $pages,'model'=>$model,'DataPaket'=>$DataPaket,'kota' => $listkota]); } /** * Displays pesan travel. * * @return mixed */ public function actionPesanTravel() { return $this->render('pesan_travel' ,[]); } } <file_sep><?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; use yii\helpers\Url; $this->title = 'Pesan Travel'; $this->params['breadcrumbs'][] = $this->title; ?> <!-- breadcrumb start --> <!-- ================ --> <div class="breadcrumb-container"> <div class="container"> <ol class="breadcrumb"> <li><i class="fa fa-home pr-10"></i><a class="link-dark" href="/">Home</a></li> <li class="active"><?php echo $this->title;?></li> </ol> </div> </div> <!-- breadcrumb end --> <!-- main-container start --> <!-- ================ --> <section class="main-container"> <div class="container"> <div class="row"> <!-- main start --> <!-- ================ --> <div class="main col-md-12"> <!-- page-title start --> <!-- ================ --> <h1 class="page-title">Form Pemesanan Travel</h1> <div class="separator-2"></div> <!-- page-title end --> <div class="space-bottom"></div> <fieldset> <legend>Billing information</legend> <?php $form = ActiveForm::begin(['id' => 'billing-information','options' => ['class'=>'form-horizontal']]); ?> <div class="row"> <div class="col-lg-3"> <h3 class="title">Personal Info</h3> </div> <div class="col-lg-8 col-lg-offset-1"> </div> </div> </fieldset> <div class="text-right"> <?= Html::submitButton('Pesan', ['class' => 'btn btn-group btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div> <!-- main end --> </div> </div> </section> <!-- main-container end --> <?php $this->registerJsFile('@web/js/paket_wisata.js', ['depends' => [\frontend\assets\AppAsset::className()]]); ?> <file_sep><?php namespace common\assets; use yii\web\AssetBundle; /** * Asset bundle for common js files. * */ class CommonJsAsset extends AssetBundle { public $sourcePath = '@common/shared-assets'; public $js = [ 'js/nprogress.js', ]; public $publishOptions = [ 'forceCopy' => YII_DEBUG, ]; } <file_sep><?php namespace common\models; use Yii; /** * This is the model class for table "tr_travel". * * @property integer $id * @property integer $kota_asal * @property integer $kota_tujuan * @property string $jam * @property integer $company_id * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property Company $company * @property Kota $kotaAsal * @property Kota $kotaTujuan */ class TrTravel extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'tr_travel'; } /** * @inheritdoc */ public function rules() { return [ [['kota_asal', 'kota_tujuan', 'company_id', 'status', 'created_at', 'updated_at'], 'integer'], [['created_at', 'updated_at'], 'required'], [['company_id'], 'exist', 'skipOnError' => true, 'targetClass' => Company::className(), 'targetAttribute' => ['company_id' => 'id']], [['kota_asal'], 'exist', 'skipOnError' => true, 'targetClass' => Kota::className(), 'targetAttribute' => ['kota_asal' => 'id']], [['kota_tujuan'], 'exist', 'skipOnError' => true, 'targetClass' => Kota::className(), 'targetAttribute' => ['kota_tujuan' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'kota_asal' => Yii::t('app', 'Kota Asal'), 'kota_tujuan' => Yii::t('app', 'Kota Tujuan'), 'company_id' => Yii::t('app', 'Company ID'), 'status' => Yii::t('app', 'Status'), 'created_at' => Yii::t('app', 'Created At'), 'updated_at' => Yii::t('app', 'Updated At'), ]; } /** * @return \yii\db\ActiveQuery */ public function getCompany() { return $this->hasOne(Company::className(), ['id' => 'company_id']); } /** * @return \yii\db\ActiveQuery */ public function getKotaAsal() { return $this->hasOne(Kota::className(), ['id' => 'kota_asal']); } /** * @return \yii\db\ActiveQuery */ public function getKotaTujuan() { return $this->hasOne(Kota::className(), ['id' => 'kota_tujuan']); } /** * @return \yii\db\ActiveQuery */ public function getTrJadwals() { return $this->hasMany(TrJadwal::className(), ['tr_travel_id' => 'id']); } public static function GetListTravel($id_kota_berangkat,$id_kota_tujuan,$tgl_berangkat,$jam_berangkat) { $data = TrTravel::find() ->joinWith('company') ->joinWith('kotaAsal AS kotaasal') ->joinWith('kotaTujuan AS kotatujuan'); // ->where(['=', 'company.id_kota', $id_kota]); return $data; } } <file_sep>(function($){ $(document).ready(function(){ var geocoder = new google.maps.Geocoder(); function initialize_from() { // penjemputan var origin_input = document.getElementById('automap'); var origin_autocomplete = new google.maps.places.Autocomplete((origin_input),{/*types:['geocode']*/}); origin_autocomplete.addListener('place_changed', function() { var place = origin_autocomplete.getPlace(); var id = 'origin'; set_address(place, id); if (!place.geometry) { window.alert("Autocomplete's returned place contains no geometry"); return; } }); } function set_address(results, id){ var kode_pos = ""; var kelurahan = ""; var kecamatan = ""; if (id == "origin"){ var components = results.address_components; for (var i = 0; i < components.length; i++) { //kode_pos if (components[i].types[0] == "postal_code"){ kode_pos = components[i].long_name; } //kelurahan if (components[i].types[0] == "administrative_area_level_4"){ kelurahan = components[i].long_name; } //kecamatan if (components[i].types[0] == "administrative_area_level_3"){ kecamatan = components[i].long_name; } } } else if (id == "destination") { var components = results.address_components; for (var i = 0; i < components.length; i++) { //kode_pos if (components[i].types[0] == "postal_code"){ kode_pos = components[i].long_name; } //kelurahan if (components[i].types[0] == "administrative_area_level_4"){ kelurahan = components[i].long_name; } //kecamatan if (components[i].types[0] == "administrative_area_level_3"){ kecamatan = components[i].long_name; } } } cek_overarea(id,kode_pos,kelurahan,kecamatan); } function cek_overarea(id,kode_pos,kelurahan,kecamatan){ console.log(id+"-"+kode_pos+"-"+kelurahan+"-"+kecamatan); } google.maps.event.addDomListener(window, 'load', initialize_from); }); })(this.jQuery);<file_sep><?php namespace frontend\models; use Yii; use yii\base\Model; /** * TravelForm is the model behind the paket wisata form. */ class TravelForm extends Model { public $id_kota_berangkat; public $id_kota_tujuan; public $tgl_berangkat; public $jam_berangkat; /** * @inheritdoc */ public function rules() { return [ [['id_kota_berangkat','id_kota_tujuan','tgl_berangkat','jam_berangkat'], 'required'], [['tgl_berangkat','jam_berangkat'], 'string'], [['id_kota_berangkat','id_kota_tujuan'], 'integer'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id_kota_berangkat' => 'Pilih Kota Tempat Anda Berangkat', 'id_kota_tujuan' => 'Pilih Kota Tempat Tujuan Anda', 'tgl_berangkat' => 'Tanggal Anda Berangkat', 'jam_berangkat' => 'Jam Anda Berangkat', ]; } } <file_sep><?php namespace common\models; use Yii; /** * This is the model class for table "company". * * @property integer $id * @property string $nama * @property string $alamat * @property integer $id_kota * @property string $telp * @property string $pimpinan * @property string $username * @property string $auth_key * @property string $password_hash * @property string $password_reset_token * @property string $email * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property Kota $idKota * @property Overarea[] $overareas * @property PwPaket[] $pwPakets * @property TrTravel[] $trTravels */ class Company extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'company'; } /** * @inheritdoc */ public function rules() { return [ [['id_kota', 'status', 'created_at', 'updated_at'], 'integer'], [['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'], [['nama', 'alamat', 'username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255], [['telp', 'pimpinan'], 'string', 'max' => 20], [['auth_key'], 'string', 'max' => 32], [['username'], 'unique'], [['email'], 'unique'], [['password_reset_token'], 'unique'], [['id_kota'], 'exist', 'skipOnError' => true, 'targetClass' => Kota::className(), 'targetAttribute' => ['id_kota' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'nama' => Yii::t('app', 'Nama'), 'alamat' => Yii::t('app', 'Alamat'), 'id_kota' => Yii::t('app', 'Id Kota'), 'telp' => Yii::t('app', 'Telp'), 'pimpinan' => Yii::t('app', 'Pimpinan'), 'username' => Yii::t('app', 'Username'), 'auth_key' => Yii::t('app', 'Auth Key'), 'password_hash' => Yii::t('app', 'Password Hash'), 'password_reset_token' => Yii::t('app', 'Password Reset Token'), 'email' => Yii::t('app', 'Email'), 'status' => Yii::t('app', 'Status'), 'created_at' => Yii::t('app', 'Created At'), 'updated_at' => Yii::t('app', 'Updated At'), ]; } /** * @return \yii\db\ActiveQuery */ public function getIdKota() { return $this->hasOne(Kota::className(), ['id' => 'id_kota']); } /** * @return \yii\db\ActiveQuery */ public function getOverareas() { return $this->hasMany(Overarea::className(), ['company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getPwPakets() { return $this->hasMany(PwPaket::className(), ['company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTrTravels() { return $this->hasMany(TrTravel::className(), ['company_id' => 'id']); } } <file_sep><?php namespace frontend\controllers; use Yii; use Faker; use yii\web\Controller; /** * Seeder controller */ class SeederController extends Controller { /** * Banyak data yang ingin di-generate. * Note: batchInsert() dapat men-generate maksimal ~9000 data sekaligus. * * @var integer */ private $countMobil = 10; private $countKota = 30; private $countCompany = 50; private $countOverarea = 200; private $countPwKategori = 6; private $countPwPaket = 100; private $countTrTravel = 300; /** * Generate all seeders. * * @return void */ public function actionGenerate() { $start = microtime(true); $this->seederMobil(); $this->seederKota(); $this->seederCompany(); $this->seederOverarea(); $this->seederPwKategori(); $this->seederPwPaket(); $this->seederTrTravel(); $elapsed = microtime(true) - $start; echo 'Done. Elapsed time = '.$elapsed; } /** * Seeder tabel Mobil. * * @return void */ private function seederMobil() { $faker = Faker\Factory::create($this->locale); $data = []; for ($a = 0; $a < $this->countMobil; $a++) { $data[$a] = [ 'Mobil '.$faker->word, $faker->word, time(), time(), ]; } Yii::$app->db->createCommand()->batchInsert('mobil', [ 'nama', 'gambar', 'created_at', 'updated_at', ], $data)->execute(); } /** * Seeder tabel Kota. * * @return void */ private function seederKota() { $faker = Faker\Factory::create($this->locale); $data = []; for ($a = 0; $a < $this->countKota; $a++) { $data[$a] = [ $faker->city, time(), time(), ]; } Yii::$app->db->createCommand()->batchInsert('kota', [ 'nama', 'created_at', 'updated_at', ], $data)->execute(); } /** * Seeder tabel Company. * * @return void */ private function seederCompany() { $faker = Faker\Factory::create($this->locale); $data = []; for ($a = 0; $a < $this->countCompany; $a++) { $data[$a] = [ $faker->company, $faker->address, mt_rand(1, $this->countKota), $faker->phoneNumber, $faker->name, $faker->userName, $faker->uuid, $faker->md5, $faker->md5, $faker->email, time(), time(), ]; } Yii::$app->db->createCommand()->batchInsert('company', [ 'nama', 'alamat', 'id_kota', 'telp', 'pimpinan', 'username', 'auth_key', '<PASSWORD>_<PASSWORD>', 'password_reset_token', 'email', 'created_at', 'updated_at', ], $data)->execute(); } /** * Seeder tabel Overarea. * * @return void */ private function seederOverarea() { $faker = Faker\Factory::create($this->locale); $data = []; for ($a = 0; $a < $this->countOverarea; $a++) { $data[$a] = [ $faker->state, mt_rand(1, $this->countKota), mt_rand(1, $this->countCompany), time(), time(), ]; } Yii::$app->db->createCommand()->batchInsert('overarea', [ 'kelurahan', 'kota_id', 'company_id', 'created_at', 'updated_at', ], $data)->execute(); } /** * Seeder tabel PwKategori. * * @return void */ private function seederPwKategori() { $faker = Faker\Factory::create($this->locale); $data = []; for ($a = 0; $a < $this->countPwKategori; $a++) { $data[$a] = [ $faker->word, time(), time(), ]; } Yii::$app->db->createCommand()->batchInsert('pw_kategori', [ 'nama', 'created_at', 'updated_at', ], $data)->execute(); } /** * Seeder tabel PwPaket. * * @return void */ private function seederPwPaket() { $faker = Faker\Factory::create($this->locale); $data = []; for ($a = 0; $a < $this->countPwPaket; $a++) { $data[$a] = [ 'Paket '.$faker->words(2, true), $faker->text(), mt_rand(1, 10) * 1000, mt_rand(1, $this->countPwKategori), mt_rand(1, $this->countCompany), time(), time(), ]; } Yii::$app->db->createCommand()->batchInsert('pw_paket', [ 'nama', 'deskripsi', 'harga', 'kategori_id', 'company_id', 'created_at', 'updated_at', ], $data)->execute(); } /** * Seeder tabel TrTravel. * * @return void */ private function seederTrTravel() { $faker = Faker\Factory::create($this->locale); $data = []; for ($a = 0; $a < $this->countTrTravel; $a++) { $data[$a] = [ mt_rand(1, $this->countKota), mt_rand(1, $this->countKota), mt_rand(1, $this->countCompany), mt_rand(1, 10) * 1000, time(), time(), ]; } Yii::$app->db->createCommand()->batchInsert('tr_travel', [ 'kota_asal', 'kota_tujuan', 'company_id', 'harga', 'created_at', 'updated_at', ], $data)->execute(); } /** * Localization (Indonesia). * * @var string */ private $locale = 'id_ID'; } <file_sep><?php namespace frontend\models; use Yii; use yii\base\Model; /** * UmrohForm is the model behind the paket wisata form. */ class UmrohForm extends Model { public $id_kota; /** * @inheritdoc */ public function rules() { return [ [['id_kota'], 'required'], [['id_kota'], 'integer'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id_kota' => 'Pilih Kota Tempat Anda Berangkat', ]; } } <file_sep><?php use yii\db\Migration; class m161217_135248_create_tbl_paket_wisata extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('{{%pw_paket}}', [ 'id' => $this->primaryKey(), 'nama' => $this->string(255), 'deskripsi' => $this->string(), 'harga' => $this->integer(), 'kategori_id' => $this->integer(), 'company_id' => $this->integer(), 'status' => $this->smallInteger()->notNull()->defaultValue(10), 'created_at' => $this->integer()->notNull(), 'updated_at' => $this->integer()->notNull(), ], $tableOptions); $this->addForeignKey ('fk_kategori_paket', 'pw_paket', 'kategori_id', 'pw_kategori', 'id', 'NO ACTION', 'NO ACTION'); $this->addForeignKey ('fk_company_paket', 'pw_paket', 'company_id', 'company', 'id', 'NO ACTION', 'NO ACTION'); } public function down() { $this->dropTable('{{%pw_paket}}'); } } <file_sep><?php use yii\db\Migration; class m170108_054555_add_status_umroh_tbl_pw_wisata extends Migration { public function up() { $this->addColumn('pw_paket','status_wisata',$this->integer()->defaultValue(1)->after('company_id')); } public function down() { $this->dropColumn('pw_paket','status_wisata'); return false; } } <file_sep><?php namespace common\models; use Yii; /** * This is the model class for table "pw_kategori". * * @property integer $id * @property string $nama * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property PwPaket[] $pwPakets */ class PwKategori extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'pw_kategori'; } /** * @inheritdoc */ public function rules() { return [ [['status', 'created_at', 'updated_at'], 'integer'], [['created_at', 'updated_at'], 'required'], [['nama'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'nama' => Yii::t('app', 'Nama'), 'status' => Yii::t('app', 'Status'), 'created_at' => Yii::t('app', 'Created At'), 'updated_at' => Yii::t('app', 'Updated At'), ]; } /** * @return \yii\db\ActiveQuery */ public function getPwPakets() { return $this->hasMany(PwPaket::className(), ['kategori_id' => 'id']); } } <file_sep> <?php use yii\helpers\Html; use yii\helpers\Url; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; ?> <!-- banner start --> <!-- ================ --> <div class="banner banner-big-height dark-translucent-bg padding-bottom-clear" style="background-image:url('images/hotel-banner.jpg');background-position: 50% 32%;"> <div class="container"> <div class="row"> <div class="col-md-8 text-center col-md-offset-2 pv-20"> <h1 class="title">Umroh</h1> <div class="separator mt-10"></div> <p class="text-center">Cari dan temukan layanan umroh di kota anda.</p> </div> </div> </div> <!-- section start --> <!-- ================ --> <div class="dark-translucent-bg section"> <div class="container"> <!-- filters start --> <div class="sorting-filters text-center mb-20"> <?php $form = ActiveForm::begin(['id' => 'frmPwWisata','options' => ['class'=>'form-inline','role'=>'form']]); ?> <?= $form->field($model, 'id_kota')->dropDownList(ArrayHelper::map($kota, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control']) ?> <div class="form-group"> <label class="control-label">&nbsp;</label> <?= Html::submitButton('Cari', ['class' => 'btn btn-gray-transparent btn-animated margin-clear']) ?> <div class="mt-5 mb-10"></div> </div> <?php ActiveForm::end(); ?> </div> <!-- filters end --> </div> </div> <!-- section end --> </div> <!-- banner end --> <!-- section start --> <!-- ================ --> <section class="light-gray-bg pv-40 border-clear"> <div class="container"> <div class="col-md-8 col-md-offset-2"> <h2 class="text-center title">Paket Umroh Favorit</h2> <div class="separator"></div> </div> </div> <div class="container-fluid"> <div class="row"> <?php foreach($newest_umroh as $key => $umroh_terbaru):?> <div class="col-sm-3"> <div class="image-box style-2 mb-20"> <div class="overlay-container overlay-visible"> <img src="images/hotel-service-1.jpg" alt=""> <a href="<?php echo Url::to(['detail-paket-wisata', 'id' => $umroh_terbaru->id])?>" class="overlay-link"><i class="fa fa-link"></i></a> <div class="overlay-bottom"> <div class="text"> <p class="lead margin-clear text-left mobile-visible"><?php echo $umroh_terbaru->nama?></p> <p class="margin-clear text-left mobile-visible"><?php echo $umroh_terbaru->company->nama?></p> </div> </div> </div> <div class="body padding-horizontal-clear"> <a class="link-dark" href="<?php echo Url::to(['detail-paket-umroh', 'id' => $umroh_terbaru->id])?>">Read More</a> </div> </div> </div> <?php endforeach;?> </div> </div> </section> <!-- section end --> <!-- section start --> <!-- ================ --> <section class="dark-translucent-bg background-img-9 pv-40" style="background-position: 50% 50%;"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="testimonial text-center"> <div class="testimonial-image"> <img src="images/testimonial-1.jpg" alt="<NAME>" title="<NAME>" class="img-circle"> </div> <h3>Just Perfect!</h3> <div class="separator"></div> <div class="testimonial-body"> <blockquote> <p>Sed ut perspiciatis unde omnis iste natu error sit voluptatem accusan tium dolore laud antium.</p> </blockquote> <div class="testimonial-info-1">- <NAME></div> <div class="testimonial-info-2">By Company</div> </div> </div> </div> <div class="col-md-4"> <div class="testimonial text-center"> <div class="testimonial-image"> <img src="../images/testimonial-2.jpg" alt="<NAME>" title="<NAME>" class="img-circle"> </div> <h3>Amazing!</h3> <div class="separator"></div> <div class="testimonial-body"> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et cupiditate deleniti ratione.</p> </blockquote> <div class="testimonial-info-1">- <NAME></div> <div class="testimonial-info-2">By Company</div> </div> </div> </div> <div class="col-md-4"> <div class="testimonial text-center"> <div class="testimonial-image"> <img src="images/testimonial-3.jpg" alt="<NAME>" title="<NAME>" class="img-circle"> </div> <h3>Amazing!</h3> <div class="separator"></div> <div class="testimonial-body"> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et cupiditate deleniti ratione.</p> </blockquote> <div class="testimonial-info-1">- <NAME></div> <div class="testimonial-info-2">By Company</div> </div> </div> </div> </div> </div> </section> <!-- section end --> <file_sep>(function($){ $(document).ready(function(){ $('.clockpicker').clockpicker(); $('.datepicker').datepicker({ language: "id", todayHighlight: true, autoclose: true, }); }); })(this.jQuery);<file_sep><?php use yii\db\Migration; class m170114_141847_add_harga_tbl_trtravel extends Migration { public function up() { $this->addColumn('tr_travel','harga',$this->integer()->after('company_id')); } public function down() { $this->dropColumn('tr_travel','harga'); return false; } } <file_sep><?php /* @var $this \yii\web\View */ /* @var $content string */ use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use frontend\assets\GlobalAsset; use common\widgets\Alert; GlobalAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <!--[if IE 9]> <html lang="en" class="ie9"> <![endif]--> <!--[if gt IE 9]> <html lang="en" class="ie"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <meta name="description" content="The Project a Bootstrap-based, Responsive HTML5 Template"> <meta name="author" content="htmlcoder.html"> <!-- Mobile Meta --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Favicon --> <link rel="shortcut icon" href="../images/favicon.ico"> <?php $this->head(); ?> </head> <!-- body classes: --> <!-- "boxed": boxed layout mode e.g. <body class="boxed"> --> <!-- "pattern-1 ... pattern-9": background patterns for boxed layout mode e.g. <body class="boxed pattern-1"> --> <!-- "transparent-header": makes the header transparent and pulls the banner to top --> <!-- "gradient-background-header": applies gradient background to header --> <!-- "page-loader-1 ... page-loader-6": add a page loader to the page (more info @components-page-loaders.html) --> <body class="no-trans front-page page-loader-2"> <?php $this->beginBody() ?> <!-- scrollToTop --> <!-- ================ --> <div class="scrollToTop circle"><i class="icon-up-open-big"></i></div> <!-- page wrapper start --> <!-- ================ --> <div class="page-wrapper"> <!-- header-container start --> <div class="header-container"> <!-- header-top start --> <!-- classes: --> <!-- "dark": dark version of header top e.g. class="header-top dark" --> <!-- "colored": colored version of header top e.g. class="header-top colored" --> <!-- ================ --> <div class="header-top dark "> <div class="container"> <div class="row"> <div class="col-xs-2 col-sm-5"> <!-- header-top-first start --> <!-- ================ --> <div class="header-top-first clearfix"> <ul class="social-links circle small clearfix hidden-xs"> <li class="twitter"><a target="_blank" href="http://www.twitter.com/"><i class="fa fa-twitter"></i></a></li> <li class="skype"><a target="_blank" href="http://www.skype.com/"><i class="fa fa-skype"></i></a></li> <li class="linkedin"><a target="_blank" href="http://www.linkedin.com/"><i class="fa fa-linkedin"></i></a></li> <li class="googleplus"><a target="_blank" href="http://plus.google.com/"><i class="fa fa-google-plus"></i></a></li> <li class="youtube"><a target="_blank" href="http://www.youtube.com/"><i class="fa fa-youtube-play"></i></a></li> <li class="flickr"><a target="_blank" href="http://www.flickr.com/"><i class="fa fa-flickr"></i></a></li> <li class="facebook"><a target="_blank" href="http://www.facebook.com/"><i class="fa fa-facebook"></i></a></li> <li class="pinterest"><a target="_blank" href="http://www.pinterest.com/"><i class="fa fa-pinterest"></i></a></li> </ul> <div class="social-links hidden-lg hidden-md hidden-sm circle small"> <div class="btn-group dropdown"> <button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><i class="fa fa-share-alt"></i></button> <ul class="dropdown-menu dropdown-animation"> <li class="twitter"><a target="_blank" href="http://www.twitter.com/"><i class="fa fa-twitter"></i></a></li> <li class="skype"><a target="_blank" href="http://www.skype.com/"><i class="fa fa-skype"></i></a></li> <li class="linkedin"><a target="_blank" href="http://www.linkedin.com/"><i class="fa fa-linkedin"></i></a></li> <li class="googleplus"><a target="_blank" href="http://plus.google.com/"><i class="fa fa-google-plus"></i></a></li> <li class="youtube"><a target="_blank" href="http://www.youtube.com/"><i class="fa fa-youtube-play"></i></a></li> <li class="flickr"><a target="_blank" href="http://www.flickr.com/"><i class="fa fa-flickr"></i></a></li> <li class="facebook"><a target="_blank" href="http://www.facebook.com/"><i class="fa fa-facebook"></i></a></li> <li class="pinterest"><a target="_blank" href="http://www.pinterest.com/"><i class="fa fa-pinterest"></i></a></li> </ul> </div> </div> </div> <!-- header-top-first end --> </div> <div class="col-xs-10 col-sm-7"> <!-- header-top-second start --> <!-- ================ --> <div id="header-top-second" class="clearfix text-right"> <ul class="list-inline"> <li><i class="fa fa-phone pr-5 pl-10"></i>+12 123 123 123</li> <li><i class="fa fa-envelope-o pr-5 pl-10"></i> <EMAIL></li> </ul> </div> <!-- header-top-second end --> </div> </div> </div> </div> <!-- header-top end --> <!-- header start --> <!-- classes: --> <!-- "fixed": enables fixed navigation mode (sticky menu) e.g. class="header fixed clearfix" --> <!-- "dark": dark version of header e.g. class="header dark clearfix" --> <!-- "full-width": mandatory class for the full-width menu layout --> <!-- "centered": mandatory class for the centered logo layout --> <!-- ================ --> <header class="header fixed clearfix"> <div class="container"> <div class="row"> <div class="col-md-3 "> <!-- header-left start --> <!-- ================ --> <div class="header-left clearfix"> <!-- logo --> <div id="logo" class="logo"> <a href="/"><img id="logo_img" src="../images/logo_gold.png" alt="The Project"></a> </div> <!-- name-and-slogan --> <div class="site-slogan"> Multipurpose HTML5 Template </div> </div> <!-- header-left end --> </div> <div class="col-md-9"> <!-- header-right start --> <!-- ================ --> <div class="header-right clearfix"> <!-- main-navigation start --> <!-- classes: --> <!-- "onclick": Makes the dropdowns open on click, this the default bootstrap behavior e.g. class="main-navigation onclick" --> <!-- "animated": Enables animations on dropdowns opening e.g. class="main-navigation animated" --> <!-- "with-dropdown-buttons": Mandatory class that adds extra space, to the main navigation, for the search and cart dropdowns --> <!-- ================ --> <div class="main-navigation animated with-dropdown-buttons"> <!-- navbar start --> <!-- ================ --> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <!-- Toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <!-- main-menu --> <ul class="nav navbar-nav "> <!-- mega-menu start --> <li><a href="/paket-wisata">Paket Wisata</a></li> <li> <a href="/umroh">Umroh</a></li> <li> <a href="travel">Travel</a></li> <li> <a href="drop">Drop</a></li> <li> <a href="rental">Rental</a></li> </ul> <!-- main-menu end --> <!-- header buttons --> <div class="header-dropdown-buttons"> <a href="mailto:<EMAIL>" class="btn btn-sm hidden-xs btn-default">Contact Us <i class="fa fa-envelope-o pl-5"></i></a> <a href="mailto:<EMAIL>" class="btn btn-lg visible-xs btn-block btn-default">Contact Us <i class="fa fa-envelope-o pl-5"></i></a> </div> <!-- header buttons end--> </div> </div> </nav> <!-- navbar end --> </div> <!-- main-navigation end --> </div> <!-- header-right end --> </div> </div> </div> </header> <!-- header end --> </div> <!-- header-container end --> <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --> <?= $content ?> <!-- footer start (Add "dark" class to #footer in order to enable dark footer) --> <!-- ================ --> <footer id="footer" class="clearfix "> <!-- .footer start --> <!-- ================ --> <div class="footer"> <div class="container"> <div class="footer-inner"> <div class="row"> <div class="col-md-8"> <div class="footer-content"> <div class="logo-footer"><img id="logo-footer" src="../images/logo_gold.png" alt=""></div> <div class="row"> <div class="col-md-6"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus illo vel dolorum soluta consectetur doloribus sit. Delectus non tenetur odit dicta vitae debitis suscipit doloribus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed dolore fugit vitae quia dicta inventore reiciendis. Ipsa, aut voluptas quaerat.</p> <ul class="social-links circle animated-effect-1"> <li class="facebook"><a target="_blank" href="http://www.facebook.com/"><i class="fa fa-facebook"></i></a></li> <li class="twitter"><a target="_blank" href="http://www.twitter.com/"><i class="fa fa-twitter"></i></a></li> <li class="googleplus"><a target="_blank" href="http://plus.google.com/"><i class="fa fa-google-plus"></i></a></li> <li class="linkedin"><a target="_blank" href="http://www.linkedin.com/"><i class="fa fa-linkedin"></i></a></li> <li class="xing"><a target="_blank" href="http://www.xing.com/"><i class="fa fa-xing"></i></a></li> <li class="skype"><a target="_blank" href="http://www.skype.com/"><i class="fa fa-skype"></i></a></li> <li class="youtube"><a target="_blank" href="https://www.youtube.com/"><i class="fa fa-youtube"></i></a></li> </ul> <ul class="list-icons"> <li><i class="fa fa-map-marker pr-10 text-default"></i> One infinity loop, 54100</li> <li><i class="fa fa-phone pr-10 text-default"></i> +00 1234567890</li> <li><a href="mailto:<EMAIL>"><i class="fa fa-envelope-o pr-10"></i><EMAIL>.com</a></li> </ul> </div> <div class="col-md-6"> <div id="map-canvas"></div> </div> </div> </div> </div> <div class="col-md-4"> <div class="footer-content"> <h2 class="title">Contact Us</h2> <br> <div class="alert alert-success hidden" id="MessageSent2"> We have received your message, we will contact you very soon. </div> <div class="alert alert-danger hidden" id="MessageNotSent2"> Oops! Something went wrong please refresh the page and try again. </div> <form role="form" id="footer-form" class="margin-clear"> <div class="form-group has-feedback"> <label class="sr-only" for="name2">Name</label> <input type="text" class="form-control" id="name2" placeholder="Name" name="name2"> <i class="fa fa-user form-control-feedback"></i> </div> <div class="form-group has-feedback"> <label class="sr-only" for="email2">Email address</label> <input type="email" class="form-control" id="email2" placeholder="Enter email" name="email2"> <i class="fa fa-envelope form-control-feedback"></i> </div> <div class="form-group has-feedback"> <label class="sr-only" for="message2">Message</label> <textarea class="form-control" rows="6" id="message2" placeholder="Message" name="message2"></textarea> <i class="fa fa-pencil form-control-feedback"></i> </div> <input type="submit" value="Send" class="margin-clear submit-button btn btn-default"> </form> </div> </div> </div> </div> </div> </div> <!-- .footer end --> <!-- .subfooter start --> <!-- ================ --> <div class="subfooter"> <div class="container"> <div class="subfooter-inner"> <div class="row"> <div class="col-md-12"> <p class="text-center">Copyright © 2016 The Project by <a target="_blank" href="http://htmlcoder.me/">HtmlCoder</a>. All Rights Reserved</p> </div> </div> </div> </div> </div> <!-- .subfooter end --> </footer> <!-- footer end --> </div> <!-- page-wrapper end --> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?> <file_sep><?php /* @var $this yii\web\View */ use yii\helpers\Html; use yii\widgets\ActiveForm; $this->title = 'My Yii Application'; ?> <header class="header-home"> <div class="panel-home"> <div class="container"> <form method="get" action="<?php echo Yii::$app->homeUrl ?>/test/search"> <div class="row"> <?php for ($a = 0; $a < 3; $a++): ?> <div class="col-xs-3"> <div class="form-group form-group-lg has-feedback"> <?php echo Html::label('Form '.($a+1), 'field'.($a+1)) ?> <?php echo Html::input('text', 'field'.($a+1), '', ['id' => 'field'.($a+1), 'class' => 'form-control', 'placeholder' => 'Form '.($a+1)]) ?> <span class="fa fa-lg fa-pencil form-control-feedback" aria-hidden="true"></span> </div> </div> <?php endfor ?> <div class="col-xs-3"> <div class="form-group"> <?php echo Html::label('&nbsp;') ?> <?php echo Html::submitButton('<i class="fa fa-fw fa-search"></i> FIND', ['class' => 'btn btn-lg btn-block btn-primary']) ?> </div> </div> </div> </form> </div> </div> <div class="home-carousel"> <?php echo Html::img('@web/images/banner/1.jpg', ['class' => 'img-responsive']) ?> <?php echo Html::img('@web/images/banner/2.jpg', ['class' => 'img-responsive']) ?> <?php echo Html::img('@web/images/banner/3.jpg', ['class' => 'img-responsive']) ?> </div> </header> <section> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h2 class="section-title">POPULAR <strong>DESTINATION</strong></h2> <div class="separator"></div> </div> </div> </div> <div class="container"> <div class="row section-body"> <?php $images = array('sample1', 'sample2', 'sample3', 'sample4', 'sample1', 'sample2', 'sample3', 'sample4'); ?> <?php foreach ($images as $row): ?> <div class="col-lg-3 col-md-4 col-xs-6"> <div class="overlay-container"> <?php echo Html::a(Html::img('@web/images/'.$row.'.jpg', ['class' => 'img-responsive']), '@web/single') ?> <div class="overlay-top"> <h4>Image Title Overlay</h4> </div> <div class="overlay-bottom"> <div class="row"> <div class="col-md-8 col-md-offset-2 col-xs-10 col-xs-offset-1"> <?php echo Html::a('PREVIEW', 'single', ['class' => 'btn btn-lg btn-block btn-default']) ?> </div> </div> </div> </div> </div> <?php endforeach; ?> </div> </div> </section> <file_sep><?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; use yii\helpers\Url; $this->title = 'Pemesanan Paket Wisata Sukses'; $this->params['breadcrumbs'][] = $this->title; ?> <!-- breadcrumb start --> <!-- ================ --> <div class="breadcrumb-container"> <div class="container"> <ol class="breadcrumb"> <li><i class="fa fa-home pr-10"></i><a class="link-dark" href="/">Home</a></li> <li class="active"><?php echo $this->title;?></li> </ol> </div> </div> <!-- breadcrumb end --> <!-- main-container start --> <!-- ================ --> <section class="main-container jumbotron light-gray-bg text-center margin-clear"> <div class="container"> <div class="row"> <!-- main start --> <!-- ================ --> <div class="main col-md-6 col-md-offset-3 pv-40"> <h2 class="page-title"><span class="text-default">Pemesanan Sukses</span></h2> <h2>Kode Pemesanan anda adalah <br/><?php echo Yii::$app->session->getFlash('no_order'); ?></h2> <p>Terima kasih sudah melakukan pemesanan bersama kami.</p> <a href="/" class="btn btn-default btn-animated btn-lg">Return Home <i class="fa fa-home"></i></a> </div> <!-- main end --> </div> </div> </section> <!-- main-container end --> <file_sep><?php /* @var $this yii\web\View */ use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\ActiveForm; $this->title = 'My Yii Application'; ?> <header class="header-home"> <div class="panel-home"> <div class="container"> <?php $form = ActiveForm::begin([ 'id' => 'frmPwWisata', 'options' => ['role' => 'form'], 'fieldConfig' => ['options' => ['class' => 'form-group form-group-lg has-feedback']], ]); ?> <div class="row"> <div class="col-md-2 col-md-offset-3 col-xs-4"> <?= $form ->field( $model, 'id_kategori', ['template' => "{label}\n{input}\n".'<span class="fa fa-lg fa-tags form-control-feedback" aria-hidden="true"></span>'."\n{hint}\n{error}"] ) ->dropDownList( ArrayHelper::map($kategori, 'id', 'nama'), ['id' => 'idKategori', 'class' => 'form-control'] ) ?> </div> <div class="col-md-2 col-xs-4"> <?= $form ->field( $model, 'id_kota', ['template' => "{label}\n{input}\n".'<span class="fa fa-lg fa-map-marker form-control-feedback" aria-hidden="true"></span>'."\n{hint}\n{error}"] ) ->dropDownList( ArrayHelper::map($kota, 'id', 'nama'), ['id' => 'idKota', 'class' => 'form-control'] ) ?> </div> <div class="col-md-2 col-xs-4"> <?php echo Html::label('&nbsp;') ?> <?= Html::submitButton('CARI', ['class' => 'btn btn-lg btn-block btn-primary']) ?> </div> </div> <?php ActiveForm::end(); ?> </div> </div> <div class="home-carousel"> <?php echo Html::img('@web/images/banner/1.jpg', ['class' => 'img-responsive']) ?> <?php echo Html::img('@web/images/banner/2.jpg', ['class' => 'img-responsive']) ?> <?php echo Html::img('@web/images/banner/3.jpg', ['class' => 'img-responsive']) ?> </div> </header> <section> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h2 class="section-title">POPULAR <strong>DESTINATION</strong></h2> <div class="separator"></div> </div> </div> </div> <div class="container"> <div class="row section-body"> <?php $images = array('sample1', 'sample2', 'sample3', 'sample4', 'sample1', 'sample2', 'sample3', 'sample4'); ?> <?php foreach ($images as $row): ?> <div class="col-lg-3 col-md-4 col-xs-6"> <div class="overlay-container"> <?php echo Html::a(Html::img('@web/images/'.$row.'.jpg', ['class' => 'img-responsive']), '@web/single') ?> <div class="overlay-top"> <h4>Image Title Overlay</h4> </div> <div class="overlay-bottom"> <div class="row"> <div class="col-md-8 col-md-offset-2 col-xs-10 col-xs-offset-1"> <?php echo Html::a('PREVIEW', 'single', ['class' => 'btn btn-lg btn-block btn-default']) ?> </div> </div> </div> </div> </div> <?php endforeach; ?> </div> </div> </section> <file_sep><?php use yii\db\Migration; class m161217_145801_add_id_kota_tbl_tr_overarea extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('{{%overarea}}', [ 'id' => $this->primaryKey(), 'kelurahan' => $this->string(255), 'kelurahan' => $this->string(255), 'kota_id' => $this->integer(), 'company_id' => $this->integer(), 'status' => $this->smallInteger()->notNull()->defaultValue(10), 'created_at' => $this->integer()->notNull(), 'updated_at' => $this->integer()->notNull(), ], $tableOptions); $this->addForeignKey ('fk_kota_overarea', 'overarea', 'kota_id', 'kota', 'id', 'NO ACTION', 'NO ACTION'); $this->addForeignKey ('fk_company_overarea', 'overarea', 'company_id', 'company', 'id', 'NO ACTION', 'NO ACTION'); } public function down() { $this->dropTable('{{%overarea}}'); } } <file_sep><?php use yii\db\Migration; class m170121_141624_add_field_logo extends Migration { public function up() { $this->addColumn('company','logo',$this->string(60)->after('username')); } public function down() { $this->dropColumn('company','logo'); return false; } } <file_sep><?php namespace frontend\models; use Yii; use yii\base\Model; /** * WisataForm is the model behind the paket wisata form. */ class WisataForm extends Model { public $id_kategori; public $id_kota; /** * @inheritdoc */ public function rules() { return [ [['id_kategori', 'id_kota'], 'required'], [['id_kategori', 'id_kota'], 'integer'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id_kategori' => 'Kategori', 'id_kota' => 'Kota', ]; } } <file_sep><?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; use yii\helpers\Url; $this->title = 'Pesan Paket Wisata'; $this->params['breadcrumbs'][] = $this->title; ?> <!-- breadcrumb start --> <!-- ================ --> <div class="breadcrumb-container"> <div class="container"> <ol class="breadcrumb"> <li><i class="fa fa-home pr-10"></i><a class="link-dark" href="/">Home</a></li> <li class="active"><?php echo $this->title;?></li> </ol> </div> </div> <!-- breadcrumb end --> <!-- main-container start --> <!-- ================ --> <section class="main-container"> <div class="container"> <div class="row"> <!-- main start --> <!-- ================ --> <div class="main col-md-12"> <!-- page-title start --> <!-- ================ --> <h1 class="page-title">Form Pemesanan Paket Wisata</h1> <div class="separator-2"></div> <!-- page-title end --> <table class="table cart" style="width: 100%"> <thead> <tr> <th>Nama Paket </th> <th>Vendor </th> <th class="amount">Harga </th> </tr> </thead> <tbody> <tr> <td class="product"><a href="<?php echo Url::to(['detail-paket-wisata', 'id' => $DataPaket->id])?>"><?php echo $DataPaket->nama;?></a></td> <td class="price"><?php echo $DataPaket->company->nama;?></td> <td class="amount">$199.00 </td> </tr> </tbody> </table> <div class="space-bottom"></div> <fieldset> <legend>Billing information</legend> <?php $form = ActiveForm::begin(['id' => 'billing-information','options' => ['class'=>'form-horizontal']]); ?> <div class="row"> <div class="col-lg-3"> <h3 class="title">Personal Info</h3> </div> <div class="col-lg-8 col-lg-offset-1"> <?= $form->field($model, 'nama_pemesan',['template' => '{label}<div class="col-sm-7">{input}{error}{hint}</div>','labelOptions' => [ 'class' => 'col-md-3 control-label' ]]) ?> <?= $form->field($model, 'telp1',['template' => '{label}<div class="col-sm-3">{input}{error}{hint}</div>','labelOptions' => [ 'class' => 'col-md-3 control-label' ]]) ?> <?= $form->field($model, 'telp2',['template' => '{label}<div class="col-sm-3">{input}{error}{hint}</div>','labelOptions' => [ 'class' => 'col-md-3 control-label' ]]) ?> <?= $form->field($model, 'harga')->hiddenInput(['value' => $DataPaket->harga])->label(false) ?> <?= $form->field($model, 'paket_id')->hiddenInput(['value' => $DataPaket->id])->label(false) ?> <?= $form->field($model, 'alamat_jemput',['template' => '{label}<div class="col-sm-9">{input}{error}{hint}</div>','labelOptions' => [ 'class' => 'col-md-3 control-label' ]])->textInput(['id' => 'automap']) ?> <?= $form->field($model, 'detail_jemput',['template' => '{label}<div class="col-sm-9">{input}{error}{hint}</div>','labelOptions' => [ 'class' => 'col-md-3 control-label' ]])->textArea(['rows' => '6']) ?> <?= $form->field($model, 'keterangan',['template' => '{label}<div class="col-sm-9">{input}{error}{hint}</div>','labelOptions' => [ 'class' => 'col-md-3 control-label' ]])->textArea(['rows' => '6']) ?> <?= $form->field($model, 'metode_bayar',['template' => '{label}<div class="col-sm-9">{input}{error}{hint}</div>','labelOptions' => [ 'class' => 'col-md-3 control-label' ]])->radioList(array('1'=>'BRI',2=>'Mandiri',3=>'BCA')); ?> </div> </div> </fieldset> <div class="text-right"> <?= Html::submitButton('Pesan', ['class' => 'btn btn-group btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div> <!-- main end --> </div> </div> </section> <!-- main-container end --> <?php $this->registerJsFile('@web/js/paket_wisata.js', ['depends' => [\frontend\assets\AppAsset::className()]]); ?> <file_sep>/* |---------- | Nav-pack & go-top behavior |------------------------------ */ $(window).scroll(function() { if ($(this).scrollTop() > 70) { $('.nav-pack').addClass('fixed'); $('#go-top').addClass('active'); } else { $('.nav-pack').removeClass('fixed'); $('#go-top').removeClass('active'); } }); $('#go-top .btn').click(function() { $('html, body').animate( { scrollTop: 0 }, 'slow'); return false; }); /* |---------- | Sidebar navigation & overlay screen |---------------------------------------- */ var sideNav = $('.sidenav'); $('#view-filter').click(function() { if (window.innerWidth < 992) { var sidenavOverlay = $('<div id="sidenav-overlay"></div>'); sidenavOverlay.click(function() { /* |---------- | Callback untuk menyembunyikan sidenav |-------------------------------------------------- */ if (window.innerWidth < 992) { // Restore scrolling $('body').css( { overflow: '', width: '', }) // Remove overlay .find('#sidenav-overlay').fadeOut(function() { $(this).remove(); }); sideNav.removeClass('active'); } }); // Disable scrolling var body = $('body'); var oldWidth = body.innerWidth(); body.css('overflow', 'hidden').width(oldWidth); // Add overlay $('body').append(sidenavOverlay).find('#sidenav-overlay').fadeIn(); sideNav.addClass('active'); } }); $('.sidenav .close').on('click', function() { $('#sidenav-overlay').trigger('click'); }); /* |---------- | Init home carousel |------------------------------ */ $(".home-carousel").slick( { autoplay : true, autoplaySpeed: 5000, dots : true, prevArrow : '<button type="button" class="slick-prev"><i class="fa fa-angle-left"></i></button>', nextArrow : '<button type="button" class="slick-next"><i class="fa fa-angle-right"></i></button>', }); /* |---------- | Init preview image & thumbnail |---------------------------------------- */ $(".preview .preview-image").slick( { arrows : false, asNavFor : '.preview .preview-thumbnail', autoplay : true, autoplaySpeed : 3000, dots : false, fade : true, prevArrow : '<button type="button" class="slick-prev"><i class="fa fa-angle-left"></i></button>', nextArrow : '<button type="button" class="slick-next"><i class="fa fa-angle-right"></i></button>', }); $(".preview .preview-thumbnail").slick( { arrows : false, asNavFor : '.preview .preview-image', centerMode : true, dots : false, focusOnSelect : true, slidesToShow : 5, responsive: [ { breakpoint: 992, settings : { // arrows : false, // centerMode : true, slidesToShow : 3, } }, ] }); /* |---------- | NProgress |-------------------- */ if (typeof NProgress != 'undefined') { $(document).ready(function () { NProgress.start(); }); $(window).load(function () { NProgress.done(); }); } <file_sep><?php use yii\db\Migration; class m170112_142320_update_field_jam_tr_travel extends Migration { public function up() { $this->alterColumn('tr_travel','jam','string(11)'); } public function down() { echo "m170112_142320_update_field_jam_tr_travel cannot be reverted.\n"; return false; } } <file_sep><?php use yii\db\Migration; class m170118_150743_remove_jam_tr_travel extends Migration { public function up() { $this->dropColumn('tr_travel','jam'); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ } <file_sep><?php namespace common\models; use Yii; /** * This is the model class for table "tr_paketwisata". * * @property integer $id * @property string $kode * @property string $nama_pemesan * @property string $telp1 * @property string $telp2 * @property string $alamat_jemput * @property string $detail_jemput * @property integer $harga * @property integer $metode_bayar * @property integer $paket_id * @property string $keterangan * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property PwPaket $paket */ class TrPaketwisata extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'trx_paketwisata'; } /** * @inheritdoc */ public function rules() { return [ [['detail_jemput', 'keterangan'], 'string'], [['harga', 'metode_bayar', 'paket_id', 'status', 'created_at', 'updated_at'], 'integer'], [['updated_at'], 'safe'], [['created_at'], 'required'], [['kode'], 'string', 'max' => 255], [['nama_pemesan', 'alamat_jemput'], 'string', 'max' => 225], [['telp1', 'telp2'], 'string', 'max' => 15], [['paket_id'], 'exist', 'skipOnError' => true, 'targetClass' => PwPaket::className(), 'targetAttribute' => ['paket_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'kode' => Yii::t('app', 'Kode'), 'nama_pemesan' => Yii::t('app', 'Nama Pemesan'), 'telp1' => Yii::t('app', 'Telp1'), 'telp2' => Yii::t('app', 'Telp2'), 'alamat_jemput' => Yii::t('app', 'Alamat Jemput'), 'detail_jemput' => Yii::t('app', 'Detail Jemput'), 'harga' => Yii::t('app', 'Harga'), 'metode_bayar' => Yii::t('app', 'Metode Bayar'), 'paket_id' => Yii::t('app', 'Paket ID'), 'keterangan' => Yii::t('app', 'Keterangan'), 'status' => Yii::t('app', 'Status'), 'created_at' => Yii::t('app', 'Created At'), 'updated_at' => Yii::t('app', 'Updated At'), ]; } /** * @return \yii\db\ActiveQuery */ public function getPaket() { return $this->hasOne(PwPaket::className(), ['id' => 'paket_id']); } }
463cc3afbd18f9ddc2701b0e0f80dd25b3e144ed
[ "JavaScript", "PHP" ]
45
PHP
sigitsuhardiono/travelmarket
4e371b669bd6a7bd470f9007feeb6a58c7974c91
8550e442987db62c15dfae5d53e474e9a4781e5f
refs/heads/master
<repo_name>jaelyangChoi/Multi-Chatting-Program<file_sep>/MultiChattingProgram/src/Message.java public class Message { private String id; private String msg; private String type; // 메시지 유형(longin, logout, msg, secret) private String rcvId; // 귓속말 수신자 아이디 public Message(String id, String msg, String type, String rcvId) { super(); this.id = id; this.msg = msg; this.type = type; this.rcvId = rcvId; } public Message() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getRcvId() { return rcvId; } public void setRcvId(String rcvId) { this.rcvId = rcvId; } } <file_sep>/README.md # Multi-Chatting-Program 여러 유저 간 동시 채팅이 가능한 멀티 채팅 프로그램 # 기술 요소 ##### 객체 지향 개념 적용 - 클라이언트와 서버로 메인 프로그램을 분리하고, 프로그램을 구성하는 클래스는 객체지향 프로그래밍 기법에 따라 세분화시키고 계층화. - 인터페이스, 추상 클래스, 상속, 메서드 오버로딩, 메서드 오버라이딩 등을 직간접적으로 적용하고 구현. ##### MVC 패턴 도입 - GUI 프로그램의 기본 프로그래밍 모델인 MVC 패턴을 적용 ##### 다양한 프로그래밍 기술 적용 - Swing을 이용하여 클라이언트 UI를 구성 - 동시에 여러 사용자가 접속할 수 있도록 멀티스레드 네트워크 서버를 구현 - 메시지 입력과 수신을 동시에 처리해야 하므로 스레드 기반 클라이언트로 구현한다. - TCP/IP 소켓을 이용하여 네트워크 프로그래밍을 구현 ##### 스마트폰 등 모바일 클라이언트 고려 - JSON을 기반으로 메시지를 사용하고, Google Gson 파서를 적용 - 클라이언트 프로그램을 안드로이드 버전으로 손쉽게 바꿀 수 있는 구조로 설계 # 기능 정의: 본 프로그램은 클라이언트와 서버로 구성된다 ##### 클라이언트 - 로그인 로그아웃 - 대화명 입력 및 표시 - 채팅 메시지 출력 - 프로그램 종료 ##### 서버 - 클라이언트 대기 및 연결 - 다중 클라이언트 채팅 지원 - 연결된 클라이언트 목록 관리 - 채팅 메시지 수신 및 브로드캐스팅 - 로그 출력 - 귓속말 기능
1af01f14fa709d7b4def6b46028bb0ac16ca1376
[ "Markdown", "Java" ]
2
Java
jaelyangChoi/Multi-Chatting-Program
d1b0e79c437f931ea03a29d0e1aaad7475d8e29c
5fa235a5bcf545e16329d08c24865a5fd3eb7f88
refs/heads/master
<repo_name>jhanisusM/Hashi-Project2<file_sep>/dataBase/schema.sql CREATE DATABASE caballus; USE caballus;<file_sep>/dataBase/seeds.sql INSERT INTO horse (age, gender, name, sire, mare ) VALUES (5,'G', "Best of the Blues", "Eastwood Decat", "Blues Apparition"); INSERT INTO horse (age, gender, name, sire, mare, createdAt, updatedAt ) VALUES (3,'G', "Go For Moonshine", "Old Fashioned", "Go For The Moon",2018-06-17 23:14:00, 2018-06-17 23:14:00); create table horses ( id int auto_increment not null, age integer, gender varchar(255), name varchar(255), sire varchar(255), mare varchar(255), primary key (id) ); 5,G,Best of the Blues,Eastwood Decat,Blues Apparition 4,F,Cause to Wonder,Eskendraya,Female Drama 4,F,Yankee Pride,Proud Citizen ,Yankee Dooodle Girl 3,C,Strong Current,Orb,Summer Cruise 3,G,Zero Gravity,Orb,Freedom Rings 3,G,Go For Moonshine,Old Fashioned,Go For The Moon 3,,Nobutzaboutit,Proud Citizen ,Yankee Dooodle Girl 3,G,Lovanksol,Lovango,Pleasant Guest 3,,Link,Matts Broken Vow,Tez Savitra 3,F,She's all Skeet,Trappe Shot,She's all Scat 3,F,Sirenusa,Tiznow,Spun Silver 3,F,Maho Bay,Spring at Last,Sarah's Song 3,F,Firstmate,Midshipman,Lion Cub 2,C,Speed Fafctor,The Factor, 2,C,Sharp Proposal,Into Mischief,Boom Town Girl 2,C,Gopher Gold,Horses Greeley,Lion Cub 2,G,Jockers Wild,Lovango,Pleasant Guest 2,C,Stroll Daddy,Stroll,She's all Scat 2,C,Cool Sailer,Ice Box,Miss Kekoa 2,F,Delfina,Verrazano,R Victorious Girl 2,F,She's so Savvy,Bodemeister, 2,F,Que Sera Sera,Blame,Sarah's Song 2,F,Steal the Thunder,, 2,F,<NAME>,Matts Broken Vow,Tez Savitra 2,F,Laser Ladee,Data Link,Go For The Moon 2,F,Strong Patriot,Strong Mandate,Yankee Dooodle Girl<file_sep>/app/models/horse.js // Dependencies // ============================================================= // Sequelize library const Sequelize = require("sequelize"); // Connection to the database (connection.js) const sequelize = require ("../config/connection.js"); // A "horse" model with the following configuration const Horse = sequelize.define("horse",{ // 1. Age age: Sequelize.INTEGER, // 2. Gender---But Gender is a spectrum :D gender: Sequelize.STRING, // 3. Name name: Sequelize.STRING, // 4. Sire sire: Sequelize.STRING, // 4. Mare mare: Sequelize.STRING }); // Sync model with DB Horse.sync(); // Export the horse model for other files to use module.exports = Horse;<file_sep>/README.md # JockeyExpress <img src="https://image.ibb.co/ddgVXz/jockey_Express.png" /> Jockey Express is a desktop,and web application that enables horse owners to oversee, access, update, view, modify and update a stable database.This application was deployed through heroku, and utilizes JavaScript, Express, Sequelize, MySQL, HTML and CSS. Jockey Express Built With * HTML * CSS/Bootstrap * Draw.io (wireframe) * JavaScript * JQuery * MySQL * Node * Express.js
a0ea9718959bf43e79b54274d78f0857e70a6832
[ "JavaScript", "SQL", "Markdown" ]
4
SQL
jhanisusM/Hashi-Project2
510ee58ea194794f032a493dc1158afd9d0bdde0
681e2b14b8f1e4384df5a1b69f6d66de021ab1d5
refs/heads/master
<file_sep>import recsys.algorithm import os recsys.algorithm.VERBOSE = True from recsys.algorithm.factorize import SVD from recsys.datamodel.data import Data def getSVD(): filename = "/home/udaysagar/Documents/Classes/239/recsys/model/movielens.zip" if os.path.exists(filename): return SVD("./model/movielens") else: svd = SVD() svd.load_data(filename='./data/movielens/ratings.dat', sep='::', format={'col':0, 'row':1, 'value':2, 'ids': int}) k = 100 svd.compute(k=k, min_values=10, pre_normalize=None, mean_center=True, post_normalize=True, savefile='./model/movielens') return svd def getPredictedRating(ITEMID): USERID = 1 MIN_RATING = 0.0 MAX_RATING = 5.0 svd = getSVD() predictedRating = 0 totalUsers = 6040 for USERID in xrange(1, totalUsers+1): predictedRating += svd.predict(ITEMID, USERID, MIN_RATING, MAX_RATING) print predictedRating/totalUsers def getAverageRating(ITEMID): averageRating = 0 totalUsers = 0 data = Data() data.load('./data/movielens/ratings.dat', sep='::', format={'col':0, 'row':1, 'value':2, 'ids':int}) for rating, item_id, user_id in data.get(): if(item_id == ITEMID): totalUsers += 1 averageRating += rating print averageRating/totalUsers def main(): movieData = Data() <file_sep>package utils; import java.io.*; public class RecsysConnectionManager{ public static String execute(String command){ try{ ProcessBuilder pb = new ProcessBuilder("python", "-c", command); pb.directory(new File("/home/udaysagar/Documents/Classes/239/workspace/predictMovieRatings/src/recsys/")); Process p = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuffer sb = new StringBuffer(); String thisLine; while ((thisLine = in.readLine()) != null) { sb.append(thisLine); } System.out.println("result from rcm "+sb.toString()); return sb.toString(); }catch(Exception e){ System.out.println(e); } return null; } }
4db7fecaeb694d4209fd1e48e4ab79b5e89e834e
[ "Java", "Python" ]
2
Python
udaysagar2177/predictMovieRatings
1c1da69c77828b6f804516c6f811f318af93aecf
59be03302ccf9dfc24835482693d1d46cd6ff01e
refs/heads/master
<file_sep>import Vue from "vue"; import Router from "vue-router"; import Home from "./views/Home.vue"; import Doc from "./views/Documentation.vue"; import DocElButton from "./views/documentation/elements/Button.vue"; import DocElDropdown from "./views/documentation/elements/Dropdown.vue"; import DocElModal from "./views/documentation/elements/Modal.vue"; import DocElNavbar from "./views/documentation/elements/Navbar.vue"; import DocElTable from "./views/documentation/elements/Table.vue"; import DocElImage from "./views/documentation/elements/Image.vue"; import DocElTabs from "./views/documentation/elements/Tabs.vue"; import DocElCard from "./views/documentation/elements/Card.vue"; import DocElList from "./views/documentation/elements/List.vue"; import DocFormGeneral from "./views/documentation/form/General.vue"; import DocFormInput from "./views/documentation/form/Input.vue"; import DocFormTextarea from "./views/documentation/form/Textarea.vue"; import DocFormCheckbox from "./views/documentation/form/Checkbox.vue"; import DocFormRadio from "./views/documentation/form/Radio.vue"; import DocFormSelect from "./views/documentation/form/Select.vue"; import DocFormFile from "./views/documentation/form/File.vue"; import DocGridFlex from "./views/documentation/grids/Flexible.vue"; import DocGridSize from "./views/documentation/grids/Size.vue"; import DocGridResponsive from "./views/documentation/grids/Responsive.vue"; import DocLayCon from "./views/documentation/layout/Container.vue"; import DocCollStep from "./views/documentation/collection/Step.vue"; import DocCollLoader from "./views/documentation/collection/Loader.vue"; import DocCollProgress from "./views/documentation/collection/Progressbar.vue"; import DocCollMessage from "./views/documentation/collection/Message.vue"; import DocUtilityText from "./views/documentation/utility/Text.vue"; import DocUtilityColor from "./views/documentation/utility/Color.vue"; import DocUtilityPosition from "./views/documentation/utility/Position.vue"; import DocUtilityFloat from "./views/documentation/utility/Float.vue"; import DocUtilityDisplay from "./views/documentation/utility/Display.vue"; Vue.use(Router); export default new Router({ mode: "history", hash: false, routes: [ { path: "/", name: "home", component: Home }, { path: "/documentation", name: "documentation", component: Doc }, { path: "/documentation/elements/button", name: "button", component: DocElButton }, { path: "/documentation/elements/dropdown", name: "dropdown", component: DocElDropdown }, { path: "/documentation/elements/modal", name: "modal", component: DocElModal }, { path: "/documentation/elements/card", name: "card", component: DocElCard }, { path: "/documentation/elements/list", name: "list", component: DocElList }, { path: "/documentation/elements/image", name: "image", component: DocElImage }, { path: "/documentation/elements/tabs", name: "tabs", component: DocElTabs }, { path: "/documentation/elements/navbar", name: "navbar", component: DocElNavbar }, { path: "/documentation/elements/table", name: "table", component: DocElTable }, { path: "/documentation/form/general", name: "general", component: DocFormGeneral }, { path: "/documentation/form/input", name: "input", component: DocFormInput }, { path: "/documentation/form/textarea", name: "textarea", component: DocFormTextarea }, { path: "/documentation/form/checkbox", name: "checkbox", component: DocFormCheckbox }, { path: "/documentation/form/radio", name: "radio", component: DocFormRadio }, { path: "/documentation/form/select", name: "select", component: DocFormSelect }, { path: "/documentation/form/file", name: "file", component: DocFormFile }, { path: "/documentation/grids/flexible", name: "grid flexible", component: DocGridFlex }, { path: "/documentation/grids/size", name: "grid size", component: DocGridSize }, { path: "/documentation/grids/responsive", name: "grid responsive", component: DocGridResponsive }, { path: "/documentation/layout/container", name: "container", component: DocLayCon }, { path: "/documentation/collection/step", name: "step", component: DocCollStep }, { path: "/documentation/collection/loader", name: "loader", component: DocCollLoader }, { path: "/documentation/collection/progressbar", name: "progressbar", component: DocCollProgress }, { path: "/documentation/collection/message", name: "message", component: DocCollMessage }, { path: "/documentation/utility/text", name: "text", component: DocUtilityText }, { path: "/documentation/utility/color", name: "color", component: DocUtilityColor }, { path: "/documentation/utility/position", name: "position", component: DocUtilityPosition }, { path: "/documentation/utility/float", name: "float", component: DocUtilityFloat }, { path: "/documentation/utility/display", name: "display", component: DocUtilityDisplay } ] }); <file_sep>$(document).on("click", ".openModal", function() { let target = $(this).attr("data-target"); $(target).addClass("active"); $("body").addClass("overflow-hidden"); }); $(document).on("click", ".closeModal", function() { let target = $(this).closest(".modals"); $(target).removeClass("active"); $("body").removeClass("overflow-hidden"); }); $(document).on("click", ".openCollapse", function() { $(this).toggleClass("active"); $(this) .parent() .children(".collapse") .toggleClass("active"); }); $(document).on("click", ".openHamburger", function() { let target = $(this).attr("data-target"); $(this).toggleClass("active"); $(target).toggleClass("active"); }); $(document).on("change", ".uploadImage", function() { let target = $(this); let input = this; if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $(target).attr("src", e.target.result); }; reader.readAsDataURL(input.files[0]); } }); $(document).on("change", ".uploadImageMultiple", function() { let target = $(this); var files = event.target.files; //FileList object for (var i = 0; i < files.length; i++) { var file = files[i]; if (!file.type.match("image")) continue; var picReader = new FileReader(); picReader.addEventListener("load", function(event) { var picFile = event.target; $(target).after( "<div class='view many images'><img src='" + picFile.result + "'" + "title='" + picFile.name + "'/><div class='deleteImage'>Delete</div></div>" ); $(".deleteImage").click(function() { $(this) .parent() .remove(); }); }); picReader.readAsDataURL(file); } }); window.onclick = function(event) { if (!event.target.matches(".openDropdown")) { $(".openDropdown").each(function() { $(this).removeClass("active"); $(this) .parent() .removeClass("active"); }); } }; $(document).on("click", ".openDropdown", function() { if ($(this).hasClass("active")) { $(this).toggleClass("active"); $(this) .parent() .toggleClass("active"); } else { $(".openDropdown").each(function() { $(this).removeClass("active"); $(this) .parent() .removeClass("active"); }); $(this).toggleClass("active"); $(this) .parent() .toggleClass("active"); } }); $(document).on("click", ".openTab", function() { let target = $(this).attr("data-target"); let type = $(this).closest(".ini.tabs"); let header = $(type).find(".tab.header li"); let content = $(type).find(".tab.body .content"); $(content).each(function() { $(this).removeClass("active"); }); $(header).each(function() { $(this).removeClass("active"); }); $(this).addClass("active"); $(target).addClass("active"); }); $(document).on("click", ".closeMessage", function() { $(this) .parent() .addClass("hidden"); }); //keyboadr esc $(document).on("keyup", function(evt) { if (evt.keyCode == 27) { $(".openDropdown").each(function() { $(this).removeClass("active"); $(this) .parent() .removeClass("active"); }); $(".closeModal").each(function() { let target = $(this).closest(".modals"); $(target).removeClass("active"); $("body").removeClass("overflow-hidden"); }); } }); <file_sep>$(document).on('click', '.onCopy', function () { var element = $(this).parent().parent().children('textarea'); $(element).removeClass('hidden'); $(element).select(); document.execCommand("copy"); $(element).addClass('hidden'); var doc = document; var text = $(this).parent().parent().children('.area.selected')[0]; if (doc.body.createTextRange) { // ms var range = doc.body.createTextRange(); range.moveToElementText(text); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = doc.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); } });
18db5466feb94fc9dbee67b1780a6ca2b4b4ded3
[ "JavaScript" ]
3
JavaScript
Ovinsyah/inicss
7686b3e109f44bb468ed8818a9b8079c9ecc5d19
920254c1c0f6d0b1fda39d5d219f16f6cdd157aa
refs/heads/master
<repo_name>minsOne/Dodi<file_sep>/Projects/DodiDetail/Sources/EditableDetail/EditableDetailPresenter.swift // // EditableDetailPresenter.swift // DodiDetail // // Created by Geektree0101 on 2021/08/13. // import Foundation protocol EditableDetailPresenterLogic: AnyObject { func load(_ response: EditableDetailModel.Load.Response) } final class EditableDetailPresenter: EditableDetailPresenterLogic { weak var viewController: EditableDetailDisplayLogic? func load(_ response: EditableDetailModel.Load.Response) { self.viewController?.load( EditableDetailModel.Load.ViewModel( contentViewModel: EditableDetailNode.ViewModel( title: response.todo.title, description: response.todo.description ) ) ) } } <file_sep>/Projects/DodiList/Sources/Home/HomeListBloc.swift // // HomeListBloc.swift // DodiList // // Created by Geektree0101 on 2021/08/13. // import Foundation import DeepDiff import DodiUI import DodiRepository import DodiCore protocol HomeListAction { func reload() func update(_ todo: Todo) } protocol HomeListRender: AnyObject { func reload(_ items: [CardCellNode.ViewModel]) func update(_ updatedItems: [CardCellNode.ViewModel]) } protocol HomeListBloc: HomeListAction { func addRender(render: HomeListRender) } final class HomeListBlocImpl: HomeListBloc { struct Dependency { let todoCachedRepository: TodoCachedRepository let presenter: HomeListPresenter } private let dependency: Dependency private weak var render: HomeListRender? private var todos: [Todo] = [] init(dependency: Dependency) { self.dependency = dependency } func addRender(render: HomeListRender) { self.render = render } func reload() { self.todos = self.dependency.todoCachedRepository.allTodos() self.render?.reload( self.dependency.presenter.mapping( todos: self.todos ) ) } func update(_ todo: Todo) { guard let index = self.todos.firstIndex(where: { $0.id == todo.id }) else { return } self.todos[index] = todo self.render?.update( self.dependency.presenter.mapping( todos: self.todos ) ) } } <file_sep>/Projects/DodiCore/Sources/Todo/TodoRepository.swift // // TodoRepository.swift // DodiRepository // // Created by Geektree0101 on 2021/08/13. // import Foundation public protocol TodoRepository { func todo(id: Int) -> Todo? func appendTodo(_ todo: Todo) func insertTodo(_ todo: Todo, at index: Int) func allTodos() -> [Todo] func save(_ todos: [Todo]) func update(_ todo: Todo) } <file_sep>/Projects/DodiDetail/Tests/UserDetail/UserDetailViewControllerTests.swift // // UserDetailViewControllerTests.swift // DodiDetailTests // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // import XCTest @testable import DodiDetail final class UserDetailViewControllerTests: XCTestCase { // MARK: - Test Double Objects final class UserDetailInteractorSpy: UserDetailBusinessLogic { var loadRequest: UserDetailModel.Load.Request? func load(request: UserDetailModel.Load.Request) { self.loadRequest = request } var deleteRequest: UserDetailModel.Delete.Request? func delete(request: UserDetailModel.Delete.Request) { self.deleteRequest = request } } final class UserDetailRouterSpy: UserDetailRoutingLogic, UserDetailDataPassing { var dataStore: UserDetailDataStore? } // MARK: - Properties var interactor: UserDetailInteractorSpy! var router: UserDetailRouterSpy! var viewController: UserDetailViewController! override func setUp() { self.interactor = UserDetailInteractorSpy() self.router = UserDetailRouterSpy() self.viewController = UserDetailViewController() self.viewController.interactor = self.interactor self.viewController.router = self.router } } // MARK: - TODO TestName (BDD) extension UserDetailViewControllerTests { func test_doSomething() { // given // when // then } }<file_sep>/Projects/DodiList/Sources/Home/HomeListViewController.swift // // HomeListViewController.swift // DodiList // // Created by Geektree0101 on 2021/08/13. // import Foundation import DeepDiff import DodiUI import DodiDetail public final class HomeListViewController: BaseViewController { public struct Dependency { let homeBloc: HomeListBloc let detailBuilder: DetailBuilder } // MARK: - UI private let collectionNode = ASCollectionNode( collectionViewLayout: UICollectionViewFlowLayout().then { $0.minimumLineSpacing = 0.0 $0.minimumInteritemSpacing = 0.0 $0.scrollDirection = .vertical } ).then { $0.alwaysBounceVertical = true } private let refreshControl = UIRefreshControl() // MARK: - Prop private let action: HomeListAction private let detailBuilder: DetailBuilder private var items: [CardCellNode.ViewModel] = [] public init(dependeny: Dependency) { self.action = dependeny.homeBloc self.detailBuilder = dependeny.detailBuilder super.init() self.title = "Home" dependeny.homeBloc.addRender(render: self) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() self.collectionNode.delegate = self self.collectionNode.dataSource = self self.collectionNode.view.refreshControl = self.refreshControl.then { $0.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged) } self.action.reload() } public override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASInsetLayoutSpec( insets: self.node.safeAreaInsets, child: self.collectionNode ) } @objc private func didPullToRefresh() { self.refreshControl.beginRefreshing() self.action.reload() } } // MARK: - ASCollectionDelegate extension HomeListViewController: ASCollectionDelegate { public func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) { let detailViewController = self.detailBuilder.editableDetailViewController.then { $0.router?.dataStore?.todoID = self.items[indexPath.item].id } detailViewController.await { result in guard case let .saved(todo) = result else { return } self.action.update(todo) } self.present( UINavigationController( rootViewController: detailViewController ), animated: true, completion: nil ) } public func collectionNode(_ collectionNode: ASCollectionNode, constrainedSizeForItemAt indexPath: IndexPath) -> ASSizeRange { return ASSizeRange( min: CGSize(width: collectionNode.bounds.width, height: 0.0), max: CGSize(width: collectionNode.bounds.width, height: .infinity) ) } } // MARK: - ASCollectionDataSource extension HomeListViewController: ASCollectionDataSource { public func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int { return self.items.count } public func collectionNode(_ collectionNode: ASCollectionNode, nodeBlockForItemAt indexPath: IndexPath) -> ASCellNodeBlock { let item = self.items[indexPath.item] return { CardCellNode( item, style: CardCellNode.CardStyle( margin: UIEdgeInsets( top: 12.0, left: 12.0, bottom: 12.0, right: 12.0 ), padding: UIEdgeInsets( top: 16.0, left: 16.0, bottom: 16.0, right: 16.0 ) ) ) } } } // MARK: - render extension HomeListViewController: HomeListRender { func reload(_ items: [CardCellNode.ViewModel]) { self.refreshControl.endRefreshing() self.items = items self.collectionNode.reloadData() } func update(_ updatedItems: [CardCellNode.ViewModel]) { let changes = diff(old: self.items, new: updatedItems) self.items = updatedItems self.collectionNode.reload( changes: changes, section: 0, animated: true, completion: nil ) } } <file_sep>/Projects/DodiCore/Tests/DodiKitTests.swift import Foundation import XCTest final class DodiKitTests: XCTestCase { func test_example() { XCTAssertEqual("DodiKit", "DodiKit") } }<file_sep>/Projects/DodiDetail/Sources/UserDetail/UserDetailModel.swift // // UserDetailModel.swift // DodiDetail // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // enum UserDetailModel { enum Load { struct Request { } struct Response { } struct ViewModel { } } enum Delete { struct Request { } struct Response { } struct ViewModel { } } } <file_sep>/Projects/DodiRepository/Sources/Todo/TodoCachedRepositoryImpl.swift // // TodoCachedRepositoryImpl.swift // DodiRepository // // Created by Geektree0101 on 2021/08/13. // import Foundation import DodiCore struct TodoCachedRepositoryImpl: TodoCachedRepository { private enum Const { static let todosKey: String = "TodoCachedRepository.todos" } private let userDefaults: UserDefaults init(userDefaults: UserDefaults) { self.userDefaults = userDefaults } func todo(id: Int) -> Todo? { let todos = self.cachedTodos() return todos.first(where: { $0.id == id }) } func appendTodo(_ todo: Todo) { var todos = self.cachedTodos() todos.append(todo) self.save(todos) } func insertTodo(_ todo: Todo, at index: Int) { var todos = self.cachedTodos() todos.insert(todo, at: index) self.save(todos) } func save(_ todos: [Todo]) { guard let jsonString = try? PropertyListEncoder().encode(todos) else { return } self.userDefaults.setValue(jsonString, forKey: Const.todosKey) } func allTodos() -> [Todo] { return self.cachedTodos() } func update(_ todo: Todo) { var todos = self.cachedTodos() guard let index = todos.firstIndex(where: { $0.id == todo.id }) else { return } todos[index] = todo self.save(todos) } private func cachedTodos() -> [Todo] { guard let data = self.userDefaults.value(forKey: Const.todosKey) as? Data, let todos = try? PropertyListDecoder().decode([Todo].self, from: data) else { return [] } return todos } } <file_sep>/Projects/DodiDetail/Sources/EditableDetail/EditableDetailModel.swift // // EditableDetailModel.swift // DodiDetail // // Created by Geektree0101 on 2021/08/13. // import Foundation import DodiCore enum EditableDetailModel { enum Load { struct Request { } struct Response { let todo: Todo } struct ViewModel { let contentViewModel: EditableDetailNode.ViewModel } } enum Save { struct Request { let title: String let description: String } } } <file_sep>/Projects/DodiDetail/Sources/UserDetail/UserDetailInteractor.swift // // UserDetailInteractor.swift // DodiDetail // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // import Foundation protocol UserDetailBusinessLogic: AnyObject { func load(request: UserDetailModel.Load.Request) func delete(request: UserDetailModel.Delete.Request) } protocol UserDetailDataStore: AnyObject { } final class UserDetailInteractor: UserDetailDataStore { var presenter: UserDetailPresentationLogic? } // MARK: - Business Logic extension UserDetailInteractor: UserDetailBusinessLogic { func load(request: UserDetailModel.Load.Request) { } func delete(request: UserDetailModel.Delete.Request) { } }<file_sep>/Projects/DodiUI/Sources/Views/BaseViewController.swift // // BaseViewController.swift // DodiUI // // Created by Geektree0101 on 2021/08/13. // import Foundation import AsyncDisplayKit open class BaseViewController: ASDKViewController<BaseNode>, BaseProxyDelegate { public override init() { super.init(node: BaseNode()) self.node.delegate = self } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func didLoad() { // override } open func layout() { // override } open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { // override return ASLayoutSpec() } } <file_sep>/Workspace.swift import ProjectDescription import ProjectDescriptionHelpers let workspace = Workspace( name: "Dodi", projects: [ "Projects/Dodi", "Projects/DodiList", "Projects/DodiDetail", "Projects/DodiCore", "Projects/DodiRepository", "Projects/DodiUI" ], fileHeaderTemplate: nil, additionalFiles: [] ) <file_sep>/Projects/DodiCore/Sources/Todo/Todo.swift import Foundation import Then public struct Todo: Codable, Hashable, Then { public let id: Int public var title: String public var description: String public init(id: Int, title: String, description: String) { self.id = id self.title = title self.description = description } } <file_sep>/Tuist/ProjectDescriptionHelpers/Project+DynamicFramework.swift import ProjectDescription /// Project helpers are functions that simplify the way you define your project. /// Share code to create targets, settings, dependencies, /// Create your own conventions, e.g: a func that makes sure all shared targets are "static frameworks" /// See https://docs.tuist.io/guides/helpers/ extension Project { public static func dynamicFramework( name: String, platform: Platform, dependencies: [TargetDependency] ) -> Project { return Project( name: name, targets: [ Target( name: name, platform: platform, product: .framework, bundleId: "com.dodi.\(name)", infoPlist: .default, sources: ["Sources/**"], dependencies: dependencies ), Target( name: "\(name)Tests", platform: platform, product: .unitTests, bundleId: "com.dodi.\(name)Tests", infoPlist: .default, sources: ["Tests/**"], dependencies: [ .target(name: "\(name)") ] ) ], schemes: [ Scheme( name: name, shared: true, buildAction: BuildAction( targets: [ TargetReference(projectPath: nil, target: name) ] ), testAction: TestAction( targets: [ TestableTarget( target: TargetReference( projectPath: nil, target: "\(name)Tests" ) ) ], arguments: Arguments( environment: [ "OS_ACTIVITY_MODE": "disable" ] ) ) ) ] ) } } <file_sep>/Podfile platform :ios, '14.0' use_frameworks! inhibit_all_warnings! workspace 'Dodi' def common_framework pod 'NeedleFoundation' pod 'Then' end def ui_framework pod 'Texture' pod 'BonMot' pod 'DeepDiff' end target 'DodiUI' do project 'Projects/DodiUI/DodiUI' common_framework ui_framework end target 'DodiCore' do project 'Projects/DodiCore/DodiCore' common_framework end target 'DodiRepository' do project 'Projects/DodiRepository/DodiRepository' common_framework end target 'DodiDetail' do project 'Projects/DodiDetail/DodiDetail' common_framework end target 'DodiList' do project 'Projects/DodiList/DodiList' common_framework end target 'Dodi' do project 'Projects/Dodi/Dodi' common_framework end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['CONFIGURATION_BUILD_DIR'] = '$PODS_CONFIGURATION_BUILD_DIR' end end end <file_sep>/README.md # Dodi Modular iOS with Uber needle &amp; tuist example <br/> medium: https://h2s1880.medium.com/%EB%AA%A8%EB%93%88%ED%99%94%ED%95%98%EA%B3%A0-needle-%EC%A0%81%EC%9A%A9%ED%95%B4%EB%B3%B4%EA%B8%B0-bd5e9f3c450b ## Setup ```sh brew install needle bash <(curl -Ls https://install.tuist.io) ``` and run ```sh make all ``` ## Point of concern 1. I'm debating whether to provide a Builder for the Repository or an repository interface of a specific implementation object(such as TodoCachedRepository) from RootComponent... ### RootComponent ```swift import DodiList import DodiDetail import DodiRepository class RootComponent: BootstrapComponent { var userDefaults: UserDefaults { return UserDefaults.standard } var repositoryBuilder: RepositoryBuilder { return shared { RepositoryComponent(parent: self) } } var listBuilder: ListBuilder { return shared { ListComponent(parent: self) } } var detailBuilder: DetailBuilder { return shared { DetailComponent(parent: self) } } var rootViewController: UIViewController { return UINavigationController( rootViewController: self.listBuilder.homeListViewController ) } } ``` ### ListComponent ```swift import DodiRepository import DodiDetail public protocol ListDependency: Dependency { var repositoryBuilder: RepositoryBuilder { get } //<--- Is it Okey? var detailBuilder: DetailBuilder { get } } public protocol ListBuilder { var homeListViewController: HomeListViewController { get } } public class ListComponent: Component<ListDependency>, ListBuilder { public var homeListViewController: HomeListViewController { return HomeListViewController( dependeny: HomeListViewController.Dependency( homeBloc: HomeListBlocImpl( dependency: HomeListBlocImpl.Dependency( todoCachedRepository: self.repositoryBuilder.todoCachedRepository, presenter: HomeListPresenter() ) ), detailBuilder: self.detailBuilder ) ) } } ``` ## Graph <img src="https://github.com/GeekTree0101/Dodi/blob/master/graph.png" /> > tuist graph -t <file_sep>/Projects/DodiDetail/Sources/UserDetail/UserDetailRouter.swift // // UserDetailRouter.swift // DodiDetail // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // import UIKit protocol UserDetailRoutingLogic: AnyObject { } protocol UserDetailDataPassing: AnyObject { var dataStore: UserDetailDataStore? { get set } } final class UserDetailRouter: UserDetailDataPassing { weak var viewController: UserDetailViewController? var dataStore: UserDetailDataStore? } // MARK: - Routing Logic extension UserDetailRouter: UserDetailRoutingLogic { }<file_sep>/Projects/DodiList/Sources/ListComponent.swift // // Assembly.swift // DodiList // // Created by Geektree0101 on 2021/08/13. // import Foundation import NeedleFoundation import DodiRepository import DodiDetail public protocol ListDependency: Dependency { var repositoryBuilder: RepositoryBuilder { get } var detailBuilder: DetailBuilder { get } } public protocol ListBuilder { var homeListViewController: HomeListViewController { get } } public class ListComponent: Component<ListDependency>, ListBuilder { public var homeListViewController: HomeListViewController { return HomeListViewController( dependeny: HomeListViewController.Dependency( homeBloc: HomeListBlocImpl( dependency: HomeListBlocImpl.Dependency( todoCachedRepository: self.repositoryBuilder.todoCachedRepository, presenter: HomeListPresenter() ) ), detailBuilder: self.detailBuilder ) ) } } <file_sep>/Projects/DodiRepository/Sources/Todo/TodoCachedRepository.swift // // TodoCachedRepository.swift // DodiRepository // // Created by Geektree0101 on 2021/08/13. // import Foundation import DodiCore public protocol TodoCachedRepository: TodoRepository { } <file_sep>/Projects/DodiDetail/Sources/EditableDetail/EditableDetailViewController.swift // // EditableDetailViewController.swift // DodiDetail // // Created by Geektree0101 on 2021/08/13. // import Foundation import DodiUI import DodiRepository import DodiCore public enum EditableDetailResult { case saved(todo: Todo) } protocol EditableDetailDisplayLogic: AnyObject { func load(_ viewModel: EditableDetailModel.Load.ViewModel) } public final class EditableDetailViewController: BaseViewController { public struct Dependency { let todoCachedRepository: TodoCachedRepository } // MARK: - UI private let closeButtonItem = UIBarButtonItem(systemItem: .close) private let saveButtonItem = UIBarButtonItem(systemItem: .save) private let scrollNode = ASScrollNode().then { $0.automaticallyManagesSubnodes = true $0.automaticallyManagesContentSize = true $0.scrollableDirections = [.up, .down] } private let contentNode = EditableDetailNode() // MARK: - Prop public var router: (EditableDetailRouterLogic & EditableDetailDataPassing)! private var interactor: EditableDetailInteractorLogic! var awaitHandler: ((EditableDetailResult) -> Void)? public init(dependency: Dependency) { super.init() self.configure(dependency: dependency) self.title = "Editor" } private func configure(dependency: Dependency) { let viewController = self let router = EditableDetailRouter() let presenter = EditableDetailPresenter() let interactor = EditableDetailInteractor( dependency: EditableDetailInteractor.Dependency( todoCachedRepository: dependency.todoCachedRepository, presenter: presenter ) ) presenter.viewController = viewController router.viewController = viewController router.dataStore = interactor viewController.interactor = interactor viewController.router = router } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func await(_ awaitHandler: @escaping (EditableDetailResult) -> Void) { self.awaitHandler = awaitHandler } public override func viewDidLoad() { super.viewDidLoad() self.scrollNode.layoutSpecBlock = { [weak self] (_, _) -> ASLayoutSpec in return self?.scrollLayoutSpec() ?? ASLayoutSpec() } self.navigationItem.leftBarButtonItem = self.closeButtonItem.then { $0.target = self $0.action = #selector(close) } self.navigationItem.rightBarButtonItem = self.saveButtonItem.then { $0.target = self $0.action = #selector(didTapSave) } self.interactor.load( EditableDetailModel.Load.Request() ) } public override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASInsetLayoutSpec( insets: self.node.safeAreaInsets, child: self.scrollNode ) } private func scrollLayoutSpec() -> ASLayoutSpec { return ASInsetLayoutSpec( insets: UIEdgeInsets(top: 56.0, left: 16.0, right: 16.0), child: self.contentNode ) } @objc private func didTapSave() { self.interactor.save( EditableDetailModel.Save.Request( title: self.contentNode.currentTitle ?? "", description: self.contentNode.currentDescription ?? "" ) ) self.router.saved() } @objc private func close() { self.dismiss(animated: true, completion: nil) } } // MARK: - EditableDetailDisplayLogic extension EditableDetailViewController: EditableDetailDisplayLogic { func load(_ viewModel: EditableDetailModel.Load.ViewModel) { self.contentNode.render(viewModel.contentViewModel) } } <file_sep>/Projects/Dodi/Sources/AppDelegate.swift import UIKit import DodiCore @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil ) -> Bool { registerProviderFactories() let rootComponent = RootComponent() rootComponent.repositoryBuilder.todoCachedRepository.save([ Todo(id: 1, title: "test", description: "test"), Todo(id: 2, title: "test-2", description: "test"), Todo(id: 3, title: "test-3", description: "test"), Todo(id: 4, title: "test-4", description: "test") ]) self.window = UIWindow(frame: UIScreen.main.bounds) let viewController = UIViewController() viewController.view.backgroundColor = .white self.window?.rootViewController = rootComponent.rootViewController self.window?.makeKeyAndVisible() return true } } <file_sep>/go.mod module github.com/Geektree0101/Dodi go 1.16 require github.com/Geektree0101/clean-swift-scaffold v1.0.0 // indirect <file_sep>/Projects/DodiDetail/Sources/EditableDetail/EditableDetailRouter.swift // // EditableDetailRouter.swift // DodiDetail // // Created by Geektree0101 on 2021/08/13. // import Foundation public protocol EditableDetailRouterLogic: AnyObject { func saved() } public protocol EditableDetailDataPassing: AnyObject { var dataStore: EditableDetailDataStore? { get set } } final class EditableDetailRouter: EditableDetailRouterLogic, EditableDetailDataPassing { var dataStore: EditableDetailDataStore? weak var viewController: EditableDetailViewController? func saved() { if let todo = self.dataStore?.todo { self.viewController?.awaitHandler?( .saved(todo: todo) ) } self.viewController?.dismiss(animated: true, completion: nil) } } <file_sep>/Projects/DodiUI/Sources/Extensions/CGSize+Init.swift // // CGSize+Init.swift // DodiUI // // Created by Geektree0101 on 2021/08/13. // import UIKit public extension CGSize { init(all: CGFloat) { self.init(width: all, height: all) } } <file_sep>/Projects/Dodi/Sources/RootComponent.swift // // RootComponent.swift // Dodi // // Created by Geektree0101 on 2021/08/13. // Copyright © 2021 com.dodi. All rights reserved. // import Foundation import NeedleFoundation import DodiList import DodiDetail import DodiRepository class RootComponent: BootstrapComponent { var userDefaults: UserDefaults { return UserDefaults.standard } var repositoryBuilder: RepositoryBuilder { return shared { RepositoryComponent(parent: self) } } var listBuilder: ListBuilder { return shared { ListComponent(parent: self) } } var detailBuilder: DetailBuilder { return shared { DetailComponent(parent: self) } } var rootViewController: UIViewController { return UINavigationController( rootViewController: self.listBuilder.homeListViewController ) } } <file_sep>/Projects/DodiList/Project.swift import ProjectDescription import ProjectDescriptionHelpers let project = Project.dynamicFramework( name: "DodiList", platform: .iOS, dependencies: [ .sdk(name: "Foundation.framework", status: .required), .project(target: "DodiRepository", path: "../DodiRepository"), .project(target: "DodiCore", path: "../DodiCore"), .project(target: "DodiUI", path: "../DodiUI"), .cocoapods(path: "../../"), ] ) <file_sep>/main.go package main import ( scaffold "github.com/Geektree0101/clean-swift-scaffold" "github.com/spf13/cobra" ) var ( rootCmd = &cobra.Command{ Use: "dodi", Short: "dodi cmd tools", } ) func main() { rootCmd.AddCommand(scaffold.NewRunnerCommand("scaffold")) rootCmd.Execute() } <file_sep>/Tuist/ProjectDescriptionHelpers/Project+Excutable.swift import ProjectDescription /// Project helpers are functions that simplify the way you define your project. /// Share code to create targets, settings, dependencies, /// Create your own conventions, e.g: a func that makes sure all shared targets are "static frameworks" /// See https://docs.tuist.io/guides/helpers/ extension Project { public static func excutable( name: String, platform: Platform, dependencies: [TargetDependency] ) -> Project { return Project( name: name, organizationName: "com.dodi", targets: [ Target( name: name, platform: platform, product: .app, bundleId: "com.dodi.\(name)", infoPlist: .extendingDefault( with: [ "CFBundleShortVersionString": "1.0", "CFBundleVersion": "1", "UIMainStoryboardFile": "", "UILaunchStoryboardName": "LaunchScreen" ] ), sources: ["Sources/**"], resources: ["Resources/**"], dependencies: dependencies ), Target( name: "\(name)Tests", platform: platform, product: .unitTests, bundleId: "com.dodi.\(name)Tests", infoPlist: .default, sources: ["Tests/**"], dependencies: [ .target(name: "\(name)") ] ) ] ) } } <file_sep>/Projects/DodiDetail/Sources/EditableDetail/EditableDetailNode.swift // // EditableDetailNode.swift // DodiDetail // // Created by Geektree0101 on 2021/08/13. // import Foundation import Then import DodiUI final class EditableDetailNode: ASDisplayNode { private enum Typo { static let indicator = StringStyle( .font(UIFont.boldSystemFont(ofSize: 14.0)), .color(UIColor.darkGray) ) static let titlePlaceHolder = StringStyle( .font(UIFont.boldSystemFont(ofSize: 30.0)), .color(UIColor.gray) ) static let descPlaceHolder = StringStyle( .font(UIFont.systemFont(ofSize: 24.0)), .color(UIColor.gray) ) static let title = StringStyle( .font(UIFont.boldSystemFont(ofSize: 30.0)), .color(UIColor.black) ) static let desc = StringStyle( .font(UIFont.systemFont(ofSize: 24.0)), .color(UIColor.black) ) } struct ViewModel { let title: String let description: String } // MARK: - UI private let titleIndicatorNode = ASTextNode().then { $0.attributedText = "Title".styled(with: Typo.indicator) } private let titleNode = ASEditableTextNode().then { $0.attributedPlaceholderText = "Title...".styled(with: Typo.titlePlaceHolder) $0.typingAttributes = Typo.title.attributes.toStringWithAny } private let descriptionIndicatorNode = ASTextNode().then { $0.attributedText = "Description".styled(with: Typo.indicator) } private let descriptionNode = ASEditableTextNode().then { $0.attributedPlaceholderText = "Description...".styled(with: Typo.descPlaceHolder) $0.typingAttributes = Typo.desc.attributes.toStringWithAny } var currentTitle: String? { return self.titleNode.attributedText?.string } var currentDescription: String? { return self.descriptionNode.attributedText?.string } override init() { super.init() self.automaticallyManagesSubnodes = true self.titleNode.delegate = self self.descriptionNode.delegate = self } func render(_ viewModel: ViewModel) { self.titleNode.attributedText = viewModel.title.styled(with: Typo.title) self.descriptionNode.attributedText = viewModel.description.styled(with: Typo.desc) self.setNeedsLayout() } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASStackLayoutSpec( direction: .vertical, spacing: 24.0, justifyContent: .start, alignItems: .stretch, children: [ self.titleFieldLayoutSpec(), self.descriptionFieldLayoutSpec() ] ) } private func titleFieldLayoutSpec() -> ASLayoutSpec { return ASStackLayoutSpec( direction: .vertical, spacing: 8.0, justifyContent: .start, alignItems: .stretch, children: [ self.titleIndicatorNode, self.titleNode ] ) } private func descriptionFieldLayoutSpec() -> ASLayoutSpec { return ASStackLayoutSpec( direction: .vertical, spacing: 8.0, justifyContent: .start, alignItems: .stretch, children: [ self.descriptionIndicatorNode, self.descriptionNode ] ) } } // MARK: - ASEditableTextNodeDelegate extension EditableDetailNode: ASEditableTextNodeDelegate { func editableTextNodeDidUpdateText(_ editableTextNode: ASEditableTextNode) { self.setNeedsLayout() } } <file_sep>/Projects/DodiUI/Sources/Exports.swift // // Exports.swift // DodiUI // // Created by Geektree0101 on 2021/08/13. // import Foundation @_exported import AsyncDisplayKit @_exported import BonMot <file_sep>/Projects/DodiRepository/Sources/RepositoryComponent.swift // // Assembly.swift // DodiRepository // // Created by Geektree0101 on 2021/08/13. // import Foundation import NeedleFoundation public protocol RepositoryDependency: Dependency { var userDefaults: UserDefaults { get } } public protocol RepositoryBuilder { var todoCachedRepository: TodoCachedRepository { get } } public class RepositoryComponent: Component<RepositoryDependency>, RepositoryBuilder { public var todoCachedRepository: TodoCachedRepository { return shared { TodoCachedRepositoryImpl( userDefaults: self.userDefaults ) } } } <file_sep>/Projects/DodiList/Sources/Home/HomeListPresenter.swift // // HomeListPresenter.swift // DodiList // // Created by Geektree0101 on 2021/08/13. // import Foundation import DodiUI import DodiCore struct HomeListPresenter { func mapping(todos: [Todo]) -> [CardCellNode.ViewModel] { return todos.map { CardCellNode.ViewModel( id: $0.id, title: "Title: " + $0.title, description: "Description: " + $0.description ) } } } <file_sep>/Projects/DodiDetail/Sources/UserDetail/UserDetailViewController.swift // // UserDetailViewController.swift // DodiDetail // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // import UIKit protocol UserDetailDisplayLogic: AnyObject { func displayLoad(viewModel: UserDetailModel.Load.ViewModel) func displayDelete(viewModel: UserDetailModel.Delete.ViewModel) } final class UserDetailViewController: UIVIewController { // MARK: - Properties var router: (UserDetailRoutingLogic & UserDetailDataPassing)? var interactor: UserDetailBusinessLogic? // MARK: - Initializing override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.configure() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Configuring private func configure() { let viewController = self let interactor = UserDetailInteractor() let presenter = UserDetailPresenter() let router = UserDetailRouter() interactor.presenter = presenter presenter.view = viewController router.viewController = viewController router.dataStore = interactor viewController.interactor = interactor viewController.router = router } } // MARK: - Display Logic extension UserDetailViewController: UserDetailDisplayLogic { func displayLoad(viewModel: UserDetailModel.Load.ViewModel) { } func displayDelete(viewModel: UserDetailModel.Delete.ViewModel) { } }<file_sep>/Projects/DodiDetail/Tests/UserDetail/UserDetailPresenterTests.swift // // UserDetailPresenterTests.swift // DodiDetailTests // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // import XCTest @testable import DodiDetail final class UserDetailPresenterTests: XCTestCase { // MARK: - Test Double Objects final class UserDetailDisplaySpy: UserDetailDisplayLogic { var displayLoadViewModel: UserDetailModel.Load.ViewModel? func displayLoad(viewModel: UserDetailModel.Load.ViewModel) { self.displayLoadViewModel = viewModel } var displayDeleteViewModel: UserDetailModel.Delete.ViewModel? func displayDelete(viewModel: UserDetailModel.Delete.ViewModel) { self.displayDeleteViewModel = viewModel } } // MARK: - Properties var presenter: UserDetailPresenter! var display: UserDetailDisplaySpy! override func setUp() { self.presenter = UserDetailPresenter() self.display = UserDetailDisplaySpy() self.presenter.viewController = self.display } } // MARK: - TODO TestName (BDD) extension UserDetailPresenterTests { func test_doSomething() { // given // when // then } }<file_sep>/Projects/Dodi/Project.swift import ProjectDescription import ProjectDescriptionHelpers let project = Project.excutable( name: "Dodi", platform: .iOS, dependencies: [ .sdk(name: "Foundation.framework", status: .required), .sdk(name: "UIKit.framework", status: .required), .project(target: "DodiUI", path: "../DodiUI"), .project(target: "DodiList", path: "../DodiList"), .project(target: "DodiDetail", path: "../DodiDetail"), .cocoapods(path: "../..") ] ) <file_sep>/Projects/DodiUI/Sources/Views/BaseNode.swift // // BaseNode.swift // DodiUI // // Created by Geektree0101 on 2021/08/13. // import Foundation import AsyncDisplayKit protocol BaseProxyDelegate: AnyObject { func didLoad() func layout() func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec } public final class BaseNode: ASDisplayNode { weak var delegate: BaseProxyDelegate? override init() { super.init() self.automaticallyManagesSubnodes = true self.backgroundColor = UIColor.systemBackground } public override func didLoad() { self.delegate?.didLoad() } public override func layout() { self.delegate?.layout() } public override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return self.delegate?.layoutSpecThatFits(constrainedSize) ?? ASLayoutSpec() } } <file_sep>/Projects/DodiUI/Sources/Extensions/ASCollectionNode+Diff.swift // // ASCollectionNode+Diff.swift // DodiUI // // Created by Geektree0101 on 2021/08/13. // import Foundation import AsyncDisplayKit import DeepDiff extension ASCollectionNode { /// Animate reload in a batch update /// /// - Parameters: /// - changes: The changes from diff /// - section: The section that all calculated IndexPath belong /// - animated: The animation for performBatch /// - completion: Called when operation completes public func reload<T: DiffAware>( changes: [Change<T>], section: Int, animated: Bool, batchUpdate: (() -> Void)? = nil, completion: ((Bool) -> Void)?) { let changesWithIndexPath = IndexPathConverter().convert(changes: changes, section: section) self.performBatch(animated: animated, updates: { batchUpdate?() self.internalBatchUpdates(changesWithIndexPath: changesWithIndexPath) }, completion: completion) changesWithIndexPath.replaces.executeIfPresent { self.reloadItems(at: $0) } } public func reloadSections<T: DiffAware>( changes: [Change<T>], animated: Bool, completion: ((Bool) -> Void)? = nil) { self.performBatch(animated: animated, updates: { changes.compactMap({ $0.delete }).map({ $0.index }) .executeIfPresent({ sections in self.deleteSections(IndexSet(sections)) }) changes.compactMap({ $0.insert }).map({ $0.index }) .executeIfPresent({ sections in self.insertSections(IndexSet(sections)) }) changes.compactMap({ $0.move }) .executeIfPresent({ moves in for move in moves { self.moveSection(move.fromIndex, toSection: move.toIndex) } }) }, completion: completion) self.reloadSections( IndexSet(changes.compactMap({ $0.replace }).map({ $0.index })) ) } // MARK: - Helper private func internalBatchUpdates(changesWithIndexPath: ChangeWithIndexPath) { changesWithIndexPath.deletes.executeIfPresent { self.deleteItems(at: $0) } changesWithIndexPath.inserts.executeIfPresent { self.insertItems(at: $0) } changesWithIndexPath.moves.executeIfPresent { $0.forEach { move in self.moveItem(at: move.from, to: move.to) } } } } <file_sep>/Projects/DodiDetail/Sources/UserDetail/UserDetailPresenter.swift // // UserDetailPresenter.swift // DodiDetail // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // import UIKit protocol UserDetailPresentationLogic: AnyObject { func presentLoad(response: UserDetailModel.Load.Response) func presentDelete(response: UserDetailModel.Delete.Response) } final class UserDetailPresenter { weak var viewController: UserDetailDisplayLogic? } // MARK: - Presentation Logic extension UserDetailPresenter: UserDetailPresentationLogic { func presentLoad(response: UserDetailModel.Load.Response) { } func presentDelete(response: UserDetailModel.Delete.Response) { } }<file_sep>/Projects/DodiDetail/Sources/EditableDetail/EditableDetailInteractor.swift // // EditableDetailInteractor.swift // DodiDetail // // Created by Geektree0101 on 2021/08/13. // import Foundation import DodiRepository import DodiCore protocol EditableDetailInteractorLogic: AnyObject { func load(_ request: EditableDetailModel.Load.Request) func save(_ request: EditableDetailModel.Save.Request) } public protocol EditableDetailDataStore: AnyObject { var todoID: Int { get set } var todo: Todo? { get } } final class EditableDetailInteractor: EditableDetailInteractorLogic, EditableDetailDataStore { struct Dependency { let todoCachedRepository: TodoCachedRepository let presenter: EditableDetailPresenterLogic } var todoID: Int = -1 private let dependency: Dependency internal var todo: Todo? init(dependency: Dependency) { self.dependency = dependency } func load(_ request: EditableDetailModel.Load.Request) { guard let todo = self.dependency.todoCachedRepository.todo(id: self.todoID) else { return } self.todo = todo self.dependency.presenter.load( EditableDetailModel.Load.Response( todo: todo ) ) } func save(_ request: EditableDetailModel.Save.Request) { self.todo?.title = request.title self.todo?.description = request.description guard let savedTodo = self.todo else { return } self.dependency.todoCachedRepository.update(savedTodo) } } <file_sep>/Projects/DodiDetail/Sources/DetailComponent.swift // // Assembly.swift // DodiDetail // // Created by Geektree0101 on 2021/08/13. // import Foundation import NeedleFoundation import DodiRepository public protocol DetailDependency: Dependency { var repositoryBuilder: RepositoryBuilder { get } } public protocol DetailBuilder { var editableDetailViewController: EditableDetailViewController { get } } public class DetailComponent: Component<DetailDependency>, DetailBuilder { public var editableDetailViewController: EditableDetailViewController { return EditableDetailViewController( dependency: EditableDetailViewController.Dependency( todoCachedRepository: self.repositoryBuilder.todoCachedRepository ) ) } } <file_sep>/Projects/Dodi/Sources/NeedleGenerated.swift import DodiDetail import DodiList import DodiRepository import Foundation import NeedleFoundation // swiftlint:disable unused_declaration private let needleDependenciesHash : String? = nil // MARK: - Registration public func registerProviderFactories() { __DependencyProviderRegistry.instance.registerDependencyProviderFactory(for: "^->RootComponent") { component in return EmptyDependencyProvider(component: component) } __DependencyProviderRegistry.instance.registerDependencyProviderFactory(for: "^->RootComponent->ListComponent") { component in return ListDependency9c2f5b85fb6808210ea1Provider(component: component) } __DependencyProviderRegistry.instance.registerDependencyProviderFactory(for: "^->RootComponent->DetailComponent") { component in return DetailDependencyb171f3bdca6113e7a5d9Provider(component: component) } __DependencyProviderRegistry.instance.registerDependencyProviderFactory(for: "^->RootComponent->RepositoryComponent") { component in return RepositoryDependency7488f146cdfa18e51394Provider(component: component) } } // MARK: - Providers private class ListDependency9c2f5b85fb6808210ea1BaseProvider: ListDependency { var repositoryBuilder: RepositoryBuilder { return rootComponent.repositoryBuilder } var detailBuilder: DetailBuilder { return rootComponent.detailBuilder } private let rootComponent: RootComponent init(rootComponent: RootComponent) { self.rootComponent = rootComponent } } /// ^->RootComponent->ListComponent private class ListDependency9c2f5b85fb6808210ea1Provider: ListDependency9c2f5b85fb6808210ea1BaseProvider { init(component: NeedleFoundation.Scope) { super.init(rootComponent: component.parent as! RootComponent) } } private class DetailDependencyb171f3bdca6113e7a5d9BaseProvider: DetailDependency { var repositoryBuilder: RepositoryBuilder { return rootComponent.repositoryBuilder } private let rootComponent: RootComponent init(rootComponent: RootComponent) { self.rootComponent = rootComponent } } /// ^->RootComponent->DetailComponent private class DetailDependencyb171f3bdca6113e7a5d9Provider: DetailDependencyb171f3bdca6113e7a5d9BaseProvider { init(component: NeedleFoundation.Scope) { super.init(rootComponent: component.parent as! RootComponent) } } private class RepositoryDependency7488f146cdfa18e51394BaseProvider: RepositoryDependency { var userDefaults: UserDefaults { return rootComponent.userDefaults } private let rootComponent: RootComponent init(rootComponent: RootComponent) { self.rootComponent = rootComponent } } /// ^->RootComponent->RepositoryComponent private class RepositoryDependency7488f146cdfa18e51394Provider: RepositoryDependency7488f146cdfa18e51394BaseProvider { init(component: NeedleFoundation.Scope) { super.init(rootComponent: component.parent as! RootComponent) } } <file_sep>/Projects/DodiDetail/Tests/UserDetail/UserDetailInteractorTests.swift // // UserDetailInteractorTests.swift // DodiDetailTests // // Created by clean-swift-scaffold on 18/8/2021. // Copyright © 2021 Geektree0101. All rights reserved. // import XCTest @testable import DodiDetail final class UserDetailInteractorTests: XCTestCase { final class UserDetailPresenterSpy: UserDetailPresentationLogic { var presentLoadResponse: UserDetailModel.Load.Response? func presentLoad(response: UserDetailModel.Load.Response) { self.presentLoadResponse = response } var presentDeleteResponse: UserDetailModel.Delete.Response? func presentDelete(response: UserDetailModel.Delete.Response) { self.presentDeleteResponse = response } } // MARK: - Properties var presenter: UserDetailPresenterSpy! var interactor = UserDetailInteractor! override func setUp() { self.presenter = UserDetailPresenterSpy() self.interactor = UserDetailInteractor() self.interactor.presenter = self.presenter } } // MARK: - TODO TestName (BDD) extension UserDetailInteractorTests { func test_doSomething() { // given // when // then } }<file_sep>/Projects/DodiUI/Sources/Views/CardNode.swift // // CardNode.swift // DodiUI // // Created by Geektree0101 on 2021/08/12. // import AsyncDisplayKit import BonMot import DeepDiff import Then public final class CardCellNode: ASCellNode { public struct ViewModel: DiffAware { public typealias DiffId = Int public var diffId: DiffId { return self.id } public let id: Int public let title: String public let description: String public init(id: Int, title: String, description: String) { self.id = id self.title = title self.description = description } public static func compareContent(_ a: CardCellNode.ViewModel, _ b: CardCellNode.ViewModel) -> Bool { return a.title == b.title && a.description == b.description } } public struct CardStyle { public let margin: UIEdgeInsets public let padding: UIEdgeInsets public init(margin: UIEdgeInsets, padding: UIEdgeInsets) { self.margin = margin self.padding = padding } } private enum Typo { static let title = StringStyle( .font(UIFont.boldSystemFont(ofSize: 24.0)), .color(UIColor.black) ) static let desc = StringStyle( .font(UIFont.systemFont(ofSize: 16.0)), .color(UIColor.darkGray) ) } private let titleNode = ASTextNode() private let descriptionNode = ASTextNode() private let backgroundNode = ASDisplayNode().then { $0.backgroundColor = UIColor.white $0.shadowColor = UIColor.black.cgColor $0.shadowOffset = CGSize(width: 0.0, height: 2.0) $0.shadowRadius = 4.0 $0.shadowOpacity = 0.5 } private let cardStyle: CardStyle public init(_ viewModel: ViewModel, style cardStyle: CardStyle) { self.cardStyle = cardStyle super.init() self.automaticallyManagesSubnodes = true self.render(viewModel) } public override func layout() { super.layout() self.backgroundNode.cornerRadius = 8.0 } public override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASInsetLayoutSpec( insets: self.cardStyle.margin, child: ASBackgroundLayoutSpec( child: ASInsetLayoutSpec( insets: self.cardStyle.padding, child: ASStackLayoutSpec( direction: .vertical, spacing: 8.0, justifyContent: .start, alignItems: .start, children: [ self.titleNode.styled { $0.flexShrink = 1.0 }, self.descriptionNode.styled { $0.flexShrink = 1.0 } ] ).styled { $0.minHeight = ASDimensionMake(120.0) } ), background: self.backgroundNode ) ) } public func render(_ viewModel: ViewModel) { self.titleNode.attributedText = viewModel.title .styled(with: Typo.title) self.descriptionNode.attributedText = viewModel.description .styled(with: Typo.desc) self.updateAccessibility() } private func updateAccessibility() { self.accessibilityElements = [ self.titleNode, self.descriptionNode ] } } <file_sep>/Projects/DodiUI/Sources/Extensions/Dictionary+Extension.swift // // Dictionary+Extension.swift // DodiUI // // Created by Geektree0101 on 2021/08/13. // import Foundation extension Dictionary where Key == NSAttributedString.Key, Value == Any { public var toStringWithAny: [String: Any] { return self.reduce([:], { result, item -> [String: Any] in var mutableResult: [String: Any] = result mutableResult[item.key.rawValue] = item.value return mutableResult }) } } <file_sep>/Projects/DodiUI/Tests/DodiUITests.swift import Foundation import XCTest final class DodiUITests: XCTestCase { func test_example() { XCTAssertEqual("DodiUI", "DodiUI") } }
55ec9bf301ecc5b3a7d6cdbbd9308fa80770aecb
[ "Ruby", "Swift", "Markdown", "Go", "Go Module" ]
45
Swift
minsOne/Dodi
fc7b3937d7d799b53c7f92a9aec07ee22700a55d
1586ed787eb96366653e1ea099237486b2c06602
refs/heads/master
<repo_name>clamiax/lazy-bash<file_sep>/lazy #!/bin/bash declare -g WEBROOT="$(pwd)" declare -g LOGFILE="/tmp/lazy.log" declare -gr CONTENT=0 declare -gr STATUSCODE=4 declare -gr FILE=5 declare -gr CRLF="$(printf '\r\n')" send() { local buf clen ctype status msg buf="$1" status=${2:-200} msg=${3:-OK} ctype="${4:-text/html; charset-utf-8}" clen=$(echo -n "$buf" |wc -c) printf "HTTP/1.1 %s %s\r\n" "$status" "$msg" printf "Content-Length: %s\r\n" "$clen" printf "Content-Type: %s\r\n" "$ctype" printf "Connection: close\r\n" printf "Date: %s\r\n" "$(date)" printf "Server: lazy/0.1\r\n" printf "\r\n" printf "%s" "$buf" } sendsc() { case $1 in 404) send "Not Found: ${header[Resource]}" 404 "Not Found";; *) send "Internal Server Error" 500 "Internal Server Error";; esac } serve() { header=$1 case "${header[Method]}" in HEAD) send "";; GET) ret="$(cd "$WEBROOT";. main)" rv=$? case $rv in $CONTENT) send "$ret";; $STATUSCODE) sendsc "$ret";; $FILE) ret="${WEBROOT}/${ret}" if [ ! -f "$ret" ]; then sendsc 404 break fi mime="$(mimetype "$ret" |cut -d: -f2 |tr -d ' ')" send "$(cat "$ret")" 200 "OK" "$mime" ;; esac ;; *) send "Server Error: unknown method ${header[Method]}." 500 "Internal Server Error";; esac } newreq() { local -A header local comp k v while read -r line; do if [ -z "${header[Method]}" ]; then header["Method"]="$(echo -n $line |cut -d' ' -f1)" header["Resource"]="$(echo -n $line |cut -d' ' -f2)" header["Http-Version"]="$(echo -n $(echo $line |cut -d' ' -f3) | cut -d'/' -f2)" continue fi if [ "$line" != "$CRLF" ]; then k="$(echo -n $line |cut -d: -f1)" v="$(echo -n $line |cut -d: -f2-)" header[$k]="$v" else serve "$header" header=() # reset fi done < "$1" } detecthost() { iface="$(ifconfig -s |cut -d' ' -f1 |grep -v 'Iface\|lo' |head -1)" host="$(ifconfig $iface |grep inet: |cut -d: -f2 |cut -d' ' -f1)" [ -z "$host" ] && host="localhost" echo -n "$host" } main() { local -r host="${1:-$(detecthost)}" local -r port="${2:-1234}" [ -n "$3" ] && WEBROOT=$3 if [ ! -d "$WEBROOT" ]; then echo "${0}: ${WEBROOT}: wrong path" exit -2 fi if [ ! -f "${WEBROOT}/main" ]; then echo "$0: ${WEBROOT}: missing main file" exit -3 fi netchan "$host" "$port" newreq "$LOGFILE" echo } # netchan is a simple script which open a bi-directional channel to allow # client-server communications. Protocol handling happen into a single function # which read the input data and is responsible to parse, understand and reply # by following the protocol rules. netchan_cleanup() { for FN in $@; do [ -e "$FN" ] && rm -f "$FN" done } # netchan <host> <port> [callback] [error log] netchan() { local -r host="$1" local -r port="$2" local -r callback="${3:-netchan_request}" local -r errlog="${4:-/dev/null}" local -r fifo="$(mktemp -u /tmp/netchan.fifo.XXXXX)" local -r pids="$(mktemp -u /tmp/netchan.pids.XXXXX)" trap "netchan_cleanup '$fifo' '$pids'" EXIT INT TERM HUP mkfifo -m 600 "$fifo" noreq="$(type -t "$callback" |grep -q function ;echo $?)" if [ "$noreq" -eq 1 ]; then echo "$0: ${callback}: no callback defined" exit 1 fi echo "Running on ${host}:${port}..." nc -kl "$host" $port \ 0< <(echo -n " $BASHPID " >> "$pids"; while : ; do $callback "$fifo" ; done) \ 1> >(echo -n " $BASHPID " >> "$pids"; while : ; do cat - > "$fifo" ; done) \ 2>> "$errlog" rv=$? if [ $rv -ne 0 -a $rv -ne 130 ]; then echo "$0: an error occurred." kill $(cat $pids) rm -f "$pids" exit 1 fi } main "$@" <file_sep>/Makefile PREFIX = /usr/local install: @echo installing executable file to ${DESTDIR}${PREFIX}/bin @mkdir -p ${DESTDIR}${PREFIX}/bin @cp -f lazy ${DESTDIR}${PREFIX}/bin @chmod 755 ${DESTDIR}${PREFIX}/bin/lazy @echo installing application file to ${DESTDIR}${PREFIX}/etc @mkdir -p ${DESTDIR}${PREFIX}/etc/lazy @cp -rf app ${DESTDIR}${PREFIX}/etc/lazy @chmod -R 755 ${DESTDIR}${PREFIX}/etc/lazy uninstall: @echo removing executable file from ${DESTDIR}${PREFIX}/bin @rm -f ${DESTDIR}${PREFIX}/bin/lazy @echo removing application file from ${DESTDIR}${PREFIX}/etc @rm -rf ${DESTDIR}${PREFIX}/etc/lazy <file_sep>/app/res/utils.js function collects(elems) { var len = elems.length, name, i, ret = {}; for(i = 0; i < len; ++i) { name = elems[i].getAttribute('name'); /* handle [] */ if(name.indexOf('[]') != -1) { name = name.replace('[]', ''); if(typeof ret[name] == 'undefined') ret[name] = []; ret[name].push(elems[i].value); } else ret[name] = elems[i].value; } return ret; } function serialize(obj, _name) { var i, pfx, str = []; if(!obj) return _name; if(obj.length && typeof obj[i] != 'string') { /* arrays */ for(i = 0; i < obj.length; ++i) { pfx = (_name ? _name+'['+i+']' : i); str.push(pfx+'='+obj[i]); } } else { /* objects */ for(i in obj) { pfx = (_name ? _name+'['+i+']' : i); if(typeof obj[i] == 'string' || typeof obj[i] == 'number') { if(obj[i].replace) str.push(pfx+'='+obj[i].replace(/&/g, '%26')); else str.push(pfx+'='+obj[i]); } else str.push(serialize(obj[i], (_name ? _name+'['+i+']' : i))); } } return str.join('&'); } function xhr(method, action, data, callback) { var r = new XMLHttpRequest(); r.onreadystatechange = function() { if(r.readyState == 4 && r.status == 200) callback(JSON.parse(r.responseText)); /* always expect JSON */ }; //r.overrideMimeType('text/plain; charset=x-user-defined'); switch(method.toUpperCase()) { case 'POST': r.open(method, action, true); r.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); data = serialize(data); break; case 'GET': if(data) { data = serialize(data); action += ((action.indexOf('?') == -1) ? '?' : '&')+data; data = null; } r.open(method, action, true); break; default: console.err(method+': method not supported'); return; } r.send(data); } <file_sep>/README.md Lazy - browser-based remote control interface ============================================= Lazy is a shell based non-standard web server which only implements the bare minimum to run commands on the local host through a web page. It aims to be the remote control bridge between my Linux box and my smartphone. Since it runs on a browser there's no need to install any app on the device. Status ====== I'm still playing around with design, it's likely that some refactoring may happen but the core should be more or less ready. Requirements ============ In order to run lazy-bash you need the bash shell and a Unix userland and, of course, the netcat program. Installation ============ To install lazy enter the following command (as root if needed): ``` # make install ``` Running ======= ``` $ cd <web-root> $ lazy ``` The lazy command will tell you on which host:port is listening so just point your browser there to get started. Note: you must be root in order to run lazy-bash on port 80. Alternatively, you can specify the webroot in the command line: ``` $ lazy "" "" <web-root> ``` The empty strings "" let lazy decide the address and port (respectively) to listen on. You may want to make an alias for the above command in your shell in order to only type "lazy". Configuration ============= The customization is done by editing the source code.
142bc9165fd945044f68481eccf929603f465512
[ "JavaScript", "Makefile", "Markdown", "Shell" ]
4
Shell
clamiax/lazy-bash
fb2a70a7ba7476cd8dd83c6d40ea2a5a0a42c35d
95a10d3effb151222b876a10ee8735d4e24d8e06
refs/heads/master
<file_sep># education Some programs for educational purposes written for my children <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- #run this program in a terminal with: python europe-geography.py --level 1 #tested on Ubuntu 16.04 import argparse import logging import os import random import re from random import randint class Tuple(object): def __init__(self, country, capital): self.country = country self.capital = capital def getCountry(self): return self.country def getCapital(self): return self.capital # Parse command line arguments argparser = argparse.ArgumentParser(description="Geografi för Tova och Erik.") argparser.add_argument("-l", "--level", required = True, dest = "level", help = "Svårighetsgrad, har ingen effekt ännu") args = argparser.parse_args() level = eval(args.level) print "Välkommen till Geografi Europa\n\r" def select(): print "Välj vad du vill träna på?" print "\t Tryck a för frågor typ: Vad heter huvudstaden i ...?" print "\t Tryck b för frågor typ: I vilket land är ... huvudstad?" print "\t Tryck c för blandat med båda typerna av frågor" return (raw_input()) csvDelimiter = ', ' pairs = [] with open("contries-capitals.txt") as f: for line in f: next = Tuple(line.split(csvDelimiter)[0], line.split(csvDelimiter)[1][:-1]) # :-1 deletes last character (CR or LF?) pairs.append(next); f.close() random.seed() level = eval(args.level) # currently not used typeOfQuestion = select() while True: if typeOfQuestion is "a": selector = 0 elif typeOfQuestion is "b": selector = 1 else: selector = randint(0, 1) if selector == 0: r = randint(0, len(pairs) - 1) print "\r\nVad heter huvudstaden i", pairs[r].getCountry(), "?", svar = raw_input() if svar == pairs[r].getCapital(): # Must use == to compare the values print "Rätt" else: print "Fel. Rätt svar är", pairs[r].getCapital() else: r = randint(0, len(pairs) - 1) print "\r\nI vilket land är", pairs[r].getCapital(), "huvudstad ?", svar = raw_input() if svar == pairs[r].getCountry(): # Must use == to compare the values print "Rätt" else: print "Fel. Rätt svar är", pairs[r].getCountry() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- #to know how to use this program do: python filename --help #tested on Ubuntu 16.04 import argparse import logging import os import random import time from random import randint class Tuple(object): def __init__(self, x, y): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def numInput(): while True: try: number = int(input()) return number break except: print "Du måste svara med ett tal" # Parse command line arguments argparser = argparse.ArgumentParser(description="Öva multiplikation.") argparser.add_argument("--start", required = True, dest = "start", help = "minsta faktor") argparser.add_argument("--stop", required = True, dest = "stop", help = "högsta faktor") args = argparser.parse_args() start = eval(args.start) stop = eval(args.stop) problems = [] nOfProblems = 0 for i in range(start, stop + 1): for j in range(start, stop + 1): next = Tuple (i, j) problems.append(next) nOfProblems = nOfProblems + 1 random.seed() nOfCorrectAnswers = 0 nOfAnswers = 0 startTime = time.time() while nOfProblems > 0: r = randint(0, nOfProblems - 1) factorX = int(problems[r].getX()) factorY = int(problems[r].getY()) correctAnswer = factorX * factorY print factorX, "*", factorY, "=", usersAnswer = numInput() nOfAnswers = nOfAnswers + 1 if usersAnswer == correctAnswer: nOfCorrectAnswers = nOfCorrectAnswers + 1; print "Rätt. Du har svarat rätt", nOfCorrectAnswers, "av", nOfAnswers, "gånger på", int(time.time() - startTime), "sekunder" else: print "Fel. Rätt svar är", correctAnswer problems.pop(r) nOfProblems = nOfProblems - 1 assert nOfProblems == 0, "FATAL: nOfProblems still not zero" <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- #run this program in a terminal with: python matteskola.py --level 1 #tested on Ubuntu 16.04 import argparse import logging import os import random import re import sys import time from random import randint class status(object): def __init__(self): self.nofCorrect = 0 self.nofFail = 0 def incrementNofCorrect(self): self.nofCorrect += 1 def incrementNofFail(self): self.nofFail += 1 def getNofCorrect(self): return self.nofCorrect def getNofFail(self): return self.nofFail def getTotal(self): return (self.nofCorrect + self.nofFail) def numInput(): while True: try: number = int(input()) return number break except: print "Du måste svara med ett tal" def select(): print "Välj vad du vill träna på:" print "\t Tryck a för addition" print "\t Tryck s för subtraktion" print "\t Tryck m för multiplikation" print "\t Tryck d för division" print "\t Tryck v för avrundning" print "\t Tryck b för blandat med alla räknesätten" return (raw_input()) def addition(): a = randint(0, 10*level) b = randint(0, 10*level) print "\r\n", a, "+", b,"=", svar = numInput() if (a + b) == svar: myStatus.incrementNofCorrect() print "Rätt. Du har svarat rätt", myStatus.getNofCorrect(), "av", myStatus.getTotal(), "gånger på", else: myStatus.incrementNofFail() print "Fel. Rätt svar är", a + b return svar def subtraktion(): a = randint(0, 10*level) b = randint(0, 10*level) if a < b: c = b b = a a = c print "\r\n", a, "-", b,"=", svar = numInput() if (a - b) == svar: myStatus.incrementNofCorrect() print "Rätt. Du har svarat rätt", myStatus.getNofCorrect(), "av", myStatus.getTotal(), "gånger på", else: myStatus.incrementNofFail() print "Fel. Rätt svar är", a - b return svar def multiplikation(): a = randint(2, 3*level) b = randint(2, 3*level) print "\r\n", a, "*", b,"=", svar = numInput() if (a * b) == svar: myStatus.incrementNofCorrect() print "Rätt. Du har svarat rätt", myStatus.getNofCorrect(), "av", myStatus.getTotal(), "gånger på", else: myStatus.incrementNofFail() print "Fel. Rätt svar är", a * b return svar def division(): a = randint(1, 3*level) b = randint(0, 3*level) print "\r\n", a * b, "/", a, "=", svar = numInput() if (b) == svar: myStatus.incrementNofCorrect() print "Rätt. Du har svarat rätt", myStatus.getNofCorrect(), "av", myStatus.getTotal(), "gånger på", else: myStatus.incrementNofFail() print "Fel. Rätt svar är", b return svar def approximation(): a = randint(1000, 9999) nofZeros = randint(1, 3) precision = 10 ** nofZeros b = ((a + precision / 2) // precision) * precision if nofZeros == 1: print "\r\nAvrunda", a, "till närmaste tiotal", elif nofZeros == 2: print "\r\nAvrunda", a, "till närmaste hundratal", else: print "\r\nAvrunda", a, "till närmaste tusental", svar = numInput() if (b) == svar: myStatus.incrementNofCorrect() print "Rätt. Du har svarat rätt", myStatus.getNofCorrect(), "av", myStatus.getTotal(), "gånger på", else: myStatus.incrementNofFail() print "Fel. Rätt svar är", b return svar # Parse command line arguments argparser = argparse.ArgumentParser(description="Matteskola för Tova och Erik.") argparser.add_argument("-l", "--level", required = True, dest = "level", help = "Svårighetsgrad (1 = lättast, ju högre desto svårare)") args = argparser.parse_args() level = eval(args.level) print "Välkommen till Eriks och Tovas matteskola\n\r" random.seed() myStatus = status() raknesatt = select() startTime = time.time() while True: valtRaknesatt = raknesatt if raknesatt is "b": listaMedRaknesatt = ["a", "s", "m", "d"] slumptal = randint(0, 3) valtRaknesatt = listaMedRaknesatt[slumptal] if valtRaknesatt is "a": retValue = addition() if valtRaknesatt is "s": retValue = subtraktion() if valtRaknesatt is "m": retValue = multiplikation() if valtRaknesatt is "d": retValue = division() if valtRaknesatt is "v": retValue = approximation() if retValue == -1: break currentTime = time.time() print int(currentTime - startTime), "sekunder" sys.exit(0) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- #run this program in a terminal with: python matteskola.py --level 1 #tested on Ubuntu 16.04 import argparse import logging import os import random import re from random import randint class WordTuple(object): def __init__(self, eng, swe): self.eng = eng self.swe = swe def getEng(self): return self.eng def getSwe(self): return self.swe # Parse command line arguments argparser = argparse.ArgumentParser(description="Ordkunskap engelska-svenska för Tova och Erik.") argparser.add_argument("-l", "--level", required = True, dest = "level", help = "Svårighetsgrad, har ingen effekt ännu") args = argparser.parse_args() level = eval(args.level) print "Välkommen till Ordkunskap engelska-svenska\n\r" def select(): print "Välj vad du vill träna på:" print "\t Tryck 1 för svenska till engelska" print "\t Tryck 2 för engelska till svenska" return (raw_input()) csvDelimiter = '\t' words = [] with open("eng-swe-dictionary.txt") as f: #TODO remove all capital letters in that file for line in f: next = WordTuple(line.split(csvDelimiter)[0], line.split(csvDelimiter)[1][:-1]) # :-1 deletes last character (CR or LF?) words.append(next); f.close() while True: r = randint(0, len(words) - 1) print "\r\nVad betyder", words[r].getEng(), "?", svar = raw_input() if svar == words[r].getSwe(): # Must use == to compare the values print "Rätt" else: print "Fel. Rätt svar är", words[r].getSwe()
855d8a64c2e0162413084af497ad3e4671009008
[ "Markdown", "Python" ]
5
Markdown
tobiasmelin71/education
80feee550f5976c52774a3d773b1e957f6d48301
632e86dc8f51e2e280376077ac0e6defeb36a244
refs/heads/master
<file_sep>//arrays to hold values for the dynamic programming algorithms var alphaToParent = []; var alphaFromParent = []; var betaToParent = []; var betaFromParent = []; var gammaToParent = []; var gammaFromParent = []; var parentId = []; //the current tree var riverNetwork; //json representing flow in and out and total network value var networkInfo; var totalNetworkValue; //True if UI is displaying flow in valuse var showFlowIn = true; //UI data var svg; var radius; var data; //for total network value calculation var parentForCalc = "a"; var childForCalc = "b"; //d3 tree json var root; /*****DATA TYPES*****/ /** Tree class Each tree has a number of nodes, a list of nodes (of type node), and a 2-D array of the probability of a fish swimming from one node to another (probability of passing a barrier) */ function Tree(numNodes, nodeList, nodeHash, edgeProbs, root){ //properties //number of nodes in the tree this.numNodes = numNodes; //list of nodes in the tree (of type Node) this.nodeList = nodeList; this.nodeHash = nodeHash; this.root = root; //2-D array of the different edge probabilities //edgeProbs[i] = [startNode, endNode, probability] //where i is some index, start node is the node where //the directed edge start, end node is the node where //the directed edge ends, and probability is between 0 and 1 this.edgeProbs = edgeProbs; //transform edgeProbs into a matrix this.newEdgeProbs = new Array(edgeProbs.length); this.createNewEdgeProbs = function(){ for(var i = 0; i < edgeProbs.length; i++){ this.newEdgeProbs[i] = new Array(edgeProbs.length); } for(var i = 0; i < edgeProbs.length; i++){ var first = edgeProbs[i][0]; var second = edgeProbs[i][1]; var third = edgeProbs[i][2]; this.newEdgeProbs[this.nodeHash[first].nodeId][this.nodeHash[second].nodeId] = third; } } this.createNewEdgeProbs(); /** get the node associated with a given id */ this.getNodeById = function(theId){ return nodeList[theId]; } /** get the node associated with a given label */ this.getNodeByLabel = function(theLabel){ return nodeHash[theLabel]; } /** get the node id associated with a given label */ this.getNodeIdByLabel = function(theLabel){ return nodeHash[theLabel].nodeId; } /** get the node label for the node based on the node id */ this.getNodeLabelById = function(theId){ return nodeList[theId].nodeLabel; } /** get the proability can go from idStart to idEnd */ this.getDirectedProbabilityByIds = function (idStart, idEnd){ return this.newEdgeProbs[idStart][idEnd]; } /** * update the correct edges given the barrier id * and values in each direction */ this.updateEdgeValues = function(id, upstream, downstream){ //user cannot change the values of the non-barrier edges if(id == -1){ return; } for(var i = 0; i < this.edgeProbs.length; i++){ if(edgeProbs[i][3] == id){ edgeProbs[i][2] = upstream; edgeProbs[i+1][2] = downstream; this.createNewEdgeProbs(); return; } } } /** * Get the id for the barrier that connects * idStart and idEnd */ this.getBarrierId = function(idStart, idEnd){ if(idStart==null || idEnd == null){ return; } for(var i = 0; i < this.edgeProbs.length; i++){ if(edgeProbs[i][0] == idStart && edgeProbs[i][1]==idEnd){ return edgeProbs[i][3]; } } } } /** Node class A node has an id, a value, coordinates for the location on the screen, and a list of neighbor ids */ function Node(theId, theLabel, val, coords, neighbors){ //properties //id of the node this.nodeId = theId; //label on the node this.nodeLabel = theLabel; //the value of the node this.val = val; //coordinates of the node (where it will be on the screen) this.coordinates = coords; //list of node labels that are the node's neighbors this.neighbors = neighbors; } /*****CREATE TREE*****/ /** This function reads in JSON data and creates a tree */ function readTree(){ //assign node ids 0 through numNodes-1 for the dynamic //calculation of the network values //create and array for all of the nodes in the tree var nodeList = []; var nodeHash = {}; var tempNode; //create the root of the tree var theRoot = new Node(data.numNodes - 1, data.nodeLabels[0], data.vals[0], data.coords[0], getNeighbors(data.probBtwNodes, data.nodeLabels[0])); nodeList[data.numNodes - 1] = theRoot; nodeHash[theRoot.nodeLabel] = theRoot; //create the other nodes of the tree for(var i = 1; i<data.nodeLabels.length; i++){ var neighbors = getNeighbors(data.probBtwNodes, data.nodeLabels[i]); var nodeId = i - 1; tempNode = new Node(nodeId, data.nodeLabels[i], data.vals[i], data.coords[i], neighbors); nodeHash[tempNode.nodeLabel] = tempNode; nodeList[nodeId] = tempNode; } //create the tree from the given data var theTree = new Tree(data.numNodes, nodeList, nodeHash, data.probBtwNodes, theRoot); //make sure the tree is valid var validTree = checkTree(theTree); if(validTree === "true"){ riverNetwork = theTree; computeNetworkValueGeneral(theTree); //create the new d3 tree root = JSON.parse(createD3Tree(null,riverNetwork.root)); } else{ //if the tree is not valid show an alert message window.alert(validTree); } } /** * create the d3 json representation of the current river network */ function createD3Tree(parent, node){ var neighbors = node.neighbors; var children = []; var numChildren = 0; for(var i = 0; i < neighbors.length; i++){ if(parent == null || neighbors[i] != parent.nodeLabel){ children[numChildren] = neighbors[i]; numChildren++; } } if(numChildren == 0){ return "{\"name\":\""+node.nodeLabel+"\", \"value\":" + node.val + ",\"flowInto\":" + getFlowInto(node.nodeLabel) +",\"flowOut\":" + getFlowOut(node.nodeLabel)+"}"; } else{ var json = "{\"name\":\""+node.nodeLabel+"\", \"value\":" + node.val + ",\"flowInto\":" + getFlowInto(node.nodeLabel) +",\"flowOut\":" + getFlowOut(node.nodeLabel) + ","; json += "\"children\":["; for(var i = 0; i<numChildren; i++){ json += createD3Tree(node, riverNetwork.getNodeByLabel(children[i])); if(i != numChildren-1){ json +=","; } } json += "]}"; } return json; } /** get the flow into value for the specified node from the network info */ function getFlowInto(nodeLabel){ var flowIntoArr = networkInfo.flowInto; for(var i = 0; i < flowIntoArr.length; i++){ if(flowIntoArr[i][0] == nodeLabel){ return flowIntoArr[i][1]; } } } /** get the flow out value for the specified node from the network info */ function getFlowOut(nodeLabel){ var flowOutArr = networkInfo.flowOut; for(var i = 0; i < flowOutArr.length; i++){ if(flowOutArr[i][0] == nodeLabel){ return flowOutArr[i][1]; } } } /** finds all the neighbors of a given node based on the data for the probability for moving between nodes */ function getNeighbors(probabilities, nodeLabel){ var neighbors = []; //loop through all of the probabilities and find //where the given nodeId is the first one listed //and store the nodes the given node is connected to for(var i = 0; i < probabilities.length; i++){ if(probabilities[i][0] === nodeLabel){ neighbors.push(probabilities[i][1]); } } return neighbors; } /** This function checks that the tree created by the given data is a legal tree (i.e. no loops, bidirected edges) */ function checkTree(tree){ //if odd number of probabilities the tree is not bidirected if(tree.edgeProbs.length%2 ===1){ return "The edges must be bidirected"; } //if any pair of nodes a b has a probability //from a to b it must have a probability from b to a //if not return false for(var i = 0; i < tree.edgeProbs.length; i++){ //the starting and ending nodes //whose reverse we are looking for var startNode = tree.edgeProbs[i][0]; var endNode = tree.edgeProbs[i][1]; var pairExists = false; //loop through all the probabilities and find //the set that goes the other way for(var j = 0; j < tree.edgeProbs.length; j++){ var otherStart = tree.edgeProbs[j][0]; var otherEnd = tree.edgeProbs[j][1]; //if we find the other direction the pair exists if(startNode === otherEnd && endNode === otherStart){ pairExists = true; } } //if the pair does not exist the tree is not valid if(!pairExists){ return "The edges must be bidirected"; } } //make sure numNodes is correct if(tree.numNodes != tree.nodeList.length){ return "numNodes must match the number of nodes in the nodeLabels array"; } //make sure every node has at least 1 neighbor for(var n = 0; n<tree.numNodes; n++){ if(tree.nodeList[n].neighbors.length===0){ return "Every node must have at least 1 neighbor"; } } //make sure all probabilities are between 0 and 1 for(var m = 0; m<tree.edgeProbs.length; m++){ if(tree.edgeProbs[m][2]>1 || tree.edgeProbs[m][2]<0){ window.alert("m is: " + m + " and node id is: " + tree.edgeProbs[m][3]); return "The edge probabilities must be between 0 and 1"; } } //make sure all nodes have coordinates for(var f = 0; f < tree.nodeList.length; f++){ if(tree.nodeList[f].coordinates === null || tree.nodeList[f].coordinates === undefined){ return "All nodes must have coordinates listed"; } } //check for loops //breadth first search should never see //the same node twice var visitedNodes = []; //queue holds an array of number pairs //the first number is the node id //the second is the id of the parent var queue = [ [tree.nodeList[0].nodeId, -2] ]; while(visitedNodes.length < tree.nodeList.length){ //get the first node in the queue var curNodeInfo = queue.pop(); var curNode = curNodeInfo[0]; var curNodeParent = curNodeInfo[1]; //mark this node as visited visitedNodes.push(curNode); //for all the neighbors of this node //check if any neighbors who are not the parent //of this node have already been visited //if a neighbor other than the parent has been visited //there is a cycle for(var l = 0; l < tree.getNodeById(curNode).neighbors.length; l++){ //get a neighbor of the node var curNeighbor = tree.getNodeIdByLabel(tree.getNodeById(curNode).neighbors[l]); //if the neighbor is not the parent and has been visited //the tree is not valid if(curNeighbor !== curNodeParent){ for(var p = 0; p < visitedNodes.length; p++){ if(curNeighbor === visitedNodes[p]){ return "There cannot be any cycles in the tree"; } } //if the node has not been visited add the neighbor //to the queue queue.push([curNeighbor, curNode]); } } } //if no cycles or 1 way edges are found //the tree is valid return "true"; } /*****COMPUTE ALPHA, BETA, GAMMA*****/ /** calculate the value of the river network based on the root */ function computeNetworkValueGeneral(tree){ computeNetworkValueGeneral_AlphaValues(tree); computeNetworkValueGeneral_BetaValues(tree); computeNetworkValueGeneral_GammaValues(tree); totalNetworkValue = computeTotalNetworkValue(tree, childForCalc, parentForCalc); networkInfo = JSON.parse(getNetworkInformation()); } function computeNetworkValueAtRoot(iId, iAlpha, iBeta, iGamma, childIds, childAlphas, childBetas, childGammas){ var root = riverNetwork.root; var networkValue = 0; var rootBeta = root.val; for(var i = 0; i<childIds.length; i++){ rootBeta += riverNetwork.getDirectedProbabilityByIds(root.nodeId, childIds[i])*childBetas[i]; } var rootAlpha = root.val; for(var i = 0; i<childIds.length; i++){ rootAlpha += riverNetwork.getDirectedProbabilityByIds(childIds[i], root.nodeId)*childAlphas[i]; } var rootGamma = root.val*rootBeta + root.val*rootAlpha - root.val*root.val; for(var i = 0; i<childIds.length; i++){ rootGamma += childGammas[i]; } networkValue += iGamma; networkValue += iAlpha*riverNetwork.getDirectedProbabilityByIds(iId, root.nodeId)*rootBeta; networkValue += iBeta* riverNetwork.getDirectedProbabilityByIds(root.nodeId, iId)*rootAlpha; networkValue += rootGamma; return networkValue; } /** compute the alpha values of the network */ function computeNetworkValueGeneral_AlphaValues(tree){ //calculate the alpha to parent values of the whole tree computeAlphaToParent(tree, tree.root, -1); //cut off the calculation alpha to parent of the root alphaToParent.length = tree.numNodes -1; //find the alpha values the root sends to each child computeAlphaFromParent(tree); //cut off the calculation alpha from parent of the root alphaFromParent.length = tree.numNodes - 1; } /** Compute values for the alpha to parent array starting at the node, and caluclating the values of all neighbors, excluding the parent */ function computeAlphaToParent(tree, node, parent){ parentId[node.nodeId] = parent.nodeId; //if the node is a leaf node return the node val if(node.neighbors.length === 1 && tree.getNodeIdByLabel(node.neighbors[0]) === parent.nodeId){ alphaToParent[node.nodeId] = node.val; } else{ //alpha value is the nodeValue //plus probability to traverse up tree //from each child times the alpha value //of the child alphaToParent[node.nodeId] = node.val; for(var i = 0; i < node.neighbors.length; i++){ if(tree.getNodeIdByLabel(node.neighbors[i]) !== parent.nodeId){ //recursively call the algorithm to calculate the alpha value //of the children computeAlphaToParent(tree, tree.getNodeByLabel(node.neighbors[i]), node); //get the child's alpha value alphaToParent[node.nodeId] += alphaToParent[tree.getNodeIdByLabel(node.neighbors[i])]* tree.getDirectedProbabilityByIds (tree.getNodeIdByLabel(node.neighbors[i]), node.nodeId); } } } } /** Compute the alpha values for the tree from the parent */ function computeAlphaFromParent(tree){ //loop through all children of the root for(var j = 0; j < tree.root.neighbors.length; j++){ //calculate the alpha from parent for all children of the root computeAlphaFromRoot(tree, tree.getNodeByLabel(tree.root.neighbors[j])); var curNode = tree.getNodeByLabel(tree.root.neighbors[j]); //loop through the children of the current node for(var m = 0; m < curNode.neighbors.length; m++){ if(curNode.neighbors[m]!= tree.root.nodeLabel){ //calculate the child's alpha value computeAlphaFromChildOfRoot(tree, tree.getNodeByLabel(curNode.neighbors[m]), curNode, tree.root); } } } } /** compute the alpha values going from the root to the given node */ function computeAlphaFromRoot(tree, node){ //the value from the root to each of it's children //plus the alpha value of every other child up to the root //times the probablilty from child to root alphaFromParent[node.nodeId] = tree.root.val; for(var i = 0; i < tree.root.neighbors.length; i++){ var curChild = tree.root.neighbors[i]; //if the current child is not the node we are getting the //alpha value to then add the alpha from that child //to the root if(curChild != node.nodeLabel){ var curChildIndex = tree.getNodeIdByLabel(curChild); alphaFromParent[node.nodeId] += alphaToParent[curChildIndex] *tree.getDirectedProbabilityByIds( curChildIndex, tree.root.nodeId); } } } /** compute the alpha values coming down the tree from the parent */ function computeAlphaFromChildOfRoot(tree, node, parent, grandparent){ //use the alphaFromParent value of the parent to calculate //the alpha value alphaFromParent[node.nodeId] = alphaFromParent[parent.nodeId] *tree.getDirectedProbabilityByIds(grandparent.nodeId, parent.nodeId) + parent.val; for(var j = 0; j < parent.neighbors.length; j++){ if(parent.neighbors[j] != node.nodeLabel && parent.neighbors[j] != grandparent.nodeLabel){ var curNodeId = tree.getNodeIdByLabel(parent.neighbors[j]); alphaFromParent[node.nodeId] += alphaToParent[curNodeId] * tree.getDirectedProbabilityByIds(curNodeId, parent.nodeId); } } //if it is a leaf node return if(node.neighbors.length === 1 && tree.getNodeIdByLabel(node.neighbors[0]) === parent.nodeId){ return; } //else recursively call the function for all neighbors //who are not the parent else{ for(var i = 0; i < node.neighbors.length; i++){ if(node.neighbors[i] != parent.nodeLabel){ computeAlphaFromChildOfRoot(tree, tree.getNodeByLabel(node.neighbors[i]), node, parent); } } } } /** compute the beta values of the network */ function computeNetworkValueGeneral_BetaValues(tree){ //find all beta values going from the leaf nodes up to the root computeBetaToParent(tree, tree.root, -1); //do not include root beta to parent value betaToParent.length = tree.numNodes -1; //find all beta values from parent computeBetaFromParent(tree); //do not include root beta from parent value betaFromParent.length = tree.numNodes - 1; } /** Calculate the beta values from child to parent of the network of the subtree, with the root of the subtree at the node */ function computeBetaToParent(tree, node, parent){ //if the node is a leaf node return the node val if(node.neighbors.length === 1 && tree.getNodeIdByLabel(node.neighbors[0]) === parent.nodeId){ betaToParent[node.nodeId] = node.val; } else{ //beta value is the nodeValue //plus probability to traverse down tree //to each child times the beta value //of the child betaToParent[node.nodeId] = node.val; for(var i = 0; i < node.neighbors.length; i++){ if(tree.getNodeIdByLabel(node.neighbors[i]) !== parent.nodeId){ //recursively call the algorithm to calculate the beta value //of the children computeBetaToParent(tree, tree.getNodeByLabel(node.neighbors[i]), node); //get the child's beta value betaToParent[node.nodeId] += betaToParent[tree.getNodeIdByLabel(node.neighbors[i])]* tree.getDirectedProbabilityByIds(node.nodeId, tree.getNodeIdByLabel(node.neighbors[i])); } } } } function computeBetaFromParent(tree){ //find the beta values the root sends to each child for(var j = 0; j < tree.root.neighbors.length; j++){ computeBetaFromRoot(tree, tree.getNodeByLabel(tree.root.neighbors[j])); var curNode = tree.getNodeByLabel(tree.root.neighbors[j]); for(var m = 0; m < curNode.neighbors.length; m++){ if(curNode.neighbors[m]!= tree.root.nodeLabel){ computeBetaFromChildOfRoot(tree, tree.getNodeByLabel(curNode.neighbors[m]), curNode, tree.root); } } } } /** compute the beta value from the root to each child */ function computeBetaFromRoot(tree, node){ //the value from the root to each of it's children //plus the beta value of every other child up to the root //times the probablilty from root to child betaFromParent[node.nodeId] = tree.root.val; for(var i = 0; i < tree.root.neighbors.length; i++){ var curChild = tree.root.neighbors[i]; //if the current child is not the node we are getting the //beta value to then add the beta from that child //to the root if(curChild != node.nodeLabel){ var curChildIndex = tree.getNodeIdByLabel(curChild); betaFromParent[node.nodeId] += betaToParent[curChildIndex] *tree.getDirectedProbabilityByIds( tree.root.nodeId,curChildIndex); } } } /** find the beta values from the parents to the children */ function computeBetaFromChildOfRoot(tree, node, parent, grandparent){ //use the betaFromParent value of the parent to calculate //the beta value betaFromParent[node.nodeId] = betaFromParent[parent.nodeId] *tree.getDirectedProbabilityByIds(parent.nodeId, grandparent.nodeId) + parent.val; for(var j = 0; j < parent.neighbors.length; j++){ if(parent.neighbors[j] != node.nodeLabel && parent.neighbors[j] != grandparent.nodeLabel){ var curNodeId = tree.getNodeIdByLabel(parent.neighbors[j]); betaFromParent[node.nodeId] += betaToParent[curNodeId] * tree.getDirectedProbabilityByIds(parent.nodeId, curNodeId); } } //if it is a leaf node return if(node.neighbors.length === 1 && tree.getNodeIdByLabel(node.neighbors[0]) === parent.nodeId){ return; } //else recursively call the function for all neighbors //who are not the parent else{ for(var i = 0; i < node.neighbors.length; i++){ if(node.neighbors[i] != parent.nodeLabel){ computeBetaFromChildOfRoot(tree, tree.getNodeByLabel(node.neighbors[i]), node, parent); } } } } /** Calculate the gamma values to and from the parent for each node */ function computeNetworkValueGeneral_GammaValues(tree){ //find all gamma values going from the leaf nodes up to the root computeGammaToParent(tree, tree.root, -1); //exclude the root value from the gamma array gammaToParent.length = tree.numNodes - 1; //compute gamma from parent values computeGammaFromParent(tree); //exclude gamma from parent for the root gammaFromParent.length = tree.numNodes - 1; } /** Compute the gamma value for the network using dynamic programming */ function computeGammaToParent(tree, node, parent){ //if the node is a leaf node return the node val if(node.neighbors.length === 1 && tree.getNodeIdByLabel(node.neighbors[0]) === parent.nodeId){ gammaToParent[node.nodeId] = node.val*node.val; } else{ //gamma is all the paths in the subtree where //node is the root, excluding the parent //This means gamma is the sum of: //alpha (all paths from within the tree to the root) //beta (all paths from the root down to another node) //paths from one node to another in the tree, passing //through the root //gamma of all subtrees (where the roots of those //trees are the children of the current root) gammaToParent[node.nodeId] = node.val * alphaToParent[node.nodeId]; gammaToParent[node.nodeId] += node.val * betaToParent[node.nodeId]; gammaToParent[node.nodeId] -= node.val * node.val; for(var i = 0; i < node.neighbors.length; i++){ if(tree.getNodeIdByLabel(node.neighbors[i]) !== parent.nodeId){ for(var j = 0; j< node.neighbors.length; j++){ if(i !== j && tree.getNodeIdByLabel(node.neighbors[j]) !== parent.nodeId){ //find the probability going from the ith to the jth subtree gammaToParent[node.nodeId] += alphaToParent[tree.getNodeIdByLabel(node.neighbors[i])] * tree.getDirectedProbabilityByIds( tree.getNodeIdByLabel(node.neighbors[i]), node.nodeId) * tree.getDirectedProbabilityByIds(node.nodeId, tree.getNodeIdByLabel(node.neighbors[j])) * betaToParent[tree.getNodeIdByLabel(node.neighbors[j])]; } } //find the gamma value of node i computeGammaToParent(tree, tree.getNodeByLabel(node.neighbors[i]), node); //gamma of this node depends on gamma of the children gammaToParent[node.nodeId] += gammaToParent[tree.getNodeIdByLabel(node.neighbors[i])]; } } } } function computeGammaFromParent(tree){ //find the gamma values the root sends to each child for(var j = 0; j < tree.root.neighbors.length; j++){ computeGammaFromRoot(tree, tree.getNodeByLabel(tree.root.neighbors[j])); var curNode = tree.getNodeByLabel(tree.root.neighbors[j]); for(var m = 0; m < curNode.neighbors.length; m++){ if(curNode.neighbors[m]!= tree.root.nodeLabel){ computeGammaFromChildOfRoot(tree, tree.getNodeByLabel(curNode.neighbors[m]), curNode, tree.root); } } } } /** Compute the gamma value from the root to each of the root's children */ function computeGammaFromRoot(tree, node){ //if the root only has 1 neighbor //then gammaFromRoot is the root value squared if(tree.root.neighbors.length === 1){ gammaFromParent[node.nodeId] = tree.root.val*tree.root.val; return; } gammaFromParent[node.nodeId] = 0; //loop through all children and find all paths from a node in //one subtree to a node in another for(var i = 0; i < tree.root.neighbors.length; i++){ var curChild = tree.root.neighbors[i]; //exclude node when calculating the gammaToRoot value if(curChild != node.nodeLabel){ var curChildIndex = tree.getNodeIdByLabel(curChild); //add the gammaToParent value for each neighbor gammaFromParent[node.nodeId] += gammaToParent[curChildIndex]; for(var j = 0; j < tree.root.neighbors.length; j++){ var secondChild = tree.root.neighbors[j]; //when calculating paths from one child of the root to another //make sure both children are unique if(i != j && secondChild != node.nodeLabel){ var secondChildIndex = tree.getNodeIdByLabel(secondChild); gammaFromParent[node.nodeId] += alphaToParent[curChildIndex]* tree.getDirectedProbabilityByIds(curChildIndex, tree.root.nodeId)* tree.getDirectedProbabilityByIds(tree.root.nodeId, secondChildIndex)* betaToParent[secondChildIndex]; } } } } //add the alphaFromRoot plus betaFromRoot for the given node //plus the root value squared gammaFromParent[node.nodeId] += tree.root.val * alphaFromParent[node.nodeId] + tree.root.val * betaFromParent[node.nodeId] - tree.root.val*tree.root.val; } /** compute the gamma value from the parent to the child node */ function computeGammaFromChildOfRoot(tree, node, parent, grandparent){ //use betaFromParent gammaFromParent[node.nodeId] = 0; //start in another child of parent and end in another child of the parent for(var j = 0; j < parent.neighbors.length; j++){ if(parent.neighbors[j] != node.nodeLabel && parent.neighbors[j] != grandparent.nodeLabel){ var curNodeId = tree.getNodeIdByLabel(parent.neighbors[j]); //add the gamma value of all subtrees rooted at the children //of parent (excluding node) gammaFromParent[node.nodeId] += gammaToParent[curNodeId]; //find the paths between all sets of children of parent //excluding paths into or out of node for(var k = 0; k <parent.neighbors.length; k++){ if(parent.neighbors[k] != node.nodeLabel && parent.neighbors[k] != grandparent.nodeLabel && j != k){ var secondNodeId = tree.getNodeIdByLabel(parent.neighbors[k]); gammaFromParent[node.nodeId] += alphaToParent[curNodeId]* tree.getDirectedProbabilityByIds(curNodeId, parent.nodeId)* tree.getDirectedProbabilityByIds(parent.nodeId, secondNodeId)* betaToParent[secondNodeId]; } } //start in a child of the parent an end in the grandparent gammaFromParent[node.nodeId] += alphaToParent[curNodeId]* tree.getDirectedProbabilityByIds(curNodeId, parent.nodeId)* tree.getDirectedProbabilityByIds(parent.nodeId, grandparent.nodeId)* betaFromParent[parent.nodeId]; //start in the grandparent and end in the grandparent gammaFromParent[node.nodeId] += alphaFromParent[parent.nodeId]* tree.getDirectedProbabilityByIds(grandparent.nodeId, parent.nodeId)* tree.getDirectedProbabilityByIds(parent.nodeId, curNodeId)* betaToParent[curNodeId]; } } //add the gamma value from the parent //parent value * beta from parent //parent value * alpha from parent //minus parent value * parent value gammaFromParent[node.nodeId] += gammaFromParent[parent.nodeId] - parent.val*parent.val + parent.val * betaFromParent[node.nodeId] + parent.val*alphaFromParent[node.nodeId]; //if node has no children return if(node.neighbors.length === 1 && tree.getNodeIdByLabel(node.neighbors[0]) === parent.nodeId){ return; } //recursively call the function to calculate gammaFromParent //for all nodes for(var i = 0; i < node.neighbors.length; i++){ if(node.neighbors[i] != parent.nodeLabel){ computeGammaFromChildOfRoot(tree, tree.getNodeByLabel(node.neighbors[i]), node, parent); } } } /** Calculate the total value of the river network given a pair of nodes. The pair must be a child and a parent and must be given in the correct order. No matter the child-parent pair the value of the network will be the same. The total value is printed to the screen then returned */ function computeTotalNetworkValue(tree, child, parent){ //find the probability from going from child to parent //and parent to child var childToParent = tree.getDirectedProbabilityByIds(tree.getNodeIdByLabel(child), tree.getNodeIdByLabel(parent)); var parentToChild = tree.getDirectedProbabilityByIds(tree.getNodeIdByLabel(parent), tree.getNodeIdByLabel(child)); //calculate the value of the network //gamma of each subtree //plus the paths starting in the child's subtree and ending //in the parent's subtree //plust the paths starting in the parent's subtree and ending //in the child's subtree var childID = tree.getNodeIdByLabel(child); var totalVal = gammaToParent[childID] + gammaFromParent[childID] + alphaToParent[childID]*childToParent*betaFromParent[childID] + alphaFromParent[childID]*parentToChild*betaToParent[childID]; return totalVal; } /********* UPDATE NETWORK **********/ /** return the new network value, a list of flow into values for each barrier, and a list of flow out value for each barrier */ function getNetworkInformation(){ var JSON = "{\"networkValue\": " + totalNetworkValue + ",\n\"flowInto\": ["; var rootFlowInto = riverNetwork.root.val; for(var i = 0; i < riverNetwork.root.neighbors.length; i++){ var curNode = riverNetwork.getNodeIdByLabel(riverNetwork.root.neighbors[i]); rootFlowInto += alphaToParent[curNode] * riverNetwork.getDirectedProbabilityByIds(curNode,riverNetwork.root.nodeId); } JSON+="[\"" + riverNetwork.root.nodeLabel + "\"," + rootFlowInto + "],"; for(var i = 0; i<riverNetwork.numNodes -1; i++){ var curAlphaVal = alphaToParent[i] + alphaFromParent[i]* riverNetwork.getDirectedProbabilityByIds(parentId[i],i); var curLabel = riverNetwork.getNodeLabelById(i); JSON+= "[\"" + curLabel + "\","+ curAlphaVal+"]"; if(i!=riverNetwork.numNodes -2){ JSON += ","; } } var rootFlowOut = riverNetwork.root.val; for(var i = 0; i < riverNetwork.root.neighbors.length; i++){ var curNode = riverNetwork.getNodeIdByLabel(riverNetwork.root.neighbors[i]); rootFlowOut += betaToParent[curNode] * riverNetwork.getDirectedProbabilityByIds(riverNetwork.root.nodeId, curNode); } JSON += "],\n\"flowOut\": ["; JSON +="[\"" + riverNetwork.root.nodeLabel + "\"," + rootFlowOut + "],"; for(var i = 0; i<riverNetwork.numNodes -1; i++){ var curBetaVal = betaToParent[i] + betaFromParent[i]* riverNetwork.getDirectedProbabilityByIds(i, parentId[i]); var curLabel = riverNetwork.getNodeLabelById(i); JSON+= "[\"" + curLabel + "\","+ curBetaVal+"]"; if(i!=riverNetwork.numNodes -2){ JSON += ","; } } JSON += "]}"; return JSON; } /*****UI FUNCTIONS*****/ /** Remove all elements of the tree from the canvas */ /** draw the tree and display the network values */ function drawUI(){ drawTree(); document.getElementById("totalnetworkval").textContent = "Total Network Value: " + totalNetworkValue; } /** This function creates a visual representation of the tree */ function drawTree(){ // Create the SVG element var width = 300; var height = 300; var margin = 40; svg = d3.select("h2").append("svg") .attr("width", width + 2*margin) .attr("height", height + 2*margin) .append("g") .attr("transform", "translate(" + margin + "," + margin + ")"); // Create the diagonal path generator var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); // Create the tree var tree = d3.layout.tree().size([height, width]); var nodes = tree.nodes(root); var links = tree.links(nodes); var layerOffset = 100; // Set y position of nodes based on their depth nodes.forEach(function(d) { d.y = d.depth * layerOffset; }); var edge = svg.selectAll(".edge") .data(links) .enter().append("line") .attr("class", "edge") .attr("x1", function(d) { return d.source.y; }) .attr("y1", function(d) { return d.source.x; }) .attr("x2", function(d) { return d.target.y; }) .attr("y2", function(d) { return d.target.x; }); var edgeLabel = svg.selectAll(".edgelabel") .data(links) .enter().append("text") .attr("class", "edgelabel") .attr("dx", function(d) { return (d.source.y + d.target.y)/2; }) .attr("dy", function(d) { return (d.source.x + d.target.x)/2; }) .attr("text-anchor", "middle") .text( function(d) { var source = riverNetwork.getNodeIdByLabel(d.source.name); var target = riverNetwork.getNodeIdByLabel(d.target.name); var upstream = riverNetwork.getDirectedProbabilityByIds(source, target); var downstream = riverNetwork.getDirectedProbabilityByIds(target, source); return "\u2191 " + upstream + " \u2193 " + downstream ; } ) .on("click", click); // Create nodes as svg groups var node = svg.selectAll(".node") .data(nodes) .enter().append("g") .attr("class", "node") .attr("id", "name") .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }) .on("mouseover", mouseoverNode) .on("mouseout", mouseoutNode); radius = 10; if(showFlowIn){ // Add circle to svg group for each node node.append("circle") .style("fill", nodeColorIn) .attr("r", radius); } else{ // Add circle to svg group for each node node.append("circle") .style("fill", nodeColorOut) .attr("r", radius); } // Add text to svg group for each node node.append("text") .attr("dy", -1.4*radius) .attr("text-anchor", "middle") .text(function(d) { return d.name; }); } /** * prompt user for updated edge values when they click on an edge */ function click(d) { var source = riverNetwork.getNodeIdByLabel(d.source.name); var target = riverNetwork.getNodeIdByLabel(d.target.name); var upstream = riverNetwork.getDirectedProbabilityByIds(source, target); var downstream = riverNetwork.getDirectedProbabilityByIds(target, source); var newUpstreamVal = prompt("Please enter the new upstream value", upstream); var newDownstreamVal = prompt("Please enter the new downstream value", downstream); riverNetwork.updateEdgeValues(riverNetwork.getBarrierId(d.source.name, d.target.name), newUpstreamVal, newDownstreamVal); computeNetworkValueGeneral(riverNetwork); updateRoot(); d3.select("svg").remove(); drawUI(); } /** update the d3 json tree */ function updateRoot(){ root = JSON.parse(createD3Tree(null,riverNetwork.root)); } /** display the flow in or flow out value of the node the user is mousing over */ function mouseoverNode(d){ var disVal; if(showFlowIn){ disVal = "Flow In Value: "+d.flowInto; } else{ disVal = "Flow Out Value: "+d.flowOut; } document.getElementById("nodeval").textContent = disVal; } /** stop displaying node info when mouse exits node */ function mouseoutNode(d){ document.getElementById("nodeval").textContent = "Mouse Over Node To See Flow Value"; } /** choose the color of the node based on the flowIn value */ function nodeColorIn(d){ return chooseColor(d.flowInto); } /** choose the color of the node based on the flowOut value */ function nodeColorOut(d){ return chooseColor(d.flowOut); } /** Choose the color based on the given number */ function chooseColor(num){ if(num < 2){ return "#ff0000"; } else if(num < 4){ return "#ffa500"; } else if(num < 6){ return "#ffff00"; } else if(num < 8){ return "#008000"; } else if(num < 10){ return "#0000ff"; } else{ return "#ee82ee"; } } /** when the user chooses to change from flow in to flow out or vice versa update the node colors */ function changeColor(){ if(showFlowIn){ var node = svg.selectAll(".node") .append("circle") .attr("r", radius) .style("fill", nodeColorOut); document.getElementById("colorbutton").value = "Display Flow In"; document.getElementById("flowInfo").textContent = "Displaying flow out values." } else{ var node = svg.selectAll(".node") .append("circle") .attr("r", radius) .style("fill", nodeColorIn); document.getElementById("colorbutton").value = "Display Flow Out"; document.getElementById("flowInfo").textContent = "Displaying flow in values." } showFlowIn = !showFlowIn; } /** change the displayed tree to tree one */ function setTreeOne(){ data = tree_one; readTree(); d3.select("svg").remove(); drawUI(); } /** change the displayed tree to tree two */ function setTreeTwo(){ data = tree_two; readTree(); d3.select("svg").remove(); drawUI(); } /** change the displayed tree to tree three */ function setTreeThree(){ data = tree_three; readTree(); d3.select("svg").remove(); drawUI(); }
e4b0cd7d2ed33d26a3bdd9f2d2850f43a80ef1c4
[ "JavaScript" ]
1
JavaScript
sread94/RiverExplorer
2bc2ecdff571737c2b01e1d49b95f4c194de0db5
77e5cb164f47658323715c72fb25b733a5db43b5
refs/heads/master
<repo_name>BlueTriangleMarketing/BlueTriangleSDK-iOS<file_sep>/Example/Podfile use_frameworks! platform :ios, '8.0' target 'BlueTriangleSDK-iOS_Example' do pod 'BlueTriangleSDK-iOS', :path => '../' target 'BlueTriangleSDK-iOS_Tests' do inherit! :search_paths end end <file_sep>/README.md # BlueTriangleSDK-iOS ## Deprecated Please use the following updated Swift version of the Blue Triangle SDK for iOS: https://github.com/blue-triangle-tech/btt-swift-sdk
1cc14ff1c5237f4bb4391e7e8010ac09d9d4eeb2
[ "Markdown", "Ruby" ]
2
Ruby
BlueTriangleMarketing/BlueTriangleSDK-iOS
a962286e562e5f26e0e6c105600a2cc96ced53da
6517cf84db17088b36df68667d1ca45ae87ac908
refs/heads/master
<file_sep># Weekend To-Do List ## Set-Up - set up database in Postico per database.sql: run => "postgresql weekend-to-do-app > database.sql" in terminal - run npm install ## Objective - Create a to-do list web app with the ability to add new tasks, as well as mark them complete to view in different sector. - items in accomplished tasks sector will be able to be removed! ## Technologies - JQuery - Node - Express - SQL ## Credit Thank you Prime Staff and Students, as this project would not be made possible without your guidance and passion. <file_sep>DROP TABLE "todo-list"; CREATE TABLE "todo-list" ( "id" serial PRIMARY KEY, "task" varchar(75) NOT NULL, "done" BOOLEAN DEFAULT FALSE ); -- Populate DB INSERT INTO "todo-list"("task", "done") VALUES('take out the trash', 'FALSE') RETURNING "id", "task", "artist", "done"; SELECT * FROM "todo-list";
974f26363e451e4c29ad1c08097ce486f816b1d5
[ "Markdown", "SQL" ]
2
Markdown
cback97/Weekend-To-Do-List
b0db078b02daf20fce25b106a8c348d4f4ce1402
8e8f7938cb93caf7f600d323998eca9d770be0a7
refs/heads/master
<repo_name>wacatswh/SDI_Coursework<file_sep>/source/main.cpp #include "../header/Logger.h" #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { Logger logObj; logObj.log(3, "Logger object created.", __LINE__); cout << "Enter the word for other player to guess" << endl; logObj.log(0, "Program prompts player to enter word for other player to guess", __LINE__); string word; do { getline(cin, word); if (word == "") logObj.log(1, "Player did not enter anything", __LINE__); } while (word.empty() || all_of(word.begin(), word.end(), isspace)); logObj.log(0, "Player entered the word", __LINE__); string copy = word; string Underscore; for (int i = 0; i != word.length(); i++) { if (word.at(i) == ' ') { Underscore += " "; } else { Underscore += "_"; } } for (int i = 0; i != 50; ++i) { cout << endl; } string guess; int wrong = 0; logObj.log(2, "Before entering the game while loop", __LINE__); while (1) { if (wrong == 6) { cout << "You Lose! The word was: " << word << endl; logObj.log(3, "Player has lost the game!", __LINE__); break; } cout << Underscore << endl; cout << "There are " << word.length() << " letters with spaces" << endl; logObj.log(0, "Remind the user on how many more letters with spaces", __LINE__); cout << "You have " << 6 - wrong << " more tries left" << endl; logObj.log(0, "Remind the user on the number of tries left", __LINE__); if (Underscore == word) { cout << "You win!" << endl; logObj.log(3, "Player has won the game. Game will now quit.", __LINE__); break; } cout << "Guess a letter or a word" << endl; logObj.log(0, "Prompts for input of letter or word from player", __LINE__); getline(cin, guess); if (guess.length() > 1) { if (guess == word) { cout << "That's right, you win!" << endl; logObj.log(3, "Player has won the game. Game will now quit.", __LINE__); break; } else { cout << "wrong word " << endl; logObj.log(0, "Player has guessed wrongly.", __LINE__); wrong++; } } else if (copy.find(guess) != -1) { while (copy.find(guess) != -1) { Underscore.replace(copy.find(guess), 1, guess); copy.replace(copy.find(guess), 1, "_"); } } else { cout << "That's wrong" << endl; logObj.log(0, "Player has guessed wrongly.", __LINE__); wrong++; } cout << endl; } logObj.log(2, "Exited from the game while loop", __LINE__); logObj.printByType(0); // logObj.printAll(); logObj.showNumOfLogs(); logObj.writeFile("game.log"); // logObj.printFile("game.log"); logObj.stopLogger(); return 0; } /* Logger logObj; logObj.log(0, "log test info", __LINE__); logObj.log(1, "log test error", __LINE__); logObj.log(2, "log test debug", __LINE__); logObj.log(3, "log test warning", __LINE__); logObj.log(4, "log test default case in switch"); //logObj.printAll(); logObj.printByType(0); logObj.printByType(3); logObj.writeFile("hohohaha.log"); // Logger::printFile("hohohaha.log"); logObj.stopLogger(); system("pause"); return 0; */ <file_sep>/header/nodeType.h /* * nodeType.h * * Created on: 13/11/2016 * Author: dlynazmi */ #ifndef NODETYPE_H_ #define NODETYPE_H_ template<class Type> struct nodeType { Type info; nodeType<Type> *link; }; #endif /* NODETYPE_H_ */ <file_sep>/source/Logger.cpp #include "../header/Logger.h" #include <iostream> #include <string> #include <fstream> #include <chrono> #include <ctime> #include <sstream> using namespace std; Logger::Logger() { numOfLog = numOfInfoLog = numOfErrorLog = numOfDebugLog = 0; start = std::chrono::system_clock::now(); // start clock when Logger object is created } Logger::~Logger() { list.linkedListType::destroyList(); } void Logger::showNumOfLogs() { cout << "Total logs: " << numOfLog << endl; } void Logger::printAll() { list.linkedListType<string>::print(); } void Logger::printByType(const int i) { switch (i) { case 0: list.unorderedLinkedList::printLogType("INFO"); break; case 1: list.unorderedLinkedList::printLogType("ERROR"); break; case 2: list.unorderedLinkedList::printLogType("DEBUG"); break; case 3: list.unorderedLinkedList::printLogType("WARNING"); break; default: Logger::log(3, "Wrong parameter! Send valid logLevel 0 - 3 as parameter."); break; } } void Logger::log(const int logLevel, const string logMessage, const int lineNumber) { string temp, tempLineNumber; tempLineNumber = to_string(lineNumber); switch (logLevel) { // logLevel == 0 is info case 0: temp = "Line " + tempLineNumber + ": " + "[INFO] " + logMessage; list.unorderedLinkedList<string>::insertLast(temp); numOfLog++; break; // logLevel == 1 is error case 1: temp = "Line " + tempLineNumber + ": " + "[ERROR] " + logMessage; list.unorderedLinkedList<string>::insertLast(temp); numOfLog++; break; // logLevel == 2 is debug case 2: temp = "Line " + tempLineNumber + ": " + "[DEBUG] " + logMessage; list.unorderedLinkedList<string>::insertLast(temp); numOfLog++; break; // logLevel == 3 is warning case 3: temp = "Line " + tempLineNumber + ": " + "[WARNING] " + logMessage; list.unorderedLinkedList<string>::insertLast(temp); numOfLog++; break; default: Logger::log(3, "Wrong parameter! Send valid logLevel 0 - 3 as first parameter."); break; } } void Logger::writeFile(const string outputFileName) { list.unorderedLinkedList::writeFile(outputFileName); end = std::chrono::system_clock::now(); std::time_t end_time = std::chrono::system_clock::to_time_t(end); ofstream outFile; outFile.open(outputFileName, ios::app); outFile << "Total logs: " << numOfLog << "\n"; #pragma warning(disable : 4996) outFile << "Finished at " << std::ctime(&end_time) << "\n"; outFile.close(); } void Logger::printFile(const string inputFileName) { string s; ifstream inFile; inFile.open(inputFileName); if (!inFile) { cerr << "Unable to open file!" << endl; return; } while (getline(inFile, s, '\n')) { cout << s << endl; } inFile.close(); } void Logger::stopLogger() { end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); showNumOfLogs(); #pragma warning(disable : 4996) cout << "Finished at " << std::ctime(&end_time) << "Elapsed time: " << elapsed_seconds.count() << "s\n"; Logger::~Logger(); }<file_sep>/header/Logger.h #ifndef LOGGER_H_ #define LOGGER_H_ #include <iostream> #include <string> #include <fstream> #include <chrono> #include <ctime> #include "unorderedLinkedList.h" using namespace std; class Logger { public: Logger(); ~Logger(); void showNumOfLogs(); void stopLogger(); void printAll(); void printByType(const int i); void log(const int logLevel, const string logMessage, const int lineNumber = 0); void writeFile(const string outputFileName); static void printFile(const string inputFileName); private: int numOfLog, numOfInfoLog, numOfErrorLog, numOfDebugLog; unorderedLinkedList<string> list; std::chrono::time_point<std::chrono::system_clock> start, end; }; #endif /* LOGGER_H_ */
01d696882a098d4a5e1956a43160a7da9dbf2dd5
[ "C++" ]
4
C++
wacatswh/SDI_Coursework
5d75caa637577f3b863e0a55a76dea709d6dcbde
426d6fed267bf26fcdc77fb9215840df77293ed6
refs/heads/master
<file_sep># Usage examples ```bash cat stdin_example.com | docker run -i sdenel/https-analyzer [--dns-server 8.8.8.8] echo "google.com" | docker run -i sdenel/https-analyzer --dns-server 8.8.8.8 | tee output.json echo "google.com" | docker run -i sdenel/https-analyzer --dns-server dns-over-https | tee output.json ``` # TODO * extract HTML generation as a function * Extract certificate informations + link to crt.sh. See https://stackoverflow.com/a/7691293/1795027<file_sep>#!/usr/bin/env python3 import argparse import ipaddress import json import logging import os import re import ssl import subprocess import http.client import sys from copy import deepcopy from typing import List import requests from OpenSSL import crypto from OpenSSL.crypto import X509 from jinja2 import Template logging.getLogger().setLevel(logging.INFO) def components_to_str(components): s = '' for c in components: s += f'{c[0].decode()}={c[1].decode()}, ' return s.strip().strip(',') def get_response( ip_address: ipaddress.ip_address, hostname: str, port: int = 443, is_tls: bool = None ) -> (http.client.HTTPResponse, str): """ >>> get_response(dns_resolve('google.com'), 'google.com')[0].status 301 """ def get_proxy_host_port(proxy: str): """ >>> get_proxy_host_port('http://toto.com:3128') ('toto.com', 3128) """ proxy = proxy.strip('/') port = proxy.split(':')[-1] host = proxy.split('/')[-1].split(':')[0] # TODO check host validity assert port.isdigit(), port return host, int(port) def get_response_inner(http_connection: http.client.HTTPConnection) -> (http.client.HTTPResponse, str): http_connection.putrequest('GET', '/') http_connection.putheader('Host', hostname) http_connection.endheaders() if isinstance(http_connection, http.client.HTTPSConnection): pem_cert = ssl.DER_cert_to_PEM_cert(http_connection.sock.getpeercert(True)) x509_cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem_cert.encode()) else: x509_cert = None return http_connection.getresponse(), x509_cert if is_tls is None: is_tls = port % 1000 == 443 if is_tls: context: ssl.SSLContext = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE if 'HTTPS_PROXY' in os.environ: proxy_host, proxy_port = get_proxy_host_port(os.environ['HTTPS_PROXY']) conn = http.client.HTTPSConnection(proxy_host, proxy_port, context=context) conn.set_tunnel(str(ip_address), port=port) else: conn = http.client.HTTPSConnection(str(ip_address), port, context=context) else: if 'HTTP_PROXY' in os.environ: proxy_host, proxy_port = get_proxy_host_port(os.environ['HTTP_PROXY']) conn = http.client.HTTPConnection(proxy_host, proxy_port) conn.set_tunnel(str(ip_address), port=port) else: conn = http.client.HTTPConnection(str(ip_address), port) return get_response_inner(conn) def is_valid_hostname(hostname): """ Taken from https://stackoverflow.com/a/33214423/1795027 """ if hostname[-1] == ".": # strip exactly one dot from the right, if present hostname = hostname[:-1] if len(hostname) > 253: return False labels = hostname.split(".") # the TLD must be not all-numeric if re.match(r"[0-9]+$", labels[-1]): return False allowed = re.compile(r"(?!-)[a-z0-9-]{1,63}(?<!-)$", re.IGNORECASE) return all(allowed.match(label) for label in labels) def dns_resolve( hostname: str, dns_server: str = None ) -> ipaddress.ip_address: """ >>> ip = dns_resolve('www.akamai.com') >>> ip.is_private False >>> ip = dns_resolve('www.akamai.com', 'dns-over-https') >>> ip.is_private False """ if dns_server == 'dns-over-https': ret = requests.get(f'https://cloudflare-dns.com/dns-query?name={hostname}', headers={'accept': 'application/dns-json'}) answer = ret.json()['Answer'] type1_data = [a['data'] for a in answer if a['type'] == 1] assert len(type1_data) == 1 return ipaddress.ip_address(type1_data[0]) cmd = f"dig +short {hostname}" if dns_server: dns_server = dns_server.strip() assert is_valid_hostname(dns_server) or re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", dns_server), f"{dns_server} is not an IP not a hostname!" cmd += f" @{dns_server}" ip_as_str = subprocess.check_output(cmd, shell=True).strip().decode('utf-8').split('\n')[-1] return ipaddress.ip_address(ip_as_str) def get_certificate_san_domains(x509cert: X509) -> List[str]: """ From: https://stackoverflow.com/a/50894566/1795027 """ san = '' ext_count = x509cert.get_extension_count() for i in range(0, ext_count): ext = x509cert.get_extension(i) if 'subjectAltName' in str(ext.get_short_name()): san = ext.__str__() return [v.split(':')[1] for v in san.split(', ')] if __name__ == '__main__': # Parsing optional arguments parser = argparse.ArgumentParser() parser.add_argument("--dns-server", help="DNS server to use") args = parser.parse_args() if args.dns_server is not None: logging.info(f"Using DNS server: {args.dns_server}") sys.stderr.flush() # Parsing stdin stdin_lines = [l.split("#")[0].split(' ') for l in sys.stdin.readlines()] domains = [d.strip() for d in sum(stdin_lines, []) if len(d) > 0] print("{") for domain_idx, domain in enumerate(domains): logging.info(f"Parsing {domain}") assert is_valid_hostname(domain), f"{domain} is not a valid hostname!" ip = dns_resolve(domain, args.dns_server) http_response = get_response(ip, domain, 80) https_response = get_response(ip, domain, 443) r = { 'ip': str(ip), 'http': { 'status': http_response[0].status, 'headerLocation': http_response[0].getheader('location') }, 'https': { 'status': https_response[0].status, 'headerLocation': https_response[0].getheader('location'), 'certificate': { 'issuer': components_to_str(https_response[1].get_issuer().get_components()), 'subject': components_to_str(https_response[1].get_subject().get_components()), 'san_domains': get_certificate_san_domains(https_response[1]) # TODO: is domain is certif alternate names ? } } } sys.stdout.write(f'{"," if domain_idx > 0 else ""}"{domain}": ') print(json.dumps(r, sort_keys=True, indent=4, separators=(',', ': '))) print("}") <file_sep>FROM python:3.8-alpine RUN apk add bind-tools && \ pip install -U Jinja2 requests && \ apk add gcc musl-dev libffi-dev openssl-dev && \ pip install -U pyopenssl && \ apk del gcc musl-dev libffi-dev openssl-dev COPY / /opt/ WORKDIR /opt/ # Running unit tests RUN python3 -m doctest -v https-analyzer.py ENTRYPOINT ["/opt/https-analyzer.py"]
9443682754f7bf9ebdcd75bcb354bcd7d6870987
[ "Markdown", "Python", "Dockerfile" ]
3
Markdown
sdenel/https-analyzer
fbb2b37ad1d42ad7880ca056bbd98b452b319ee1
4b6bf4fbf62b430ab8b2d3a5956a0ff47f8d21c7
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using XBOXParty; namespace Board { public class BoardManager : MonoBehaviour { [SerializeField] private Image _logoImage; [SerializeField] private SpriteRenderer _boardImage; [SerializeField] private List<Sprite> _logoSprites; [SerializeField] private List<Sprite> _boardSprites; [SerializeField] private List<Node> _nodes; // Use this for initialization private void Awake() { int lastMinigame = GlobalGameManager.Instance.GetCurrentMinigameID(); if (lastMinigame == -1) lastMinigame = Random.Range(0, _logoSprites.Count); _logoImage.sprite = _logoSprites[lastMinigame]; _boardImage.sprite = _boardSprites[lastMinigame]; } public Node GetNode(int id) { if (id >= _nodes.Count) return null; return _nodes[id]; } public int GetNodeId(Node node) { for (int i = 0; i < _nodes.Count; ++i) { if (_nodes[i] == node) return i; } return -1; } } }
4a0201a8ea79a2197552b38b19b27ee23295c23d
[ "C#" ]
1
C#
stijndelaruelle/glupartygame
a292daef2625a2cb000967a087818ec8e9f83d05
e864ac697d832f36ffadd2f3c423b4a71926120c
refs/heads/master
<file_sep>(function (window, angular, undefined) { "use strict"; function logIn() { return { restrict: "A", template: "" + "<form ng-submit='logIn()'>" + "<input type='text' ng-model='username' required>" + "<input type='<PASSWORD>' ng-model='<PASSWORD>' required>" + "<button type='submit'>Submit</button>" + "</form>", scope: {}, controller: "LogInController" }; } function LogInController($scope, logInService) { $scope.username = null; $scope.password = <PASSWORD>; $scope.logIn = function logIn() { return logInService($scope.username, $scope.password); }; } angular.module("example-accounts") .directive("logIn", [logIn]) .controller("LogInController", ["$scope", "logInService", LogInController]); })(window, window.angular);<file_sep>(function (window, angular, undefined) { "use strict"; function signUp() { return { restrict: "A", template: "" + "<form ng-submit='signUp()'>" + "<input type='text' placeholder='username' ng-model='username' required>" + "<input type='text' placeholder='email' ng-model='email' required>" + "<input type='password' placeholder='<PASSWORD>' ng-model='password' required>" + "<button type='submit'>Submit</button>" + "</form>", scope: {}, controller: "SignUpController" }; } function SignUpController($scope, signUpService) { $scope.username = null; $scope.email = null; $scope.password = <PASSWORD>; $scope.signUp = function signUp() { return signUpService($scope.username, $scope.email, $scope.password); }; } angular.module("example-accounts") .directive("signUp", [signUp]) .controller("SignUpController", ["$scope", "signUpService", SignUpController]); })(window, window.angular);<file_sep>(function (window, angular, undefined) { "use strict"; function logOutService($http, $q, BASE_URL, AccountModel) { return function () { var deferred = $q.defer(); $http.post(BASE_URL + "accounts/log_out/").finally(function () { AccountModel.clear(); deferred.resolve(AccountModel); }); return deferred.promise; }; } angular.module("example-accounts") .factory("logOutService", ["$http", "$q", "BASE_URL", "AccountModel", logOutService]); })(window, window.angular);<file_sep>(function (window, angular, undefined) { "use strict"; function AccountModel($cookies, USER_COOKIE_KEY) { this.clear = function clear() { $cookies.remove(USER_COOKIE_KEY); }; this.getUser = function getUser() { var user = $cookies.get(USER_COOKIE_KEY); return angular.isUndefined(user) ? undefined : JSON.parse(user); }; this.hasUser = function hasUser() { var user = $cookies.get(USER_COOKIE_KEY); return angular.isDefined(user); }; this.update = function update(dict) { $cookies.put(USER_COOKIE_KEY, JSON.stringify(dict)); }; } angular.module("example-accounts") .constant("USER_COOKIE_KEY", "example.user") .service("AccountModel", ["$cookies", "USER_COOKIE_KEY", AccountModel]); })(window, window.angular);<file_sep>(function (window, angular, undefined) { "use strict"; angular.module("example-accounts", ["ngCookies"]); })(window, window.angular); (function (window, angular, undefined) { "use strict"; function AccountModel($cookies, USER_COOKIE_KEY) { this.clear = function clear() { $cookies.remove(USER_COOKIE_KEY); }; this.getUser = function getUser() { var user = $cookies.get(USER_COOKIE_KEY); return angular.isUndefined(user) ? undefined : JSON.parse(user); }; this.hasUser = function hasUser() { var user = $cookies.get(USER_COOKIE_KEY); return angular.isDefined(user); }; this.update = function update(dict) { $cookies.put(USER_COOKIE_KEY, JSON.stringify(dict)); }; } angular.module("example-accounts") .constant("USER_COOKIE_KEY", "example.user") .service("AccountModel", ["$cookies", "USER_COOKIE_KEY", AccountModel]); })(window, window.angular); (function (window, angular, undefined) { "use strict"; function logInService($http, $q, BASE_URL, AccountModel) { return function (username, password) { var deferred = $q.defer(); $http.post(BASE_URL + "accounts/log_in/", { username: username, password: <PASSWORD> }).then(function (response) { AccountModel.update(response.data); deferred.resolve(AccountModel); }, function (response) { deferred.reject(response.data); }); return deferred.promise; }; } angular.module("example-accounts") .factory("logInService", ["$http", "$q", "BASE_URL", "AccountModel", logInService]); })(window, window.angular); (function (window, angular, undefined) { "use strict"; function logOutService($http, $q, BASE_URL, AccountModel) { return function () { var deferred = $q.defer(); $http.post(BASE_URL + "accounts/log_out/").finally(function () { AccountModel.clear(); deferred.resolve(AccountModel); }); return deferred.promise; }; } angular.module("example-accounts") .factory("logOutService", ["$http", "$q", "BASE_URL", "AccountModel", logOutService]); })(window, window.angular); (function (window, angular, undefined) { "use strict"; function signUpService($http, $q, BASE_URL, AccountModel) { return function (username, email, password) { var deferred = $q.defer(); $http.post(BASE_URL + "accounts/sign_up/", { username: username, email: email, password: <PASSWORD> }).then(function (response) { AccountModel.update(response.data); deferred.resolve(AccountModel); }, function (response) { deferred.reject(response.data); }); return deferred.promise; }; } angular.module("example-accounts") .factory("signUpService", ["$http", "$q", "BASE_URL", "AccountModel", signUpService]); })(window, window.angular); (function (window, angular, undefined) { "use strict"; function logIn() { return { restrict: "A", template: "" + "<form ng-submit='logIn()'>" + "<input type='text' ng-model='username' required>" + "<input type='password' ng-model='password' required>" + "<button type='submit'>Submit</button>" + "</form>", scope: {}, controller: "LogInController" }; } function LogInController($scope, logInService) { $scope.username = null; $scope.password = <PASSWORD>; $scope.logIn = function logIn() { return logInService($scope.username, $scope.password); }; } angular.module("example-accounts") .directive("logIn", [logIn]) .controller("LogInController", ["$scope", "logInService", LogInController]); })(window, window.angular); (function (window, angular, undefined) { "use strict"; function logOut() { return { restrict: "A", template: "<button type='button' ng-click='logOut()'>Log out</button>", scope: {}, controller: "LogOutController" }; } function LogOutController($scope, logOutService) { $scope.logOut = function logOut() { return logOutService(); }; } angular.module("example-accounts") .directive("logOut", [logOut]) .controller("LogOutController", ["$scope", "logOutService", LogOutController]); })(window, window.angular); (function (window, angular, undefined) { "use strict"; function signUp() { return { restrict: "A", template: "" + "<form ng-submit='signUp()'>" + "<input type='text' placeholder='username' ng-model='username' required>" + "<input type='text' placeholder='email' ng-model='email' required>" + "<input type='<PASSWORD>' placeholder='<PASSWORD>' ng-model='<PASSWORD>' required>" + "<button type='submit'>Submit</button>" + "</form>", scope: {}, controller: "SignUpController" }; } function SignUpController($scope, signUpService) { $scope.username = null; $scope.email = null; $scope.password = <PASSWORD>; $scope.signUp = function signUp() { return signUpService($scope.username, $scope.email, $scope.password); }; } angular.module("example-accounts") .directive("signUp", [signUp]) .controller("SignUpController", ["$scope", "signUpService", SignUpController]); })(window, window.angular);<file_sep>(function (window, angular, undefined) { "use strict"; angular.module("example-accounts", ["ngCookies"]); })(window, window.angular);<file_sep>(function (window, angular, undefined) { "use strict"; function logOut() { return { restrict: "A", template: "<button type='button' ng-click='logOut()'>Log out</button>", scope: {}, controller: "LogOutController" }; } function LogOutController($scope, logOutService) { $scope.logOut = function logOut() { return logOutService(); }; } angular.module("example-accounts") .directive("logOut", [logOut]) .controller("LogOutController", ["$scope", "logOutService", LogOutController]); })(window, window.angular);
c70c9539c6b06f013d950abeddd76d4657d6fe08
[ "JavaScript" ]
7
JavaScript
ParentJA/example-accounts-angular
750999ef848b9de0a96004628658b1abe7f60068
f5c748b50d220cb15adc6ed2642b32930d3dbe72
refs/heads/main
<file_sep># demo springboot-demo <file_sep>spring.application.name=demo spring.cloud.nacos.discovery.server-addr=10.211.55.3:8848 spring.cloud.nacos.config.server-addr=10.211.55.3:8848 <file_sep>package org.example.enums; /** * Enum枚举的使用 * @author zhangchuan * @date 2020-09-09 */ public enum ColorEnum { /** * 定义枚举常量 */ REG("红色",1),GREEN("绿色",2); /** * 定义枚举常量参数值 */ private String name; private int index; /** * 获取枚举参数值 * @return */ public int index(){ return this.index; } /** * 实力话枚举参数值 * @param name * @param index */ private ColorEnum(String name, int index){ this.name=name; this.index=index; } 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; } }
9029bb9fb7427477e23dd8198d5c4713cacea887
[ "Markdown", "Java", "INI" ]
3
Markdown
zcIdea/demo
c9b218c7ecff48f07602777945f248cad6506356
349a6de103b22dd3973a8dd396ddd8a1f50a0a63
refs/heads/master
<repo_name>unnamed44/tera_2805<file_sep>/java/game/tera/gameserver/network/clientpackets/RequestServerCheck.java package tera.gameserver.network.clientpackets; import tera.gameserver.network.serverpackets.S_Visit_New_Section; /** * Пакет клиентский, для проверки сервера * * @author Ronn * @created 25.03.2012 */ public class RequestServerCheck extends ClientPacket { /** присылаемое значение */ private int[] vals; public RequestServerCheck() { this.vals = new int[3]; } @Override public boolean isSynchronized() { return false; } @Override public void readImpl() { vals[0] = readInt();//01 00 00 00 число 1 vals[1] = readInt();//01 00 00 00 число 2 vals[2] = readInt();//01 00 00 00 число 3 } @Override public void runImpl() { owner.sendPacket(S_Visit_New_Section.getInstance(vals), true); } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_User_Levelup.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, описыающий обновление уровня игрока. * * @author Ronn */ public class S_User_Levelup extends ServerPacket { private static final ServerPacket instance = new S_User_Levelup(); public static S_User_Levelup getInstance(Player player) { S_User_Levelup packet = (S_User_Levelup) instance.newInstance(); packet.objectId = player.getObjectId(); packet.subId = player.getSubId(); packet.level = player.getLevel(); return packet; } /** ид игрока */ private int objectId; /** под ид игрока */ private int subId; /** уровень игрока */ private int level; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_USER_LEVELUP; } @Override protected final void writeImpl() { writeOpcode(); writeInt(objectId); // наш ИД writeInt(subId); writeInt(level); // преобретаемый лвл } }<file_sep>/java/game/tera/gameserver/model/ai/npc/classes/PatrolAI.java package tera.gameserver.model.ai.npc.classes; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; /** * Базовая модель патрульного АИ. * * @author Ronn */ public class PatrolAI<T extends Npc> extends AbstractNpcAI<T> { /** список игроков, с которыми ведется диалог */ protected final Array<Player> dialogs; public PatrolAI(T actor, ConfigAI config) { super(actor, config); this.dialogs = Arrays.toConcurrentArray(Player.class); } @Override public void notifyStartDialog(Player player) { // TODO Автоматически созданная заглушка метода super.notifyStartDialog(player); } @Override public void notifyStopDialog(Player player) { // TODO Автоматически созданная заглушка метода super.notifyStopDialog(player); } } <file_sep>/java/game/tera/gameserver/IdFactory.java package tera.gameserver; import java.util.concurrent.ScheduledExecutorService; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.ExecutorManager; import rlib.database.ConnectFactory; import rlib.idfactory.IdGenerator; import rlib.idfactory.IdGenerators; import rlib.logging.Logger; import rlib.logging.Loggers; /** * Глобальная фабрика ид. * * @author Ronn */ public final class IdFactory { private static final Logger log = Loggers.getLogger(IdFactory.class); private static final String[][] itemTable = { {"items", "object_id"}, }; private static final String[][] playerTable = { {"characters", "object_id"}, }; private static final String[][] clanTable = { {"guilds", "id"}, }; private static IdFactory instance; public static IdFactory getInstance() { if(instance == null) instance = new IdFactory(); return instance; } /** фабрика ид для нпс */ private IdGenerator npcIds; /** фабрика ид для игроков */ private IdGenerator playerIds; /** фабрика ид для итемов */ private IdGenerator itemIds; /** фабрика ид для ресурсов */ private IdGenerator objectIds; /** фабрика ид для кланов */ private IdGenerator guildIds; /** фабрика ид для акшенов */ private IdGenerator actionIds; /** фабрика ид для выстрелов */ private IdGenerator shotIds; /** фабрика ид для квестов */ private IdGenerator questIds; /** фабрика ид для ловушек */ private IdGenerator trapIds; /** фабрика ид для ресурсов */ private IdGenerator resourseIds; public IdFactory() { // получаем менеджера БД DataBaseManager manager = DataBaseManager.getInstance(); // получаем фабрику подключений ConnectFactory connectFactory = manager.getConnectFactory(); // получаем исполнительного менеджера ExecutorManager executorManager = ExecutorManager.getInstance(); // получаем исполнителя заданий для фабрики ИД ScheduledExecutorService executor = executorManager.getIdFactoryExecutor(); log.info("prepare npc ids..."); npcIds = IdGenerators.newBitSetIdGeneratoe(connectFactory, executor, null); npcIds.prepare(); log.info("prepare objects ids..."); objectIds = IdGenerators.newBitSetIdGeneratoe(connectFactory, executor, null); objectIds.prepare(); log.info("prepare players ids..."); playerIds = IdGenerators.newBitSetIdGeneratoe(connectFactory, executor, playerTable); playerIds.prepare(); log.info("prepare guilds ids..."); guildIds = IdGenerators.newBitSetIdGeneratoe(connectFactory, executor, clanTable); guildIds.prepare(); log.info("prepare item ids..."); itemIds = IdGenerators.newBitSetIdGeneratoe(connectFactory, executor, itemTable); itemIds.prepare(); actionIds = IdGenerators.newSimpleIdGenerator(1, Integer.MAX_VALUE); shotIds = IdGenerators.newSimpleIdGenerator(1, Integer.MAX_VALUE); questIds = IdGenerators.newSimpleIdGenerator(1, Integer.MAX_VALUE); trapIds = IdGenerators.newSimpleIdGenerator(1, Integer.MAX_VALUE); resourseIds = IdGenerators.newSimpleIdGenerator(1, Integer.MAX_VALUE); } /** * @return новый ид для акшена. */ public final int getNextActionId() { return actionIds.getNextId(); } /** * @return новый ид для клана. */ public final int getNextGuildId() { return guildIds.getNextId(); } /** * @return новый ид для итема. */ public final int getNextItemId() { return itemIds.getNextId(); } /** * @return новый ид для нпс. */ public final int getNextNpcId() { return npcIds.getNextId(); } /** * @return новый ид для объекта. */ public final int getNextObjectId() { return objectIds.getNextId(); } /** * @return новый ид для игрока. */ public final int getNextPlayerId() { return playerIds.getNextId(); } /** * @return новый ид для квеста. */ public final int getNextQuestId() { return questIds.getNextId(); } /** * @return новый ид для ресурсов. */ public final int getNextResourseId() { return resourseIds.getNextId(); } /** * @return новый ид для выстрела. */ public final int getNextShotId() { return shotIds.getNextId(); } /** * @return новый ид для ловушки. */ public final int getNextTrapId() { return trapIds.getNextId(); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/PrepareManaHeal.java package tera.gameserver.model.skillengine.classes; import rlib.util.array.Array; import tera.gameserver.model.Character; import tera.gameserver.network.serverpackets.S_Action_Stage; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель скила восстанавливающего мп. * * @author Ronn */ public class PrepareManaHeal extends AbstractSkill { private int state; /** * @param template темплейт скила. */ public PrepareManaHeal(SkillTemplate template) { super(template); } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { super.startSkill(attacker, targetX, targetY, targetZ); state = template.getStartState(); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { if(state <= template.getEndState()) { character.broadcastPacket(S_Action_Stage.getInstance(character, getIconId(), castId, state++)); return; } // сила хила скила int power = getPower(); if(power < 1) return; // получаем локальные объекты LocalObjects local = LocalObjects.get(); Array<Character> targets = local.getNextCharList(); addTargets(targets, character, targetX, targetY, targetZ); Character[] array = targets.array(); for(int i = 0, length = targets.size(); i < length; i++) { Character target = array[i]; if(target.isDead() || target.isInvul() || target.isEvasioned()) continue; addEffects(character, target); // хилим таргет target.skillHealMp(getDamageId(), power, character); } } } <file_sep>/java/game/tera/gameserver/network/serverpackets/PlayerEquipment.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.Character; import tera.gameserver.model.equipment.Equipment; import tera.gameserver.model.equipment.SlotType; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, описывающий экиперовку игрока. * * @author Ronn */ public class PlayerEquipment extends ServerPacket { private static final ServerPacket instance = new PlayerEquipment(); public static PlayerEquipment getInstance(Character owner) { PlayerEquipment packet = (PlayerEquipment) instance.newInstance(); packet.objectId = owner.getObjectId(); packet.subId = owner.getSubId(); Equipment equipment = owner.getEquipment(); equipment.lock(); try { ItemInstance item = equipment.getItem(SlotType.SLOT_WEAPON); packet.weaponId = item == null ? 0 : item.getItemId(); packet.enchantLevel = item == null ? 0 : item.getEnchantLevel(); item = equipment.getItem(SlotType.SLOT_ARMOR); packet.armorId = item == null ? 0 : item.getItemId(); item = equipment.getItem(SlotType.SLOT_BOOTS); packet.bootsId = item == null ? 0 : item.getItemId(); item = equipment.getItem(SlotType.SLOT_GLOVES); packet.glovesId = item == null ? 0 : item.getItemId(); item = equipment.getItem(SlotType.SLOT_HAT); packet.hatId = item == null ? 0 : item.getItemId(); item = equipment.getItem(SlotType.SLOT_MASK); packet.maskId = item == null ? 0 : item.getItemId(); } finally { equipment.unlock(); } return packet; } /** обджект ид персонажа */ private int objectId; /** саб ид персонажа */ private int subId; /** ид оружия */ private int weaponId; /** ид армора */ private int armorId; /** ид ботинок */ private int bootsId; /** ид перчей */ private int glovesId; /** ид шапки */ private int hatId; /** ид маски */ private int maskId; /** уровень заточки */ private int enchantLevel; @Override public ServerPacketType getPacketType() { return ServerPacketType.PLAYER_EQUIPMENT; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, objectId); writeInt(buffer, subId); writeInt(buffer, weaponId); writeInt(buffer, armorId); writeInt(buffer, bootsId); writeInt(buffer, glovesId); writeInt(buffer, hatId); writeInt(buffer, maskId); writeInt(buffer, 0); writeInt(buffer, 0);// лифчик writeInt(buffer, 0); writeInt(buffer, 0); writeInt(buffer, 0); writeInt(buffer, 0); writeInt(buffer, 0); writeInt(buffer, 0); writeInt(buffer, enchantLevel);// точка ствола writeInt(buffer, 0); writeInt(buffer, 0); writeInt(buffer, 0); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Move_Inven_Pos.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Inven_Changedslot; /** * Клиентский пакет, указывающий какой итем хотим переместить в инвенторе * * @author Ronn */ public class C_Move_Inven_Pos extends ClientPacket { /** индекс старой ячейки */ private int oldcell; /** индекс новой ячейки */ private int newcell; /** игрок */ private Player player; @Override public void finalyze() { oldcell = 0; newcell = 0; player = null; } @Override public boolean isSynchronized() { return false; } @Override public void readImpl() { player = owner.getOwner(); readInt(); readInt(); oldcell = readInt() - 40; newcell = readInt() - 40; } @Override public void runImpl() { if(player == null) return; Inventory inventory = player.getInventory(); if(inventory == null) return; // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); inventory.lock(); try { Cell oldCell = inventory.getCell(oldcell); Cell newCell = inventory.getCell(newcell); if(oldCell == null || newCell == null) return; ItemInstance oldItem = newCell.getItem(); newCell.setItem(oldCell.getItem()); oldCell.setItem(oldItem); dbManager.updateLocationItem(oldCell.getItem()); dbManager.updateLocationItem(newCell.getItem()); } finally { inventory.unlock(); } eventManager.notifyInventoryChanged(player); player.sendPacket(S_Inven_Changedslot.getInstance(2, oldcell, newcell), true); } }<file_sep>/java/game/tera/gameserver/ServerThread.java package tera.gameserver; import tera.util.LocalObjects; /** * Модель серверного потока. * * @author Ronn */ public class ServerThread extends Thread { /** * @return текущий серверный поток. */ public static ServerThread currentThread() { return (ServerThread) Thread.currentThread(); } /** локальные объекты */ private final LocalObjects local; public ServerThread() { this.local = new LocalObjects(); } /** * @param group группа потоков. * @param target целевой таск. * @param name название опотка. */ public ServerThread(ThreadGroup group, Runnable target, String name) { super(group, target, name); this.local = new LocalObjects(); } /** * @return локальные объекты. */ public final LocalObjects getLocal() { return local; } } <file_sep>/java/game/tera/gameserver/model/ai/npc/thinkaction/DefaultReturnAction.java package tera.gameserver.model.ai.npc.thinkaction; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.model.NpcAIState; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.util.LocalObjects; /** * Базовая реализация генерации действий в режиме возвращения домой. * * @author Ronn */ public class DefaultReturnAction extends AbstractThinkAction { /** максимальная дистанция до спавн точки, после которой считается что НПс на месте */ protected final int distanceToSpawnLoc; /** дистанция при которой производить телепорт */ protected final int distanceToTeleport; public DefaultReturnAction(Node node) { super(node); VarTable vars = VarTable.newInstance(node); this.distanceToSpawnLoc = vars.getInteger("distanceToSpawnLoc", ConfigAI.DEFAULT_DISTANCE_TO_SPAWN_LOC); this.distanceToTeleport = vars.getInteger("distanceToTeleport", ConfigAI.DEFAULT_DISTANCE_TO_TELEPORT); } /** * @return дистанция от точки спавна, на которой считается что прибыл на место. */ public int getDistanceToSpawnLoc() { return distanceToSpawnLoc; } /** * @return дистанция при которой производить телепорт. */ public int getDistanceToTeleport() { return distanceToTeleport; } @Override public <A extends Npc> void think(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime) { // если нпс мертв if(actor.isDead()) { // очищаем задания ai.clearTaskList(); // очищаем агр лист actor.clearAggroList(); // переводим в режим ожидания ai.setNewState(NpcAIState.WAIT); // выходим return; } // получаем максимум хп int maxHp = actor.getMaxHp(); // если текущих хп НПс меньше максимума if(actor.getCurrentHp() < maxHp) { // восстанавливаем максимум actor.setCurrentHp(maxHp); // обновляем actor.updateHp(); } // если нпс щас что-то делает, выходим if(actor.isTurner() || actor.isCastingNow() || actor.isMoving() || actor.isStuned() || actor.isOwerturned()) return; // очищаем агро лист actor.clearAggroList(); // очищаем задания ai.clearTaskList(); // обнуляем дату очистки агр листа ai.setClearAggro(0); // если НПС уже на точке респа if(actor.isInRange(actor.getSpawnLoc(), getDistanceToSpawnLoc())) { // переключаемся в режим ожидания ai.setNewState(NpcAIState.WAIT); // выходим return; } // есть ли на очереди задания if(ai.isWaitingTask()) { // выполняем задание ai.doTask(actor, currentTime, local); // выходим return; } // добавляем новые задания ai.getCurrentFactory().addNewTask(ai, actor, local, config, currentTime); // если есть ожидающиеся задания if(ai.isWaitingTask()) // выполняем ai.doTask(actor, currentTime, local); } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionAddItem.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.Config; import tera.gameserver.manager.GameLogManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.network.serverpackets.S_Sytem_Message_Loot_Item; import tera.gameserver.tables.ItemTable; import tera.gameserver.templates.ItemTemplate; /** * Акшен для выдачи итема. * * @author Ronn */ public class ActionAddItem extends AbstractQuestAction { /** ид итема */ private int itemId; /** кол-во итемов */ private int itemCount; /** является ли это наградой */ private boolean reward; public ActionAddItem(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); try { VarTable vars = VarTable.newInstance(node); this.reward = vars.getBoolean("reward", false); this.itemId = vars.getInteger("id"); this.itemCount = (int) (vars.getInteger("count") * (isReward()? Config.SERVER_RATE_QUEST_REWARD : 1)); } catch(Exception e) { log.warning(this, e); throw new IllegalArgumentException(e); } } /** * @return ялвяется ли наградой. */ public boolean isReward() { return reward; } @Override public void apply(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // если игрока нет, выходим if(player == null) { log.warning(this, "not found player"); return; } // получаем инвентарь игрока Inventory inventory = player.getInventory(); // если его нет, выходим if(inventory == null) { log.warning(this, "not found inventory"); return; } // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); // получаем темплейт итема ItemTemplate template = itemTable.getItem(itemId); // если его нет, выходим if(template == null) { log.warning(this, "not found item for " + itemId); return; } int itemCount = getItemCount(); if(Config.ACCOUNT_PREMIUM_QUEST && player.hasPremium()) itemCount *= Config.ACCOUNT_PREMIUM_QUEST_RATE; if(!template.isStackable()) itemCount = 1; // добавляем итем if(!inventory.forceAddItem(itemId, itemCount, quest.getName())) return; // если это не деньги if(itemId != Inventory.MONEY_ITEM_ID) // отправляем пакет о выдачи итема player.sendPacket(S_Sytem_Message_Loot_Item.getInstance(player.getName(), itemId, itemCount), true); else PacketManager.showAddGold(player, itemCount); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем логер игровых событий GameLogManager gameLogger = GameLogManager.getInstance(); // записываем событие выдачи итема gameLogger.writeItemLog("Quest [id = " + quest.getId() + ", name = " + quest.getName() + "] added item [id = " + itemId + ", count = " + itemCount + ", name = " + template.getName() + "] to " + player.getName()); // обновляем инвентарь eventManager.notifyInventoryChanged(player); } /** * @return кол-во итемов. */ public int getItemCount() { return itemCount; } /** * @return ид итема. */ public int getItemId() { return itemId; } @Override public String toString() { return "AddItem itemId = " + itemId + ", itemCount = " + itemCount; } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/Link.java package tera.gameserver.model.npc.interaction; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.replyes.Reply; import tera.gameserver.model.playable.Player; /** * Модель ссылки в диалоге. * * @author Ronn */ public interface Link { /** * @return ид иконки. */ public int getIconId(); /** * @return уникальный ид линка. */ public int getId(); /** * @return название ссылки. */ public String getName(); /** * @return ответ на ссылку. */ public Reply getReply(); /** * @return тип ссылки. */ public LinkType getType(); /** * Обработка ответа на ссылку. * * @param npc нпс, у которого была нажата ссылка. * @param player игрок, который нажал на ссылку. */ public void reply(Npc npc, Player player); /** * @return нужно ли отображать ссылку игроку. */ public boolean test(Npc npc, Player player); } <file_sep>/java/game/tera/gameserver/model/ai/npc/taskfactory/DefaultBattleTaskFactory.java package tera.gameserver.model.ai.npc.taskfactory; import org.w3c.dom.Node; import rlib.geom.Angles; import rlib.util.Rnd; import rlib.util.VarTable; import rlib.util.array.Array; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.skillengine.OperateType; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.SkillGroup; import tera.gameserver.model.skillengine.SkillType; import tera.util.LocalObjects; /** * Дефолтная модель фабрики заданий в бою НПС. * * @author Ronn */ public class DefaultBattleTaskFactory extends AbstractTaskFactory { /** шансы каста скилов */ protected final int[] groupChance; /** шанс отправки сообщения */ protected final int shortRange; /** использовать ли быстрый поворот */ protected final boolean fastTurn; public DefaultBattleTaskFactory(Node node) { super(node); try { // парсим атрибуты VarTable vars = VarTable.newInstance(node); // получаем шанс групп скилов по умолчанию int def = vars.getInteger("groupChance", ConfigAI.DEFAULT_GROUP_CHANCE); // получаем список всех групп скилов SkillGroup[] groups = SkillGroup.values(); // парсим параметры vars = VarTable.newInstance(node, "set", "name", "val"); // создаем таблицу шансов групп скилов this.groupChance = new int[groups.length]; this.shortRange = vars.getInteger("shortRange", ConfigAI.DEFAULT_SHORT_RATE); this.fastTurn = vars.getBoolean("fastTurn", false); // заполняем таблицу for(int i = 0, length = groupChance.length; i < length; i++) groupChance[i] = vars.getInteger(groups[i].name(), def); } catch(Exception e) { throw new IllegalArgumentException(e); } } @Override public <A extends Npc> void addNewTask(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime) { // если выпал случай использования бафа if(chance(SkillGroup.HEAL)) { // получаем скил для хила Skill skill = actor.getRandomSkill(SkillGroup.HEAL); // если он есть и не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // если скил можно на себя юзать и не фул хп у себя if(!skill.isNoCaster() && actor.getCurrentHp() < actor.getMaxHp()) { // добавляем задание [bkmyenmcz ai.addCastTask(skill, actor); return; } // если скил не только на себя и есть фракция у НПС else if(!skill.isTargetSelf() && actor.getFractionRange() > 0) { // получаем фракцию НПС String fraction = actor.getFraction(); // получаем окружающих НПС Array<Npc> npcs = World.getAround(Npc.class, local.getNextNpcList(), actor, actor.getFractionRange()); // если НПС в радиусе фракции есть if(!npcs.isEmpty()) // перебираем их for(Npc npc : npcs.array()) { if(npc == null) break; // если НПС принадлежит его фракции и не имеет полного хп if(fraction.equals(npc.getFraction()) && npc.getCurrentHp() < npc.getMaxHp()) { // добавляем задание хильнуть его ai.addCastTask(skill, npc); return; } } } } } // если выпал случай использования бафа if(chance(SkillGroup.BUFF)) { // получаем скил для бафа Skill skill = actor.getRandomSkill(SkillGroup.BUFF); // если он есть и не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // если баф не висит на НПС if(!skill.isNoCaster() && !actor.containsEffect(skill)) { // добавляем задание бафнуться ai.addCastTask(skill, actor); return; } // если скил не только на себя и есть фракция у НПС else if(!skill.isTargetSelf() && actor.getFractionRange() > 0) { // получаем фракцию НПС String fraction = actor.getFraction(); // получаем окружающих НПС Array<Npc> npcs = World.getAround(Npc.class, local.getNextNpcList(), actor, actor.getFractionRange()); // если НПС в радиусе фракции есть if(!npcs.isEmpty()) // перебираем их for(Npc npc : npcs.array()) { if(npc == null) break; // если НПС принадлежит его фракции и не имеет этого эффекта if(fraction.equals(npc.getFraction()) && !npc.containsEffect(skill)) { // добавляем задание бафнуть его ai.addCastTask(skill, npc); return; } } } } } // если выпал случай на установку ловушки if(chance(SkillGroup.TRAP)) { // получаем скил ловушки Skill skill = actor.getRandomSkill(SkillGroup.TRAP); // если он есть и не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // добавляем на каст ai.addCastTask(skill, actor); return; } } // получаем текущую цель Character target = ai.getTarget(); // если ее нет, выходим if(target == null) return; // если выпал случай использования бафа if(chance(SkillGroup.DEBUFF)) { // получаем скил для бафа Skill skill = actor.getRandomSkill(SkillGroup.DEBUFF); // если он есть и не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // добавляем на каст ai.addCastTask(skill, target); return; } } // если НПС не в боевой стойке if(!actor.isBattleStanced()) { // отправляем в боевую стойку ai.addNoticeTask(target, true); return; } if(!isFastTurn()) { // если цель не спереди и НПС не в движении if(!actor.isInFront(target) && !actor.isMoving()) { // поворачиваемся в сторону цели ai.addNoticeTask(target, false); return; } // если нпс не в движении if(!actor.isMoving()) { if(actor.isTurner()) { if(!actor.isInTurnFront(target)) { // обновляем внимание ai.addNoticeTask(target, false); return; } } // если фокусная цель не спереди else if(!actor.isInFront(target)) { // обновляем внимание ai.addNoticeTask(target, false); return; } } } // получаем кастующий скил цели Skill castingSkill = target.getCastingSkill(); // если цель что-то кастует TODO if(castingSkill != null && castingSkill.getOperateType() == OperateType.ACTIVE && castingSkill.getSkillType() != SkillType.BUFF) { // если срабатывает случай на использование блока if(chance(SkillGroup.SHIELD)) { // получаем скил блока Skill skill = actor.getRandomSkill(SkillGroup.SHIELD); // если он есть и не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // получаем итоговую зону поражения скила int range = castingSkill.getRange() + castingSkill.getRadius(); // если НПС входит в зону поражения и цель находится с переди if(actor.isInRange(target, range) && target.isInFront(actor)) { // добавляем на каст ai.addCastTask(skill, target); return; } } } // если срабатывает шанс на использование скила прыжка if(chance(SkillGroup.JUMP)) { // пробуем получить прыжковый скил Skill skill = actor.getRandomSkill(SkillGroup.JUMP); // если такой скил есть и он не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // получаем дистанцию прыжка int range = skill.getMoveDistance(); // определяем направление прыжка boolean positive = range > 0; // определяем боковое ли это движение boolean isSide = skill.getHeading() != 0; // если это боковое движение if(isSide) { // если кастуемый скил нацеленный if(castingSkill.isOneTarget()) { // добавляем в задание скастануть боковое движение ai.addCastTask(skill, actor, Angles.calcHeading(actor.getX(), actor.getY(), target.getX(), target.getY())); return; } } // если цель находится в оборонительной стойке, а мы в зоне обороны else if(target.isDefenseStance() && target.isInFront(actor)) { // нужный разворот int newHeading = 0; // определеям нужный разворот для запрыгивания заспину if(positive) newHeading = actor.calcHeading(target.getX(), target.getY()); else newHeading = target.calcHeading(actor.getX(), actor.getY()); // добавляем задание запрыгнуть за спину ai.addCastTask(skill, actor, newHeading); return; } // если прыжок - отпрыгивание назад else if(!positive) { // если мы находимся под ударом и имеем возможность отскочить if(castingSkill.getRange() < getShortRange() && actor.getGeomDistance(target) < getShortRange()) { // добавляем отскок от него ai.addCastTask(skill, actor, actor.calcHeading(target.getX(), target.getY())); return; } } // если это укланение else if(skill.isEvasion()) { // добавляем задание использовать укланение ai.addCastTask(skill, target); return; } } } } // получаем мили скил Skill shortSkill = actor.getRandomSkill(SkillGroup.SHORT_ATTACK); // получаем дистанционный скил Skill longSkill = actor.getRandomSkill(SkillGroup.LONG_ATTACK); // если цель находится в ближнем радиусе if(actor.getGeomDistance(target) < getShortRange()) { // если полученный скил в откате if(shortSkill != null && actor.isSkillDisabled(shortSkill)) shortSkill = actor.getFirstEnabledSkill(SkillGroup.SHORT_ATTACK); // если ближний скил доступен if(shortSkill != null) { // используем ближний скил ai.addCastTask(shortSkill, target); return; } // иначе если доступен дальний скил else if(longSkill != null && !actor.isSkillDisabled(longSkill)) { // используем дальний скил ai.addCastTask(longSkill, target); return; } } // если цель в дальнем радиусе else { // если полученный скил в откате if(longSkill != null && actor.isSkillDisabled(longSkill)) shortSkill = actor.getFirstEnabledSkill(SkillGroup.LONG_ATTACK); // если дальний скил доступен if(longSkill != null) { // используем дальний скил ai.addCastTask(longSkill, target); return; } // иначе если ближний доступен else if(shortSkill != null && !actor.isSkillDisabled(shortSkill)) { // используем ближний скил ai.addCastTask(shortSkill, target); return; } } } /** * @return сработала ли указанная группа. */ protected boolean chance(SkillGroup group) { return Rnd.chance(groupChance[group.ordinal()]); } /** * @return дистанция, считающася ближней. */ protected final int getShortRange() { return shortRange; } /** * @return использовать ли быстрый разворот. */ public boolean isFastTurn() { return fastTurn; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/PlayerPvPOff.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Пакет показывает информацию игроку об другом игроке * * @author Ronn */ public class PlayerPvPOff extends ServerPacket { private static final ServerPacket instance = new PlayerPvPOff(); public static PlayerPvPOff getInstance(Player player) { PlayerPvPOff packet = (PlayerPvPOff) instance.newInstance(); packet.id = player.getObjectId(); packet.subId = player.getSubId(); return packet; } /** ид игрока */ private int id; /** саб ид игрока */ private int subId; @Override public ServerPacketType getPacketType() { return ServerPacketType.PLAYER_PVP_OFF; } protected final void writeImpl() { writeOpcode(); writeInt(id);//Обжект ид writeInt(subId);//саб ид } }<file_sep>/java/game/tera/gameserver/model/items/ArmorType.java package tera.gameserver.model.items; import tera.gameserver.model.equipment.SlotType; /** * Перечисление типов брони. * * @author Ronn */ public enum ArmorType { /** боты */ BOOTS("boots", SlotType.SLOT_BOOTS), /** перчатки */ GLOVES("gloves", SlotType.SLOT_GLOVES), /** майка */ SHIRT("shirt", SlotType.SLOT_SHIRT), /** тело */ BODY("body", SlotType.SLOT_ARMOR), /** серьга */ EARRING("earring", SlotType.SLOT_EARRING), /** кольцо */ RING("ring", SlotType.SLOT_RING), /** ожерелье */ NECKLACE("necklace", SlotType.SLOT_NECKLACE), /** маска */ MASK("mask", SlotType.SLOT_MASK), /** шапочке */ HAT("hat", SlotType.SLOT_HAT), /** ремодел брони */ REMODEL("remodel", SlotType.SLOT_ARMOR_REMODEL), BELT("belt", SlotType.SLOT_BELT), BROOCH("brooch", SlotType.SLOT_BROOCH), COSTUME_HEAD("costume_head", SlotType.SLOT_COSTUME_HEAD), COSTUME_FACE("costume_face", SlotType.SLOT_COSTUME_FACE), COSTUME_WEAPON("costume_weapon", SlotType.SLOT_COSTUME_WEAPON), COSTUME_BODY("costume_body", SlotType.SLOT_COSTUME_BODY), COSTUME_BACK("costume_back", SlotType.SLOT_COSTUME_BACK); /** * Получение нужного армор типа по названию в xml. * * @param name название в xml. * @return соответствующий армор тип. */ public static ArmorType valueOfXml(String name) { for(ArmorType type : values()) if(type.getXmlName().equals(name)) return type; throw new IllegalArgumentException(); } /** название типа в xml */ private String xmlName; /** слот, куда одевается данный тип брони */ private SlotType slot; /** * @param xmlName название в хмл. * @param slot одеваемый слот. */ private ArmorType(String xmlName, SlotType slot) { this.xmlName = xmlName; this.slot = slot; } /** * @return слот, в который одевается броня. */ public final SlotType getSlot() { return slot; } /** * @return xml название. */ public final String getXmlName() { return xmlName; } } <file_sep>/java/game/tera/gameserver/model/GuildIcon.java package tera.gameserver.model; import java.text.SimpleDateFormat; import java.util.Date; /** * Модель иконки гильдии. * * @author Ronn */ public class GuildIcon { private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH_mm_ss"); /** название иконки */ private String name; /** сама иконка */ private byte[] icon; public GuildIcon(String name, byte[] icon) { this.name = name; this.icon = icon; } /** * @return the icon */ public byte[] getIcon() { return icon; } /** * @return the name */ public String getName() { return name; } /** * @return есть ли иконка. */ public boolean hasIcon() { return icon != null && icon.length > 4; } /** * @param icon иконка гильдии. */ public void setIcon(Guild guild, byte[] icon) { this.icon = icon; this.name = "guildlogo_" + guild.getId() + "_" + timeFormat.format(new Date()); } } <file_sep>/java/game/tera/remotecontrol/PacketHandler.java package tera.remotecontrol; /** * Интерфейс для обработчика пакетов * * @author Ronn * @created 26.03.2012 */ public interface PacketHandler { /** * Обработка указанного пакета * * @param packet */ public abstract Packet processing(Packet packet); } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestNpcConfirmSkillShop.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.npc.interaction.dialogs.Dialog; import tera.gameserver.model.npc.interaction.dialogs.DialogType; import tera.gameserver.model.npc.interaction.dialogs.SkillShopDialog; import tera.gameserver.model.playable.Player; /** * Клиентский пакет подтверждающий изучение скила * * @author Ronn * @created 25.02.2012 */ public class RequestNpcConfirmSkillShop extends ClientPacket { /** игрок */ private Player player; /** ид изучаемого скила */ private int skillId; @Override public void finalyze() { player = null; } @Override public boolean isSynchronized() { return false; } @Override protected void readImpl() { player = owner.getOwner(); readInt();//4D 6E 04 00 skillId = readInt();//04 87 01 00 readByte();//01 } @Override protected void runImpl() { if(player == null) return; Dialog dialog = player.getLastDialog(); if(dialog == null || dialog.getType() != DialogType.SKILL_SHOP) return; SkillShopDialog shop = (SkillShopDialog) dialog; if(shop.studySkill(skillId)) shop.apply(); } } <file_sep>/java/game/tera/gameserver/model/items/ArmorInstance.java package tera.gameserver.model.items; import tera.gameserver.templates.ArmorTemplate; import tera.gameserver.templates.ItemTemplate; /** * Модель брони. * * @author Ronn */ public final class ArmorInstance extends GearedInstance { /** защита */ private int defense; /** баланс */ private int balance; /** * @param objectId уникальный ид. * @param template темплейт итема. */ public ArmorInstance(int objectId, ItemTemplate template) { super(objectId, template); } @Override public boolean checkCrystal(CrystalInstance crystal) { if (crystals == null || crystal.getType() != CrystalType.ARMOR) return false; if (crystal.getItemLevel() > template.getItemLevel()) return false; return crystals.hasEmptySlot(); } @Override public ArmorInstance getArmor() { return this; } /** * @return armorKind материал брони. */ public ArmorKind getArmorKind() { return getTemplate().getArmorKind(); } @Override public ArmorTemplate getTemplate() { return (ArmorTemplate) template; } @Override public boolean isArmor() { return true; } @Override protected void updateEnchantStats() { int defense = super.getDefence(); int balance = super.getBalance(); float mod = 4.5F * getEnchantLevel() / 100F + 1; defense *= mod; mod = 7F * getEnchantLevel() / 100F + 1; balance *= mod; setDefense(defense); setBalance(balance); } @Override public int getDefence() { return defense; } @Override public int getBalance() { return balance; } private void setDefense(int defense) { this.defense = defense; } private void setBalance(int balance) { this.balance = balance; } } <file_sep>/java/game/tera/gameserver/document/DocumentSkill.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.gameserver.model.skillengine.Condition; import tera.gameserver.model.skillengine.funcs.Func; import tera.gameserver.parser.ConditionParser; import tera.gameserver.parser.FuncParser; import tera.gameserver.parser.EffectParser; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; /** * Парсер скилов c хмл. * * @author Ronn */ public final class DocumentSkill extends AbstractDocument<Array<SkillTemplate[]>> { /** * @param file отпрасиваемый фаил. */ public DocumentSkill(File file) { super(file); } @Override protected Array<SkillTemplate[]> create() { return result = Arrays.toArray(SkillTemplate[].class); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node skill = list.getFirstChild(); skill != null; skill = skill.getNextSibling()) if("skill".equals(skill.getNodeName())) try { result.add(parseSkill(skill)); } catch(Exception e) { log.warning(this, "incorrect file " + file + ", and skill " + skill.getAttributes().getNamedItem("id")); log.warning(this, e); } } /** * @param node данные с хмл. * @return новый скил. */ private SkillTemplate[] parseSkill(Node node) { // заготавливаем массив if,kjyjd SkillTemplate[] skills; // создаем таблицу таблиц статов Table<String, String[]> table = Tables.newObjectTable(); // соpдаем массив эффетков Array<EffectTemplate> effects = Arrays.toArray(EffectTemplate.class); // создаем массив пассивных функций Array<Func> passiveFuncs = Arrays.toArray(Func.class); // создаепм массив активных функций Array<Func> castFuncs = Arrays.toArray(Func.class); // подготавливаем условие Condition condition = null; // получаем атрибуты скила VarTable attrs = VarTable.newInstance(node); // получаем ид, уровни и класс скила int id = attrs.getInteger("id"); int levels = attrs.getInteger("levels"); int classId = attrs.getInteger("class"); // получаем имя скила String skillName = attrs.getString("name"); // вынимаем табличные параметры for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if(child.getNodeType() != Node.ELEMENT_NODE) continue; // ищем таблицу if("table".equals(child.getNodeName())) { Node item = child.getAttributes().getNamedItem("name"); if(item == null) continue; // получаем название таблицы String name = item.getNodeValue(); if(name == null) continue; // вынимаем значения Node values = child.getFirstChild(); if(values == null) continue; String value = values.getNodeValue(); if(value == null) continue; // вставляем в карту table.put(name, value.split(" ")); } } // создаем массив скилов в соотвтествии с уровнями skills = new SkillTemplate[levels]; VarTable vars = VarTable.newInstance(); // получаем парсер условий ConditionParser condParser = ConditionParser.getInstance(); // получаем парсер эффектов EffectParser effectParser = EffectParser.getInstance(); // получаем парсер функций статов FuncParser funcParser = FuncParser.getInstance(); // идем по массиву for(int order = 0; order < levels; order++) { // создаем таблицу статов VarTable stats = VarTable.newInstance(); // вставяем туда ид, левел, классИд, имя stats.set("id", (id + order)); stats.set("level", 1 + order); stats.set("classId", classId); stats.set("name", skillName); // очищаем функции и эффекты passiveFuncs.clear(); castFuncs.clear(); effects.clear(); // нулим условие condition = null; for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { // если это не узел, пропускаем if(child.getNodeType() != Node.ELEMENT_NODE) continue; // находим параметр скила if("set".equals(child.getNodeName())) { // парсим атрибуты vars.parse(child); // получаем имя параметра String name = vars.getString("name"); // получаем значение параметра String value = vars.getString("value"); // если значение табличное, вытягиваем с таблицы if(value.startsWith("#")) { // получаем массив значений String[] array = table.get(value); // применяем значение из таблицы value = array[Math.min(array.length -1, order)]; } // вставляем в таблицу статов параметр stats.set(name, value); } // находим условия скила else if("cond".equals(child.getNodeName())) { // перебираем условия for(Node condNode = child.getFirstChild(); condNode != null; condNode = condNode.getNextSibling()) { // если это не узел, пропускаем if(condNode.getNodeType() != Node.ELEMENT_NODE) continue; // пробуем отпарсить Condition cond = condParser.parseCondition(condNode, id + order, file); // если не получилось, сообщаем if(cond == null) { log.warning(this, new Exception("not found condition")); continue; } // объеденяем условия condition = condParser.joinAnd(condition, cond); } } else if("cast".equals(child.getNodeName())) // парсим активные функции funcParser.parse(child, castFuncs, table, order, id + order, file); // находим добавление к скилу else if("for".equals(child.getNodeName())) { // парсим пассивные функции funcParser.parse(child, passiveFuncs, table, order, id + order, file); // перебираем добавки for(Node added = child.getFirstChild(); added != null; added = added.getNextSibling()) { // если это не узел, пропускаем if(added.getNodeType() != Node.ELEMENT_NODE) continue; // если это является эффектом if("effect".equals(added.getNodeName())) { EffectTemplate effect = effectParser.paraseEffects(order, added, table, id + order, file); // если его не пропарсили, пропускаем if(effect == null) { log.warning(this, "not found effect to name " + added.getNodeName() + " on file" + file + "."); continue; } // добавляем в список effects.add(effect); } } } } effects.trimToSize(); passiveFuncs.trimToSize(); castFuncs.trimToSize(); // создаем шаблон и кладем в массив skills[order] = new SkillTemplate(stats, Arrays.copyOf(effects.array(), 0), condition, Arrays.copyOf(passiveFuncs.array(), 0), Arrays.copyOf(castFuncs.array(), 0)); } return skills; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Dungeon_Clear_Count_List.java package tera.gameserver.network.serverpackets; import tera.gameserver.config.MissingConfig; import tera.gameserver.model.dungeons.DungeonList; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; import java.util.List; public class S_Dungeon_Clear_Count_List extends ServerPacket { private static final ServerPacket instance = new S_Dungeon_Clear_Count_List(); public static S_Dungeon_Clear_Count_List getInstance(Player player) { S_Dungeon_Clear_Count_List packet = (S_Dungeon_Clear_Count_List) instance.newInstance(); packet.player = player; return packet; } /** кол-во ожидания секунд */ private Player player; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_DUNGEON_CLEAR_COUNT_LIST; } @Override protected final void writeImpl() { List<DungeonList> dungeons = DungeonList.getDungeonAvailableTroughtLevel(player.getLevel()); int n = 12; writeOpcode(); writeShort(dungeons.size()); writeShort(n); writeInt(player.getObjectId()); for(int i = dungeons.size() - 1; i >= 0; i--) { int clearcount = player.getDungeonClearCount(dungeons.get(i).getDungeonId()); writeShort(n); writeShort((i == 0) ? 0 : (n += 13)); writeInt(dungeons.get(i).getDungeonId()); writeInt(clearcount); writeByte((clearcount < MissingConfig.DUNGEON_CLEAR_COUNT_ROOKIE) ? 1 : 0); } } } <file_sep>/java/game/tera/gameserver/network/clientpackets/ClientKey.java package tera.gameserver.network.clientpackets; import tera.gameserver.network.serverpackets.ServerKey; /** * Клиентский пакет читающий клиентский ключ для криптора * * @author Ronn */ public class ClientKey extends ClientPacket { private byte[] data; public ClientKey() { this.data = new byte[128]; } @Override public void readImpl() { readBytes(data); } @Override @SuppressWarnings("incomplete-switch") public void runImpl() { switch(owner.getCryptorState()) { case WAIT_FIRST_SERVER_KEY: case WAIT_SECOND_SERCER_KEY: { // ложим на отправку owner.sendPacket(ServerKey.getInstance(), true); } } } }<file_sep>/java/game/tera/gameserver/model/skillengine/classes/HealPercent.java package tera.gameserver.model.skillengine.classes; import rlib.util.array.Array; import tera.gameserver.model.Character; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель исцеляющего скила. * * @author Ronn */ public class HealPercent extends AbstractSkill { /** * @param template темплейт скила. */ public HealPercent(SkillTemplate template) { super(template); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { //сила хила скила int power = getPower(); if(power < 1) return; // получаем локальные объекты LocalObjects local = LocalObjects.get(); Array<Character> targets = local.getNextCharList(); addTargets(targets, character, targetX, targetY, targetZ); Character[] array = targets.array(); for(int i = 0, length = targets.size(); i < length; i++) { Character target = array[i]; if(target.isDead() || target.isInvul()) continue; addEffects(character, target); int heal = target.getMaxHp() / 100 * power; //хилим таргет target.skillHealHp(getDamageId(), heal, character); // если цель в ПвП режиме а кастер нет if(target.isPvPMode() && !character.isPvPMode()) { // включаем пвп режим character.setPvPMode(true); // включаем боевую стойку character.startBattleStance(target); } } } } <file_sep>/java/game/tera/gameserver/model/quests/QuestPanelState.java package tera.gameserver.model.quests; /** * Состояние квеста относительно панели квестов. * * @author Ronn */ public enum QuestPanelState { REMOVED, ADDED, ACCEPTED, UPDATE, NONE; public static final QuestPanelState valueOf(int index) { QuestPanelState[] values = values(); if(index < 0 || index >= values.length) return NONE; return values()[index]; } } <file_sep>/java/game/tera/remotecontrol/handlers/RemovePlayerItemHandler.java package tera.remotecontrol.handlers; import rlib.concurrent.Locks; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.World; import tera.gameserver.model.equipment.Equipment; import tera.gameserver.model.equipment.Slot; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Обновление итема игрока. * * @author Ronn * @created 09.04.2012 */ public class RemovePlayerItemHandler implements PacketHandler { public static final RemovePlayerItemHandler instance = new RemovePlayerItemHandler(); @Override public Packet processing(Packet packet) { Player player = World.getPlayer(packet.nextString()); if(player == null) return null; int objectId = packet.nextInt(); Inventory inventory = player.getInventory(); Equipment equipment = player.getEquipment(); if(inventory == null || equipment == null) return null; // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); Locks.lock(inventory, equipment); try { Cell cell = inventory.getCellForObjectId(objectId); if(cell != null) { ItemInstance item = cell.getItem(); item.setOwnerId(0); cell.setItem(null); dbManager.updateLocationItem(item); eventManager.notifyInventoryChanged(player); return new Packet(PacketType.RESPONSE); } Slot slot = equipment.getSlotForObjectId(objectId); if(slot != null) { ItemInstance item = slot.getItem(); item.setOwnerId(0); slot.setItem(null); dbManager.updateLocationItem(item); eventManager.notifyEquipmentChanged(player); return new Packet(PacketType.RESPONSE); } } finally { Locks.unlock(inventory, equipment); } return null; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Show_Pegasus_Map.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.util.Iterator; import rlib.util.table.IntKey; import rlib.util.table.Table; import tera.gameserver.model.Route; import tera.gameserver.model.TownInfo; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, передающий код маршута для пегаса. * * @author Ronn * @created 26.02.2012 */ public class S_Show_Pegasus_Map extends ServerPacket { private static final ServerPacket instance = new S_Show_Pegasus_Map(); public static S_Show_Pegasus_Map getInstance(Table<IntKey, Route> routs, int townId) { S_Show_Pegasus_Map packet = (S_Show_Pegasus_Map) instance.newInstance(); packet.routs = routs; packet.townId = townId; return packet; } /** маршруты */ private Table<IntKey, Route> routs; /** ид города */ private int townId; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SHOW_PEGASUS_MAP; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 0x0008000B); int n = 8; for(Iterator<Route> iterator = routs.iterator(); iterator.hasNext();) { Route route = iterator.next(); writeShort(buffer, n); if(!iterator.hasNext()) n = 0; else n += 24; // если последний то нулим. writeShort(buffer, n);// 24 разница writeInt(buffer, route.getIndex());// номер маршрута по счёту writeInt(buffer, route.getPrice()); writeInt(buffer, townId);// //откуда ид города // получаем целевой город TownInfo target = route.getTarget(); writeInt(buffer, target.getId());// куда ид города writeInt(buffer, 0);// неизвестно 10-17 } } } <file_sep>/java/game/tera/gameserver/tasks/OwerturnTask.java package tera.gameserver.tasks; import java.util.concurrent.ScheduledFuture; import rlib.util.SafeTask; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Character; /** * Модель обработчика опрокидывания. * * @author Ronn */ public class OwerturnTask extends SafeTask { /** персонаж */ private final Character character; /** ссылка на исполняемое задание */ private volatile ScheduledFuture<OwerturnTask> schedule; public OwerturnTask(Character character) { this.character = character; } /** * Запустить опрокидывание на указанное время. * * @param time время опрокидывания. */ public synchronized void nextOwerturn(int time) { if(schedule != null) schedule.cancel(true); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // запускаем задачу schedule = executor.scheduleGeneral(this, time); } @Override protected synchronized void runImpl() { // отменяем опрокидывание character.cancelOwerturn(); // зануляем ссылку schedule = null; } } <file_sep>/java/game/tera/gameserver/scripts/commands/ConfigCommand.java package tera.gameserver.scripts.commands; import java.lang.reflect.Field; import tera.Config; import tera.gameserver.model.playable.Player; /** * Набор команд для работы с конфигом. * * @author Ronn */ public class ConfigCommand extends AbstractCommand { public ConfigCommand(int access, String[] commands) { super(access, commands); } @Override public void execution(String command, Player player, String values) { switch(command) { case "config_reload": Config.reload(); break; case "config_set": { String[] vals = values.split(" "); if(vals.length < 3) { player.sendMessage("не хватает аргументов."); return; } try { Field field = Config.class.getField(vals[0]); Object val = null; switch(vals[1]) { case "int": val = Integer.valueOf(vals[2]); break; case "boolean": val = Boolean.valueOf(vals[2]); break; case "string": val = String.valueOf(vals[2]); break; case "float": val = Float.valueOf(vals[2]); break; } field.set(null, val); player.sendMessage("Новое значение: " + field.get(null)); } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { player.sendMessage(e.getClass().getSimpleName()); } } } } } <file_sep>/java/game/tera/gameserver/model/quests/QuestData.java package tera.gameserver.model.quests; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.playable.Player; /** * Набор квестов для данного нпс. * * @author Ronn */ public class QuestData { /** массив квестов */ private Quest[] quests; /** * Добавление нужных ссылок для диалога. * * @param container контейнер ссылок. * @param npc нпс, у которого открывается диалог. * @param player игрок, который хочет поговорить. */ public void addLinks(Array<Link> container, Npc npc, Player player) { // получаем доступные квесты Quest[] quests = getQuests(); // если их нет ,выходим if(quests == null) return; // перебираем квесты и добавляем с них ссылки for(int i = 0, length = quests.length; i < length; i++) quests[i].addLinks(container, npc, player); } /** * Добавление квеста к НПС. * * @param quest добавляемый квест. */ public void addQuest(Quest quest) { // получаем доступные квесты Quest[] quests = getQuests(); // если они есть if(quests == null) setQuests((Quest[]) Arrays.toGenericArray(quest)); else { // проверяем, добавлен ли уже такой квест for(int i = 0, length = quests.length; i < length; i++) if(quests[i] == quest) return; // добавляем новый квест setQuests(Arrays.addToArray(quests, quest, Quest.class)); } } /** * @return доступные квесты. */ private final Quest[] getQuests() { return quests; } /** * Проверяет наличие квеста для игрока. * * @param npc нпс. * @param player игрок. */ public QuestType hasQuests(Npc npc, Player player) { // получаем доступные квесты Quest[] quests = getQuests(); // если их нет, выходим if(quests == null) return null; // перебираем квест for(int i = 0, length = quests.length; i < length; i++) { // получаем квест Quest quest = quests[i]; // если этот квест можно взять if(quest.isAvailable(npc, player)) // возвращаем его тип return quest.getType(); } return null; } /** * @param quests доступные квесты. */ private final void setQuests(Quest[] quests) { this.quests = quests; } } <file_sep>/java/game/tera/gameserver/model/items/BindType.java package tera.gameserver.model.items; /** * Перечисление типов боундинга. * * @author Ronn */ public enum BindType { UNKNOWN("unknown"), UNKNOW("unknow"), NONE("none"), ON_PICK_UP("onPickUp"), ON_EQUIP("onEquip"); /** * Получение нужного боунд типа по названию в xml. * * @param name название в xml. * @return соответствующий боунд тип. */ public static BindType valueOfXml(String name) { for(BindType type : values()) if(type.getXmlName().equals(name)) return type; throw new IllegalArgumentException("no enum " + name); } /** xml название */ private String xmlName; /** * @param xmlName название в хмл. */ private BindType(String xmlName) { this.xmlName = xmlName; } /** * @return xml название. */ public final String getXmlName() { return xmlName; } } <file_sep>/java/game/tera/gameserver/model/GuildMember.java package tera.gameserver.model; import rlib.util.Strings; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.model.playable.Player; /** * Модель члена клана в Тера. * * @author Ronn */ public final class GuildMember implements Foldable { private static final FoldablePool<GuildMember> pool = Pools.newConcurrentFoldablePool(GuildMember.class); /** * @return новый клан мембер. */ public static final GuildMember newInstance() { GuildMember member = pool.take(); if(member == null) return new GuildMember(); return member; } /** ник нейм мембера */ private String name; /** заметка для гильдии о игроке */ private String note; /** обджект ид мембера */ private int objectId; /** уровень мембера */ private int level; /** пол мембера */ private int sex; /** раса мембера */ private int raceId; /** класс мембера */ private int classId; /** ид зоны, в которой находится игрок */ private int zoneId; /** время последнего входа в игру */ private int lastOnline; /** ранг мембера */ private GuildRank rank; /** онлаин ли он сейчас */ private boolean online; public GuildMember() { this.note = Strings.EMPTY; } @Override public boolean equals(Object object) { if(object instanceof Player) { Player player = (Player) object; return objectId == player.getObjectId(); } return super.equals(object); } @Override public void finalyze() { rank = null; } public void fold() { pool.put(this); } /** * @return класс мембера. */ public final int getClassId() { return classId; } /** * @return lastOnline */ public final int getLastOnline() { return lastOnline; } /** * @return ранг мембера. */ public final int getLawId() { return rank.getLawId(); } /** * @return уровень мембера. */ public final int getLevel() { return level; } /** * @return имя мембера. */ public final String getName() { return name; } /** * @return пометка об игроке. */ public final String getNote() { return note; } /** * @return уникальный ид мембера. */ public final int getObjectId() { return objectId; } /** * @return раса мембера. */ public final int getRaceId() { return raceId; } /** * @return ранг мембера. */ public final GuildRank getRank() { return rank; } /** * @return ранг мембера. */ public final int getRankId() { return rank == null? 0 : rank.getIndex(); } /** * @return пол мембера. */ public final int getSex() { return sex; } /** * @return the zoneId */ public final int getZoneId() { return zoneId; } /** * @return онлаин ли мембер. */ public final boolean isOnline() { return online; } @Override public void reinit(){} /** * @param classId класс мембера. */ public final void setClassId(int classId) { this.classId = classId; } /** * @param lastOnline задаваемое lastOnline */ public final void setLastOnline(int lastOnline) { this.lastOnline = lastOnline; } /** * @param level уровень мембера. */ public final void setLevel(int level) { this.level = level; } /** * @param name имя мембера. */ public final void setName(String name) { this.name = name; } /** * @param note пометка об игроке. */ public final void setNote(String note) { this.note = note; } /** * @param objectId уникальный ид мембера. */ public final void setObjectId(int objectId) { this.objectId = objectId; } /** * @param online онлаин ли мембер. */ public final void setOnline(boolean online) { this.online = online; } /** * @param raceId раса мембера. */ public final void setRaceId(int raceId) { this.raceId = raceId; } /** * @param rank ранг мембера. */ public final void setRank(GuildRank rank) { this.rank = rank; } /** * @param sex пол мембера. */ public final void setSex(int sex) { this.sex = sex; } /** * @param zoneId the zoneId to set */ public final void setZoneId(int zoneId) { this.zoneId = zoneId; } @Override public String toString() { return "GuildMember name = " + name + ", note = " + note + ", objectId = " + objectId + ", level = " + level + ", sex = " + sex + ", raceId = " + raceId + ", classId = " + classId + ", zoneId = " + zoneId + ", lastOnline = " + lastOnline + ", rank = " + rank + ", online = " + online; } } <file_sep>/java/game/tera/gameserver/model/npc/spawn/SummonSpawn.java package tera.gameserver.model.npc.spawn; import java.util.concurrent.ScheduledFuture; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.SafeTask; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Character; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAIClass; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.summons.Summon; import tera.gameserver.templates.NpcTemplate; import tera.util.Location; /** * @author Ronn */ public class SummonSpawn extends SafeTask implements Spawn { private static final Logger LOGGER = Loggers.getLogger(SummonSpawn.class); /** шаблон сумона */ private final NpcTemplate template; /** место спавна */ private final Location location; /** конфиг АИ суммона */ private final ConfigAI configAI; /** класс АИ суммона */ private final NpcAIClass aiClass; /** время жизни суммона */ private final int lifeTime; /** владелец сумона */ private volatile Character owner; /** отспавненный сумон */ private volatile Summon spawned; /** мертвый сумон */ private volatile Summon dead; /** ссылка на задачу спавна */ private volatile ScheduledFuture<SummonSpawn> schedule; public SummonSpawn(NpcTemplate template, ConfigAI configAI, NpcAIClass aiClass, int lifeTime) { this.template = template; this.configAI = configAI; this.aiClass = aiClass; this.lifeTime = lifeTime; this.location = new Location(); } @Override public void doDie(Npc npc) { if(!npc.isSummon()) { return; } setDead((Summon) npc); setSpawned(null); deSpawn(); } @Override public Location getLocation() { return location; } @Override public int getTemplateId() { return template.getTemplateId(); } @Override public int getTemplateType() { return template.getTemplateType(); } @Override public void setLocation(Location location) { this.location.set(location); } @Override public synchronized void start() { Summon spawned = getSpawned(); if(spawned != null) { LOGGER.warning(this, "found duplicate spawn!"); return; } Character owner = getOwner(); if(owner == null) { return; } Location location = getLocation(); Summon summon = getDead(); if(summon != null) { summon.finishDead(); summon.reinit(); summon.setOwner(owner); summon.spawnMe(location); } else { summon = (Summon) template.newInstance(); summon.setOwner(owner); summon.setSpawn(this); summon.setAi(aiClass.newInstance(summon, configAI)); summon.spawnMe(location); } setDead(null); setSpawned(summon); owner.setSummon(summon); ExecutorManager executorManager = ExecutorManager.getInstance(); setSchedule(executorManager.scheduleGeneral(this, lifeTime)); } @Override public synchronized void stop() { ScheduledFuture<SummonSpawn> schedule = getSchedule(); if(schedule != null) { schedule.cancel(true); setSchedule(null); } Summon spawned = getSpawned(); if(spawned != null) { spawned.remove(); } } /** * @return владелец сумона. */ public Character getOwner() { return owner; } /** * @param owner владелец сумона. */ public void setOwner(Character owner) { this.owner = owner; } /** * @param dead мертвый сумон. */ public void setDead(Summon dead) { this.dead = dead; } /** * @param spawned отспавненный суммон. */ public void setSpawned(Summon spawned) { this.spawned = spawned; } /** * @return отспавненный суммон. */ public Summon getSpawned() { return spawned; } public Summon getDead() { return dead; } @Override protected void runImpl() { deSpawn(); } /** * Деспавн суммона. */ private synchronized void deSpawn() { Summon spawned = getSpawned(); if(spawned != null) { spawned.remove(); } ScheduledFuture<SummonSpawn> schedule = getSchedule(); if(schedule != null) { schedule.cancel(true); setSchedule(null); } } /** * @returnс сылка на задачу деспавна сумона. */ public ScheduledFuture<SummonSpawn> getSchedule() { return schedule; } /** * @param schedule ссылка на задачу деспавна сумона. */ public void setSchedule(ScheduledFuture<SummonSpawn> schedule) { this.schedule = schedule; } @Override public Location[] getRoute() { return null; } } <file_sep>/java/game/tera/gameserver/model/ai/AbstractAI.java package tera.gameserver.model.ai; import rlib.logging.Logger; import rlib.logging.Loggers; import tera.gameserver.model.Character; /** * Базовая модель АИ. * * @author Ronn * @created 12.04.2012 */ public abstract class AbstractAI<E extends Character> implements AI { protected static final Logger log = Loggers.getLogger(AI.class); /** тот, кем АИ управляет */ protected E actor; /** * @param actor управляемый АИ. */ public AbstractAI(E actor) { this.actor = actor; } /** * @return управляемый АИ. */ public E getActor() { return actor; } /** * Удалить управляемого. */ public void removeActor() { actor = null; } /** * @param actor управляемый АИ. */ public void setActor(E actor) { this.actor = actor; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/ConfirmServer.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Пакет ответа на запрос проверки сервера * * @author Ronn * @created 25.03.2012 */ public class ConfirmServer extends ServerPacket { private static final ServerPacket instance = new ConfirmServer(); public static ConfirmServer getInstance(int index) { ConfirmServer packet = (ConfirmServer) instance.newInstance(); packet.index = index; return packet; } /** индекс подтверждения */ private int index; @Override public ServerPacketType getPacketType() { return ServerPacketType.REQUEST_CHECKING_SERVER; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, index); writeByte(buffer, 1); } }<file_sep>/java/game/tera/gameserver/network/ClientPacketType.java package tera.gameserver.network; import java.util.HashSet; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.network.clientpackets.*; /** * Перечисление типов клиентских пакетов. * * @author Ronn */ public enum ClientPacketType { C_HARDWARE_INFO(0xBBAA, new C_Hardware_Info()), C_LOGIN_ARBITER(0xED4F, new C_Login_Arbiter()), C_CHECK_VERSION(0x4DBC, new C_Check_Version()), C_GET_USER_LIST(0xE943, new C_Get_User_List()), C_CAN_CREATE_USER(0x9A04, new C_Can_Create_User()), C_CHECK_USERNAME(0x8912, new C_Check_Username()), //C_CREATE_USER(0x8912, new C_Create_User()), C_CREATE_USER(0xCBED, new C_Create_User()), C_DELETE_USER(0xF4E7, new C_Delete_User()), C_SELECT_USER(0xF9BF, new C_Select_User()), C_LOAD_TOPO_FIN(0x8B97, new C_Load_Topo_Fin()), C_CHAT(0xB342, new C_Chat()), C_RETURN_TO_LOBBY(0xBF6F, new C_Return_To_Lobby()), C_EXIT(0xCC22, new C_Exit()), C_CANCEL_EXIT(0xD863, new C_Cancel_Exit()), C_CANCEL_RETURN_TO_LOBBY(0xBE6F, new C_Cancel_Return_To_Lobby()), C_PLAYER_LOCATION(0xE9C7, new C_Player_Location()), C_SIMPLE_TIP_REPEAT_CHECK(0xF65E, new C_Simple_Tip_Repeat_Check()), C_TRADE_BROKER_HIGHEST_ITEM_LEVEL(0xF7B2, new C_Trade_Broker_Highest_Item_Level()), C_UNION_SUMMARY(0x856B, new C_Union_Summary()), C_UPDATE_CONTENTS_PLAYTIME(0xA77C, new C_Update_Content_Playtime()), C_GUARD_PK_POLICY(0xF6F6, new C_Guard_Pk_Policy()), C_VISIT_NEW_SECTION(0x4F4D, new C_Visit_New_Section()), C_REIGN_INFO(0x946F, new C_Reign_Info()), C_DIALOG_EVENT(0x908D, new C_Dialog_Event()), C_SHOW_INVEN(0x945F, new C_Show_Inven()), C_SAVE_CLIENT_USER_SETTING(0xEEA5, new C_Save_Client_User_Settings()), C_UPDATE_FRIEND_INFO(0xCB0F, new C_Update_Friend_Info()), C_ADD_FRIEND(0xA6DB, new C_Add_Friend()), C_DELETE_FRIEND(0x9B0A, new C_Delete_Friend()), C_WHISPER(0xB5D3, new C_Whisper()), C_NPC_CONTACT(0xAA00, new C_Npc_Contact()), C_DIALOG(0x5AA2, new C_Dialog()), C_NOTIFY_LOCATION_IN_ACTION(0x6364, new C_Notify_Player_In_Action()), C_BROADCAST_CLIMBING(0x84A1, new C_Broadcast_Climbing()), C_START_CLIMBING(0x740F, new C_Start_Climbing()), C_END_CLIMBING(0xFCD2, new C_End_Climbing()), C_APPLY_TITLE(0x9CEA, new C_Apply_Title()), C_SOCIAL(0xA566, new C_Social()), C_EQUIP_ITEM(0x79FD, new C_Equip_Item()), C_INVENTORY_AUTO_SORT(0x8012, new C_Inventory_Auto_Sort()), C_MOVE_INVEN_POS(0xB547, new C_Move_Inven_Pos()), C_DEL_ITEM(0xD7C3, new C_Del_Item()), C_USE_ITEM(0x80AC, new C_Use_Item()), C_TOGGLE_TASK_INFO_WINDOW(0xF1F1, new C_Toggle_Task_Info_Window()), C_CANCEL_QUEST(0xC936, new C_Cancel_Quest()), C_STR_EVALUATE_LIST(0x5F09, new C_Str_Evaluate_List()), C_SHOW_ITEM_TOOLTIP_EX(0xE52D, new C_Show_Item_Tooltip_Ex()), C_TRY_LOOT_DROPITEM(0xA3AD, new C_Try_Loot_Dropitem()), C_SHOW_ITEM_TOOLTIP(0xAC92, new C_Show_Item_Tooltip()), C_REQUEST_RET_VILLAGE_INFO(0x779A, new C_Request_Ret_Village_Info()), C_START_SKILL(0xAB5F, new C_START_SKILL()), C_START_INSTANCE_SKILL(0xC0FB, new C_Start_Instance_Skill()), C_START_COMBO_INSTANT_SKILL(0xBF3C, new C_Start_Combo_Instant_Skill()), C_REQUEST_CONTRACT(0xEA03, new C_Request_Contract()), C_REPLY_THROUGH_ARBITER_CONTRACT(0x8906, new C_Reply_Through_Arbiter_Contract()), C_BAN_PARTY_MEMBER(0x52AA, new C_Ban_Party_Member()), C_LEAVE_PARTY(0x6E3B, new C_Leave_Party()), C_REQUEST_REFRESH_GUILD_DATA(0xA53D, new C_Request_Refresh_Guild_Data()), C_GET_GUILD_HISTORY(0xF116, new C_Get_Guild_History()), C_GUILD_APPLY_LIST(0x85C4, new C_Guild_Apply_List()), C_VIEW_MY_GUILD_WAR(0xEB3E, new C_View_My_Guild_War()), C_REQUEST_GUILD_LIST(0xD1CF, new C_Request_Guild_List()), C_RECOMMEND_GUILD(0xB4B7, new C_Recommend_Guild()), C_REQUEST_GUILD_INFO_BEFORE_APPLY_GUILD(0xFB52, new C_Request_Guild_Info_Before_Apply_Guild()), C_APPLY_GUILD(0xA1DA, new C_Apply_Guild()), C_ACCEPT_GUILD_APPLY(0xE844, new C_Accept_Guild_Apply()), C_COLLECTION_PICKSTART(0xF102, new C_Collection_Pickstart()), C_CREATE_GUILDGROUP(0xD07A, new C_Create_Guildgroup()), C_REMOVE_GUILDGROUP(0xA178, new C_Remove_Guildgroup()), C_CHANGE_GUILDGROUP(0x50A0, new C_Change_Guildgroup()), C_ASK_INTERACTIVE(0xF13A, new C_Ask_Interactive()), C_CHANGE_GUILD_CHIEF(0x5468, new C_Change_Guild_Chief()), C_SET_GUILDGROUP_AUTHORITY(0x5627, new C_Set_Guildgroup_Authority()), C_UNION_MY_UNION(0xF27D, new C_Union_My_Union()), C_VIEW_UNION_INFO(0x68F0, new C_View_Union_Info()), C_UNION_CHANGE_TAXRATE(0xD0C3, new C_Union_Change_taxrate()), C_UNION_CHANGE_NOTICE(0x56A5, new C_Union_Change_Notice()), C_REQUEST_UPDATE_NOTICE(0xF27A, new C_Request_Update_Notice()), C_UPDATE_GUILD_TITLE(0xEB8E, new C_Update_Guild_Title()), C_REQUEST_UPDATE_INTRODUCE(0xC9AC, new C_Request_Update_Introduce()), C_REVIVE_NOW(0x8EBE, new C_Revive_Now()), // 0C 00 20 E0 00 00 00 00 FF FF FF FF C_REQUEST_USER_PAPERDOLL_INFO_WITH_GAMEID(0xAB81, new C_Request_User_Paperdoll_Info_With_Gameid()), C_UNEQUIP_ITEM(0xD491, new C_Equip_Item()), C_END_MOVIE(0x7BC6, new C_End_Movie()), C_RIDE_PEGASUS(0x96B3, new C_Ride_Pegasus()), // 08 00 62 C7 08 00 00 00 C_DUNGEON_CLEAR_COUNT_LIST(0x81BC, new C_Dungeon_Clear_Count_List()), C_VIEW_INTER_PARTY_MATCH_DUNGEON_LIST(0x6DF7, new C_View_Inter_Party_Match_Dungeon_List()), C_DUNGEON_COOL_TIME_LIST(0xAB05, new C_Dungeon_Cool_Time_List()), C_VIEW_BATTLE_FIELD_RESULT(0xCD33, new C_View_Battle_Field_Result()), REQUEST_WORLD_ZONE(0x5E43, new RequestWorldZone()), REQUEST_STATE(0xAB5E, new RequestState()), //REQUEST_TAKING_ITEM(0xB983, new C_Equip_Item()), REQUEST_BANK_MOVING_ITEM(0xEFC9, new RequestBankMovingItem()), REQUEST_BANK_CHANGE_TAB(0xDBB0, new RequestBankChangeTab()), REQUEST_INVENTORY_ITEM_INFO(0xBC87, new RequestInventoryInfoItem()), // 28 00 F4 C4 1E 00 13 00 00 00 C4 71 00 00 00 00 REQUEST_PICK_UP_ITEM(0x4E2D, new RequestPickUpItem()), REQUEST_USE_ITEM(0xE307, new C_Use_Item()), // 3A 00 F6 B0 AB 76 00 00 00 00 00 00 47 1F 00 00 REQUEST_USE_SCROLL(0x8386, new C_Request_Ret_Village_Info()), REQUEST_ITEM_TEMPLATE_INFO(0xA9DA, new C_Show_Item_Tooltip()), REQUEST_GUILD_LEAVE(0x9EBD, new RequestGuildLeave()), REQUEST_GUILD_EXLUDE(0x8EB7, new RequestGuildExclude()), REQUEST_GUILD_UPDATE_RANK(0xFF13, new C_Change_Guildgroup()), REQUEST_GUIL_LOAD_ICON(0xF883, new RequestGuildLoadIcon()), REQUEST_GUILD_ICON_INFO(0xAC93, new RequestGuildIcon()), REQUEST_USE_QUEUE_SKILL(0xCED8, new C_Start_Combo_Instant_Skill()), REQUEST_USE_RANGE_SKILL(0x7017, new C_Start_Instance_Skill()), REQUEST_USE_RUSH_SKILL(0xBF14, new RequestUseRushSkill()), REQUEST_USE_DEFENSE_SKILL(0x57E6, new RequestUseDefenseSkill()), REQUEST_LOCK_ON_TARGET(0xD1F2, new RequestLockOnTarget()), REQUEST_SKILL_ACTION(0xA6B8, new RequestSkillAction()), UPDATE_HOT_KEY(0xB6BA, new UpdateHotKey()), REQUEST_CONFIRM_SERVER(0x9FCA, new RequestConfirmServer()), REQUEST_CHECK_SERVER(0xD6C0, new RequestServerCheck()), REQUEST_LOCAL_TELEPORT(0xCADC, new RequestLocalTeleport()), REQUEST_DUEL_CANCEL(0xF0AE, new RequestDuelCancel()), REQUEST_NPC_ADD_BUY_SHOP(0xF406, new RequestNpcAddBuyShop()), // 1C 00 CC EB F5 5F 00 00 00 00 00 00 65 B1 B6 48 REQUEST_NPC_SUB_BUY_SHOP(0xA087, new RequestNpcSubBuyShop()), // 20 00 12 CC F5 5F 00 00 00 00 00 00 65 B1 B6 48 REQUEST_NPC_ADD_SELL_SHOP(0x8EC1, new RequestNpcAddSellShop()), // 18 00 5E F5 F5 5F 00 00 00 00 00 00 65 B1 B6 48 REQUEST_NPC_SUB_SELL_SHOP(0x51D3, new RequestNpcSubSellShop()), // 18 00 74 D1 F5 5F 00 00 00 00 00 00 65 B1 B6 48 REQUEST_NPC_CONFIRM_SHOP(0x8082, new RequestNpcConfirmShop()), // 10 00 77 65 F5 5F 00 00 00 00 00 00 65 B1 B6 48 REQUEST_NPC_CONFIRM_SKILL_SHOP(0xC456, new RequestNpcConfirmSkillShop()), REQUEST_NPC_BANK_ADD(0xF25D, new RequestBankAdd()), REQUEST_NPC_BANK_SUB(0xEF1D, new RequestBankSub()), REQUEST_QUEST_PANEL(0xB1B2, new RequestUpdateQuestPanel()), REQUEST_QUEST_CANCEL(0x59AE, new RequestCancelQuest()), // TODO /** клиентский пакет с выбором скила для изучения */ CLIENT_SELECT_SKILL_LEARN(0xBFDD, new SelectSkillLearn()), /** запрос на запуск полета на пегасе по указанному маршруту, версия 172 */ /** запрос на закрытие диалогов, версия 172 */ REQUEST_DIALOG_CANCEL(0xBFB9, new RequestDialogCancel()), // 0C 00 31 C5 09 00 00 00 65 B1 B6 48 /** запрос на блокировку трейда, версия 172 */ REQUEST_TRADE_LOCK(0x637C, new RequestTradeLock()), /** запрос на добавление итема в трейд, версия 172 */ REQUEST_TRADE_ADD_ITEM(0x683A, new RequestTradeAddItem()), /** согласие на начало трейда, версия 172 */ ASSENT_TRADE(0x65A6, new AssentTrade()), // A6 65 03 00 /** отмена трейда, версия 172 0x72D6 */ CANCEL_TRADE(0x72D6, new CancelTrade()), // D6 72 03 00 00 00 00 00 00 00 /** запрос на приглашение игрока в акшен, версия 172 */ REQUEST_ACTION_INVITE(0xADE2, new RequestActionInvite()), /** согласие на участие в акшене, версия 172 */ REQUEST_ACTION_AGREE(0xA05D, new C_Reply_Through_Arbiter_Contract()), /** отмена акшена игроком, версия 172 */ /** запрос на приглашение человека в пати, версия 172 */ REQUEST_PARTY_INVITE(0x0111, new RequestPartyInvite()), /** запрос на выход из пати, версия 172 */ /** запрос на изменение группе */ REQUEST_PARTY_CHANGE(0x784F, new RequestPartyChange()), /** запрос на смену лидера в группе */ REQUEST_PARTY_MAKE_LEADER(0xB14B, new RequestPartyMakeLeader()), /** запрос на кик из группы */ REQUEST_PARTY_KICK(0xFD15, new C_Ban_Party_Member()), /** запрос на расформирование группы */ REQUEST_PARTY_DISBAND(0xC041, new RequestPartyDisband()), /** клиентский запрос на сбор ресурса */ /** запрос на список друзей */ /** проверка на корректность имени, версия 172 */ /** пакет, запрашивающий возможность применить новое имя игроку, версия 172 */ NAME_CHANGED(0xBB7A, new NameChange()), /** пакет с клиентским ключем */ CLIENT_KEY(0xFFFF, new ClientKey()), /** запрос на добавление предмета в диалог заточки */ REQUEST_ADD_ENCHANT_ITEM(0x5E4E, new RequestAddEnchantItem()), /** уведомление о завершении анимации заточки */ ENCHANT_FINISH(0xDDB4, new EnchantFinish()), /** пакет входа в мир персонажа, версия */ PLAYER_REQUEST_UNSTUCK(0x86E2, new RequestPlayerUnstuck()); private static final Logger log = Loggers.getLogger(ClientPacketType.class); /** массив пакетов */ private static ClientPacket[] packets; /** * Возвращает новый экземпляр пакета в соответствии с опкодом * * @param opcode опкод пакета. * @return экземпляр нужного пакета. */ public static ClientPacket createPacket(int opcode) { ClientPacket packet = packets[opcode]; return packet == null ? null : packet.newInstance(); } /** * Инициализация клиентских пакетов. */ public static void init() { HashSet<Integer> set = new HashSet<Integer>(); ClientPacketType[] elements = values(); for (ClientPacketType packet : elements) { int index = packet.getOpcode(); if (set.contains(index)) log.warning("found duplicate opcode " + index + " or " + Integer.toHexString(packet.getOpcode()) + " for " + packet + "!"); set.add(index); } set.clear(); packets = new ClientPacket[Short.MAX_VALUE * 2 + 2]; for (ClientPacketType element : elements) packets[element.getOpcode()] = element.getPacket(); log.info("client packets prepared."); } /** пул клиенстких пакетов */ private final FoldablePool<ClientPacket> pool; /** экземпляр пакета */ private final ClientPacket packet; /** опкод пакета */ private int opcode; /** * @param opcode опкод пакета. * @param packet экземпляр пакета. */ private ClientPacketType(int opcode, ClientPacket packet) { this.opcode = opcode; this.packet = packet; this.packet.setPacketType(this); this.pool = Pools.newConcurrentFoldablePool(ClientPacket.class); } /** * @return опкод пакета. */ public final int getOpcode() { return opcode; } /** * @return экземпляр пакета. */ public final ClientPacket getPacket() { return packet; } /** * @return получить пул пакетов соотвествующего типа. */ public final FoldablePool<ClientPacket> getPool() { return pool; } /** * @param opcode опкод пакета. */ public final void setOpcode(int opcode) { this.opcode = opcode; } }<file_sep>/java/game/tera/gameserver/network/serverpackets/GuildBank.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import tera.gameserver.model.Guild; import tera.gameserver.model.inventory.Bank; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с описанием содержимого банка гильдии. * * @author Ronn */ public class GuildBank extends ServerPacket { private static final ServerPacket instance = new GuildBank(); public static GuildBank getInstance(Player player, int startCell) { GuildBank packet = (GuildBank) instance.newInstance(); // получаем гильдию игрока Guild guild = player.getGuild(); // если гильдии нет, выходим if(guild == null) { log.warning(GuildBank.class, new Exception("not found guild")); return null; } // получаем банк гильдии Bank bank = guild.getBank(); // определяем стартовую ячейку startCell = Math.min(startCell, bank.getMaxSize()); // определяем конечную ячейку int endCell = Math.min(startCell + bank.getTabSize(), bank.getMaxSize()); ByteBuffer buffer = packet.prepare; int bytes = 44; int last = endCell - 1; packet.writeShort(buffer, bank.getUsedCount());// 2A 00 кол-во итемовв банке packet.writeShort(buffer, bytes);// 2C 00 //44 packet.writeInt(buffer, player.getObjectId());// 45 53 0D 00 обжект ид packet.writeInt(buffer, player.getSubId());// 00 80 00 01 Саб ид packet.writeInt(buffer, 1);// 01 00 00 00 00 00 00 00 packet.writeInt(buffer, 0);// 01 00 00 00 00 00 00 00 packet.writeInt(buffer, 0);// 00 00 00 00 packet.writeInt(buffer, 0);// 4D 00 00 00 //77 packet.writeInt(buffer, 48);// 30 00 00 00 //48 packet.writeLong(buffer, bank.getMoney());// 00 00 00 00 00 00 00 00 bank.lock(); try { // получаем массив ячеяк Cell[] cells = bank.getCells(); int ownerId = player.getObjectId(); // перебираем их for(int i = startCell; i < endCell; i++) { // получаем ячейку Cell cell = cells[i]; if(cell.isEmpty()) continue; // получаем итем в ячейки ItemInstance item = cell.getItem(); packet.writeShort(buffer, bytes);// 2C 00 if(i == last) bytes = 0; else bytes += 62; packet.writeShort(buffer, bytes);// 6A 00 packet.writeInt(buffer, 0);// packet.writeInt(buffer, item.getItemId());// ИД итема packet.writeInt(buffer, item.getObjectId());// Обжект ИД итема packet.writeInt(buffer, item.getSubId()); packet.writeInt(buffer, ownerId);// Обжект ИД наш packet.writeInt(buffer, 0);// packet.writeInt(buffer, i - startCell);// Номер ячейки в которой лежит итем на складе packet.writeInt(buffer, 1); packet.writeInt(buffer, 1);// меняется packet.writeInt(buffer, (int) item.getItemCount());// меняется как правило одинакого с переменной выше воз-но кол-во packet.writeInt(buffer, 0); packet.writeInt(buffer, 1);// тут иногда 1 packet.writeLong(buffer, 0); packet.writeShort(buffer, 0); } } finally { bank.unlock(); } return packet; } /** промежуточный буффер */ private ByteBuffer prepare; public GuildBank() { super(); this.prepare = ByteBuffer.allocate(1024000).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.GUILD_BANK; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); prepare.flip(); buffer.put(prepare); } }<file_sep>/java/game/tera/gameserver/network/clientpackets/C_Show_Item_Tooltip.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.tables.ItemTable; import tera.gameserver.templates.ItemTemplate; /** * Запрос на отображение информации темплейта итема. * * @author Ronn */ public class C_Show_Item_Tooltip extends ClientPacket { /** игрок, запросивший инфу */ private Player player; /** ид запрашиваемого итема */ private int itemId; @Override public void finalyze() { player = null; } @Override public boolean isSynchronized() { return false; } @Override protected void readImpl() { player = owner.getOwner(); itemId = readInt(); } @Override protected void runImpl() { if(player == null) return; // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); ItemTemplate template = itemTable.getItem(itemId); if(template == null) return; //player.sendMessage("itemId = " + itemId + ", itemLevel " + template.getItemLevel()); //player.sendPacket(ItemTemplateInfo.getInstance(template.getItemId()), true); } } <file_sep>/java/game/tera/gameserver/scripts/commands/DeveloperCommand.java package tera.gameserver.scripts.commands; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import rlib.geoengine.GeoQuard; import rlib.logging.GameLoggers; import rlib.logging.Loggers; import rlib.util.array.Array; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.EventManager; import tera.gameserver.manager.GeoManager; import tera.gameserver.model.World; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.skillengine.Calculator; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.model.skillengine.funcs.StatFunc; import tera.gameserver.model.skillengine.funcs.stat.MathFunc; import tera.gameserver.model.skillengine.lambdas.FloatMul; import tera.gameserver.model.skillengine.lambdas.FloatSet; import tera.gameserver.network.serverpackets.*; import tera.gameserver.tables.NpcDialogTable; import tera.gameserver.tables.SkillTable; import tera.remotecontrol.handlers.LoadChatHandler; /** * Обработчик команд для разработчиков. * * @author Ronn */ public class DeveloperCommand extends AbstractCommand { private static final StatFunc SPEED = new MathFunc(StatType.RUN_SPEED, 0x45, null, new FloatSet(500)); private static final StatFunc ATTACK = new MathFunc(StatType.ATTACK, 0x30, null, new FloatMul(50)); public DeveloperCommand(int access, String[] commands) { super(access, commands); } @Override public void execution(String command, Player player, String values) { switch(command) { case "event_reg_all_players": { EventManager eventManager = EventManager.getInstance(); Array<Player> players = World.getPlayers(); players.readLock(); try { for(Player target : players.array()) { if(target == null) { break; } eventManager.registerPlayer(values, target); } } finally { players.readUnlock(); } break; } case "zone":{ player.sendMessage("ZONE :" + player.getZoneId()); break; } case "change_class": { DataBaseManager dbManager = DataBaseManager.getInstance(); PlayerClass cs = PlayerClass.valueOf(values); if(cs == player.getPlayerClass()) { return; } dbManager.updatePlayerClass(player.getObjectId(), cs); player.sendMessage("Player class have changed to " + cs); break; } case "kick": { Player target = World.getPlayer(values); if(target == null) { return; } player.sendMessage("игрок \"" + target.getName() + "\" кикнут."); target.getClient().close(); return; } case "start_gc": { System.gc(); break; } case "start_event": { EventManager eventManager = EventManager.getInstance(); eventManager.startEvent(values); break; } case "a": { World.sendAnnounce(values); break; } case "reload_dialogs": { NpcDialogTable dialogTable = NpcDialogTable.getInstance(); dialogTable.reload(); break; } case "gm_speed": { player.addStatFunc(SPEED); player.updateInfo(); break; } case "check_geo": { GeoManager geoManager = GeoManager.getInstance(); GeoQuard[] quards = geoManager.getQuards(player.getContinentId(), player.getX(), player.getY()); player.sendMessage("geo : " + Arrays.toString(quards)); break; } case "send_state": { int val = Integer.parseInt(values); player.sendPacket(CharState.getInstance(player.getObjectId(), player.getSubId(), val), true); player.sendMessage("send state " + val); break; } case "add_attack": { ATTACK.addFuncTo(player); player.updateInfo(); break; } case "send_system": { player.sendPacket(S_Sytem_Message.getInstance(values.replace('&', (char) 0x0B)), true); break; } case "send_event": { player.sendPacket(EventMessage.getInstance(values, "", ""), true); break; } case "sub_attack": { ATTACK.removeFuncTo(player); player.updateInfo(); break; } case "save_all": { DataBaseManager dbManager = DataBaseManager.getInstance(); for(Player member : World.getPlayers()) { dbManager.fullStore(member); QuestList questList = member.getQuestList(); questList.save(); player.sendMessage("Character saved : \"" + member.getName() + "\""); } GameLoggers.finish(); break; } case "save_point": { String point = "<point x=\"" + (int) player.getX() + "\" y=\"" + (int) player.getY() + "\" z=\"" + (int) player.getZ() + "\" heading=\"" + player.getHeading() + "\" />"; LoadChatHandler.add(point); System.out.println(point); break; } case "get_my_id": { ByteBuffer buffer = ByteBuffer.wrap(new byte[4]).order(ByteOrder.LITTLE_ENDIAN); buffer.clear(); buffer.putInt(player.getObjectId()); buffer.flip(); StringBuilder text = new StringBuilder(); for(byte byt : buffer.array()) { text.append(Integer.toHexString(byt & 0xFF)).append(" "); } player.sendMessage("Server: your object id " + text.toString()); break; } case "my_funcs": { Calculator[] calcs = player.getCalcs(); StringBuilder text = new StringBuilder("Funcs: "); for(Calculator calc : calcs) { if(calc != null && calc.getFuncs() != null && calc.getFuncs().size() > 0) { text.append(calc.getFuncs()).append(", "); } } player.sendMessage(text.toString()); break; } case "invul": { player.setInvul(!player.isInvul()); break; } case "send_bytes": { try { String[] strBytes = values.split(" "); List<Short> list = new ArrayList<Short>(); for(int i = 0; i < strBytes.length; i++) { list.add(Short.parseShort(strBytes[i], 16)); } player.sendPacket(SeverDeveloperPacket.getInstance(list), true); } catch(Exception e) { e.printStackTrace(); } break; } case "send_file": { for(int i = 0; i < 10; i++) { File file = new File("./data/packets/packet" + (i == 0 ? "" : String.valueOf(i)) + ".txt"); try(Scanner in = new Scanner(file)) { List<Short> list = new ArrayList<Short>(); if(in.hasNext()) { for(String str = in.next(); in.hasNext(); str = in.next()) { list.add(Short.parseShort(str, 16)); } } player.sendPacket(SeverDeveloperPacket.getInstance(list), true); } catch(IOException e) { break; } } for(int i = 0; i < 10; i++) { File file = new File("./data/packet" + (i == 0 ? "" : String.valueOf(i)) + ".txt"); try(Scanner in = new Scanner(file)) { List<Short> list = new ArrayList<Short>(); if(in.hasNext()) { for(String str = in.next(); in.hasNext(); str = in.next()) { list.add(Short.parseShort(str, 16)); } } player.sendPacket(SeverDeveloperPacket.getInstance(list), true); } catch(IOException e) { break; } } break; } case "reload_skills": { SkillTable skillTable = SkillTable.getInstance(); skillTable.reload(); break; } case "set_level": { try { String[] vals = values.split(" "); if(vals.length < 1) { return; } byte level = Byte.parseByte(vals[0]); Player target = player; if(vals.length > 1) { target = World.getAroundByName(Player.class, player, vals[1]); } if(target == null) { return; } if(level > target.getLevel()) { for(int i = target.getLevel(); i < level; i++) { target.increaseLevel(); } } else { target.setLevel(level); target.updateInfo(); } DataBaseManager dbManager = DataBaseManager.getInstance(); dbManager.updatePlayerLevel(target); } catch(NumberFormatException e) { Loggers.warning(getClass(), "error parsing " + values); } break; } case "set_access_level": { try { int val = Integer.parseInt(values); player.setAccessLevel(val); } catch(NumberFormatException e) { Loggers.warning(getClass(), "error parsing " + values); } break; } case "get_access_level": { player.sendMessage(String.valueOf(player.getAccessLevel())); break; } case "set_heart": { try { player.setStamina(Integer.parseInt(values)); player.updateInfo(); } catch(NumberFormatException e) { Loggers.warning(getClass(), "error parsing " + values); } } } } } <file_sep>/java/game/tera/gameserver/model/regenerations/Regen.java package tera.gameserver.model.regenerations; /** * Интерфейс для реализации регена у персонажей. * * @author Ronn * @created 14.04.2012 */ public interface Regen { /** * @return нужно ли выполнить реген. */ public boolean checkCondition(); /** * Выполнение регена. */ public void doRegen(); } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Player_Change_Prof.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.resourse.ResourseType; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с увеличением уровня сбора ресурсов. * * @author Ronn */ public class S_Player_Change_Prof extends ServerPacket { private static final ServerPacket instance = new S_Player_Change_Prof(); public static S_Player_Change_Prof getInstance(ResourseType type, int level) { S_Player_Change_Prof packet = (S_Player_Change_Prof) instance.newInstance(); packet.level = level; packet.type = type; return packet; } /** тип ресурса */ private ResourseType type; /** уровень навыка */ private int level; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_PLAYER_CHANGE_PROF; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, type.ordinal()); writeShort(buffer, level); //06 00 кол-во } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/Debuff.java package tera.gameserver.model.skillengine.classes; import rlib.util.array.Array; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.npc.Npc; import tera.gameserver.network.serverpackets.S_Each_Skill_Result; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель скила для вешания дебафа на цель. * * @author Ronn */ public class Debuff extends Effect { /** * @param template темплейт скила. */ public Debuff(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем информацию о атаке AttackInfo info = local.getNextAttackInfo(); // рассчитывам блокированность дебафа info.setBlocked(target.isBlocked(attacker, impactX, impactY, this)); // если дебаф не заблокирован if(!info.isBlocked()) { // добавляем эффекты addEffects(attacker, target); // если цель нпс, агрмм его на себя if(target.isNpc()) { Npc npc = target.getNpc(); // добавялем агр поинты npc.addAggro(attacker, attacker.getLevel() * attacker.getLevel(), false); } } // если цель в ПвП режиме и не ПК, а атакующей н в ПвП режиме if(target.isPvPMode() && !attacker.isPvPMode()) attacker.setPvPMode(true); // отображаем анимацию приминения дебафа target.broadcastPacket(S_Each_Skill_Result.getInstance(attacker, target, template.getDamageId(), getPower(), false, false, S_Each_Skill_Result.EFFECT)); return info; } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // набор целей Array<Character> targets = local.getNextCharList(); // добавление в набор целей подходящих addTargets(targets, character, targetX, targetY, targetZ); Character[] array = targets.array(); // перебор for(int i = 0, length = targets.size(); i < length; i++) { // цель Character target = array[i]; // если мертва или в инвуле или в уклоне, не подходит if(target.isDead() || target.isInvul() || target.isEvasioned()) continue; // применяем скил applySkill(character, target); } } } <file_sep>/java/game/tera/gameserver/model/items/CrystalInstance.java package tera.gameserver.model.items; import tera.gameserver.templates.CrystalTemplate; import tera.gameserver.templates.ItemTemplate; /** * Модель кристала. * * @author Ronn */ public class CrystalInstance extends ItemInstance { public CrystalInstance(int objectId, ItemTemplate template) { super(objectId, template); } @Override public CrystalInstance getCrystal() { return this; } /** * @return тсэк тип кристала. */ public StackType getStackType() { return getTemplate().getStackType(); } @Override public CrystalTemplate getTemplate() { return (CrystalTemplate) template; } @Override public CrystalType getType() { return (CrystalType) template.getType(); } @Override public boolean isCrystal() { return true; } /** * @return запрощено ли больше 1 однотипного кристала. */ public boolean isNoStack() { return getTemplate().isNoStack(); } } <file_sep>/java/game/tera/gameserver/templates/WeaponTemplate.java package tera.gameserver.templates; import rlib.util.VarTable; import tera.gameserver.model.equipment.SlotType; import tera.gameserver.model.items.WeaponType; import tera.gameserver.model.playable.Player; /** * Модель шаблона оружия. * * @author Ronn */ public final class WeaponTemplate extends GearedTemplate { public WeaponTemplate(WeaponType type, VarTable vars) { super(type, vars); slotType = SlotType.SLOT_WEAPON; } @Override public boolean checkClass(Player player) { return getType().checkClass(player); } @Override public int getClassIdItemSkill() { return -11; } @Override public final WeaponType getType() { return (WeaponType) type; } } <file_sep>/java/game/tera/gameserver/model/npc/Npc.java package tera.gameserver.model.npc; import java.util.Comparator; import rlib.geom.Angles; import rlib.geom.Coords; import rlib.util.Rnd; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import rlib.util.random.Random; import tera.Config; import tera.gameserver.IdFactory; import tera.gameserver.manager.EventManager; import tera.gameserver.manager.GeoManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.manager.RandomManager; import tera.gameserver.model.Character; import tera.gameserver.model.EmotionType; import tera.gameserver.model.Party; import tera.gameserver.model.World; import tera.gameserver.model.WorldRegion; import tera.gameserver.model.ai.CharacterAI; import tera.gameserver.model.geom.Geom; import tera.gameserver.model.geom.NpcGeom; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.npc.interaction.DialogData; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.npc.playable.NpcAppearance; import tera.gameserver.model.npc.spawn.Spawn; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.NpcIconType; import tera.gameserver.model.quests.QuestData; import tera.gameserver.model.quests.QuestType; import tera.gameserver.model.regenerations.NpcRegenHp; import tera.gameserver.model.regenerations.NpcRegenMp; import tera.gameserver.model.regenerations.Regen; import tera.gameserver.model.skillengine.Formulas; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.SkillGroup; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.network.serverpackets.*; import tera.gameserver.tables.SkillTable; import tera.gameserver.taskmanager.RegenTaskManager; import tera.gameserver.tasks.EmotionTask; import tera.gameserver.tasks.TurnTask; import tera.gameserver.templates.NpcTemplate; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; import tera.util.Location; /** * Базовая модель нпс. * * @author Ronn */ public abstract class Npc extends Character implements Foldable { /** таблица штрафа на экспу в зависимости от разницы в уровнях */ public static final float[] PENALTY_EXP = { 1F, // 0 1F, // 1 1F, // 2 1F, // 3 1F, // 4 1F, // 5 0.5F, // 6 0.4F, // 7 0.3F, // 8 0.2F, // 9 0.1F, // 10 0F, // 12 }; public static final int INTERACT_RANGE = 200; /** * public static final float[] PENALTY_EXP = { 1F, // 0 1F, // 1 1F, // 2 * 1F, // 3 1F, // 4 1F, // 5 0.6F, // 6 0.5F, // 7 0.4F, // 8 0.35F, // 9 * 0.3F, // 10 0.25F, // 11 0.2F, // 12 0.15F, // 13 0.1F, // 14 0.08F, // * 15 0.06F, // 16 0.04F, // 17 0.02F, // 18 0.01F, // 19 0F, // 20 }; */ /** сортировщик аггресоров по уровню агрессии */ private static final Comparator<AggroInfo> AGGRO_COMPORATOR = new Comparator<AggroInfo>() { @Override public int compare(AggroInfo info, AggroInfo next) { if(info == null) { return 1; } if(next == null) { return -1; } return next.compareTo(info); } }; /** * Спавн объектов вокруг объекта. * * @param character центральный объект. * @param items список объектов, которые нужно отспавнить. * @param length кол-во объектов. */ public static void spawnDropItems(Character character, ItemInstance[] items, int length) { if(length < 1) { return; } RandomManager randManager = RandomManager.getInstance(); Random random = randManager.getDropItemPointRandom(); float x = character.getX(); float y = character.getY(); float z = character.getZ(); int continentId = character.getContinentId(); GeoManager geoManager = GeoManager.getInstance(); for(int i = 1; i <= length; i++) { float radians = Angles.headingToRadians(random.nextInt(0, Short.MAX_VALUE * 2)); int distance = random.nextInt(40, 80); float newX = Coords.calcX(x, distance, radians); float newY = Coords.calcY(y, distance, radians); float newZ = geoManager.getHeight(continentId, newX, newY, z); ItemInstance item = items[i - 1]; item.setContinentId(continentId); item.spawnMe(newX, newY, newZ, 0); } } /** пул контейнеров информации об агре */ protected final FoldablePool<AggroInfo> aggroInfoPool; /** аггро лист */ protected final Array<AggroInfo> aggroList; /** обработчик разворота нпс */ protected final TurnTask turnTask; /** спавнер */ protected Spawn spawn; /** точка спавна */ protected Location spawnLoc; /** таблица скилов НПС */ protected Skill[][] skills; /** отсортирован ли агро лист */ protected volatile boolean aggroSorted; /** * @param objectId уникальный ид. * @param template темплейт нпс. */ public Npc(int objectId, NpcTemplate template) { super(objectId, template); aggroInfoPool = Pools.newConcurrentFoldablePool(AggroInfo.class); aggroList = Arrays.toConcurrentArray(AggroInfo.class); turnTask = new TurnTask(this); SkillTemplate[][] temps = template.getSkills(); skills = new Skill[temps.length][]; for(int i = 0, length = temps.length; i < length; i++) { SkillTemplate[] list = temps[i]; if(list == null) { continue; } skills[i] = SkillTable.create(list); addSkills(skills[i], false); } Formulas formulas = Formulas.getInstance(); formulas.addFuncsToNewNpc(this); RegenTaskManager regenManager = RegenTaskManager.getInstance(); regenManager.addCharacter(this); } /** * Добавление агрессии на персонажа. * * @param aggressor агрессор. * @param aggro агр поинты. * @param damage урон ли это. */ public void addAggro(Character aggressor, long aggro, boolean damage) { if(aggro < 1) return; aggressor.addHated(this); aggro *= aggressor.calcStat(StatType.AGGRO_MOD, 1, this, null); Array<AggroInfo> aggroList = getAggroList(); aggroList.writeLock(); try { int index = aggroList.indexOf(aggressor); if(index < 0) { aggroList.add(newAggroInfo(aggressor, aggro, damage ? aggro : 0)); } else { AggroInfo info = aggroList.get(index); info.addAggro(aggro); if(damage) { info.addDamage(Math.min(aggro, getCurrentHp())); } } setAggroSorted(index == 0); } finally { aggroList.writeUnlock(); } ObjectEventManager eventManager = ObjectEventManager.getInstance(); eventManager.notifyAgression(this, aggressor, aggro); } @Override public void addMe(Player player) { player.sendPacket(S_Spawn_Npc.getInstance(this, player), true); if(isBattleStanced()) { PacketManager.showBattleStance(player, this, getEnemy()); } ObjectEventManager eventManager = ObjectEventManager.getInstance(); eventManager.notifyAddNpc(player, this); super.addMe(player); } /** * Рассчет выдачи экспы. * * @param killer убийца нпс. */ protected void calculateRewards(Character killer) { Character top = getMostDamager(); if(top == null) { top = killer; } if(top.isPK()) return; if(top.isSummon()) { top = top.getOwner(); } if(top == null || !top.isPlayer()) { return; } NpcTemplate template = getTemplate(); int exp = (int) (template.getExp() * Config.SERVER_RATE_EXP); Player player = top.getPlayer(); if(exp > 0) { Party party = player.getParty(); if(party != null) party.addExp(exp, player, this); else { float reward = exp; int diff = Math.abs(player.getLevel() - getLevel()); if(diff >= PENALTY_EXP.length) { reward *= 0F; } else if(diff > 5) { reward *= PENALTY_EXP[diff]; } if(Config.ACCOUNT_PREMIUM_EXP && player.hasPremium()) { reward *= Config.ACCOUNT_PREMIUM_EXP_RATE; } player.addExp((int) reward, this, getName()); } } if(template.isCanDrop()) { LocalObjects local = LocalObjects.get(); Array<ItemInstance> items = template.getDrop(local.getNextItemList(), this, player); if(items != null) { Party party = player.getParty(); ItemInstance[] array = items.array(); for(int i = 0, length = items.size(); i < length; i++) { ItemInstance item = array[i]; item.setDropper(this); item.setTempOwner(player); item.setTempOwnerParty(party); } spawnDropItems(this, array, items.size()); } } } /** * Проверка на возможность разговора игрока с нпс. * * @param player игрок, который хочет взаимодействовать с нпс. * @return может ли игрок взаимодействовать. */ public boolean checkInteraction(Player player) { return isInRange(player, INTERACT_RANGE); } @Override public boolean checkTarget(Character target) { return true; } /** * Полная очистка аггр листа. */ public void clearAggroList() { Array<AggroInfo> aggroList = getAggroList(); FoldablePool<AggroInfo> pool = getAggroInfoPool(); aggroList.writeLock(); try { AggroInfo[] array = aggroList.array(); for(int i = 0, length = aggroList.size(); i < length; i++) { AggroInfo info = array[i]; Character aggressor = info.getAggressor(); aggressor.removeHate(this); pool.put(info); } aggroList.clear(); } finally { aggroList.writeUnlock(); } setAggroSorted(true); } @Override public void decayMe(int type) { super.decayMe(type); clearAggroList(); } @Override public void deleteMe() { CharacterAI ai = getAI(); if(ai != null) { ai.stopAITask(); } super.deleteMe(); } /** * Увеличение счетчика убийств. * * @param attacker убийца. */ protected void addCounter(Character attacker) { World.addKilledNpc(); if(attacker != null) { attacker.addPvECount(); if(attacker.isPK() && attacker.isPlayer()) { Player player = attacker.getPlayer(); player.clearKarma(this); } } } @Override public void doDie(Character attacker) { addCounter(attacker); synchronized(this) { if(isSpawned()) calculateRewards(attacker); super.doDie(attacker); deleteMe(S_Despawn_Npc.DEAD); } Spawn spawn = getSpawn(); if(spawn != null) { spawn.doDie(this); } } @Override public void doOwerturn(Character attacker) { if(isOwerturned()) { return; } super.doOwerturn(attacker); float radians = Angles.degreeToRadians(Angles.headingToDegree(heading) + 180); NpcTemplate template = getTemplate(); int distance = template.getOwerturnDist(); float newX = Coords.calcX(x, distance, radians); float newY = Coords.calcY(y, distance, radians); GeoManager geoManager = GeoManager.getInstance(); float newZ = geoManager.getHeight(getContinentId(), newX, newY, getZ()); setXYZ(newX, newY, newZ); owerturnTask.nextOwerturn(template.getOwerturnTime()); } @Override public void finalyze() { } /** * Получить кол-во агра на персонажа. * * @param aggressor агрессор. * @return кол-во агра. */ public long getAggro(Character aggressor) { Array<AggroInfo> aggroList = getAggroList(); aggroList.writeLock(); try { int index = aggroList.indexOf(aggressor); if(index < 0) { return -1; } AggroInfo info = aggroList.get(index); return info.getAggro(); } finally { aggroList.writeUnlock(); } } /** * @return пул контейнеров информации об агре. */ protected FoldablePool<AggroInfo> getAggroInfoPool() { return aggroInfoPool; } /** * @return список агрессоров. */ public final Array<AggroInfo> getAggroList() { return aggroList; } /** * @return радиус агра нпс. */ public final int getAggroRange() { return getTemplate().getAggro(); } @Override public final CharacterAI getAI() { return (CharacterAI) ai; } @Override public final int getAttack(Character attacked, Skill skill) { return (int) calcStat(StatType.ATTACK, getTemplate().getAttack(), attacked, skill); } @Override protected EmotionType[] getAutoEmotions() { return EmotionTask.MONSTER_TYPES; } @Override public final int getBalance(Character attacker, Skill skill) { return (int) calcStat(StatType.BALANCE, getTemplate().getBalance(), attacker, skill); } @Override public final int getDefense(Character attacker, Skill skill) { return (int) calcStat(StatType.DEFENSE, getTemplate().getDefense(), attacker, skill); } /** * @return конечное направление. */ public final int getEndHeading() { return turnTask.getEndHeading(); } /** * @return базовый получаемый опыт с нпс. */ public final int getExp() { return getTemplate().getExp(); } /** * @return название фракции нпс. */ public final String getFraction() { return getTemplate().getFactionId(); } /** * @return радиус фракции нпс. */ public final int getFractionRange() { return getTemplate().getFactionRange(); } @Override public final int getImpact(Character attacked, Skill skill) { return (int) calcStat(StatType.IMPACT, getTemplate().getImpact(), attacked, skill); } @Override public int getLevel() { return getTemplate().getLevel(); } /** * @param player игрок, запрашивающий диалог. * @return набор ссылок. */ public final Array<Link> getLinks(Player player) { NpcTemplate template = getTemplate(); LocalObjects local = LocalObjects.get(); Array<Link> links = local.getNextLinkList(); EventManager eventManager = EventManager.getInstance(); eventManager.addLinks(links, this, player); DialogData dialog = template.getDialog(); if(dialog != null) dialog.addLinks(links, this, player); QuestData quests = template.getQuests(); quests.addLinks(links, this, player); return links; } /** * @return лидер этого миниона. */ public MinionLeader getMinionLeader() { return null; } /** * @return персонаж, который само много надэмажил. */ public Character getMostDamager() { Array<AggroInfo> aggroList = getAggroList(); if(aggroList.isEmpty()) { return null; } Character top = null; aggroList.readLock(); try { AggroInfo[] array = aggroList.array(); long damage = -1; for(int i = 0, length = aggroList.size(); i < length; i++) { AggroInfo info = array[i]; if(info == null) { continue; } if(info.getDamage() > damage) { top = info.getAggressor(); damage = info.getDamage(); } } } finally { aggroList.readUnlock(); } return top; } /** * @return приоритетная цель нпс. */ public Character getMostHated() { Array<AggroInfo> aggroList = getAggroList(); if(aggroList.isEmpty()) { return null; } if(!isAggroSorted()) { aggroList.sort(AGGRO_COMPORATOR); setAggroSorted(true); } AggroInfo top = aggroList.first(); return top != null ? top.getAggressor() : null; } @Override public final String getName() { return getTemplate().getName(); } @Override public Npc getNpc() { return this; } /** * @return тип НПС. */ public final NpcType getNpcType() { return getTemplate().getNpcType(); } @Override public int getOwerturnId() { return 0x482DEB16; } /** * @return случайный скил из указанной группы. */ public Skill getRandomSkill(SkillGroup group) { Skill[] list = skills[group.ordinal()]; return list == null || list.length < 1 ? null : list[Rnd.nextInt(0, list.length - 1)]; } /** * Получить первый доступный скил указанной группы. * * @param group группа скилов. * @return первый доступный в не откате скил. */ public Skill getFirstEnabledSkill(SkillGroup group) { Skill[] array = skills[group.ordinal()]; if(array.length > 0) { for(Skill skill : array) { if(!isSkillDisabled(skill)) { return skill; } } } return null; } /** * @return спанер нпс. */ public final Spawn getSpawn() { return spawn; } /** * @return точка спавна. */ public final Location getSpawnLoc() { return spawnLoc; } @Override public final int getSubId() { return Config.SERVER_NPC_SUB_ID; } @Override public final NpcTemplate getTemplate() { return (NpcTemplate) template; } /** * @return есть ли у нпс диалог. */ public final boolean hasDialog() { return getTemplate().getDialog() != null; } /** * @return аггресивный ли нпс. */ public final boolean isAggressive() { return getTemplate().getAggro() > 0; } /** * @return отсортирован ли аггро лист. */ public final boolean isAggroSorted() { return aggroSorted; } /** * @return является ли НПС дружелюбным. */ public boolean isFriendNpc() { return false; } /** * @return является ли НПС гвардом. */ public boolean isGuard() { return false; } /** * @return является ли НПС минионом. */ public boolean isMinion() { return false; } /** * @return является ли НПС лидером минионов. */ public boolean isMinionLeader() { return false; } /** * @return является ли НПС монстром. */ public boolean isMonster() { return false; } @Override public final boolean isNpc() { return true; } /** * @return является ли НПС РБ. */ public boolean isRaidBoss() { return false; } /** * @return находится ли нпс в процессе разворота. */ public boolean isTurner() { return turnTask.isTurner(); } /** * @param aggressor агрессор. * @param aggro уровень агрессии. * @param damage нанесенный урон. * @return новый контейнер информации об агре. */ protected AggroInfo newAggroInfo(Character aggressor, long aggro, long damage) { AggroInfo info = aggroInfoPool.take(); if(info == null) info = new AggroInfo(); info.setAggressor(aggressor); info.setAggro(aggro); info.setDamage(damage); return info; } @Override protected Geom newGeomCharacter() { NpcTemplate template = getTemplate(); return new NpcGeom(this, template.getGeomHeight(), template.getGeomRadius()); } @Override protected Regen newRegenHp() { return new NpcRegenHp(this); } @Override protected Regen newRegenMp() { return new NpcRegenMp(this); } @Override protected Regen newRegenFatigability() { return null; } /** * Развернуть нпс до указанного направления. * * @param newHeading новое направление. */ public void nextTurn(int newHeading) { turnTask.nextTurn(newHeading); } @Override public void reinit() { IdFactory idFactory = IdFactory.getInstance(); objectId = idFactory.getNextNpcId(); } /** * Удалить персонажа с аггр листа. * * @param agressor удаляемый персонаж. */ public void removeAggro(Character agressor) { Array<AggroInfo> aggroList = getAggroList(); aggroList.writeLock(); try { int index = aggroList.indexOf(agressor); if(index >= 0) { AggroInfo aggroInfo = aggroList.get(index); long aggro = aggroInfo.getAggro(); agressor.removeHate(this); aggroInfoPool.put(aggroInfo); aggroList.fastRemove(index); setAggroSorted(index != 0); ObjectEventManager eventManager = ObjectEventManager.getInstance(); eventManager.notifyAgression(this, agressor, -aggro); } } finally { aggroList.writeUnlock(); } } @Override public void removeMe(Player player, int type) { player.sendPacket(S_Despawn_Npc.getInstance(this, type), true); } /** * @param aggroSorted отсортирован ли список агрессоров. */ public final void setAggroSorted(boolean aggroSorted) { this.aggroSorted = aggroSorted; } /** * @param spawn спавнер нпс. */ public final void setSpawn(Spawn spawn) { this.spawn = spawn; } /** * @param spawnLoc точка спавна. */ public final void setSpawnLoc(Location spawnLoc) { this.spawnLoc = spawnLoc; } @Override public void spawnMe() { super.spawnMe(); World.addSpawnedNpc(); } @Override public void spawnMe(Location loc) { setSpawnLoc(loc); setCurrentHp(getMaxHp()); setCurrentMp(getMaxMp()); super.spawnMe(loc); WorldRegion region = getCurrentRegion(); if(region != null && region.isActive()) { getAI().startAITask(); emotionTask.start(); } } @Override public boolean startBattleStance(Character enemy) { if(enemy != null && enemy != getEnemy() || enemy == null && isBattleStanced()) { PacketManager.showBattleStance(this, enemy); } setBattleStanced(enemy != null); setEnemy(enemy); return true; } @Override public void stopBattleStance() { setBattleStanced(false); broadcastPacketToOthers(S_Npc_Status.getInstance(this, 0, 0)); } /** * Уменьшени агрессии. * * @param aggressor агрессор. * @param aggro агр поинты. */ public void subAggro(Character aggressor, long aggro) { Array<AggroInfo> aggroList = getAggroList(); aggroList.writeLock(); try { int index = aggroList.indexOf(aggressor); if(index > -1) { AggroInfo info = aggroList.get(index); info.subAggro(aggro); if(info.getAggro() < 1) { aggroList.fastRemove(index); aggressor.removeHate(this); aggroInfoPool.put(info); } setAggroSorted(index != 0); ObjectEventManager eventManager = ObjectEventManager.getInstance(); eventManager.notifyAgression(this, aggressor, aggro * -1); } } finally { aggroList.writeUnlock(); } } @Override public void teleToLocation(int continentId, float x, float y, float z, int heading) { decayMe(S_Despawn_Npc.DISAPPEARS); super.teleToLocation(continentId, x, y, z, heading); spawnMe(getSpawnLoc()); } @Override public String toString() { return "NpcInstance id = " + getTemplateId() + ", type = " + getTemplateType(); } @Override public void updateHp() { S_Show_Hp packet = S_Show_Hp.getInstance(this, S_Show_Hp.RED); Array<AggroInfo> aggroList = getAggroList(); aggroList.readLock(); try { AggroInfo[] array = aggroList.array(); for(int i = 0, length = aggroList.size(); i < length; i++) { Character aggressor = array[i].getAggressor(); if(aggressor != null && (aggressor.isPlayer() || aggressor.isSummon())) { packet.increaseSends(); } } for(int i = 0, length = aggroList.size(); i < length; i++) { Character aggressor = array[i].getAggressor(); if(aggressor != null) { if(aggressor.isPlayer()) { aggressor.sendPacket(packet, false); } else if(aggressor.isSummon() && aggressor.getOwner() != null) { aggressor.getOwner().sendPacket(packet, false); } } } } finally { aggroList.readUnlock(); } } /** * @param player игрок. */ public void updateQuestInteresting(Player player, boolean delete) { if(player == null) { log.warning(this, new Exception("not found player")); return; } QuestData quests = getTemplate().getQuests(); QuestType type = quests.hasQuests(this, player); if(type == null && delete) player.sendPacket(S_Quest_Villager_Info.getInstance(this, NpcIconType.NONE), true); else if(type != null) { switch(type) { case STORY_QUEST: player.sendPacket(S_Quest_Villager_Info.getInstance(this, NpcIconType.RED_NOTICE), true); break; case LEVEL_UP_QUEST: case ZONE_QUEST: player.sendPacket(S_Quest_Villager_Info.getInstance(this, NpcIconType.YELLOW_NOTICE), true); break; case GUILD_QUEST: player.sendPacket(S_Quest_Villager_Info.getInstance(this, NpcIconType.BLUE_NOTICE), true); break; case DEALY_QUEST: player.sendPacket(S_Quest_Villager_Info.getInstance(this, NpcIconType.GREEN_NOTICE), true); break; } } } /** * Является ли дружественным для указанного игрока. * * @param player игрок. * @return является ли дружественным. */ public boolean isFriend(Player player) { return isFriendNpc(); } /** * @return модификатор отмытия кармы. */ public int getKarmaMod() { return 1; } @Override public boolean isOwerturnImmunity() { return getTemplate().isOwerturnImmunity(); } /** * Будет ли цель спереди после разворота НПС. * * @param target проверяемая цель. * @return будет ли она спереди. */ public boolean isInTurnFront(Character target) { if(target == null) return false; float dx = target.getX() - getX(); float dy = target.getY() - getY(); int head = (int) (Math.atan2(-dy, -dx) * HEADINGS_IN_PI + 32768); head = turnTask.getEndHeading() - head; if(head < 0) head = head + 1 + Integer.MAX_VALUE & 0xFFFF; else if(head > 0xFFFF) head &= 0xFFFF; return head != -1 && head <= 8192 || head >= 57344; } /** * @return внешность НПС. */ public NpcAppearance getAppearance() { return null; } /** * @return цвет имени НПС. */ public int getNameColor() { return S_Change_Relation.COLOR_NORMAL; } /** * Завершение отображения смерти. */ public void finishDead() { } @Override public boolean isBroadcastEndSkillForCollision() { return true; } /** * @return маршрут патрулирования. */ public Location[] getRoute() { return getSpawn().getRoute(); } }<file_sep>/java/game/tera/gameserver/network/clientpackets/C_Update_Guild_Title.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.Guild; import tera.gameserver.model.GuildRank; import tera.gameserver.model.playable.Player; /** * Обнвление титула гильдии. * * @author Ronn * @created 26.04.2012 */ public class C_Update_Guild_Title extends ClientPacket { /** имя передоваемого */ private String title; /** мастер гильдии */ private Player player; @Override public void finalyze() { player = null; title = null; } @Override protected void readImpl() { player = owner.getOwner(); readShort(); title = readString();//61 00 75 00 73 00 74 00 00 00 ..AO..F.a.u.s.t. } @Override protected void runImpl() { try { if(player == null || title.length() > 44) return; GuildRank rank = player.getGuildRank(); if(rank == null || !rank.isChangeTitle()) return; Guild guild = player.getGuild(); if(guild != null) guild.setTitle(title); } finally { player.updateGuild(); } } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_End_Pegasus.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакт для того, чтобы персонаж мог слезть с пегаса * * @author Ronn * */ public class S_End_Pegasus extends ServerPacket { private static final ServerPacket instance = new S_End_Pegasus(); public static S_End_Pegasus getInstance(Character actor) { S_End_Pegasus packet = (S_End_Pegasus) instance.newInstance(); packet.actor = actor; return packet; } /** персонаж */ private Character actor; @Override public void finalyze() { actor = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_END_PEGASUS; } @Override protected void writeImpl() { writeOpcode(); writeInt(actor.getObjectId());//обжект айди наш writeInt(actor.getSubId()); // саб айди нашь } } <file_sep>/java/game/tera/gameserver/manager/DataBaseManager.java package tera.gameserver.manager; import java.net.InetAddress; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import rlib.database.ConnectFactory; import rlib.database.DBUtils; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Strings; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import rlib.util.wraps.Wrap; import rlib.util.wraps.Wraps; import tera.Config; import tera.gameserver.events.global.regionwars.Region; import tera.gameserver.events.global.regionwars.RegionState; import tera.gameserver.model.*; import tera.gameserver.model.Character; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.base.Race; import tera.gameserver.model.base.Sex; import tera.gameserver.model.dungeons.PlayerDungeon; import tera.gameserver.model.equipment.Equipment; import tera.gameserver.model.equipment.PlayerEquipment; import tera.gameserver.model.inventory.Bank; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.inventory.PlayerBank; import tera.gameserver.model.inventory.PlayerInventory; import tera.gameserver.model.items.CrystalInstance; import tera.gameserver.model.items.CrystalList; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.items.ItemLocation; import tera.gameserver.model.playable.*; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestDate; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestPanelState; import tera.gameserver.model.quests.QuestState; import tera.gameserver.model.skillengine.Effect; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.territory.Territory; import tera.gameserver.network.serverpackets.S_Delete_User; import tera.gameserver.tables.ItemTable; import tera.gameserver.tables.PlayerTable; import tera.gameserver.tables.SkillTable; import tera.gameserver.tables.TerritoryTable; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.ItemTemplate; import tera.gameserver.templates.NpcTemplate; import tera.gameserver.templates.PlayerTemplate; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; import tera.util.Location; import com.jolbox.bonecp.BoneCPConfig; /** * Менеджер для работы с БД. * * @author Ronn * @created 04.03.2012 */ public final class DataBaseManager { private static final Logger LOGGER = Loggers.getLogger(DataBaseManager.class); private static final String UPDATE_ITEM = "UPDATE `items` SET `item_count`=?, `owner_id`=?, `location`=?, `index`=?, `has_crystal`=?, `autor`=?, `bonus_id`=?, `enchant_level`=?, `owner_name`=? WHERE `object_id`=? LIMIT 1"; private static final String UPDATE_DATA_ITEM = "UPDATE `items` SET `item_count`=?, `has_crystal`=?, `autor`=?, `bonus_id`=?, `enchant_level`=?, `owner_name`=? WHERE `object_id`=? LIMIT 1"; private static final String UPDATE_LOCATION_ITEM = "UPDATE `items` SET `owner_id`=?, `location`=?, `index`=? WHERE `object_id`=? LIMIT 1"; private static final String CREATE_ITEM = "INSERT INTO `items` (object_id, item_id, item_count, location) VALUES (?,?,?,?)"; private static final String SELECT_ITEM = "SELECT * from `items` WHERE `object_id` = ? LIMIT 1"; private static final String UPDATE_INVENTORY = "UPDATE `character_inventors` SET `owner_id`=? WHERE `owner_id`=? LIMIT 1"; private static final String CREATE_INVENTORY = "INSERT INTO `character_inventors` (owner_id, level) VALUES (?,?)"; private static final String INSERT_ACCOUNT_BANK = "INSERT INTO `account_bank` (account_name) VALUES (?)"; private static final String RESTORE_ACCOUNT_BANK = "SELECT * FROM `account_bank` WHERE `account_name` = ? LIMIT 1"; private static final String UPDATE_ACCOUNT_FATIGABILITY = "UPDATE `accounts` SET `fatigability` = ? WHERE `AccountId` = ? LIMIT 1"; private static final String CREATE_SKILL = "INSERT INTO `character_skills` (object_id, class_id, skill_id) VALUES (?,?,?)"; private static final String DELETE_SKILL = "DELETE FROM `character_skills` WHERE `object_id`=? AND `class_id`=? AND `skill_id`=? LIMIT 1"; private static final String UPDATE_PLAYER_LEVEL = "UPDATE `characters` SET `level`=? WHERE `object_id`=? LIMIT 1"; private static final String UPDATE_PLAYER_ZONE_ID = "UPDATE `characters` SET `zone_id`=? WHERE `object_id`=? LIMIT 1"; private static final String UPDATE_PLAYER_CONTINENT_ID = "UPDATE `characters` SET `continent_id`=? WHERE `object_id`=? LIMIT 1"; private static final String UPDATE_PLAYER_GUILD = "UPDATE `characters` SET `guild_id`=?, `guild_rank`=? WHERE `object_id`=? LIMIT 1"; private static final String UPDATE_PLAYER_TITLE = "UPDATE `characters` SET `title`= ? WHERE `object_id`= ? LIMIT 1"; private static final String UPDATE_PLAYER_DESCRIPTION = "UPDATE `characters` SET `description`= ? WHERE `object_id`= ? LIMIT 1"; private static final String UPDATE_PLAYER_GUILD_NOTE = "UPDATE `characters` SET `guild_note`= ? WHERE `object_id`= ? LIMIT 1"; private static final String CREATE_QUEST = "REPLACE INTO `character_quests` (object_id, quest_id, state, date) VALUES (?,?,?,?)"; private static final String UPDATE_QUEST = "UPDATE `character_quests` SET `state` = ?, `panel_state` = ? WHERE `object_id` = ? AND `quest_id` = ?"; private static final String FINISH_QUEST = "UPDATE `character_quests` SET `state` = 0, date = ? WHERE `object_id` = ? AND `quest_id` = ?"; private static final String REMOVE_QUEST = "DELETE FROM `character_quests` WHERE `object_id` = ? AND `quest_id` = ?"; private static final String STORE_QUEST_VAR = "REPLACE INTO `character_quest_vars` (object_id, quest_id, name, value) VALUES (?,?,?,?)"; private static final String RESTORE_QUEST_VAR = "SELECT * FROM `character_quest_vars` WHERE `object_id` = ? AND quest_id = ?"; private static final String CLEAR_QUEST_VAR = "DELETE FROM `character_quest_vars` WHERE `object_id` = ? AND quest_id = ?"; private static final String CREATE_GUILD_RANK = "INSERT INTO `guild_ranks` (`guild_id`, `rank_name`, `order`, `law`) VALUES (?,?,?,?)"; private static final String REMOVE_GUILD_RANK = "DELETE FROM `guild_ranks` WHERE `guild_id` = ? AND `order` = ? LIMIT 1"; private static final String REMOVE_GUILD_RANK_FOR_PLAYERS = "UPDATE `characters` SET `guild_rank` = ? WHERE `guild_id` = ? AND `guild_rank` = ? LIMIT ?"; private static final String UPDATE_GUILD_ICON = "UPDATE `guilds` SET `icon` = ?, icon_name = ? WHERE `id` = ? LIMIT 1"; private static final String UPDATE_GUILD_RANK = "UPDATE `guild_ranks` SET `rank_name` = ?, law = ? WHERE `order` = ? AND `guild_id` = ? LIMIT 1"; private static final String UPDATE_GUILD_TITLE = "UPDATE `guilds` SET `title` = ? WHERE `id` = ? LIMIT 1"; private static final String UPDATE_GUILD_MESSAGE = "UPDATE `guilds` SET `message` = ? WHERE `id` = ? LIMIT 1"; private static final String UPDATE_GUILD_PRAISE = "UPDATE `guilds` SET `praise` = ? WHERE `id` = ? LIMIT 1"; private static final String CREATE_GUILD_APPLY = "INSERT INTO `wait_guild_apply` (guild_id, character_id, message) VALUES (?,?,?)"; private static final String UPDATE_GUILD_ALLIANCE = "UPDATE `guilds` SET `alliance` = ? WHERE `id` = ? LIMIT 1"; private static final String REMOVE_WAIT_ITEM = "DELETE FROM `wait_items` WHERE `order` = ? LIMIT 1"; private static final String REMOVE_WAIT_SKILL = "DELETE FROM `wait_skills` WHERE `order` = ? LIMIT 1"; private static final String ADD_STORE_TERRITORY = "INSERT INTO `character_territories` (object_id, territory_id) VALUES (?,?)"; private static final String SELECT_SERVER_VARIABLES = "SELECT * FROM `server_variables`"; private static final String REMOVE_SERVER_VARIABLE = "DELETE FROM `server_variables` WHERE `var_name` = ? LIMIT 1"; private static final String INSERT_SERVER_VARIABLE = "INSERT INTO `server_variables` (var_name, var_value) VALUES(?,?)"; private static final String UPDATE_SERVER_VARIABLE = "UPDATE `server_variables` SET `var_value` = ? WHERE `var_name` = ? LIMIT 1"; private static final String SELECT_PLAYER_VARIABLES = "SELECT * FROM `character_variables` WHERE `object_id` = ?"; private static final String REMOVE_PLAYER_VARIABLE = "DELETE FROM `character_variables` WHERE `object_id` = ? AND `var_name` = ? LIMIT 1"; private static final String INSERT_PLAYER_VARIABLE = "INSERT INTO `character_variables` (object_id, var_name, var_value) VALUES(?,?,?)"; private static final String UPDATE_PLAYER_VARIABLE = "UPDATE `character_variables` SET `var_value` = ? WHERE `object_id` = ? AND `var_name` = ? LIMIT 1"; private static final String SELECT_BOSS_SPAWNS = "SELECT * FROM `boss_spawn`"; private static final String INSERT_BOSS_SPAWNS = "INSERT INTO `boss_spawn` (npc_id, npc_type, spawn) VALUES(?,?,?)"; private static final String UPDATE_BOSS_SPAWNS = "UPDATE `boss_spawn` SET `spawn` = ? WHERE `npc_id` = ? AND `npc_type` = ?"; private static final String SELECT_PLAYER_FRIENDS = "SELECT `friend_id`, `friend_note` FROM `character_friends` WHERE `object_id` = ?"; private static final String SELECT_PLAYER_FRIEND = "SELECT `class_id`, `race_id`, `level`, char_name FROM `characters` WHERE `object_id` = ? LIMIT 1"; private static final String INSERT_PLAYER_FRIEND = "INSERT INTO `character_friends` (object_id, friend_id, friend_note) VALUES(?,?,?)"; // private static final String UPDATE_PLAYER_FRIEND_NOTE = // "UPDATE `character_friends` SET `friend_note` = ? WHERE `object_id` = ? AND `friend_id` = ? LIMIT 1"; private static final String REMOME_PLAYER_FRIEND = "DELETE FROM `character_friends` WHERE `object_id` = ? AND `friend_id` = ? LIMIT 1"; private static final String SELECT_REGION_STATUS = "SELECT * FROM `region_status` WHERE `region_id` = ? LIMIT 1"; private static final String SELECT_REGION_REGISTER = "SELECT * FROM `region_war_register` WHERE `region_id` = ?"; private static final String INSERT_REGION_STATUS = "INSERT INTO `region_status` (region_id, owner_id, state) VALUES(?,?,?)"; private static final String INSERT_REGION_REGISTER_GUILD = "INSERT INTO `region_war_register` (region_id, guild_id) VALUES(?,?)"; private static final String REMOVE_REGION_REGISTER_GUILD = "DELETE FROM `region_war_register` WHERE `region_id` = ? AND `guild_id` = ? LIMIT 1"; private static final String UPDATE_REGION_STATE = "UPDATE `region_status` SET `state`= ? WHERE `region_id`= ? LIMIT 1"; private static final String UPDATE_REGION_OWNER = "UPDATE `region_status` SET `owner_id`= ? WHERE `region_id`= ? LIMIT 1"; private static final String SELECT_ALLIANCE = "SELECT u.*, c.`char_name`, g.`name` FROM `union` u LEFT JOIN `characters` c ON (c.`object_id` = u.`leader_id`) LEFT JOIN `guilds` g ON (g.`id` = c.`guild_id`)"; private static final String SELECT_ALLIANCE_GUILDS = "SELECT id FROM `guilds` WHERE alliance = ?;"; private static final String UPDATE_ALLIANCE_TAXRATE = "UPDATE `union` SET `tax_rate` = ? WHERE `union_id` = ?"; private static final String UPDATE_ALLIANCE_MESSAGE = "UPDATE `union` SET `message` = ? WHERE `union_id` = ?"; private static final String SELECT_GUILDS = "SELECT * FROM `guilds`"; private static final String SELECT_GUILD_NAME = "SELECT id FROM `guilds` WHERE `name`= ?"; private static final String SELECT_GUILD_RANKS = "SELECT * FROM `guild_ranks` WHERE `guild_id` = ?"; private static final String SELECT_GUILD_APPLY = "SELECT * FROM `wait_guild_apply` g LEFT JOIN `characters` c ON (c.`object_id` = g.`character_id`) where g.`guild_id` = ?"; private static final String DELETE_GUILD_APPLY = "DELETE FROM `wait_guild_apply` WHERE `character_id` = ? AND `guild_id` = ?"; private static final String DELETE_ALL_GUILD_APPLY = "DELETE FROM `wait_guild_apply` WHERE `character_id` = ?"; private static final String SELECT_GUILD_BANK_ITEMS = "SELECT * FROM `items` WHERE `owner_id` = ? AND `location` = '" + ItemLocation.GUILD_BANK.ordinal() + "' LIMIT " + (Config.WORLD_GUILD_BANK_MAX_SIZE + 1); private static final String SELECT_GUILD_MEMBERS = "SELECT class_id, level, char_name, guild_note, zone_id, object_id, race_id, guild_rank, sex, last_online FROM `characters` WHERE `guild_id` = ?"; private static final String REMOVE_GUILD = "DELETE FROM `guilds` WHERE `id` = ? LIMIT 1"; private static final String REMOVE_GUILD_MEMBERS = "UPDATE `characters` SET `guild_id` = '0', `guild_rank` = '0' WHERE `guild_id` = ?"; private static final String INSERT_GUILD = "INSERT INTO `guilds` (`id`, `name`, `title`, `level`) VALUES (?, ?, ''," + 1 + ")"; private static final String SELECT_PLAYER_LIST = "SELECT `object_id` FROM `characters` WHERE `account_name` = ? LIMIT 8"; private static final String SELECT_PLAYER_OJECT_ID = "SELECT object_id FROM `characters` WHERE `char_name`= ? LIMIT 1"; private static final String SELECT_PLAYER_FACE = "SELECT * FROM `character_faces` WHERE `objectId`= ? LIMIT 1"; private static final String SELECT_PLAYER_PREVIEW = "SELECT * FROM `characters` WHERE `object_id`= ? LIMIT 1"; private static final String SELECT_PLAYER_PREVIEW_WITH_NAME = "SELECT * FROM `characters` WHERE `char_name`= ? LIMIT 1"; private static final String SELECT_PLAYER_ACCOUNT = "SELECT `char_name` FROM `characters` WHERE `account_name`= ? LIMIT 8"; private static final String DELETE_PLAYER = "DELETE FROM `characters` WHERE `object_id` = ? AND `account_name` = ? LIMIT 1"; private static final String SELECT_PLAYER_CHECK_NAME = "SELECT object_id FROM `characters` WHERE `char_name` = ? LIMIT 1"; private static final String SELECT_PLAYER_CHECK_ID = "SELECT `object_id` FROM `characters` WHERE `object_id`= ? LIMIT 1"; private static final String UPDATE_PLAYER_LOCATION = "UPDATE `characters` SET `x` = ?, `y` = ?, `z` = ?, `heading` = ?, `continent_id` = ?, `zone_id` = ? WHERE `char_name`= ? LIMIT 1"; private static final String UPDATE_PLAYER_CLASS = "UPDATE `characters` SET `class_id` = ? WHERE `object_id`= ? LIMIT 1"; private static final String UPDATE_PLAYER_RACE = "UPDATE `characters` SET `race_id` = ?, `sex` = ? WHERE `object_id`= ? LIMIT 1"; private static final String SELECT_PLAYER_DUNGEONS = "SELECT * from `character_dungeons` WHERE `object_id` = ?"; private static final String RESET_PLAYER_DUNGEONS = "UPDATE `character_dungeons` set `daily_count` = 0 WHERE 1"; private static final String SELECT_ACCOUNT = "SELECT AccountId, password, email, last_ip, allow_ips, comments, end_block, end_pay, access_level, fatigability FROM `accounts` WHERE `login`= ? LIMIT 1"; private static final String INSERT_ACCOUNT = "INSERT INTO `accounts` (login, password, email, access_level, end_pay, end_block, last_ip, allow_ips, comments) VALUES (?,?,?,?,?,?,?,?,?)"; private static final String INSERT_PLAYER_APPEARANCE = "INSERT INTO `character_appearances` (object_id, face_color, face_skin, adorments_skin, features_skin, features_color, voice, bone_structure_brow, " + "bone_structure_cheekbones, bone_structure_jaw, bone_structure_jaw_jut, ears_rotation, ears_extension, ears_trim, ears_size, eyes_width, eyes_height, eyes_separation, eyes_angle," + "eyes_inner_brow, eyes_outer_brow, nose_extension, nose_size, nose_bridge, nose_nostril_width, nose_tip_width, nose_tip, nose_nostril_flare, mouth_pucker," + "mouth_position, mouth_width, mouth_lip_thickness, mouse_corners, eyes_shape, nose_bend, bone_structure_jaw_width, mouth_gape) VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; private static final String UPDATE_PLAYER_APPEARANCE = "UPDATE `character_appearances` SET `face_color` = ?, `face_skin` = ?, `adorments_skin` = ?, `features_skin` = ?, `features_color` = ?, `voice` = ?, `bone_structure_brow` = ?, " + "`bone_structure_cheekbones` = ?, `bone_structure_jaw` = ?, `bone_structure_jaw_jut` = ?, `ears_rotation` = ?, `ears_extension` = ?, `ears_trim` = ?, `ears_size` = ?, `eyes_width` = ?, `eyes_height` = ?, `eyes_separation` = ?, `eyes_angle` = ?," + "`eyes_inner_brow` = ?, `eyes_outer_brow` = ?, `nose_extension` = ?, `nose_size` = ?, `nose_bridge` = ?, `nose_nostril_width` = ?, `nose_tip_width` = ?, `nose_tip` = ?, `nose_nostril_flare` = ?, `mouth_pucker` = ?," + "`mouth_position` = ?, `mouth_width` = ?, `mouth_lip_thickness` = ?, `mouse_corners` = ?, `eyes_shape` = ?, `nose_bend` = ?, `bone_structure_jaw_width` = ?, `mouth_gape` = ? WHERE `object_id` = ? LIMIT 1"; private static final String SELECT_PLAYER_APPEARANCE = "SELECT face_color, face_skin, adorments_skin, features_skin, features_color, voice, bone_structure_brow, " + "bone_structure_cheekbones, bone_structure_jaw, bone_structure_jaw_jut, ears_rotation, ears_extension, ears_trim, ears_size, eyes_width, eyes_height, eyes_separation, eyes_angle," + "eyes_inner_brow, eyes_outer_brow, nose_extension, nose_size, nose_bridge, nose_nostril_width, nose_tip_width, nose_tip, nose_nostril_flare, mouth_pucker," + "mouth_position, mouth_width, mouth_lip_thickness, mouse_corners, eyes_shape, nose_bend, bone_structure_jaw_width, mouth_gape FROM `character_appearances` WHERE `object_id`= ? LIMIT 1"; private static final String SELECT_CHAR_PRE_2 = "SELECT * FROM `character_presets_2` WHERE `objectId`= ? LIMIT 1"; private static final String INSERT_CHAR_PRE_2 = "INSERT INTO `character_presets_2` (objectId,temp1,temp2,temp3,temp4,temp5,temp6,temp7,temp8,temp9,temp10,temp11,temp12,temp13,temp14,temp15,temp16,temp17,temp18," +"temp19,temp20,temp21,temp22,temp23,temp24,temp25,temp26,temp27,temp28,temp29,temp30,temp31,temp32,temp33,temp34,temp35,temp36,temp37,temp38,temp39," +"temp40,temp41,temp42,temp43,temp44,temp45,temp46,temp47,temp48,temp49,temp50,temp51,temp52,temp53,temp54,temp55,temp56,temp57,temp58,temp59,temp60," +"temp61,temp62,temp63,temp64) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; private static final String UPDATE_CHAR_PRE_2 = "UPDATE `character_presets_2` SET `temp1` = ?, `temp2` = ?, ` = ?, `temp3` = ?, `temp4` = ?, `temp5` = ?, `temp6` = ?, `temp7` = ?, `temp8` = ?, `temp9` = ?, `temp10` = ?, `temp11` = ?, `temp12` = ?, `temp13` = ?, `temp14` = ?, `temp15` = ?, `temp16` = ?, `temp17` = ?, `temp18`" +"temp19` = ?, `temp20` = ?, `temp21` = ?, `temp22` = ?, `temp23` = ?, `temp24` = ?, `temp25` = ?, `temp26` = ?, `temp27` = ?, `temp28` = ?, `temp29` = ?, `temp30` = ?, `temp31` = ?, `temp32` = ?, `temp33` = ?, `temp34` = ?, `temp35` = ?, `temp36` = ?, `temp37` = ?, `temp38` = ?, `temp39`" +"temp40` = ?, `temp41` = ?, `temp42` = ?, `temp43` = ?, `temp44` = ?, `temp45` = ?, `temp46` = ?, `temp47` = ?, `temp48` = ?, `temp49` = ?, `temp50` = ?, `temp51` = ?, `temp52` = ?, `temp53` = ?, `temp54` = ?, `temp55` = ?, `temp56` = ?, `temp57` = ?, `temp58` = ?, `temp59` = ?, `temp60` = ?, `temp61` = ?, `temp62` = ?, `temp63` = ?, `temp64` = ?WHERE `object_id` = ? LIMIT 1"; private static DataBaseManager instance; public static DataBaseManager getInstance() { if(instance == null) instance = new DataBaseManager(Config.DATA_BASE_CONFIG, Config.DATA_BASE_DRIVER); return instance; } /** фабрика подключений */ private final ConnectFactory connectFactory; private DataBaseManager(BoneCPConfig config, String driver) { this.connectFactory = ConnectFactory.newBoneCPConnectFactory(config, driver); } /** * Проверка на свободность названия гильдии. * * @param name название гильдии. * @return подходит ли название. */ public final boolean checkGuildName(String name) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_GUILD_NAME); statement.setString(1, name); rset = statement.executeQuery(); return !rset.next(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return false; } /** * Очистка переменных квеста. * * @param state состояние квеста. */ public final void clearQuestVar(QuestState state) { Player player = state.getPlayer(); if(player == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(CLEAR_QUEST_VAR); statement.setInt(1, player.getObjectId()); statement.setInt(2, state.getQuestId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Создает в бд новый аккаунт. * * @param accountName имя аккаунта. * @param password <PASSWORD>. * @param address ип с которого создан аккаунт. * @return новый аккаунт. */ public final Account createAccount(String accountName, String password, InetAddress address) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); Account newAccount = Account.valueOf(accountName, password, address != null ? address.getHostAddress() : "", "auto"); statement = con.prepareStatement(INSERT_ACCOUNT); statement.setString(1, newAccount.getName()); statement.setString(2, newAccount.getPassword()); statement.setString(3, newAccount.getEmail()); statement.setInt(4, newAccount.getAccessLevel()); statement.setLong(5, -1L); statement.setLong(6, -1L); statement.setString(7, newAccount.getLastIP()); statement.setString(8, newAccount.getAllowIPs()); statement.setString(9, newAccount.getComments()); statement.execute(); return newAccount; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return null; } /** * Создает в бд новый банк аккаунта. * * @param accountName имя аккаунта. * @return успешно ли создан банк. */ public final boolean createAccountBank(String accountName) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_ACCOUNT_BANK); statement.setString(1, accountName); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Создает строку в БД с новой внешностью. * * @param face внешность игрока. * @return успешно ли создано поле. */ public final boolean createFace(DeprecatedPlayerFace face) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con .prepareStatement("INSERT INTO `character_faces` (objectId, faceColor, hairColor, eyebrowsFirstVal, eyebrowsSecondVal, eyebrowsThridVal, eyeFirstVal, eyeSecondVal, eyeThridVal, eyePosVertical, eyeWidth, eyeHeight, chin, cheekbonePos, earsFirstVal, earsSecondVal, earsThridVal, earsFourthVal, noseFirstVal, noseSecondVal, noseThridVal, noseFourthVal, noseFifthVal, lipsFirstVal, lipsSecondVal, lipsThridVal, lipsFourthVal, lipsFifthVal, lipsSixthVal, cheeks, bridgeFirstVal, bridgeSecondVal, bridgeThridVal, temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10, temp11, temp12, temp13, temp14, temp15, temp16, temp17, temp18) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); statement.setInt(1, face.getObjectId()); statement.setInt(2, face.getFaceColor()); statement.setInt(3, face.getHairColor()); statement.setInt(4, face.getEyebrowsFirstVal()); statement.setInt(5, face.getEyebrowsSecondVal()); statement.setInt(6, face.getEyebrowsThridVal()); statement.setInt(7, face.getEyeFirstVal()); statement.setInt(8, face.getEyeSecondVal()); statement.setInt(9, face.getEyeThridVal()); statement.setInt(10, face.getEyePosVertical()); statement.setInt(11, face.getEyeWidth()); statement.setInt(12, face.getEyeHeight()); statement.setInt(13, face.getChin()); statement.setInt(14, face.getCheekbonePos()); statement.setInt(15, face.getEarsFirstVal()); statement.setInt(16, face.getEarsSecondVal()); statement.setInt(17, face.getEarsThridVal()); statement.setInt(18, face.getEarsFourthVal()); statement.setInt(19, face.getNoseFirstVal()); statement.setInt(20, face.getNoseSecondVal()); statement.setInt(21, face.getNoseThridVal()); statement.setInt(22, face.getNoseFourthVal()); statement.setInt(23, face.getNoseFifthVal()); statement.setInt(24, face.getLipsFirstVal()); statement.setInt(25, face.getLipsSecondVal()); statement.setInt(26, face.getLipsThridVal()); statement.setInt(27, face.getLipsFourthVal()); statement.setInt(28, face.getLipsFifthVal()); statement.setInt(29, face.getLipsSixthVal()); statement.setInt(30, face.getCheeks()); statement.setInt(31, face.getBridgeFirstVal()); statement.setInt(32, face.getBridgeSecondVal()); statement.setInt(33, face.getBridgeThridVal()); statement.setInt(34, face.tempVals[0]); statement.setInt(35, face.tempVals[1]); statement.setInt(36, face.tempVals[2]); statement.setInt(37, face.tempVals[3]); statement.setInt(38, face.tempVals[4]); statement.setInt(39, face.tempVals[5]); statement.setInt(40, face.tempVals[6]); statement.setInt(41, face.tempVals[7]); statement.setInt(42, face.tempVals[8]); statement.setInt(43, face.tempVals[9]); statement.setInt(44, face.tempVals[10]); statement.setInt(45, face.tempVals[11]); statement.setInt(46, face.tempVals[12]); statement.setInt(47, face.tempVals[13]); statement.setInt(48, face.tempVals[14]); statement.setInt(49, face.tempVals[15]); statement.setInt(50, face.tempVals[16]); statement.setInt(51, face.tempVals[17]); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Создание ранка для гильдии. * * @param guild гильдия. * @param rank ранг. * @return успешно ли создан. */ public final boolean createGuildRank(Guild guild, GuildRank rank) { if(rank == null || guild == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(CREATE_GUILD_RANK); statement.setInt(1, guild.getId()); statement.setString(2, rank.getName()); statement.setInt(3, rank.getIndex()); statement.setInt(4, rank.getLawId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Создание строки в БД нового инвенторя. * * @param owner <NAME>. * @param inventory инвентарь. * @return успешно ли создан. */ public final boolean createInventory(Character owner, Inventory inventory) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(CREATE_INVENTORY); statement.setInt(1, owner.getObjectId()); statement.setInt(2, inventory.getLevel()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Создание строки в БД нового итема. * * @param item новый итем. * @return успешно ли создан. */ public final boolean createItem(ItemInstance item) { if(item == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(CREATE_ITEM); statement.setInt(1, item.getObjectId()); statement.setInt(2, item.getItemId()); statement.setLong(3, item.getItemCount()); statement.setInt(4, 3); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Создает строку в БД с новым игроком. * * @param player новый игрок. * @param accountName имя аккаунта игрока. * @return успешно ли создан. */ public final boolean createPlayer(Player player, String accountName) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con .prepareStatement("INSERT INTO `characters` (account_name, object_id, class_id, race_id, sex, char_name, heading, online_time, create_time, end_ban, end_chat_ban, title, guild_id, access_level, level, exp, hp, mp, x, y, z, heart, attack_counter, pvp_count, pve_count, guild_rank) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); statement.setString(1, accountName); statement.setInt(2, player.getObjectId()); statement.setInt(3, player.getClassId()); statement.setInt(4, player.getRaceId()); statement.setInt(5, player.getSexId()); statement.setString(6, player.getName()); statement.setInt(7, player.getHeading()); statement.setLong(8, player.getOnlineTime()); statement.setLong(9, player.getCreateTime()); statement.setLong(10, 0); statement.setLong(11, 0); statement.setString(12, player.getTitle()); statement.setInt(13, player.getGuildId()); statement.setInt(14, player.getAccessLevel()); statement.setByte(15, (byte) player.getLevel()); statement.setLong(16, player.getExp()); statement.setInt(17, player.getCurrentHp()); statement.setInt(18, player.getCurrentMp()); statement.setDouble(19, player.getX()); statement.setDouble(20, player.getY()); statement.setDouble(21, player.getZ()); statement.setInt(22, player.getStamina()); statement.setInt(23, 0); statement.setInt(24, 0); statement.setInt(25, 0); statement.setInt(26, 0); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Создание записи о начале квеста игроком. * * @param state состояние квеста. */ public final void createQuest(QuestState state) { Player player = state.getPlayer(); if(player == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(CREATE_QUEST); statement.setInt(1, player.getObjectId()); statement.setInt(2, state.getQuestId()); statement.setInt(3, state.getState()); statement.setLong(4, 0); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Создание строки в БД нового скила. * * @param owner владелец скила. * @param skill скил. * @return успешно ли создан. */ public final boolean createSkill(Character owner, Skill skill) { if(!owner.isPlayer()) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(CREATE_SKILL); statement.setInt(1, owner.getObjectId()); statement.setInt(2, skill.getClassId()); statement.setInt(3, skill.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Удаляет игрока с БД. * * @param objectId ид игрока. * @param accountName имя аккаунта. * @return результат удаления. */ public final int deletePlayer(int objectId, String accountName) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(DELETE_PLAYER); statement.setInt(1, objectId); statement.setString(2, accountName); int count = statement.executeUpdate(); return count > 0 ? S_Delete_User.SUCCESSFUL : S_Delete_User.FAILED; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return S_Delete_User.FAILED; } /** * Удаление строки в БД нового скила. * * @param owner владелец скила. * @param skill скил. * @return успешно ли создан. */ public final boolean deleteSkill(Character owner, Skill skill) { if(!owner.isPlayer()) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(DELETE_SKILL); statement.setInt(1, owner.getObjectId()); statement.setInt(2, skill.getClassId()); statement.setInt(3, skill.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Удаление строки в БД ожидающего итема. * * @param order индекс итема. * @return успешно ли удален. */ public final boolean deleteWaitItem(int order) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_WAIT_ITEM); statement.setInt(1, order); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Удаление строки в БД ожидающего скила. * * @param order индекс скила. * @return успешно ли удален. */ public final boolean deleteWaitSkill(int order) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_WAIT_SKILL); statement.setInt(1, order); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Завершение квеста. * * @param player игрок. * @param date дата завершения. */ public final void finishQuest(Player player, QuestDate date) { if(player == null || date == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(FINISH_QUEST); statement.setLong(1, date.getTime()); statement.setInt(2, player.getObjectId()); statement.setInt(3, date.getQuestId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Загружает игрока с БД. * * @param objectId ид игрока. * @param account аккаунт игрока. * @return загруженный игрок. */ public final Player fullRestore(int objectId, Account account) { Connection con = null; Statement statement = null; ResultSet rset = null; // получаем локальные объекты LocalObjects local = LocalObjects.get(); // ссылка на загруженного игрока Player player = null; // получаем таблицу скилов SkillTable skillTable = SkillTable.getInstance(); // получаем таблицу шаблонов игроков PlayerTable playerTable = PlayerTable.getInstance(); // получаем таблицу территорий TerritoryTable territoryTable = TerritoryTable.getInstance(); // получаем менеджера гильдии GuildManager guildManager = GuildManager.getInstance(); try { // получаем конект к БД con = connectFactory.getConnection(); // создаем запрос statement = con.createStatement(); int hp = 0; int mp = 0; int heart = 0; // загрузка игрока { // запрашиваем данные об нужном игроке rset = statement.executeQuery("SELECT * FROM `characters` WHERE `object_id`= " + objectId + " LIMIT 1"); if(!rset.next()) { LOGGER.warning("not found player for " + objectId); return null; } // если несходится аккаунт, выходим if(!rset.getString("account_name").equalsIgnoreCase(account.getName())) { LOGGER.warning("incorrect account for player"); return null; } PlayerClass playerclass = PlayerClass.values()[rset.getByte("class_id")]; Sex sex = Sex.valueOf(rset.getByte("sex")); Race race = Race.valueOf(rset.getByte("race_id"), sex); // получаем шаблон игрока PlayerTemplate template = playerTable.getTemplate(playerclass, race, sex); player = new Player(objectId, template); player.setName(rset.getString("char_name")); player.setGuildNote(rset.getString("guild_note")); player.setTitle(rset.getString("title")); player.setHeading(rset.getInt("heading")); player.setPvECount(rset.getInt("pve_count")); player.setPvPCount(rset.getInt("pvp_count")); player.setKarma(rset.getInt("karma")); player.setOnlineTime(rset.getLong("online_time")); player.setCreateTime(rset.getLong("create_time")); player.setEndBan(rset.getLong("end_ban")); player.setEndChatBan(rset.getLong("end_chat_ban")); player.setPvPMode(player.getKarma() > 0); Guild guild = guildManager.getGuild(rset.getInt("guild_id")); if(guild != null) { player.setGuild(guild); player.setGuildRank(guild.getRank(rset.getInt("guild_rank"))); } else { player.setGuildId(0); player.setGuildRank(null); } player.setAccessLevel(rset.getInt("access_level")); player.setAttackCounter(rset.getByte("attack_counter")); player.setLevel(rset.getByte("level")); player.setZoneId(rset.getInt("zone_id")); player.setContinentId(rset.getInt("continent_id")); player.setExp(rset.getInt("exp")); player.setEnergyLevel(rset.getInt("collect_energy")); player.setMiningLevel(rset.getInt("collect_mining")); player.setPlantLevel(rset.getInt("collect_plant")); player.setAllianceClass(rset.getInt("union_level")); player.setDescription(rset.getString("description")); heart = rset.getInt("heart"); hp = rset.getInt("hp"); mp = rset.getInt("mp"); player.setXYZInvisible(rset.getFloat("x"), rset.getFloat("y"), rset.getFloat("z")); // закрываем результат DBUtils.closeResultSet(rset); } // загружаем вншность игрока PlayerAppearance appearance = loadPlayerAppearance(objectId); PlayerDetails2 detailsAppearence = loadPlayerPresets2(objectId); if(detailsAppearence != null) player.setdetails2(detailsAppearence,false); // если внешность была загружена if(appearance != null) // устанавливаем ее player.setAppearance(appearance, false); else { LOGGER.warning("not found appearance for objectId " + objectId); // получаем расу игрока Race race = player.getRace(); // получаем базову внешнсоть для него appearance = race.getAppearance(player.getSex()).copy(); // устанавливаем ее player.setAppearance(appearance, true); } // загрузка скилов { // запрашиваем скилы игрока rset = statement.executeQuery("SELECT * FROM `character_skills` WHERE `object_id`= " + objectId); // если есть скилы while(rset.next()) { // получаем ид скила int id = rset.getInt("skill_id"); // получаем класс скила int classId = rset.getByte("class_id"); // получаем темплейт скила SkillTemplate skill = skillTable.getSkill(classId, id); // если его нет, пропускаем if(skill == null) { LOGGER.warning("not found skill id " + id + " class " + classId); continue; } // добавляем игроку скил player.addSkill(skill, false); } // закрываем результат по скилам DBUtils.closeResultSet(rset); // запрашиваем ожидающие скилы rset = statement.executeQuery("SELECT * FROM `wait_skills` WHERE `char_name` = '" + player.getName() + "';"); // если такие есть while(rset.next()) { // получаем ид скила int id = rset.getInt("skill_id"); // получаем класс скила int classId = rset.getInt("skill_class"); // если этого скила у игрока еще нету if(player.getSkill(id) == null) { // получаем темплейт скила SkillTemplate[] skill = skillTable.getSkills(classId, id); // если скила такого неет, сообщаем if(skill == null) LOGGER.warning("not found skill id " + id + " class " + classId); else // иначе добавляем игроку player.addSkills(skill, false); } // удаляем этот скил из табилцы deleteWaitSkill(rset.getInt("order")); } // закрываем результат DBUtils.closeResultSet(rset); } Inventory inventory = null; { rset = statement.executeQuery("SELECT * FROM `character_inventors` WHERE `owner_id` = " + objectId + " LIMIT 1"); if(rset.next()) { inventory = PlayerInventory.newInstance(player, rset.getInt("level")); } else { inventory = PlayerInventory.newInstance(player); } DBUtils.closeResultSet(rset); } // устанавливаем новый инвентарь игроку player.setInventory(inventory); // создаем контейнер экиперовки игрока Equipment equipment = PlayerEquipment.newInstance(player); // вставляем его игроку player.setEquipment(equipment); // создаем банк Bank bank = PlayerBank.newInstance(player); // добавляем его игроку player.setBank(bank); Array<ItemInstance> items = local.getNextItemList(); { rset = statement.executeQuery("SELECT * FROM `items` WHERE `owner_id` = " + objectId + " AND `location` < " + ItemLocation.BANK.ordinal()); loadItems(rset, items); DBUtils.closeResultSet(rset); rset = statement.executeQuery("SELECT * FROM `items` WHERE `owner_id` = " + account.getBankId() + " AND `location` = " + ItemLocation.BANK.ordinal()); loadItems(rset, items); ItemInstance[] array = items.array(); ItemTable itemTable = ItemTable.getInstance(); for(int i = 0, length = items.size(); i < length; i++) { ItemInstance item = array[i]; CrystalList crystals = item.getCrystals(); if(crystals == null) { continue; } DBUtils.closeResultSet(rset); rset = statement.executeQuery("SELECT * FROM `items` WHERE `owner_id` = " + item.getObjectId() + " AND `location` = " + ItemLocation.CRYSTAL.ordinal() + " LIMIT " + item.getSockets()); while(rset.next()) { ItemTemplate template = itemTable.getItem(rset.getInt("item_id")); if(template == null) { LOGGER.warning("not found item " + rset.getInt("item_id")); continue; } CrystalInstance crystal = (CrystalInstance) template.newInstance(rset.getInt("object_id")); crystal.setOwnerId(item.getObjectId()); crystal.setIndex(rset.getInt("index")); crystal.setLocation(ItemLocation.VALUES[rset.getInt("location")]); crystal.setItemCount(rset.getInt("item_count")); crystal.setEnchantLevel(rset.getShort("enchant_level")); crystal.setBonusId(rset.getInt("bonus_id")); crystal.setAutor(rset.getString("autor")); crystals.put(crystal, null, null); } } DBUtils.closeResultSet(rset); } ItemInstance[] array = items.array(); for(int i = 0, length = items.size(); i < length; i++) { ItemInstance item = array[i]; switch(item.getLocation()) { case INVENTORY: inventory.setItem(item, item.getIndex()); break; case EQUIPMENT: equipment.setItem(item, item.getIndex()); break; case BANK: bank.setItem(item.getIndex(), item); break; default: LOGGER.warning("incorrect location for item " + item); } } { rset = statement.executeQuery("SELECT `item_id`, `item_count`, `enchant_level`, `order` FROM `wait_items` WHERE `char_name` = '" + player.getName() + "';"); ItemTable itemTable = ItemTable.getInstance(); while(rset.next()) { ItemTemplate template = itemTable.getItem(rset.getInt(1)); if(template == null) { continue; } ItemInstance item = template.newInstance(); if(item == null) { continue; } if(item.isStackable()) { item.setItemCount(rset.getInt(2)); } item.setEnchantLevel(rset.getInt(3)); updateItem(item); if(inventory.putItem(item)) { deleteWaitItem(rset.getInt(4)); } } DBUtils.closeResultSet(rset); } { rset = statement.executeQuery("SELECT * FROM `character_save_effects` WHERE `object_id` = " + objectId); SkillTemplate skill = null; int skillId = 0; int count = 0; int duration = 0; int order = 0; int classId = 0; EffectList effectList = player.getEffectList(); while(rset.next()) { classId = rset.getByte("class_id"); skillId = rset.getInt("skill_id"); order = rset.getByte("effect_order"); count = rset.getInt("count"); duration = rset.getInt("duration"); if(skill == null || skill.getId() != skillId) skill = skillTable.getSkill(classId, skillId); if(skill == null) continue; EffectTemplate[] templates = skill.getEffectTemplates(); if(templates.length <= order || order < 0) continue; EffectTemplate template = templates[order]; Effect effect = template.newInstance(player, player, skill); if(effect.getCount() == 1) effect.setPeriod(template.getTime() - duration); else effect.setCount(count); effectList.addEffect(effect); } DBUtils.closeResultSet(rset); } player.setStamina(heart); player.setCurrentHp(hp); player.setCurrentMp(mp); // загрузка откатов скилов { rset = statement.executeQuery("SELECT * FROM `character_skill_reuses` WHERE `object_id` = " + objectId); Table<IntKey, ReuseSkill> reuses = player.getReuseSkills(); while(rset.next()) { ReuseSkill reuse = ReuseSkill.newInstance(rset.getInt("skill_id"), 0); reuse.setItemId(rset.getInt("item_id")); reuse.setEndTime(rset.getLong("end_time")); reuses.put(reuse.getSkillId(), reuse); } DBUtils.closeResultSet(rset); } // получаем менеджера квестов QuestManager questManager = QuestManager.getInstance(); // загрузка квестов { // запрашиваем все квесты того игрока rset = statement.executeQuery("SELECT * FROM `character_quests` WHERE `object_id`= " + objectId); // получаем квест лист игрока QuestList questList = player.getQuestList(); // перебираем while(rset.next()) { // получаем квест Quest quest = questManager.getQuest(rset.getInt("quest_id")); // если такого в таблице квестов нет, сообщаем if(quest == null) { LOGGER.warning("not found quest for id " + rset.getInt("quest_id")); continue; } // получаем время выполнения long time = rset.getLong("date"); // если оно уже выполнено if(time > 0) // вносим как выполненный questList.addCompleteQuest(questList.newQuestDate(time, quest)); else { // получаем стадию квеста int state = rset.getInt("state"); // создаем контейнер состояния квеста QuestState questState = questList.newQuestState(player, quest, state); // подготавливаем questState.prepare(); // вносим состояние на панели questState.setPanelState(QuestPanelState.valueOf(rset.getInt("panel_state"))); // добавляем в активные квесты questList.addActiveQuest(questState); } } } // загрузка территорий { // запрашиваем все территории, в которых побывал игрок rset = statement.executeQuery("SELECT * FROM `character_territories` WHERE `object_id`= " + objectId); // перебираем их while(rset.next()) { // получаем территори. Territory territory = territoryTable.getTerritory(rset.getInt("territory_id")); // вносим в таблицу игрока player.storeTerritory(territory, false); } DBUtils.closeResultSet(rset); } // загрузка раскладки и настроек { rset = statement.executeQuery("SELECT * FROM `character_hotkey` WHERE `object_id`= " + objectId + " LIMIT 1"); if(rset.next()) player.setHotkey(rset.getBytes("data"), false); DBUtils.closeResultSet(rset); rset = statement.executeQuery("SELECT * FROM `character_settings` WHERE `object_id`= " + objectId + " LIMIT 1"); if(rset.next()) player.setSettings(rset.getBytes("data"), false); } // загружаем переменные игрока loadPlayerVars(objectId, player.getVariables()); // загрузка друзей игрока loadFriends(objectId, player.getFriendList()); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return player; } /** * Полное сохранение игрока. * * @param player игрок, которого нужно сохранить. * @return сохранился ли. */ public final boolean fullStore(Player player) { if(player == null || player.isDeleted()) return false; Connection con = null; Statement statement = null; try { con = connectFactory.getConnection(); statement = con.createStatement(); // сохранение игрока { statement.executeUpdate("UPDATE `characters` SET `heading` = '" + player.getHeading() + "' , `x` = '" + player.getX() + "', `y` = '" + player.getY() + "', `z` = '" + player.getZ() + "', " + " `online_time` = '" + player.getOnlineTime() + "', `end_ban` = '" + player.getEndBan() + "', `end_chat_ban` = '" + player.getEndChatBan() + "', `exp` = '" + player.getExp() + "', " + "`hp` = " + player.getCurrentHp() + ", `mp` = " + player.getCurrentMp() + ", `heart` = " + player.getStamina() + ", " + "`attack_counter` = '" + player.getAttackCounter() + "', `pvp_count` = '" + player.getPvpCount() + "', `karma` = '" + player.getKarma() + "', `pve_count` = '" + player.getPveCount() + "', `collect_mining` = '" + player.getMiningLevel() + "', `collect_plant` = '" + player.getPlantLevel() + "', `collect_energy` = '" + player.getEnergyLevel() + "', `last_online` = '" + (System.currentTimeMillis() / 1000) + "', `continent_id` = '" + player.getContinentId() + "' WHERE `object_id` = '" + player.getObjectId() + "' LIMIT 1"); } if(player.isChangedFace()) { // TODO } Table<IntKey, ReuseSkill> reuses = player.getReuseSkills(); if(!reuses.isEmpty()) { StringBuilder message = new StringBuilder("REPLACE INTO `character_skill_reuses` VALUES "); int counter = 0; long time = System.currentTimeMillis(); for(ReuseSkill reuse : reuses) { if(reuse.getEndTime() < time) continue; counter++; if(counter == 1) message.append("('"); else message.append(", ('"); message.append(player.getObjectId()).append("', '").append(reuse.getSkillId()).append("', '").append(reuse.getItemId()).append("', '").append(reuse.getEndTime()).append("')"); } message.append(";"); if(counter > 0) statement.executeUpdate(message.toString()); } statement.execute("DELETE FROM `character_save_effects` WHERE `object_id` = " + player.getObjectId()); EffectList effectList = player.getEffectList(); if(effectList.size() > 0) { effectList.lock(); try { Array<Effect> effects = effectList.getEffects(); Effect[] array = effects.array(); for(int i = 0, length = effects.size(); i < length; i++) { Effect effect = array[i]; if(effect == null || effect.isAura() || effect.isEnded()) continue; statement.executeUpdate("REPLACE INTO `character_save_effects` (object_id, class_id, skill_id, effect_order, count, duration) VALUES(" + player.getObjectId() + ", " + effect.getSkillClassId() + ", " + effect.getSkillId() + ", " + effect.getOrder() + ", " + effect.getCount() + ", " + effect.getTime() + ")"); } } finally { effectList.unlock(); } } // сохраняем переменные в БД player.saveVars(); return storeSettingsAndHotKeys(player); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Получение кол-ва персонажей на аккаунте. * * @param account имя аккаунта. * @return кол-во кол-во персонажей на нем. */ public final int getAccountSize(String account) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { int number = 0; // получаем коннект к БД. con = connectFactory.getConnection(); // задаем запрос statement = con.prepareStatement("SELECT COUNT(char_name) FROM `characters` WHERE `account_name`=? LIMIT 8"); statement.setString(1, account); // выполняем запрос rset = statement.executeQuery(); // считаем кол-во while(rset.next()) number = rset.getInt(1); // возвращаем кол-во return number; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return 0; } /** * @return фабрика подключений к БД. */ public final ConnectFactory getConnectFactory() { return connectFactory; } /** * Внесение спавна босса в БД. * * @param template темплейт босса. * @param spawn время спавна босса. */ public final void insertBossSpawns(NpcTemplate template, long spawn) { if(template == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_BOSS_SPAWNS); statement.setInt(1, template.getTemplateId()); statement.setInt(2, template.getTemplateType()); statement.setLong(3, spawn); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Внесение друга в БД. * * @param objectId ид игрока. * @param friendId ид друга. */ public final void insertFriend(int objectId, int friendId) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_PLAYER_FRIEND); statement.setInt(1, objectId); statement.setInt(2, friendId); statement.setString(3, Strings.EMPTY); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Добавление гильдии в БД. * * @param guild гильдия. */ public final boolean insertGuild(Guild guild) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_GUILD); statement.setInt(1, guild.getObjectId()); statement.setString(2, guild.getName()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Добавление игрока переменной. * * @param objectId уникальный ид игрока. * @param name название переменной. * @param value значение переменной. */ public final void insertPlayerVar(int objectId, String name, String value) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_PLAYER_VARIABLE); statement.setInt(1, objectId); statement.setString(2, name); statement.setString(3, value); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } // new section for Char_presets_2 /** * * @param detailsappearance */ public final void insertPlayerPresets2(PlayerDetails2 detailsappearance) { PreparedStatement statement = null; Connection con = null; try { int[] dt2 = detailsappearance.getDetails2(); con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_CHAR_PRE_2); statement.setInt(1, detailsappearance.getObjectId()); statement.setInt(2, dt2[0]); statement.setInt(3, dt2[1]); statement.setInt(4, dt2[2]); statement.setInt(5, dt2[3]); statement.setInt(6, dt2[4]); statement.setInt(7, dt2[5]); statement.setInt(8, dt2[6]); statement.setInt(9, dt2[7]); statement.setInt(10, dt2[8]); statement.setInt(11, dt2[9]); statement.setInt(12, dt2[10]); statement.setInt(13, dt2[11]); statement.setInt(14, dt2[12]); statement.setInt(15, dt2[13]); statement.setInt(16, dt2[14]); statement.setInt(17, dt2[15]); statement.setInt(18, dt2[16]); statement.setInt(19, dt2[17]); statement.setInt(20, dt2[18]); statement.setInt(21, dt2[19]); statement.setInt(22, dt2[20]); statement.setInt(23, dt2[21]); statement.setInt(24, dt2[22]); statement.setInt(25, dt2[23]); statement.setInt(26, dt2[24]); statement.setInt(27, dt2[25]); statement.setInt(28, dt2[26]); statement.setInt(29, dt2[27]); statement.setInt(30, dt2[28]); statement.setInt(31, dt2[29]); statement.setInt(32, dt2[30]); statement.setInt(33, dt2[31]); statement.setInt(34, dt2[32]); statement.setInt(35, dt2[33]); statement.setInt(36, dt2[34]); statement.setInt(37, dt2[35]); statement.setInt(38, dt2[36]); statement.setInt(39, dt2[37]); statement.setInt(40, dt2[38]); statement.setInt(41, dt2[39]); statement.setInt(42, dt2[40]); statement.setInt(43, dt2[41]); statement.setInt(44, dt2[42]); statement.setInt(45, dt2[43]); statement.setInt(46, dt2[44]); statement.setInt(47, dt2[45]); statement.setInt(48, dt2[46]); statement.setInt(49, dt2[47]); statement.setInt(50, dt2[48]); statement.setInt(51, dt2[49]); statement.setInt(52, dt2[50]); statement.setInt(53, dt2[51]); statement.setInt(54, dt2[52]); statement.setInt(55, dt2[53]); statement.setInt(56, dt2[54]); statement.setInt(57, dt2[55]); statement.setInt(58, dt2[56]); statement.setInt(59, dt2[57]); statement.setInt(60, dt2[58]); statement.setInt(61, dt2[59]); statement.setInt(62, dt2[60]); statement.setInt(63, dt2[61]); statement.setInt(64, dt2[62]); statement.setInt(65, dt2[63]); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Created By Evestu * * @param objectId appearance details2. */ public final PlayerDetails2 loadPlayerPresets2(int objectId) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; int[] getpd2 = new int[64]; int count = 2; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_CHAR_PRE_2); statement.setInt(1, objectId); rset = statement.executeQuery(); if(rset.next()) { // создаем контейнер внешности PlayerDetails2 detailsappearance = PlayerDetails2.getInstance(objectId); for(int i = 0 ; i < 64 ; ++i){ getpd2[i] = rset.getByte(count); ++count; } detailsappearance.setDetails2(getpd2); return detailsappearance; } LOGGER.warning("not found appearance for " + objectId); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return null; } /** * Внесение в БД записи с внешностью персонажа. * * @param appearance внешность игрока. */ public final void insertPlayerAppearance(PlayerAppearance appearance) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_PLAYER_APPEARANCE); statement.setInt(1, appearance.getObjectId()); statement.setInt(2, appearance.getFaceColor()); statement.setInt(3, appearance.getFaceSkin()); statement.setInt(4, appearance.getAdormentsSkin()); statement.setInt(5, appearance.getFeaturesSkin()); statement.setInt(6, appearance.getFeaturesColor()); statement.setInt(7, appearance.getVoice()); statement.setInt(8, appearance.getBoneStructureBrow()); statement.setInt(9, appearance.getBoneStructureCheekbones()); statement.setInt(10, appearance.getBoneStructureJaw()); statement.setInt(11, appearance.getBoneStructureJawJut()); statement.setInt(12, appearance.getEarsRotation()); statement.setInt(13, appearance.getEarsExtension()); statement.setInt(14, appearance.getEarsTrim()); statement.setInt(15, appearance.getEarsSize()); statement.setInt(16, appearance.getEyesWidth()); statement.setInt(17, appearance.getEyesHeight()); statement.setInt(18, appearance.getEyesSeparation()); statement.setInt(19, appearance.getEyesAngle()); statement.setInt(20, appearance.getEyesInnerBrow()); statement.setInt(21, appearance.getEyesOuterBrow()); statement.setInt(22, appearance.getNoseExtension()); statement.setInt(23, appearance.getNoseSize()); statement.setInt(24, appearance.getNoseBridge()); statement.setInt(25, appearance.getNoseNostrilWidth()); statement.setInt(26, appearance.getNoseTipWidth()); statement.setInt(27, appearance.getNoseTip()); statement.setInt(28, appearance.getNoseNostrilFlare()); statement.setInt(29, appearance.getMouthPucker()); statement.setInt(30, appearance.getMouthPosition()); statement.setInt(31, appearance.getMouthWidth()); statement.setInt(32, appearance.getMouthLipThickness()); statement.setInt(33, appearance.getMouthCorners()); statement.setInt(34, appearance.getEyesShape()); statement.setInt(35, appearance.getNoseBend()); statement.setInt(36, appearance.getBoneStructureJawWidth()); statement.setInt(37, appearance.getMothGape()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление в БД записи с внешностью персонажа. * * @param appearance внешность игрока. */ public final boolean updatePlayerAppearance(PlayerAppearance appearance) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_APPEARANCE); statement.setInt(1, appearance.getFaceColor()); statement.setInt(2, appearance.getFaceSkin()); statement.setInt(3, appearance.getAdormentsSkin()); statement.setInt(4, appearance.getFeaturesSkin()); statement.setInt(5, appearance.getFeaturesColor()); statement.setInt(6, appearance.getVoice()); statement.setInt(7, appearance.getBoneStructureBrow()); statement.setInt(8, appearance.getBoneStructureCheekbones()); statement.setInt(9, appearance.getBoneStructureJaw()); statement.setInt(10, appearance.getBoneStructureJawJut()); statement.setInt(11, appearance.getEarsRotation()); statement.setInt(12, appearance.getEarsExtension()); statement.setInt(13, appearance.getEarsTrim()); statement.setInt(14, appearance.getEarsSize()); statement.setInt(15, appearance.getEyesWidth()); statement.setInt(16, appearance.getEyesHeight()); statement.setInt(17, appearance.getEyesSeparation()); statement.setInt(18, appearance.getEyesAngle()); statement.setInt(19, appearance.getEyesInnerBrow()); statement.setInt(20, appearance.getEyesOuterBrow()); statement.setInt(21, appearance.getNoseExtension()); statement.setInt(22, appearance.getNoseSize()); statement.setInt(23, appearance.getNoseBridge()); statement.setInt(24, appearance.getNoseNostrilWidth()); statement.setInt(25, appearance.getNoseTipWidth()); statement.setInt(26, appearance.getNoseTip()); statement.setInt(27, appearance.getNoseNostrilFlare()); statement.setInt(28, appearance.getMouthPucker()); statement.setInt(29, appearance.getMouthPosition()); statement.setInt(30, appearance.getMouthWidth()); statement.setInt(31, appearance.getMouthLipThickness()); statement.setInt(32, appearance.getMouthCorners()); statement.setInt(33, appearance.getEyesShape()); statement.setInt(34, appearance.getNoseBend()); statement.setInt(35, appearance.getBoneStructureJawWidth()); statement.setInt(36, appearance.getMothGape()); statement.setInt(37, appearance.getObjectId()); return statement.executeUpdate() > 0; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Загрузка внешности игрока из БД. * * @param objectId уникальный ид игрока. * @return внешность игрока. */ public final PlayerAppearance loadPlayerAppearance(int objectId) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_APPEARANCE); statement.setInt(1, objectId); rset = statement.executeQuery(); if(rset.next()) { // создаем контейнер внешности PlayerAppearance appearance = PlayerAppearance.getInstance(objectId); appearance.setFaceColor(rset.getInt(1)); appearance.setFaceSkin(rset.getInt(2)); appearance.setAdormentsSkin(rset.getInt(3)); appearance.setFeaturesSkin(rset.getInt(4)); appearance.setFeaturesColor(rset.getInt(5)); appearance.setVoice(rset.getInt(6)); appearance.setBoneStructureBrow(rset.getInt(7)); appearance.setBoneStructureCheekbones(rset.getInt(8)); appearance.setBoneStructureJaw(rset.getInt(9)); appearance.setBoneStructureJawJut(rset.getInt(10)); appearance.setEarsRotation(rset.getInt(11)); appearance.setEarsExtension(rset.getInt(12)); appearance.setEarsTrim(rset.getInt(13)); appearance.setEarsSize(rset.getInt(14)); appearance.setEyesWidth(rset.getInt(15)); appearance.setEyesHeight(rset.getInt(16)); appearance.setEyesSeparation(rset.getInt(17)); appearance.setEyesAngle(rset.getInt(18)); appearance.setEyesInnerBrow(rset.getInt(19)); appearance.setEyesOuterBrow(rset.getInt(20)); appearance.setNoseExtension(rset.getInt(21)); appearance.setNoseSize(rset.getInt(22)); appearance.setNoseBridge(rset.getInt(23)); appearance.setNoseNostrilWidth(rset.getInt(24)); appearance.setNoseTipWidth(rset.getInt(25)); appearance.setNoseTip(rset.getInt(26)); appearance.setNoseNostrilFlare(rset.getInt(27)); appearance.setMouthPucker(rset.getInt(28)); appearance.setMouthPosition(rset.getInt(29)); appearance.setMouthWidth(rset.getInt(30)); appearance.setMouthLipThickness(rset.getInt(31)); appearance.setMouthCorners(rset.getInt(32)); appearance.setEyesShape(rset.getInt(33)); appearance.setNoseBend(rset.getInt(34)); appearance.setBoneStructureJawWidth(rset.getInt(35)); appearance.setMothGape(rset.getInt(36)); return appearance; } LOGGER.warning("not found appearance for " + objectId); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return null; } /** * Внесение региона в БД. * * @param region новый регион. */ public final void insertRegion(Region region) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_REGION_STATUS); statement.setInt(1, region.getId()); statement.setInt(2, 0); statement.setInt(3, 0); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Внесение зарегестрированной гильдии на осаду региона в БД. * * @param region регион. * @param guild зарегестрированная гильдия. */ public final boolean insertRegionGuildRegister(Region region, Guild guild) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_REGION_REGISTER_GUILD); statement.setInt(1, region.getId()); statement.setInt(2, guild.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Добавление серверной переменной. * * @param name название переменной. * @param value значение переменной. */ public final void insertServerVar(String name, String value) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(INSERT_SERVER_VARIABLE); statement.setString(1, name); statement.setString(2, value); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Проверка на занятость указанного ника. * * @param name проверяемый ник. * @return свободен ли. */ public final boolean isFreeName(String name) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_CHECK_NAME); statement.setString(1, name); rset = statement.executeQuery(); return !rset.next(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return false; } /** * Проверка на занятость ид игрока. * * @param objectId проверяемый ид. * @return свободен ли. */ public final boolean isFreePlayerId(int objectId) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_CHECK_ID); statement.setInt(1, objectId); rset = statement.executeQuery(); return !rset.next(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return false; } /** * Загрузка спавнов боссов с БД. * * @param spawns таблица спавнов. */ public final void loadBossSpawns(Table<IntKey, Table<IntKey, Wrap>> spawns) { PreparedStatement statement = null; Connection con = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_BOSS_SPAWNS); rset = statement.executeQuery(); while(rset.next()) { int id = rset.getInt("npc_id"); int type = rset.getInt("npc_type"); Table<IntKey, Wrap> table = spawns.get(id); if(table == null) { table = Tables.newIntegerTable(); spawns.put(id, table); } table.put(type, Wraps.newLongWrap(rset.getLong("spawn"), true)); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка друга игрока с БД. * * @param objectId уникальный ид дрга. * @param friendList список друзей игрока. */ public final void loadFriend(int objectId, FriendList friendList) { PreparedStatement statement = null; Connection con = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_FRIEND); statement.setInt(1, objectId); rset = statement.executeQuery(); if(rset.next()) { FriendInfo info = friendList.newFriendInfo(); info.setObjectId(objectId); info.setClassId(rset.getInt(1)); info.setRaceId(rset.getInt(2)); info.setLevel(rset.getInt(3)); info.setName(rset.getString(4)); friendList.addFriend(info); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка друзей игрока с БД. * * @param objectId уникальный ид игрока. * @param friendList список друзей игрока. */ public final void loadFriends(int objectId, FriendList friendList) { PreparedStatement statement = null; Connection con = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_FRIENDS); statement.setInt(1, objectId); rset = statement.executeQuery(); while(rset.next()) loadFriend(rset.getInt(1), friendList); friendList.prepare(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Метод получение из результата списка итемов. */ public final void loadItems(ResultSet rset, Array<ItemInstance> items) { // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); try { while(rset.next()) { // получаем if,kjy итема ItemTemplate template = itemTable.getItem(rset.getInt("item_id")); // если его нет, пропускаем if(template == null) { LOGGER.warning("not found item " + rset.getInt("item_id")); continue; } // создаем новый инстанс с указанным ид ItemInstance item = template.newInstance(rset.getInt("object_id")); // вносим данные об итеме item.setIndex(rset.getInt("index")); item.setLocation(ItemLocation.valueOf(rset.getInt("location"))); item.setOwnerId(rset.getInt("owner_id")); item.setItemCount(rset.getLong("item_count")); item.setMasterworked(rset.getInt("masterworked")); item.setEnigma(rset.getInt("enigma")); item.setEnchantLevel(rset.getShort("enchant_level")); item.setBonusId(rset.getInt("bonus_id")); item.setAutor(rset.getString("autor")); item.setOwnerName(rset.getString("owner_name")); if(!item.isEnchantable() && item.getEnchantLevel() > 0) { item.setEnchantLevel(0); updateItem(item); } // добавляем в список items.add(item); } } catch(SQLException e) { LOGGER.warning(e); } } /** * Загрузка игрока переменных с БД. * * @param objectId уникальный ид игрока. * @param table контейнер переменных. */ public final void loadPlayerVars(int objectId, Table<String, Wrap> table) { PreparedStatement statement = null; Connection con = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_VARIABLES); statement.setInt(1, objectId); rset = statement.executeQuery(); while(rset.next()) table.put(rset.getString("var_name"), Wraps.newIntegerWrap(Integer.parseInt(rset.getString("var_value")), true)); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка региона с БД. * * @param region загружаемый регион. */ public final void loadRegion(Region region) { PreparedStatement statement = null; Connection con = null; ResultSet rset = null; // получаем менеджера гильдий GuildManager guildManager = GuildManager.getInstance(); try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_REGION_STATUS); statement.setInt(1, region.getId()); rset = statement.executeQuery(); if(!rset.next()) insertRegion(region); else { // вносим состояние региона region.setState(RegionState.valueOf(rset.getInt("state"))); // получаем ид владельца int ownerId = rset.getInt("owner_id"); // если есть if(ownerId > 0) // вносим владельца region.setOwner(guildManager.getGuild(ownerId)); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка зарегестрированных гильдий на регион с БД. * * @param region загружаемый регион. */ public final void loadRegionRegister(Region region) { PreparedStatement statement = null; Connection con = null; ResultSet rset = null; // получаем менеджера гильдий GuildManager guildManager = GuildManager.getInstance(); try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_REGION_REGISTER); statement.setInt(1, region.getId()); rset = statement.executeQuery(); while(rset.next()) { Guild guild = guildManager.getGuild(rset.getInt("guild_id")); if(guild != null) region.addRegisterGuild(guild); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка серверных переменных с БД. * * @param variables контейнер переменных. */ public final void loadServerVars(Table<String, String> variables) { PreparedStatement statement = null; Connection con = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_SERVER_VARIABLES); rset = statement.executeQuery(); while(rset.next()) variables.put(rset.getString("var_name"), rset.getString("var_value")); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Удаление друга игрока из БД. * * @param objectId ид игрока. * @param friendId ид друга. */ public final void removeFriend(int objectId, int friendId) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOME_PLAYER_FRIEND); statement.setInt(1, objectId); statement.setInt(2, friendId); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Удаление зарегестрированной гильдии из БД. * * @param region регион. * @param guild отрегистрируемая гильдия. */ public final void removeRegionRegisterGuild(Region region, Guild guild) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_REGION_REGISTER_GUILD); statement.setInt(1, region.getId()); statement.setInt(2, guild.getId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Удаление гильдии из БД. * * @param guild гильдия. */ public final void removeGuild(Guild guild) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_GUILD); statement.setInt(1, guild.getObjectId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } public final void removeAllGuildApply(GuildApply apply) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(DELETE_ALL_GUILD_APPLY); statement.setInt(1, apply.getPlayerId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } public final void removeGuildApply(GuildApply apply, Guild guild) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(DELETE_GUILD_APPLY); statement.setInt(1, apply.getPlayerId()); statement.setInt(2, guild.getId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Удаление всех членов гильдии из БД. * * @param guild гильдия. */ public final void removeGuildMembers(Guild guild) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_GUILD_MEMBERS); statement.setInt(1, guild.getObjectId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } public final void saveUnionTax(int allianceId, int tax) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_ALLIANCE_TAXRATE); statement.setInt(1, tax); statement.setInt(2, allianceId); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } public final void saveUnionMessage(int allianceId, String message) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_ALLIANCE_MESSAGE); statement.setString(1, message); statement.setInt(2, allianceId); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * * @param guild * @param rank * @return */ public final boolean removeGuildRank(Guild guild, GuildRank rank) { if(guild == null || rank == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_GUILD_RANK); statement.setInt(1, guild.getId()); statement.setInt(2, rank.getIndex()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * * @param guild * @param def * @param rank * @return */ public final boolean removeGuildRankForPlayer(Guild guild, GuildRank def, GuildRank rank) { if(guild == null || rank == null || def == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_GUILD_RANK_FOR_PLAYERS); statement.setInt(1, def.getIndex()); statement.setInt(2, guild.getId()); statement.setInt(3, rank.getIndex()); statement.setInt(4, guild.size()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Удаление игрока переменной. * * @param objectId уникальный ид игрока. * @param name название переменной. */ public final void removePlayerVar(int objectId, String name) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_PLAYER_VARIABLE); statement.setInt(1, objectId); statement.setString(2, name); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * удаление квеста. * * @param player игрок. * @param quest квест. */ public final void removeQuest(Player player, Quest quest) { if(player == null || quest == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_QUEST); statement.setInt(1, player.getObjectId()); statement.setInt(2, quest.getId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Удаление серверной переменной. * * @param name название переменной. */ public final void removeServerVar(String name) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(REMOVE_SERVER_VARIABLE); statement.setString(1, name); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Загружает аккаунт с БД. * * @param accountName имя аккаунта. * @return загруженный аккаунт. */ public final Account restoreAccount(String accountName) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; Account account = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_ACCOUNT); statement.setString(1, accountName); rset = statement.executeQuery(); if(rset.next()) account = Account.valueOf(accountName, rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getString(6), rset.getLong(7), rset.getLong(8), rset.getInt(9), rset.getInt(10)); } catch(Exception e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return account; } /** * Получает ид банка закрепленного за аккаунтом. * * @param accountName имя аккаунта. * @return ид банка. */ public final int restoreAccountBank(String accountName) { PreparedStatement statement = null; ResultSet rset = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(RESTORE_ACCOUNT_BANK); statement.setString(1, accountName); rset = statement.executeQuery(); if(rset.next()) return rset.getInt("bank_id"); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return -1; } /** * Загружает с БД внешность игрока. * * @param objectId уникальных ид игрока. * @return внешность игрока. */ public final DeprecatedPlayerFace restoreFace(int objectId) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_FACE); statement.setInt(1, objectId); rset = statement.executeQuery(); if(!rset.next()) { LOGGER.warning("not found player face for " + objectId); return null; } DeprecatedPlayerFace face = DeprecatedPlayerFace.newInstance(objectId); face.setFaceColor(rset.getInt("faceColor")); face.setHairColor(rset.getInt("hairColor")); face.setEyebrowsFirstVal(rset.getInt("eyebrowsFirstVal")); face.setEyebrowsSecondVal(rset.getInt("eyebrowsSecondVal")); face.setEyebrowsThridVal(rset.getInt("eyebrowsThridVal")); face.setEyeFirstVal(rset.getInt("eyeFirstVal")); face.setEyeSecondVal(rset.getInt("eyeSecondVal")); face.setEyeThridVal(rset.getInt("eyeThridVal")); face.setEyePosVertical(rset.getInt("eyePosVertical")); face.setEyeWidth(rset.getInt("eyeWidth")); face.setEyeHeight(rset.getInt("eyeHeight")); face.setChin(rset.getInt("chin")); face.setCheekbonePos(rset.getInt("cheekbonePos")); face.setEarsFirstVal(rset.getInt("earsFirstVal")); face.setEarsSecondVal(rset.getInt("earsSecondVal")); face.setEarsThridVal(rset.getInt("earsThridVal")); face.setEarsFourthVal(rset.getInt("earsFourthVal")); face.setNoseFirstVal(rset.getInt("noseFirstVal")); face.setNoseSecondVal(rset.getInt("noseSecondVal")); face.setNoseThridVal(rset.getInt("noseThridVal")); face.setNoseFourthVal(rset.getInt("noseFourthVal")); face.setNoseFifthVal(rset.getInt("noseFifthVal")); face.setLipsFirstVal(rset.getInt("lipsFirstVal")); face.setLipsSecondVal(rset.getInt("lipsSecondVal")); face.setLipsThridVal(rset.getInt("lipsThridVal")); face.setLipsFourthVal(rset.getInt("lipsFourthVal")); face.setLipsFifthVal(rset.getInt("lipsFifthVal")); face.setLipsSixthVal(rset.getInt("lipsSixthVal")); face.setCheeks(rset.getInt("cheeks")); face.setBridgeFirstVal(rset.getInt("bridgeFirstVal")); face.setBridgeSecondVal(rset.getInt("bridgeSecondVal")); face.setBridgeThridVal(rset.getInt("bridgeThridVal")); for(int i = 0; i < face.tempVals.length; i++) face.tempVals[i] = rset.getInt("temp" + (i + 1)); return face; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return null; } /** * Загрузка всех итемов банка гильдии из БД. * * @param guild гильдия. */ public final void restoreGuildBankItems(Guild guild) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_GUILD_BANK_ITEMS); statement.setInt(1, guild.getObjectId()); // делаем выборку по всем гильдиям rset = statement.executeQuery(); // создаем буферный список итемов Array<ItemInstance> items = Arrays.toArray(ItemInstance.class); // загружаем итемы loadItems(rset, items); // если итемов нет, пропускаем if(items.isEmpty()) return; // получаем банк итемов Bank bank = guild.getBank(); // вносим итемы в банк for(ItemInstance item : items) bank.setItem(item.getIndex(), item); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка всех членов гильдии из БД. * * @param guild гильдия. */ public final void restoreGuildMembers(Guild guild) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_GUILD_MEMBERS); statement.setInt(1, guild.getObjectId()); // делаем выборку по всем гильдиям rset = statement.executeQuery(); // загружаем мемберов while(rset.next()) { GuildMember member = GuildMember.newInstance(); member.setClassId(rset.getInt(1)); member.setLevel(rset.getInt(2)); member.setName(rset.getString(3)); member.setNote(rset.getString(4)); member.setZoneId(rset.getInt(5)); member.setObjectId(rset.getInt(6)); member.setOnline(false); member.setRaceId(rset.getInt(7)); member.setRank(guild.getRank(rset.getInt(8))); member.setSex(rset.getInt(9)); member.setLastOnline(rset.getInt(10)); guild.addMember(member); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка всех рангов гильдии из БД. * * @param guild гильдия. */ public final void restoreGuildRanks(Guild guild) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_GUILD_RANKS); statement.setInt(1, guild.getObjectId()); // делаем выборку по всем гильдиям rset = statement.executeQuery(); // загружаем ранги while(rset.next()) guild.addRank(GuildRank.newInstance(rset.getString("rank_name"), GuildRankLaw.valueOf(rset.getInt("law")), rset.getInt("order"))); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } public final void restoreGuildApply(Guild guild) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_GUILD_APPLY); statement.setInt(1, guild.getObjectId()); // делаем выборку по всем гильдиям rset = statement.executeQuery(); // загружаем ранги while(rset.next()) guild.addApply(GuildApply.newInstance(rset.getInt("character_id"), rset.getInt("class_id"), rset.getInt("level"), rset.getString("char_name"),rset.getString("message"))); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } public final void restoreAlliance(Table<IntKey, Alliance> alliances) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_ALLIANCE); // делаем выборку по всем гильдиям rset = statement.executeQuery(); // загружаем гильдии while(rset.next()) alliances.put(rset.getInt("union_id"), new Alliance(rset.getInt("union_id"), rset.getInt("leader_id"), rset.getString("char_name"), rset.getString("name"), rset.getInt("tax_rate"), rset.getInt("strength"), rset.getInt("bonus"), rset.getString("message"))); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } public final ItemInstance getItem(int objectId) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_ITEM); statement.setInt(1, objectId); rset = statement.executeQuery(); if(rset.next()) { ItemTable itemTable = ItemTable.getInstance(); ItemTemplate template = itemTable.getItem(rset.getInt("item_id")); if(template == null) return null; ItemInstance item = template.newInstance(rset.getInt("object_id")); item.setIndex(rset.getInt("index")); item.setLocation(ItemLocation.VALUES[rset.getInt("location")]); item.setOwnerId(objectId); item.setItemCount(rset.getLong("item_count")); item.setEnchantLevel(rset.getShort("enchant_level")); item.setBonusId(rset.getInt("bonus_id")); item.setAutor(rset.getString("autor")); item.setOwnerName(rset.getString("owner_name")); return item; } // делаем выборку по всем гильдиям } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return null; } public final void restoreAllianceGuilds(Alliance alliance) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_ALLIANCE_GUILDS); statement.setInt(1, alliance.getAllianceId()); // делаем выборку по всем гильдиям rset = statement.executeQuery(); // загружаем гильдии while(rset.next()) { Guild guild = GuildManager.getInstance().getGuild(rset.getInt("id")); alliance.addGuild(guild); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка всех гильдий из БД. * * @param guilds таблица гильдий. */ public final void restoreGuilds(Table<IntKey, Guild> guilds) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_GUILDS); // делаем выборку по всем гильдиям rset = statement.executeQuery(); // загружаем гильдии while(rset.next()) guilds.put( rset.getInt("id"), new Guild(rset.getString("name"), rset.getString("title"), rset.getString("message"), rset.getInt("id"), rset.getInt("level"), new GuildIcon(rset.getString("icon_name"), rset .getBytes("icon")), rset.getInt("praise"), rset.getInt("alliance"))); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка списка персоажей на указанном аккаунте. * * @param playerList список персонажей. * @param accountName имя аккаунта. */ public final void restorePlayerList(Array<PlayerPreview> playerList, String accountName) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_LIST); statement.setString(1, accountName); rset = statement.executeQuery(); while(rset.next()) { // получаем уникальный ид игрока int objectId = rset.getInt("object_id"); // загружаем его превью PlayerPreview playerPreview = restorePreview(objectId); // если загрузка не удалась, пропускаем if(playerPreview == null) continue; // добавляем превью в список playerList.add(playerPreview); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загрузка списка имен персоажей на указанном аккаунте. * * @param playerNames список имен персонажей. * @param accountName имя аккаунта. */ public final void restorePlayerNames(Array<String> playerNames, String accountName) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_ACCOUNT); statement.setString(1, accountName); rset = statement.executeQuery(); while(rset.next()) playerNames.add(rset.getString(1)); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } public final void getPlayerDungeons(Player player) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_DUNGEONS); statement.setInt(1, player.getObjectId()); rset = statement.executeQuery(); // если не нашли персонажа while (rset.next()) { PlayerDungeon dungeon = new PlayerDungeon(rset.getInt("object_id"), rset.getInt("dungeon_id"), rset.getInt("clear_count"), rset.getInt("last_entry"), rset.getInt("daily_count")); player.addDungeon(dungeon); } }catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } public boolean resetPlayerDungeons() { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(RESET_PLAYER_DUNGEONS); return statement.executeUpdate() > 0; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } public final PlayerPreview getPreviewWithObjectName(String name) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_PREVIEW_WITH_NAME); statement.setString(1, name); rset = statement.executeQuery(); // если не нашли персонажа if (!rset.next()) { LOGGER.warning("not found player for name " + name); return null; } PlayerPreview playerPreview = PlayerPreview.newInstance(rset.getInt("object_id")); playerPreview.setSex(rset.getByte("sex")); playerPreview.setRaceId(rset.getByte("race_id")); playerPreview.setClassId(rset.getByte("class_id")); playerPreview.setLevel(rset.getByte("level")); playerPreview.setOnlineTime(rset.getLong("online_time")); playerPreview.setName(rset.getString("char_name")); playerPreview.setHp(rset.getInt("hp")); playerPreview.setMp(rset.getInt("mp")); playerPreview.setPosX(rset.getInt("x")); playerPreview.setPosY(rset.getInt("y")); playerPreview.setPosZ(rset.getInt("z")); playerPreview.setZoneId(rset.getInt("zone_id")); playerPreview.setZoneId(rset.getInt("continent_id")); return playerPreview; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return null; } /** * Загружает с БД превью игрока. * * @param objectId уникальных ид игрока. * @return превью игрока. */ public final PlayerPreview restorePreview(int objectId) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_PREVIEW); statement.setInt(1, objectId); rset = statement.executeQuery(); // если не нашли персонажа if(!rset.next()) { LOGGER.warning("not found player for " + objectId); return null; } PlayerPreview playerPreview = PlayerPreview.newInstance(objectId); playerPreview.setSex(rset.getByte("sex")); playerPreview.setRaceId(rset.getByte("race_id")); playerPreview.setClassId(rset.getByte("class_id")); playerPreview.setLevel(rset.getByte("level")); playerPreview.setOnlineTime(rset.getLong("online_time")); playerPreview.setName(rset.getString("char_name")); playerPreview.setHp(rset.getInt("hp")); playerPreview.setMp(rset.getInt("mp")); playerPreview.setPosX(rset.getInt("x")); playerPreview.setPosY(rset.getInt("y")); playerPreview.setPosZ(rset.getInt("z")); playerPreview.setZoneId(rset.getInt("zone_id")); playerPreview.setZoneId(rset.getInt("continent_id")); // загружаем внешность игрока PlayerAppearance appearance = loadPlayerAppearance(objectId); PlayerDetails2 detailsAppearence = loadPlayerPresets2(objectId); // если загрузить внешность не удалось, выходим if(appearance == null) return null; Equipment equipment = PlayerEquipment.newInstance(null); // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); // загрузка экиперовки { rset = statement.executeQuery("SELECT * FROM `items` WHERE `owner_id` = " + objectId + " AND `location` = " + ItemLocation.EQUIPMENT.ordinal()); while(rset.next()) { ItemTemplate template = itemTable.getItem(rset.getInt("item_id")); if(template == null) continue; ItemInstance item = template.newInstance(rset.getInt("object_id")); item.setIndex(rset.getInt("index")); item.setLocation(ItemLocation.VALUES[rset.getInt("location")]); item.setOwnerId(objectId); item.setItemCount(rset.getLong("item_count")); item.setEnchantLevel(rset.getShort("enchant_level")); item.setBonusId(rset.getInt("bonus_id")); item.setAutor(rset.getString("autor")); equipment.setItem(item, item.getIndex()); } } playerPreview.setAppearance(appearance).setEquipment(equipment).setdetailsappearance(detailsAppearence); return playerPreview; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return null; } /** * Загрузка переменных квеста. * * @param state состояние квеста. */ public final void restoreQuestVar(QuestState state) { Player player = state.getPlayer(); if(player == null) return; PreparedStatement statement = null; Connection con = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(RESTORE_QUEST_VAR); statement.setInt(1, player.getObjectId()); statement.setInt(2, state.getQuestId()); rset = statement.executeQuery(); while(rset.next()) state.setVar(rset.getString("name"), Wraps.newIntegerWrap(rset.getInt("value"), true)); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Загружает с БД откаты скилов игрока. * * @param objectId уникальный ид игрока. * @return reuses таблица откатов скилов. */ public final Table<IntKey, ReuseSkill> restoreReuseSkills(int objectId) { Table<IntKey, ReuseSkill> reuses = Tables.newConcurrentIntegerTable(); Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement("SELECT * FROM `character_skill_reuses` WHERE `object_id` = ? "); statement.setInt(1, objectId); rset = statement.executeQuery(); while(rset.next()) { ReuseSkill reuse = ReuseSkill.newInstance(rset.getInt("skill_id"), 0); reuse.setItemId(rset.getInt("item_id")); reuse.setEndTime(rset.getLong("end_time")); reuses.put(reuse.getSkillId(), reuse); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return reuses; } /** * Загружает скилы игрока с БД. * * @param player игрок, для которого загружаются скилы. */ public final void restoreSkills(Player player) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement("SELECT * FROM `character_skills` WHERE `object_id`= ? "); statement.setInt(1, player.getObjectId()); rset = statement.executeQuery(); SkillTable skillTable = SkillTable.getInstance(); while(rset.next()) { int id = rset.getInt("skill_id"); byte classId = rset.getByte("class_id"); SkillTemplate skill = skillTable.getSkill(classId, id); if(skill == null) continue; player.addSkill(skill, false); } } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } } /** * Сохраняет настройки клиента и горячих клавишь игрока. * * @param player игрок. */ public final boolean storeSettingsAndHotKeys(Player player) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); byte[] bytes = player.getHotkey(); if(player.isChangeHotkey() && bytes != null) { statement = con.prepareStatement("REPLACE INTO `character_hotkey` (object_id, data) VALUES (?,?)"); statement.setInt(1, player.getObjectId()); statement.setBytes(2, bytes); statement.executeUpdate(); DBUtils.closeStatement(statement); } bytes = player.getSettings(); if(player.isChangedSettings() && bytes != null) { statement = con.prepareStatement("REPLACE INTO `character_settings` (object_id, data) VALUES (?,?)"); statement.setInt(1, player.getObjectId()); statement.setBytes(2, bytes); statement.executeUpdate(); DBUtils.closeStatement(statement); } return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeConnection(con); } return false; } /** * Создание строки в БД пройденной территории. * * @param player игрок который побывал в территории. * @param territory территория, в которой побывал игрок. * @return успешно ли создан. */ public final boolean storeTerritory(Player player, Territory territory) { if(territory == null || player == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(ADD_STORE_TERRITORY); statement.setInt(1, player.getObjectId()); statement.setInt(2, territory.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Сохранение значения переменной квеста. * * @param state состояние квеста. * @param name название переменной. * @param wrap значение переменной. */ public final void storyQuestVar(QuestState state, String name, Wrap wrap) { Player player = state.getPlayer(); if(player == null || wrap == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(STORE_QUEST_VAR); statement.setInt(1, player.getObjectId()); statement.setInt(2, state.getQuestId()); statement.setString(3, name); statement.setInt(4, wrap.getInt()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление аккаунта * * @param account * @param address */ public final void updateAccount(Account account, InetAddress address) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement("UPDATE `accounts` SET `end_block`=?, `last_ip`=? WHERE `login`=?"); statement.setLong(1, -1L); statement.setString(2, address != null ? address.getHostAddress() : ""); statement.setString(3, account.getName()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление спавна босса в БД. * * @param template темплейт босса. * @param spawn время сп<NAME>. */ public final void updateBossSpawns(NpcTemplate template, long spawn) { if(template == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_BOSS_SPAWNS); statement.setLong(1, spawn); statement.setInt(2, template.getTemplateType()); statement.setInt(3, template.getTemplateType()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление строки в БД итема. * * @param item итем. * @return успешно ли обновлен. */ public final boolean updateDataItem(ItemInstance item) { if(item == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_DATA_ITEM); statement.setLong(1, item.getItemCount()); statement.setInt(2, item.hasCrystals() ? 1 : 0); statement.setString(3, item.getAutor()); statement.setInt(4, item.getBonusId()); statement.setInt(5, item.getEnchantLevel()); statement.setString(6, item.getOwnerName()); statement.setInt(7, item.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * * @param account */ public final void updateFullAccount(Account account) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement("UPDATE `accounts` SET `email` = ?, `access_level` = ?, `end_pay` = ?, `end_block`= ?, `last_ip`= ?, `allow_ips` = ?, `comments` = ? WHERE `login`=?"); statement.setString(1, account.getEmail()); statement.setInt(2, account.getAccessLevel()); statement.setLong(3, account.getEndPay()); statement.setLong(4, account.getEndBlock()); statement.setString(5, account.getLastIP()); statement.setString(6, account.getAllowIPs()); statement.setString(7, account.getComments()); statement.setString(8, account.getName()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обоновление иконки гильдии. * * @param guild гильдия. * @return успешно ли сообновлена. */ public final boolean updateGuildIcon(Guild guild) { if(guild == null) return false; GuildIcon icon = guild.getIcon(); if(icon == null || !icon.hasIcon()) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_GUILD_ICON); statement.setBytes(1, icon.getIcon()); statement.setString(2, icon.getName()); statement.setInt(3, guild.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } public final boolean updateGuildAlliance(Guild guild, int allianceId) { if(guild == null) return false; GuildIcon icon = guild.getIcon(); if(icon == null || !icon.hasIcon()) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_GUILD_ALLIANCE); statement.setInt(1, allianceId); statement.setInt(2, guild.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление сообщения для гильдии. * * @param guild гильдия. * @return успешно ли обновлен. */ public final boolean updateGuildMessage(Guild guild) { if(guild == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_GUILD_MESSAGE); statement.setString(1, guild.getMessage()); statement.setInt(2, guild.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } public final boolean updateGuildPraise(Guild guild) { if(guild == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_GUILD_PRAISE); statement.setInt(1, guild.getPraiseNumber()); statement.setInt(2, guild.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление ранга для гильдии. * * @param guild гильдия. * @param rank ранг. * @return успешно ли обновлен. */ public final boolean updateGuildRank(Guild guild, GuildRank rank) { if(rank == null || guild == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_GUILD_RANK); statement.setString(1, rank.getName()); statement.setInt(2, rank.getLawId()); statement.setInt(3, rank.getIndex()); statement.setInt(4, guild.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление титула для гильдии. * * @param guild гильдия. * @return успешно ли обновлен. */ public final boolean updateGuildTitle(Guild guild) { if(guild == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_GUILD_TITLE); statement.setString(1, guild.getTitle()); statement.setInt(2, guild.getId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление строки в БД инвенторя. * * @param owner владелец инвенторя. * @param inventory инвентарь. * @return успешно ли обновлен. */ public final boolean updateInventory(Character owner, Inventory inventory) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_INVENTORY); statement.setLong(1, inventory.getLevel()); statement.setInt(2, owner.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление строки в БД итема. * * @param item итем. * @return успешно ли обновлен. */ public final boolean updateItem(ItemInstance item) { if(item == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_ITEM); statement.setLong(1, item.getItemCount()); statement.setInt(2, item.getOwnerId()); statement.setInt(3, item.getLocationId()); statement.setInt(4, item.getIndex()); statement.setInt(5, item.hasCrystals() ? 1 : 0); statement.setString(6, item.getAutor()); statement.setInt(7, item.getBonusId()); statement.setInt(8, item.getEnchantLevel()); statement.setString(9, item.getOwnerName()); statement.setInt(10, item.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление строки в БД местоположения итема. * * @param item итем. * @return успешно ли обновлен. */ public final boolean updateLocationItem(ItemInstance item) { if(item == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_LOCATION_ITEM); statement.setInt(1, item.getOwnerId()); statement.setInt(2, item.getLocationId()); statement.setInt(3, item.getIndex()); statement.setInt(4, item.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление строки в БД континента игрока. * * @param player обновляемый игрок. * @return успешно ли обновлен. */ public final boolean updatePlayerContinentId(Player player) { if(player == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_CONTINENT_ID); statement.setInt(1, player.getContinentId()); statement.setInt(2, player.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление строки в БД гильдии игрока. * * @param member обновляемый игрок. * @return успешно ли обновлен. */ public final boolean updatePlayerGuild(Guild guild, GuildMember member) { if(member == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_GUILD); statement.setInt(1, guild != null ? guild.getId() : 0); statement.setInt(2, member.getRankId()); statement.setInt(3, member.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } public final boolean updatePlayerGuild(int guildId, int guildRank, int playerId) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_GUILD); statement.setInt(1, guildId); statement.setInt(2, guildRank); statement.setInt(3, playerId); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление строки в БД гильдии игрока. * * @param player обновляемый игрок. * @return успешно ли обновлен. */ public final boolean updatePlayerGuild(Player player) { if(player == null) return false; return updatePlayerGuild(player.getGuildId(), player.getGuildRankId(), player.getObjectId()); } /** * Обновление гилд пометки игрок в БД * * @param player обновляемый игрок. * @return успешно ли обновлен. */ public final boolean updatePlayerGuildNote(Player player) { if(player == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_GUILD_NOTE); statement.setString(1, player.getGuildNote()); statement.setInt(2, player.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление состояние региона в БД. * * @param region обновляемый регион. */ public final void updateRegionState(Region region) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_REGION_STATE); statement.setInt(1, region.getState().ordinal()); statement.setInt(2, region.getId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление владельца региона в БД. * * @param region обновляемый регион. */ public final void updateRegionOwner(Region region) { Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_REGION_OWNER); statement.setInt(1, region.getOwnerId()); statement.setInt(2, region.getId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление строки в БД уровня игрока. * * @param player обновляемый игрок. * @return успешно ли обновлен. */ public final boolean updatePlayerLevel(Player player) { if(player == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_LEVEL); statement.setInt(1, player.getLevel()); statement.setInt(2, player.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление титула игрок в БД * * @param player обновляемый игрок. * @return успешно ли обновлен. */ public final boolean updatePlayerTitle(Player player) { if(player == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_TITLE); statement.setString(1, player.getTitle()); statement.setInt(2, player.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } public final boolean updatePlayerDescription(Player player) { if(player == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_DESCRIPTION); statement.setString(1, player.getDescription()); statement.setInt(2, player.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление игрока переменной. * * @param objectId уникальный ид игрока. * @param name название переменной. * @param value значение переменной. */ public final void updatePlayerVar(int objectId, String name, String value) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_VARIABLE); statement.setString(1, value); statement.setInt(2, objectId); statement.setString(3, name); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление строки в БД зоны игрока. * * @param player обновляемый игрок. * @return успешно ли обновлен. */ public final boolean updatePlayerZoneId(Player player) { if(player == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_ZONE_ID); statement.setInt(1, player.getZoneId()); statement.setInt(2, player.getObjectId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Обновление стадии квеста. * * @param state состояние квеста. */ public final void updateQuest(QuestState state) { Player player = state.getPlayer(); if(player == null) return; PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_QUEST); statement.setInt(1, state.getState()); statement.setInt(2, state.getPanelStateId()); statement.setInt(3, player.getObjectId()); statement.setInt(4, state.getQuestId()); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление серверной переменной. * * @param name название переменной. * @param value значение переменной. */ public final void updateServerVar(String name, String value) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_SERVER_VARIABLE); statement.setString(1, value); statement.setString(2, name); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление положения игрока в БД. * * @param location позиция игрока. * @param name имя игрока. */ public final void updatePlayerLocation(Location location, String name, int zoneId) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_LOCATION); statement.setInt(1, (int) location.getX()); statement.setInt(2, (int) location.getY()); statement.setInt(3, (int) location.getZ()); statement.setInt(4, location.getHeading()); statement.setInt(5, location.getContinentId()); statement.setInt(6, zoneId); statement.setString(7, name); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление класса игрока в БД. * * @param objectId ид игрока. * @param cs класс игрока. */ public final void updatePlayerClass(int objectId, PlayerClass cs) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_CLASS); statement.setInt(1, cs.ordinal()); statement.setInt(2, objectId); statement.execute(); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } } /** * Обновление расы игрока в БД. * * @param objectId ид игрока. * @param race раса игрока. * @param sex пол игрока. */ public final boolean updatePlayerRace(int objectId, Race race, Sex sex) { PreparedStatement statement = null; Connection con = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_PLAYER_RACE); statement.setInt(1, race.getId()); statement.setInt(2, sex.ordinal()); statement.setInt(3, objectId); return statement.executeUpdate() > 0; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } /** * Получение ид игрока с указанным именем * * @param name имя игрока. * @return уникальный ид. */ public final int getPlayerObjectId(String name) { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(SELECT_PLAYER_OJECT_ID); statement.setString(1, name); rset = statement.executeQuery(); if(rset.next()) return rset.getInt(1); } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCSR(con, statement, rset); } return 0; } public final boolean updateFatigability(Account account) { if(account == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(UPDATE_ACCOUNT_FATIGABILITY); statement.setInt(1, account.getFatigability()); statement.setInt(2, account.getAccountId()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } public final boolean createGuildApply(GuildApply apply, int guildId) { if(apply == null) return false; Connection con = null; PreparedStatement statement = null; try { con = connectFactory.getConnection(); statement = con.prepareStatement(CREATE_GUILD_APPLY); statement.setInt(1, guildId); statement.setInt(2, apply.getPlayerId()); statement.setString(3, apply.getMessage()); statement.execute(); return true; } catch(SQLException e) { LOGGER.warning(e); } finally { DBUtils.closeDatabaseCS(con, statement); } return false; } } <file_sep>/java/game/tera/gameserver/model/skillengine/conditions/ConditionPlayerOwerturned.java package tera.gameserver.model.skillengine.conditions; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Условие выполнение проверки на опрокинутости игрока.. * * @author Ronn */ public class ConditionPlayerOwerturned extends AbstractCondition { /** флаг опрокинутости */ private boolean value; /** * @param value опрокинута ли цель. */ public ConditionPlayerOwerturned(boolean value) { this.value = value; } @Override public boolean test(Character attacker, Character attacked, Skill skill, float val) { return attacker.isOwerturned() == value; } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/replyes/ReplySkillShop.java package tera.gameserver.model.npc.interaction.replyes; import org.w3c.dom.Node; import rlib.util.VarTable; import rlib.util.array.Arrays; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.inventory.Bank; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.TaxationNpc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.npc.interaction.dialogs.Dialog; import tera.gameserver.model.npc.interaction.dialogs.SkillShopDialog; import tera.gameserver.model.playable.Player; /** * Модель ссылки на магазин скилов. * * @author Ronn */ public final class ReplySkillShop extends AbstractReply { /** доступные классы */ private PlayerClass[] available; public ReplySkillShop(Node node) { super(node); VarTable vars = VarTable.newInstance(node); this.available = vars.getEnumArray("classes", PlayerClass.class, ","); } @Override public void reply(Npc npc, Player player, Link link) { // если не подходящий класс игрока, выходим if(!Arrays.contains(available, player.getPlayerClass())) { player.sendMessage("You don't have the appropriate class"); return; } // ссылка на банк для отчилсений Bank bank = null; // итоговый налог float resultTax = 1; // если НПС имеет налог if(npc instanceof TaxationNpc) { TaxationNpc taxation = (TaxationNpc) npc; // получаем банк для отчисления bank = taxation.getTaxBank(); // рассчитываем итоговый налог resultTax = 1 + (taxation.getTax() / 100F); } // создаем новый диалог шопа Dialog dialog = SkillShopDialog.newInstance(npc, player, bank, resultTax); // если его не удалось инициализировать if(!dialog.init()) // закрываем dialog.close(); } } <file_sep>/java/game/tera/gameserver/document/DocumentQuest.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestType; /** * Парсер квестов с хмл. * * @author Ronn */ public class DocumentQuest extends AbstractDocument<Array<Quest>> { public DocumentQuest(File file) { super(file); } @Override protected Array<Quest> create() { return Arrays.toArray(Quest.class); } @Override protected void parse(Document doc) { for(Node lst = doc.getFirstChild(); lst != null; lst = lst.getNextSibling()) if("list".equals(lst.getNodeName())) for(Node questNode = lst.getFirstChild(); questNode != null; questNode = questNode.getNextSibling()) if("quest".equals(questNode.getNodeName())) { VarTable vars = VarTable.newInstance(questNode); Quest quest = vars.getEnum("type", QuestType.class).newInstance(questNode); if(quest != null) result.add(quest); } } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Sytem_Message.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.MessageType; import tera.gameserver.network.ServerPacketType; /** * Пакет системного сообщения. * * @author Ronn */ public class S_Sytem_Message extends ServerPacket { private static final S_Sytem_Message instance = new S_Sytem_Message(); private static final char split = 0x0B; public static S_Sytem_Message getInstance(MessageType type) { S_Sytem_Message packet = (S_Sytem_Message) instance.newInstance(); packet.builder = new StringBuilder(type.getName()); return packet; } public static S_Sytem_Message getInstance(String message) { S_Sytem_Message packet = (S_Sytem_Message) instance.newInstance(); packet.builder = new StringBuilder(message); return packet; } /** подготовленная строка */ private StringBuilder builder; public S_Sytem_Message add(String var, String val) { builder.append(split); builder.append(var); builder.append(split); builder.append(val); return this; } /** * Добавление атакующего. */ public S_Sytem_Message addAttacker(String name) { builder.append(split); builder.append("attacker"); builder.append(split); builder.append(name); return this; } /** * Добавить итемы в сообщение. */ public S_Sytem_Message addItem(int id, int count) { builder.append(split); builder.append("ItemName"); builder.append(split); builder.append("@Item:").append(id); builder.append(split); builder.append("ItemAmount"); builder.append(split); builder.append(count); return this; } /** * Добавить итемы в сообщение. */ public S_Sytem_Message addItemName(int id) { builder.append(split); builder.append("ItemName"); builder.append(split); builder.append("@Item:").append(id); return this; } public S_Sytem_Message addLoser(String name) { builder.append(split); builder.append("loser"); builder.append(split); builder.append(name); return this; } /** * Добавить кому сколько денег выдано. */ public S_Sytem_Message addMoney(String name, int count) { builder.append(split); builder.append("UserName"); builder.append(split); builder.append(name); builder.append(split); builder.append("Money"); builder.append(split); builder.append(count); return this; } public S_Sytem_Message addOpponent(String name) { builder.append(split); builder.append("Opponent"); builder.append(split); builder.append(name); return this; } /** * Добавить сколько денег потрачено. */ public S_Sytem_Message addPaidMoney(int count) { builder.append(split); builder.append("amount"); builder.append(split); builder.append(count); return this; } /** * Добавить игрока. */ public S_Sytem_Message addPlayer(String name) { builder.append(split); builder.append("player"); builder.append(split); builder.append(name); return this; } public S_Sytem_Message addProf(int count) { builder.append(split); builder.append("prof"); builder.append(split); builder.append(count); return this; } public S_Sytem_Message addQuestName(int id) { builder.append(split); builder.append("QuestName"); builder.append(split); builder.append("@quest:"); builder.append(id).append("001"); return this; } public S_Sytem_Message addQuestName(String name) { builder.append(split); builder.append("QuestName"); builder.append(split); builder.append(name); return this; } public S_Sytem_Message addRequestor(String name) { builder.append(split); builder.append("requestor"); builder.append(split); builder.append(name); return this; } public S_Sytem_Message addSkillName(String name) { builder.append(split); builder.append("SkillName"); builder.append(split); builder.append(name); return this; } public S_Sytem_Message addTarget(String name) { builder.append(split); builder.append("target"); builder.append(split); builder.append(name); return this; } public S_Sytem_Message addUserName(String name) { builder.append(split); builder.append("UserName"); builder.append(split); builder.append(name); return this; } public S_Sytem_Message addWinner(String name) { builder.append(split); builder.append("winner"); builder.append(split); builder.append(name); return this; } public S_Sytem_Message addUnion(int allianceId) { builder.append(split); builder.append("UnionName"); builder.append(split); builder.append("@union:" + Integer.toString(allianceId)); return this; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SYSTEM_MESSAGE; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeShort(buffer, 6); writeStringBuilder(buffer, builder); } } <file_sep>/java/game/tera/gameserver/scripts/items/AbstractItemExecutor.java package tera.gameserver.scripts.items; import java.util.Arrays; import rlib.logging.Logger; import rlib.logging.Loggers; /** * Фундамент для обработки активного итема. * * @author Ronn * @created 27.03.2012 */ public abstract class AbstractItemExecutor implements ItemExecutor { protected static final Logger log = Loggers.getLogger(ItemExecutor.class); /** массив итем ид, на которых распространяется обработчик */ private int[] itemIds; /** уровень доступа игрок на выполнения обработчика */ private int access; /** * @param itemIds массив итем ид. * @param access минимальный уровень прав для доступа. */ public AbstractItemExecutor(int[] itemIds, int access) { this.itemIds = itemIds; this.access = access; } @Override public int getAccess() { return access; } @Override public int[] getItemIds() { return itemIds; } @Override public String toString() { return getClass().getSimpleName() + " " + (itemIds != null ? "itemIds = " + Arrays.toString(itemIds) + ", " : "") + "access = " + access; } } <file_sep>/java/game/tera/gameserver/scripts/commands/CommandType.java package tera.gameserver.scripts.commands; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import rlib.logging.Loggers; /** * Перечисление доступных команд. * * @author Ronn * @created 04.03.2012 */ public enum CommandType { RESOURSE_COMMANDS(ResourseCommand.class, 100, "around_resourse", "spawn_resourse", "set_export_file", "add_resourse", "export_resourse"), /** команды для работы с конфигом */ CONFIG_COMMANDS(ConfigCommand.class, 100, "config_reload", "config_set"), /** территориальные команды */ WORLD_COMMANDS(WorldCommand.class, 100, "loc", "region", "territory", "goto", "recall"), /** команды над скилами */ SKILL_COMMANDS(SkillCommand.class, 100, "start_skill", "add_skills", "learn_next_skills", "reload_skills", "clear_skills", "get_base_skills", "effect", "charm"), /** целительные команды */ HEAL_COMMANDS(HealCommand.class, 100, "set_hp", "set_mp", "heal"), /** команды разработчиков */ DEVELOPER_COMMANDS(DeveloperCommand.class, 100, "event_reg_all_players", "zone", "change_class", "kick", "check_geo", "send_event", "send_system", "send_state", "add_attack", "start_event", "sub_attack", "start_gc", "reload_dialogs", "send_packet", "set_access_level", "get_access_level", "set_heart", "set_level", "send_bytes", "send_file", "get_my_id", "invul", "set_ower_dist", "my_funcs", "save_point", "a", "save_all", "gm_speed"), /** команды над итемами */ ITEM_COMMANDS(ItemCommand.class, 100, "item_info", "create_item", "spawn_item", "reload_items"), /** пользовательские команды */ USER_COMMANDS(UserCommand.class, 0, "event_reg", "restore_characters", "player_info", "help", "version", "end_pay", "time", "kill_me", "online", "restore_skills"), /** команды цензоров */ CENSORE_COMMANDS(CensoreCommand.class, 40, "chat_ban", "chat_unban"), /** команды цензоров */ SUMMON_COMMANDS(SummonCommand.class, 100, "reload_summons", "summon_cast", "around_summon_cast"), /** команды по квестам */ QUEST_COMMANDS(QuestCommand.class, 100, "quest_cond", "quest_state", "quest_cancel", "quest_remove", "quest_accept", "quest_movie", "quest_reload", "quest_start", "quest_info"), /** команды для переменных */ VAR_COMMANDS(VariablesCommand.class, 100, "set_player_var", "get_player_var"), /** команды над нпс */ NPC_COMMANDS(NpcCommands.class, 100, "go_to_npc", "send_dialog", "test_spawn", "stop_spawns", "start_spawns", "npc_cast", "around_npc_spawn", "around_npc", "reload_npcs", "reload_spawns", "spawn", "around_npc_cast", "around_npc_long_cast"); /** список команд */ private String[] commands; /** уровень доступа к команде */ private int access; /** конструктор команды */ private Constructor<? extends Command> constructor; /** * @param type тип обработчика команд. * @param access уровень доступа к обработчику. * @param commands список обрабатываемых команд. */ private CommandType(Class<? extends Command> type, int access, String... commands) { this.commands = commands; this.access = access; try { constructor = type.getConstructor(int.class, String[].class); } catch(NoSuchMethodException | SecurityException e) { Loggers.warning(this, e); } } /** * @return минимальный уровень доступа к обработчику. */ public int getAccess() { return access; } /** * @return конструктор обработчика. */ public Constructor<? extends Command> getConstructor() { return constructor; } /** * @return кол-во обрабатываемых комманд. */ public int getCount() { return commands.length; } /** * @return новый экземпляр обработчика. */ public Command newInstance() { try { return constructor.newInstance(access, commands); } catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { Loggers.warning(this, e); } return null; } } <file_sep>/java/game/tera/remotecontrol/handlers/ServerRestartHandler.java package tera.remotecontrol.handlers; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import rlib.logging.Loggers; import tera.Config; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; public class ServerRestartHandler implements PacketHandler { @Override public Packet processing(Packet packet) { Loggers.info("ServerRestartHandler", "start save all players..."); for(Player player : World.getPlayers()) { Loggers.info(this, "store " + player.getName()); player.store(false); } Loggers.info("ServerRestartHandler", "done."); if(!Config.SERVER_ONLINE_FILE.isEmpty()) { try(PrintWriter out = new PrintWriter(new File(Config.SERVER_ONLINE_FILE))) { out.print(0); } catch(FileNotFoundException e) { Loggers.warning(this, e); } } Loggers.info(this, "start restart..."); System.exit(2); return null; } } <file_sep>/java/game/tera/gameserver/model/npc/playable/EventEpicBattleNpc.java package tera.gameserver.model.npc.playable; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.templates.NpcTemplate; /** * Модель НПС для ивента Эпичных Битв. * * @author Ronn */ public class EventEpicBattleNpc extends PlayerKiller { public EventEpicBattleNpc(int objectId, NpcTemplate template) { super(objectId, template); } @Override public void addAggro(Character aggressor, long aggro, boolean damage) { // если это не урон от игрока if(!damage && aggressor.isPlayer()) { // получаем игрока Player player = aggressor.getPlayer(); // в зависимости от класса игрока switch(player.getPlayerClass()) { case WARRIOR: case LANCER: aggro = 1; break; default: break; } } super.addAggro(aggressor, aggro, damage); } @Override public void causingDamage(Skill skill, AttackInfo info, Character attacker) { // пробуем получить игрока Player player = attacker.getPlayer(); // если это игрок и он не на ивенте, выходим if(player != null && !player.isEvent()) return; super.causingDamage(skill, info, attacker); } } <file_sep>/java/game/tera/gameserver/tables/ConfigAITable.java package tera.gameserver.tables; import java.io.File; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Files; import rlib.util.array.Array; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.Config; import tera.gameserver.document.DocumentNpcConfigAI; import tera.gameserver.model.ai.npc.ConfigAI; /** * Таблица конфигов АИ. * * @author Ronn */ public final class ConfigAITable { private static final Logger log = Loggers.getLogger(ConfigAITable.class); private static ConfigAITable instance; public static ConfigAITable getInstance() { if(instance == null) instance = new ConfigAITable(); return instance; } /** таблица конфигов */ private Table<String, ConfigAI> configs; private ConfigAITable() { configs = Tables.newObjectTable(); for(File file : Files.getFiles(new File(Config.SERVER_DIR + "/data/config_ai"), "xml")) { if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file); continue; } // парсим файл Array<ConfigAI> result = new DocumentNpcConfigAI(file).parse(); // перебираем результат парса for(ConfigAI config : result) { if(configs.containsKey(config.getName())) { log.warning(new Exception("found duplicate config " + config.getName())); continue; } // вносим конфиг АИ в таблицу configs.put(config.getName(), config); } } log.info("loaded " + configs.size() + " npc ai configs."); } /** * Получение конфига АИ по его имени. * * @param name название конфига. * @return конфиг. */ public ConfigAI getConfig(String name) { return configs.get(name); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/SingleShot.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Formulas; import tera.gameserver.model.skillengine.shots.ObjectShot; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель стреляющего скила. * * @author Ronn */ public class SingleShot extends Strike { public SingleShot(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем формулы Formulas formulas = Formulas.getInstance(); // рассчитываем урон AttackInfo info = formulas.calcDamageSkill(local.getNextAttackInfo(), this, attacker, target); // применяем влияние расстояния fineRange(attacker, target, info); // наносим урон target.causingDamage(this, info, attacker); // если удар был не заблокирован if(!info.isBlocked()) // добавляем эффекты addEffects(attacker, target); return info; } /** * Рассчет штрафа на дистанционный скил. * * @param attacker атакующий. * @param attacked атакуемый. * @param info инфа об атаке. */ protected void fineRange(Character attacker, Character attacked, AttackInfo info) { if(info.getDamage() < 2) return; // получаем максимальное расстояние float range = getRange() * getRange(); // получаем текущее расстояние float current = Math.max(attacker.getSquareDistance(attacked.getX(), attacked.getY(), attacked.getZ()), 1F); info.divDamage(3F - Math.min(range / current, 2F)); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { setImpactX(character.getX()); setImpactY(character.getY()); setImpactZ(character.getZ()); ObjectShot.startShot(character, this, targetX, targetY, targetZ); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/LockOnEffect.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.npc.Npc; import tera.gameserver.network.serverpackets.S_Each_Skill_Result; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * @author Ronn */ public class LockOnEffect extends LockOnStrike { public LockOnEffect(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // инфа об атаке AttackInfo info = local.getNextAttackInfo(); // рассчитывам блокированность дебафа info.setBlocked(target.isBlocked(attacker, impactX, impactY, this)); // если дебаф не заблокирован if(!info.isBlocked()) { // добавляем эффекты addEffects(attacker, target); // если цель нпс, агрмм его на себя if(target.isNpc()) { Npc npc = target.getNpc(); // добавялем агр поинты npc.addAggro(attacker, attacker.getLevel() * attacker.getLevel(), false); } } // отображаем анимацию приминения дебафа target.broadcastPacket(S_Each_Skill_Result.getInstance(attacker, target, template.getDamageId(), getPower(), false, false, S_Each_Skill_Result.EFFECT)); // если цель в ПвП режиме а кастер нет if(target.isPvPMode() && !attacker.isPvPMode()) { // включаем пвп режим attacker.setPvPMode(true); // включаем боевую стойку attacker.startBattleStance(target); } return info; } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/conditions/ConditionQuestComplete.java package tera.gameserver.model.npc.interaction.conditions; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestList; /** * Условие проверки на выполнение квеста. * * @author Ronn */ public class ConditionQuestComplete extends AbstractCondition { /** ид проверяемого квеста */ private int questId; public ConditionQuestComplete(Quest quest, int questId) { super(quest); this.questId = questId; } @Override public boolean test(Npc npc, Player player) { // если игрока нет, возвращаем плохо if(player == null) { log.warning(this, "not found player"); return false; } // получаем список квестов игрока QuestList questList = player.getQuestList(); // если его нет, возвращаем плохо if(questList == null) { log.warning(this, "not found quest list"); return false; } return questList.isCompleted(questId); } @Override public String toString() { return "ConditionQuestComplete questId = " + questId; } } <file_sep>/java/game/tera/gameserver/network/model/UserClient.java package tera.gameserver.network.model; import rlib.network.packets.ReadeablePacket; import rlib.network.server.client.AbstractClient; import tera.gameserver.manager.AccountManager; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Account; import tera.gameserver.model.playable.Player; import tera.gameserver.network.crypt.CryptorState; import tera.gameserver.network.crypt.TeraCrypt; import tera.gameserver.network.serverpackets.ConnectAccepted; import tera.gameserver.network.serverpackets.ServerPacket; /** * Модель клиента пользователя. * * @author Ronn * @created 24.03.2012 */ @SuppressWarnings("rawtypes") public final class UserClient extends AbstractClient<Account, Player, UserAsynConnection, TeraCrypt> implements Runnable { public UserClient(UserAsynConnection connection) { super(connection, new TeraCrypt()); } @Override public void close() { lock(); try { // ставим флаг закрытия setClosed(true); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // отправляем на отложенное завершение executor.execute(this); } finally { unlock(); } } @Override protected void executePacket(ReadeablePacket packet) { // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // если пакет должен синхронно исполнится if(packet.isSynchronized()) // отправляем на синхронное исполнение executor.runSynchPacket(packet); else // отправляем на асинхронное исполнение executor.runAsynchPacket(packet); } /** * @return состояние крипта. */ public CryptorState getCryptorState() { return crypt.getState(); } @Override public String getHostAddress() { return "unknown"; } /** * @return время последней активности. */ public long getLastActive() { return connection.getLastActive(); } @Override public void run() { try { // пробуем получить активный игрок Player owner = getOwner(); // если активный игрок есть if(owner != null) { // зануляем клиент owner.setClient(null); // удаляем из мира owner.deleteMe(); // зануляем setOwner(null); } } catch(Exception e) { log.warning(e); } lock(); try { // получаем подключение клиента UserAsynConnection connection = getConnection(); // если подключение есть if(connection != null) { // закрываем connection.close(); // зануляем клиент в нем connection.setClient(null); // зануляем подключение setConnection(null); } // получаем аккаунт клиента Account account = getAccount(); // если есть аккаунт if(account != null) { // получаем менеджер аккаунтов AccountManager accountManager = AccountManager.getInstance(); // удаляем аккаунт accountManager.closeAccount(account); // зануляем setAccount(null); } } catch(Exception e) { log.warning(e); } finally { unlock(); } } /** * отправка пакета с увеличением счетчика. * * @param packet отправляемый пакет. * @param increase увеличивать ли счетчик. */ public void sendPacket(ServerPacket packet, boolean increase) { if(increase) packet.increaseSends(); sendPacket(packet); } /** * @param closed флаг закрытия. */ public void setClosed(boolean closed) { this.closed = closed; } /** * @param connection конект пользователя. */ public void setConnection(UserAsynConnection connection) { this.connection = connection; } /** * @param state состояние криптора. */ public void setCryptorState(CryptorState state) { crypt.setState(state); } @Override public void successfulConnection() { // создаем пакет ConnectAccepted packet = ConnectAccepted.getInstance(); // увеличиваем счетчик отправлк packet.increaseSends(); // добавляем на отправку connection.sendPacket(packet); } @Override public String toString() { return "Client account = " + account + ", connection = " + connection; } }<file_sep>/java/game/tera/gameserver/network/serverpackets/Reaction.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.Character; import tera.gameserver.model.ReactionType; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет отображения реакции. * * @author Ronn */ public class Reaction extends ServerPacket { private static final ServerPacket instance = new Reaction(); public static Reaction getInstance(Character actor, ReactionType type) { Reaction packet = (Reaction) instance.newInstance(); packet.objectId = actor.getObjectId(); packet.subId = actor.getSubId(); packet.type = type; return packet; } /** тип реакции */ private ReactionType type; /** ид персонажа */ private int objectId; /** саб ид персонажа */ private int subId; @Override public ServerPacketType getPacketType() { return ServerPacketType.REACTION; } @Override protected final void writeImpl() { writeOpcode(); writeInt(objectId); writeInt(subId); writeInt(type.ordinal()); } }<file_sep>/java/game/tera/gameserver/model/skillengine/classes/CharmBuff.java package tera.gameserver.model.skillengine.classes; import rlib.util.Rnd; import rlib.util.array.Array; import tera.gameserver.model.Character; import tera.gameserver.model.MessageType; import tera.gameserver.model.TObject; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Formulas; import tera.gameserver.model.worldobject.BonfireObject; import tera.gameserver.network.serverpackets.CharmSmoke; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель скила, служащего только для активирования бафа. * * @author Ronn */ public class CharmBuff extends Buff { /** целевой костер */ private BonfireObject bonfire; /** * @param template темплейт скила. */ public CharmBuff(SkillTemplate template) { super(template); } @Override protected void addEffects(Character effector, Character effected) { // получаем игрока Player player = effected.getPlayer(); if(player == null) return; // список возможных эффектов от скила EffectTemplate[] effectTemplates = template.getEffectTemplates(); // если таких нет if(effectTemplates == null || effectTemplates.length == 0) return; EffectTemplate target = effectTemplates[Rnd.nextInt(0, effectTemplates.length - 1)]; // получаем формулы Formulas formulas = Formulas.getInstance(); // если эффект только на кастующего или шанс не сработал, пропускаем if(target.isOnCaster() || formulas.calcEffect(effector, effected, target, this) < 0) return; // активируем эффект runEffect(target.newInstance(effector, effected, template), effected); } @Override public boolean checkCondition(Character attacker, float targetX, float targetY, float targetZ) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // ищем костры вокруг Array<TObject> objects = World.getAround(BonfireObject.class, local.getNextObjectList(), attacker, 30 + attacker.getGeomRadius()); // если костров рядом нет, выходим if(objects.isEmpty()) { attacker.sendMessage(MessageType.CHARMS_CAN_ONLY_BE_USED_NEAR_A_CAMPFIRE); return false; } // запоминаем найденный костер setBonfire((BonfireObject) objects.first()); return super.checkCondition(attacker, targetX, targetY, targetZ); } private BonfireObject getBonfire() { return bonfire; } private void setBonfire(BonfireObject bonfire) { this.bonfire = bonfire; } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { // получаем костер BonfireObject bonfire = getBonfire(); // если он есть if(bonfire != null) // разворачиваем кастера к костру attacker.setHeading(attacker.calcHeading(bonfire.getX(), bonfire.getY())); super.startSkill(attacker, targetX, targetY, targetZ); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { // получаем костер BonfireObject bonfire = getBonfire(); // если его нет, выходим if(bonfire == null) return; // зануляем костер setBonfire(null); // отправляем пакет дыма character.broadcastPacket(CharmSmoke.getInstance(bonfire)); // получаем локальные объекты LocalObjects local = LocalObjects.get(); // контейнер для целей Array<Character> targets = local.getNextCharList(); // добавляем цели addTargets(targets, character, bonfire.getX(), bonfire.getY(), bonfire.getZ()); Character[] array = targets.array(); // перечисляем цели for(int i = 0, length = targets.size(); i < length; i++) { Character target = array[i]; // если цель мертва или в инву, пропускаем if(target.isDead() || target.isInvul()) continue; // применяем скил applySkill(character, target); } } } <file_sep>/java/game/tera/gameserver/network/model/ServerNetworkConfig.java package tera.gameserver.network.model; import rlib.network.NetworkConfig; import tera.Config; import tera.gameserver.ServerThread; /** * Конфигурирование асинхронной сети под сервер теры. * * @author Ronn */ public class ServerNetworkConfig implements NetworkConfig { private static ServerNetworkConfig instance; public static ServerNetworkConfig getInstance() { if(instance == null) instance = new ServerNetworkConfig(); return instance; } @Override public String getGroupName() { return "Network"; } @Override public int getGroupSize() { return Config.NETWORK_GROUP_SIZE; } @Override public int getReadBufferSize() { return Config.NETWORK_READ_BUFFER_SIZE; } @Override public Class<? extends Thread> getThreadClass() { return ServerThread.class; } @Override public int getThreadPriority() { return Config.NETWORK_THREAD_PRIORITY; } @Override public int getWriteBufferSize() { return Config.NETWORK_WRITE_BUFFER_SIZE; } @Override public boolean isVesibleReadException() { // TODO Auto-generated method stub return false; } @Override public boolean isVesibleWriteException() { // TODO Auto-generated method stub return false; } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/Passive.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.templates.SkillTemplate; /** * Моель пассивного скила. * * @author Ronn */ public class Passive extends AbstractSkill { /** * @param template темплейт скила. */ public Passive(SkillTemplate template) { super(template); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Npc_Menu_Select.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Npc_Menu_Select extends ServerPacket { /** успешное начало диалога */ public static final byte SUCCEESS = 1; /** не удачное начало диалоги */ public static final byte NOT_SUCCESS = 0; private static final ServerPacket instance = new S_Npc_Menu_Select(); public static S_Npc_Menu_Select getInstance(int result) { S_Npc_Menu_Select packet = (S_Npc_Menu_Select) instance.newInstance(); packet.result = result; return packet; } /** разрешен ли диалог */ private int result; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_NPC_MENU_SELECT; } @Override protected void writeImpl() { writeOpcode(); writeByte(result); } }<file_sep>/java/game/tera/gameserver/network/serverpackets/CharState.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Состояние игрока. * * @author Ronn */ public class CharState extends ServerPacket { private static final ServerPacket instance = new CharState(); public static CharState getInstance(int objectId, int subId, int state) { CharState packet = (CharState) instance.newInstance(); packet.objectId = objectId; packet.subId = subId; packet.state = state; return packet; } /** уникальный ид игрока */ private int objectId; /** под ид игрока */ private int subId; /** состояние игрока */ private int state; @Override public ServerPacketType getPacketType() { return ServerPacketType.CHAR_STATE; } @Override protected final void writeImpl() { writeOpcode(); writeInt(objectId); writeInt(subId); writeByte(state); } } <file_sep>/java/game/tera/gameserver/model/ai/npc/NpcAIClass.java package tera.gameserver.model.ai.npc; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import tera.gameserver.model.ai.npc.classes.BattleGuardAI; import tera.gameserver.model.ai.npc.classes.DefaultNpcAI; import tera.gameserver.model.ai.npc.classes.DefaultSummonAI; import tera.gameserver.model.ai.npc.classes.EpicBattleAI; import tera.gameserver.model.ai.npc.classes.EventMonsterAI; import tera.gameserver.model.ai.npc.classes.RegionWarDefenseAI; import tera.gameserver.model.npc.BattleGuard; import tera.gameserver.model.npc.EventMonster; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.RegionWarDefense; import tera.gameserver.model.npc.playable.EventEpicBattleNpc; import tera.gameserver.model.npc.summons.Summon; /** * Перечисление классов АИ. * * @author Ronn */ public enum NpcAIClass { /** АИ монстра для ивента */ EVENT_MOSTER(EventMonsterAI.class, EventMonster.class), /** АИ боевого гварда */ BATTLE_GUARD(BattleGuardAI.class, BattleGuard.class), /** АИ для защитника региона в битве */ REGION_WAR_DEFENSE(RegionWarDefenseAI.class, RegionWarDefense.class), /** АИ для ивента Эпичных Боев */ EPIC_BATTLE_EVENT(EpicBattleAI.class, EventEpicBattleNpc.class), /** базовое АИ суммона */ DEFAULT_SUMMON(DefaultSummonAI.class, Summon.class), /** АИ по умолчанию */ DEFAULT(DefaultNpcAI.class, Npc.class); /** конструктор АИ */ private Constructor<? extends NpcAI<? extends Npc>> constructor; private NpcAIClass(Class<? extends NpcAI<?>> type, Class<? extends Npc> actorType) { try { this.constructor = (Constructor<? extends NpcAI<?>>) type.getConstructor(actorType, ConfigAI.class); } catch(NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException(e); } } /** * Создание нового инстанса АИ. * * @param npc нпс, для которого создается АИ. * @param config конфиг для АИ. * @return новый инстанс АИ. */ @SuppressWarnings("unchecked") public <T extends Npc> NpcAI<T> newInstance(T npc, ConfigAI config) { try { return (NpcAI<T>) constructor.newInstance(npc, config); } catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e); } } } <file_sep>/java/game/tera/gameserver/model/items/ItemClass.java package tera.gameserver.model.items; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import rlib.logging.Loggers; import rlib.util.VarTable; import tera.gameserver.IdFactory; import tera.gameserver.templates.ArmorTemplate; import tera.gameserver.templates.CommonTemplate; import tera.gameserver.templates.CrystalTemplate; import tera.gameserver.templates.ItemTemplate; import tera.gameserver.templates.WeaponTemplate; import tera.util.constructors.ConstructorItem; /** * Перечисление классов итемов. * * @author Ronn */ public enum ItemClass { /** броня */ ARMOR("armor", ArmorTemplate.class, ConstructorItem.ARMOR, ArmorType.class), /** оружие */ WEAPON("weapon", WeaponTemplate.class, ConstructorItem.WEAPON, WeaponType.class), /** другие итемы */ COMMON_ITEM("common", CommonTemplate.class, ConstructorItem.COMMON, CommonType.class), /** крристалы */ CRYSTAL("crystal", CrystalTemplate.class, ConstructorItem.CRYSTAL, CrystalType.class); /** * Получение нужного класса по названию в xml. * * @param name название в xml. * @return соответствующий класс. */ public static ItemClass valueOfXml(String name) { for(ItemClass type : values()) if(type.getXmlName().equals(name)) return type; return null; } /** название в хмл */ private String xmlName; /** тип темплейта */ private Constructor<?> templateConstructor; /** экземпляр соответствующего типа */ private ConstructorItem constructor; /** тип енума типа итема */ private Method getType; /** * @param constructor конструктор итема. */ private ItemClass(String xmlName, Class<? extends ItemTemplate> templateClass, ConstructorItem constructor, Class<? extends Enum<?>> itemType) { this.xmlName = xmlName; this.constructor = constructor; try { this.templateConstructor = templateClass.getConstructors()[0]; this.getType = itemType.getMethod("valueOfXml", String.class); } catch(SecurityException | NoSuchMethodException e) { Loggers.warning(this, e); } } /** * @return xml название. */ public final String getXmlName() { return xmlName; } /** * @param objectId уник ид итема. * @param template темплейт итема. * @return новый экземпляр. */ public ItemInstance newInstance(int objectId, ItemTemplate template) { return constructor.newInstance(objectId, template); } /** * @param template темплейт итема. * @return новый экземпляр. */ public ItemInstance newInstance(ItemTemplate template) { // получаеим фабрику ид IdFactory idFactory = IdFactory.getInstance(); return constructor.newInstance(idFactory.getNextItemId(), template); } /** * Создание нового темплейта. * * @param vars набор параметров. * @param funcs набор функций. * @return новый темплейт. */ public ItemTemplate newTemplate(VarTable vars) { try { return (ItemTemplate) templateConstructor.newInstance(getType.invoke(null, vars.getString("type")), vars); } catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { Loggers.warning(this, e); System.out.println(vars); } return null; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestSkillAction.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; /** * Клиентский пакет старта мили скила. * * @author Ronn */ @SuppressWarnings("unused") public class RequestSkillAction extends ClientPacket { public static enum ActionType { NONE, NONE1, CANCEL; public static ActionType valueOf(int index) { ActionType[] values = values(); if(index >= values.length) return NONE; return values[index]; } } /** игрок */ private Player player; /** тип действия над скилом */ private ActionType type; /** скил ид */ private int skillId; @Override public void finalyze() { player = null; skillId = 0; } /** * @return игрок. */ public final Player getPlayer() { return player; } @Override public void readImpl() { player = owner.getOwner(); skillId = readInt(); type = ActionType.valueOf(readInt()); } @Override public void runImpl() { } }<file_sep>/java/game/tera/gameserver/model/skillengine/effects/SkillBlocking.java package tera.gameserver.model.skillengine.effects; import tera.gameserver.model.Character; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; /** * Эффект блокировки использования скилов. * * @author Ronn */ public class SkillBlocking extends AbstractEffect { public SkillBlocking(EffectTemplate template, Character effector, Character effected, SkillTemplate skill) { super(template, effector, effected, skill); } @Override public void onExit() { super.onExit(); effected.setSkillBlocking(false); } @Override public void onStart() { super.onStart(); effected.setSkillBlocking(true); } } <file_sep>/java/game/tera/gameserver/model/WaitCastSkill.java package tera.gameserver.model; import rlib.util.pools.Foldable; import tera.gameserver.model.skillengine.Skill; import tera.util.Location; /** * Модель ожидающего каста скила. * * @author Ronn */ public class WaitCastSkill implements Foldable { /** точка ,куда кастовать */ private Location targetLoc; /** скил, которым кастовать */ private Skill skill; public WaitCastSkill() { this.targetLoc = new Location(); } @Override public boolean equals(Object obj) { return obj == this || obj == skill; } @Override public void finalyze() { skill = null; } /** * @return кастуемый скил. */ public final Skill getSkill() { return skill; } /** * @return целевая точка. */ public final Location getTargetLoc() { return targetLoc; } @Override public void reinit(){} /** * @param skill кастуемый скил. */ public final void setSkill(Skill skill) { this.skill = skill; } /** * @param targetLoc целевая точка. */ public final void setTargetLoc(float x, float y, float z, int heading) { this.targetLoc.setXYZH(x, y, z, heading); } @Override public String toString() { return skill.getName(); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/EventMessage.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Ивентовое сообщение в чат. * * @author Ronn */ public class EventMessage extends ServerPacket { private static final ServerPacket instance = new EventMessage(); public static EventMessage getInstance(String head, String message, String info) { EventMessage packet = (EventMessage) instance.newInstance(); packet.head = head; packet.message = message; packet.info = info; return packet; } /** заголовок */ private String head; /** мессадж */ private String message; /** инфо */ private String info; @Override public void finalyze() { head = null; info = null; message = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.EVENT_MESSAGE; } @Override protected void writeImpl() { writeOpcode(); writeShort(6);//начало оглавления writeString(head);//ссылка оглавления buffer.position(buffer.position() - 2); writeShort(11);//разделитель writeString(message);//само сообщение buffer.position(buffer.position() - 2); writeShort(11);//разделитель writeString(info);//сдесь доп инфо это мб кол-во,число или ссылка } } <file_sep>/java/game/tera/gameserver/model/skillengine/conditions/ConditionTargetOwerturned.java package tera.gameserver.model.skillengine.conditions; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Условие выполнение проверки на опрокинутость цели. * * @author Ronn */ public class ConditionTargetOwerturned extends AbstractCondition { /** флаг опрокинутости */ private boolean value; /** * @param value опрокинута ли цель. */ public ConditionTargetOwerturned(boolean value) { this.value = value; } @Override public boolean test(Character attacker, Character attacked, Skill skill, float val) { return attacked != null && attacked.isOwerturned() == value; } } <file_sep>/java/game/tera/gameserver/events/Registered.java package tera.gameserver.events; import tera.gameserver.model.playable.Player; /** * Интерфейс для регистрируемых ивентов * * @author Ronn * @created 11.04.2012 */ public interface Registered { /** * Регистрация на участие игрока. * * @param player желающий участвовать игрок. * @return принят ли на ивент. */ public boolean registerPlayer(Player player); /** * Отмена регистрации на участие игрока. * * @param player игрок отказавшийся учавствовать. * @return отрегистрирован ли он. */ public boolean unregisterPlayer(Player player); } <file_sep>/java/game/tera/gameserver/document/DocumentNpcAppearance.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.table.Table; import tera.gameserver.model.npc.playable.NpcAppearance; import tera.gameserver.model.playable.PlayerAppearance; /** * Парсер готовых внешностей игроков с xml. * * @author Ronn */ public final class DocumentNpcAppearance extends AbstractDocument<Void> { private Table<String, NpcAppearance> table; public DocumentNpcAppearance(File file, Table<String, NpcAppearance> table) { super(file); this.table = table; } @Override protected Void create() { return null; } @Override protected void parse(Document doc) { VarTable vars = VarTable.newInstance(); Table<String, NpcAppearance> table = getTable(); for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node child = list.getFirstChild(); child != null; child = child.getNextSibling()) if(child.getNodeType() == Node.ELEMENT_NODE && "appearance".equals(child.getNodeName())) { // парсим атрибуты vars.parse(child); String id = vars.getString("id"); // парсим параметры внешности vars.parse(child, "set", "name", "value"); // парсим внешность NpcAppearance appearance = PlayerAppearance.fromXML(new NpcAppearance(), vars); table.put(id, appearance); } } public Table<String, NpcAppearance> getTable() { return table; } }<file_sep>/java/game/tera/gameserver/network/clientpackets/RequestTradeAddItem.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.actions.dialogs.ActionDialog; import tera.gameserver.model.actions.dialogs.ActionDialogType; import tera.gameserver.model.actions.dialogs.TradeDialog; import tera.gameserver.model.playable.Player; /** * Запрос на добавление итема в трейд. * * @author Ronn */ public class RequestTradeAddItem extends ClientPacket { /** игрок */ private Player player; /** номер ячейки */ private int index; /** кол-во итемов */ private int count; /** кол-во денег */ private long money; @Override public void finalyze() { player = null; } @Override public boolean isSynchronized() { return false; } @Override protected void readImpl() { player = owner.getOwner(); readLong();//1 ид readLong();//2 ид readLong(); readInt();// index = readInt() - 20; count = readInt(); money = readLong(); } @Override protected void runImpl() { if(player == null) return; ActionDialog dialog = player.getLastActionDialog(); if(dialog == null || dialog.getType() != ActionDialogType.TRADE_DIALOG) return; TradeDialog trade = (TradeDialog) dialog; if(money > 0) trade.addMoney(player, money); else trade.addItem(player, count, index); } } <file_sep>/java/game/tera/gameserver/model/ai/AI.java package tera.gameserver.model.ai; import tera.gameserver.model.Character; import tera.gameserver.model.EmotionType; import tera.gameserver.model.MoveType; import tera.gameserver.model.SayType; import tera.gameserver.model.TObject; import tera.gameserver.model.actions.Action; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.model.resourse.ResourseInstance; import tera.gameserver.model.skillengine.Effect; import tera.gameserver.model.skillengine.Skill; /** * Интерфейс для реализации АИ. * * @author Ronn * @created 12.04.2012 */ public interface AI { /** * Изменение уровня агрессии объекта по отношению к объекту. * * @param attacker атакующий объект. * @param aggro уровень изминения агресии. */ public void notifyAgression(Character attacker, long aggro); /** * Уведомление о наложении эффекта. * * @param effect наложенный эффект. */ public void notifyAppliedEffect(Effect effect); /** * Уведомление об прибытии объекта в назначенную точку. */ public void notifyArrived(); /** * Уведомление об блокировке перемещения объекта. */ public void notifyArrivedBlocked(); /** * Уведомление о прибытии объекта к указанной цели. * * @param target цель прибытия. */ public void notifyArrivedTarget(TObject target); /** * Уведомление о атаке объектом. * * @param attacked атакуемый объект. * @param skill атакующий скилл. * @param damage кол-во урона. */ public void notifyAttack(Character attacked, Skill skill, int damage); /** * Уведомление о атаке объекта. * * @param attacker атакующий объект. * @param skill атакующий скил. * @param damage кол-во урона. */ public void notifyAttacked(Character attacker, Skill skill, int damage); /** * Уведомление о нападении на члена клана. * * @param attackedMember атакуемый член клана. * @param attacker атакующий на члена клана. * @param damage нанесенный урон. */ public void notifyClanAttacked(Character attackedMember, Character attacker, int damage); /** * Увндомление о сборе ресурса. * * @param resourse собранный ресурс. */ public void notifyCollectResourse(ResourseInstance resourse); /** * Уведомление о смерти объекта. * * @param killer убийка объекта. */ public void notifyDead(Character killer); /** * Уведомление о завершении каста скилла объектом. * * @param skill кастуемый скил. */ public void notifyFinishCasting(Skill skill); /** * Уведомление о нападении на члена группы. * * @param attackedMember член группы. * @param attacker атакующий члена группы. * @param damage нанесенный урон. */ public void notifyPartyAttacked(Character attackedMember, Character attacker, int damage); /** * Уведомление о поднятие объектом итем с земли. * * @param item поднятый итем. */ public void notifyPickUpItem(ItemInstance item); /** * Уведомление об спавне объекта. */ public void notifySpawn(); /** * Уведомление о начале каста скила объектом. * * @param skill кастуемый скил. */ public void notifyStartCasting(Skill skill); /** * Уведомление об начале диалога объекта с игроком. * * @param player разговариваемый игрок. */ public void notifyStartDialog(Player player); /** * Уведомление об завершении диалога объекта с игроком. * * @param player разговариваемый игрок. */ public void notifyStopDialog(Player player); /** * Начать акшен. * * @param action акшен, который нужно начать. */ public void startAction(Action action); /** * Запусть режим активности. */ public void startActive(); /** * Запустить каст скила. * * @param startX стартовая координата. * @param startY стартовая координата. * @param startZ стартовая координата. * @param skill скилл, который нужно скастануть. * @param state состояние скила. * @param heading разворот, необходимый для каста скила. * @param targetX целевая координата каста. * @param targetY целевая координата каста. * @param targetZ целевая координата каста. */ public void startCast(float startX, float startY, float startZ, Skill skill, int state, int heading, float targetX, float targetY, float targetZ); /** * Запустить каст скила. * * @param skill скилл, который нужно скастануть. * @param heading разворот, необходимый для каста скила. * @param targetX целевая координата каста. * @param targetY целевая координата каста. * @param targetZ целевая координата каста. */ public void startCast(Skill skill, int heading, float targetX, float targetY, float targetZ); /** * Собрать ресурс. * * @param resourse ресурс, который нкжно собрать. */ public void startCollectResourse(ResourseInstance resourse); /** * Запуск одевания/снятия итема. * * @param index ячейка, в которой лежит нужный итем. * @param itemId ид итема снимаего. */ public void startDressItem(int index, int itemId); /** * Запустить эмоцию. * * @param type тип эмоции. */ public void startEmotion(EmotionType type); /** * Поднять итем. * * @param item итем, который нужно поднять. */ public void startItemPickUp(ItemInstance item); /** * Взаимодействовать с объектом. * * @param object объект, с которым нужно взаимодействовать. */ public void startIteract(Character object); /** * Идти в указаную точку. * * @param heading разворот, с которым идти. * @param type тип перемещения. * @param targetX координата конечной точки. * @param targetY координата конечной точки. * @param targetZ координата конечной точки. * @param broadCastMove отправлять ли пакет всем. * @param sendSelfPacket отправлять ли себе пакет. */ public void startMove(float startX, float startY, float startZ, int heading, MoveType type, float targetX, float targetY, float targetZ, boolean broadCastMove, boolean sendSelfPacket); /** * Идти в указаную точку. * * @param startX стартовая координата. * @param startY стартовая координата. * @param startZ стартовая координата. * @param heading разворот, с которым идти. * @param type тип перемещения. * @param targetX координата конечной точки. * @param targetY координата конечной точки. * @param targetZ координата конечной точки. * @param broadCastMove отправлять ли пакет всем. * @param sendSelfPacket отправлять ли себе пакет. */ public void startMove(int heading, MoveType type, float targetX, float targetY, float targetZ, boolean broadCastMove, boolean sendSelfPacket); /** * Начать разговор с НПС. * * @param npc нпс, с которым нужно начать разговор. */ public void startNpcSpeak(Npc npc); /** * Начать отдых. */ public void startRest(); /** * Сказать в чат что-то. * * @param text текст сообщения. * @param type тип сообщения. */ public void startSay(String text, SayType type); /** * Использовать итем. * * @param item итем, который нужно использовать. * @param heading направление. * @param isHeb является ли итем хербом. */ public void startUseItem(ItemInstance item, int heading, boolean isHeb); } <file_sep>/java/game/tera/gameserver/model/ai/npc/taskfactory/DefaultPatrolTaskFactory.java package tera.gameserver.model.ai.npc.taskfactory; import org.w3c.dom.Node; import rlib.util.Rnd; import rlib.util.VarTable; import rlib.util.array.Array; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.SkillGroup; import tera.gameserver.network.serverpackets.S_User_Status.NotifyType; import tera.util.LocalObjects; import tera.util.Location; /** * Модель генератора задач для патрулирование территории НПС. * * @author Ronn */ public class DefaultPatrolTaskFactory extends AbstractTaskFactory { /** шансы каста скилов */ protected final int[] groupChance; /** дистанция обращения внимания */ protected final int noticeRange; /** интервал между переходами точек маршрута */ protected final int patrolInterval; public DefaultPatrolTaskFactory(Node node) { super(node); try { // получаем список всех групп скилов SkillGroup[] groups = SkillGroup.values(); // парсим параметры VarTable vars = VarTable.newInstance(node, "set", "name", "val"); this.noticeRange = vars.getInteger("noticeRange", ConfigAI.DEFAULT_NOTICE_RANGE); this.patrolInterval = vars.getInteger("patrolInterval", 0); // создаем таблицу шансов групп скилов this.groupChance = new int[groups.length]; // заполняем таблицу for(int i = 0, length = groupChance.length; i < length; i++) groupChance[i] = vars.getInteger(groups[i].name(), 0); } catch(Exception e) { log.warning(this, e); throw new IllegalArgumentException(e); } } @Override public <A extends Npc> void addNewTask(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime) { // получаем флаг нахождения нпс в боевой стойке boolean battle = actor.isBattleStanced(); // получаем текущую цель игрока Character target = ai.getTarget(); // получаем дистанцию наблюдения int noticeRange = getNoticeRange(); // если нпс не в боевой стойке либо его цель вышла за пределы ренже внимания if(!battle || target == null || actor.getGeomDistance(target) > noticeRange) { // зануляем текущую цель target = null; // получаем список персонажей Array<Character> charList = local.getNextCharList(); // собираем сведения о целях вокруг World.getAround(Character.class, charList, actor, noticeRange); // если есть потенциальные цели if(!charList.isEmpty()) { // получаем массив целей Character[] array = charList.array(); // перебираем их for(int i = 0, length = charList.size(); i < length; i++) { // получаем потенциальную цель Character character = array[i]; // если цель враждебная if(actor.checkTarget(character)) { // запоминаем target = character; // выходим из цикла break; } } } // если найдена новая цель для внимания либо нпс в боевой стойке if(target != null) { // останавливаем НПС actor.stopMove(); // очищаем задания ai.clearTaskList(); // отображаем иконку уделния внимания цели PacketManager.showNotifyIcon(actor, NotifyType.NOTICE); // обновляем время ai.setLastNotifyIcon(currentTime); // добавляем задание на обновление фокуса внимания ai.addNoticeTask(target, false); // выходим return; } } // если нпс в боевой стойке if(battle) { // если НПС уже разворачивается if(actor.isTurner()) { // если целевой разворот не подходит if(!actor.isInTurnFront(target)) // обновляем внимание ai.addNoticeTask(target, false); } // если фокусная цель не спереди else if(!actor.isInFront(target)) // обновляем внимание ai.addNoticeTask(target, false); // выходим return; } // если выпал случай использования бафа if(chance(SkillGroup.HEAL)) { // получаем скил для хила Skill skill = actor.getRandomSkill(SkillGroup.HEAL); // если он есть и не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // если скил можно на себя юзать и не фул хп у себя if(!skill.isNoCaster() && actor.getCurrentHp() < actor.getMaxHp()) { // добавляем задание [bkmyenmcz ai.addCastTask(skill, actor); return; } // если скил не только на себя и есть фракция у НПС else if(!skill.isTargetSelf() && actor.getFractionRange() > 0) { // получаем фракцию НПС String fraction = actor.getFraction(); // получаем окружающих НПС Array<Npc> npcs = World.getAround(Npc.class, local.getNextNpcList(), actor, actor.getFractionRange()); // если НПС в радиусе фракции есть if(!npcs.isEmpty()) // перебираем их for(Npc npc : npcs.array()) { if(npc == null) break; // если НПС принадлежит его фракции и не имеет полного хп if(fraction.equals(npc.getFraction()) && npc.getCurrentHp() < npc.getMaxHp()) { // добавляем задание хильнуть его ai.addCastTask(skill, npc); return; } } } } } // если выпал случай использования бафа if(chance(SkillGroup.BUFF)) { // получаем скил для бафа Skill skill = actor.getRandomSkill(SkillGroup.BUFF); // если он есть и не в откате if(skill != null && !actor.isSkillDisabled(skill)) { // если баф не висит на НПС if(!skill.isNoCaster() && !actor.containsEffect(skill)) { // добавляем задание бафнуться ai.addCastTask(skill, actor); return; } // если скил не только на себя и есть фракция у НПС else if(!skill.isTargetSelf() && actor.getFractionRange() > 0) { // получаем фракцию НПС String fraction = actor.getFraction(); // получаем окружающих НПС Array<Npc> npcs = World.getAround(Npc.class, local.getNextNpcList(), actor, actor.getFractionRange()); // если НПС в радиусе фракции есть if(!npcs.isEmpty()) // перебираем их for(Npc npc : npcs.array()) { if(npc == null) break; // если НПС принадлежит его фракции и не имеет этого эффекта if(fraction.equals(npc.getFraction()) && !npc.containsEffect(skill)) { // добавляем задание бафнуть его ai.addCastTask(skill, npc); return; } } } } } // получаем маршрут патрулирования Location[] route = actor.getRoute(); // получаем текущий индекс точки маршрута int currentIndex = ai.getRouteIndex(); // получаем текущую точку маршрута Location point = route[currentIndex]; // получаем время перехода к след. точке long nextRoutePoint = ai.getNextRoutePoint(); // если мы к нужной точки еще не пришли if(actor.getDistance(point.getX(), point.getY(), point.getZ()) > 10) // добавляем задачу дойти до нее ai.addMoveTask(point, true); // если мы уже пришли else if(nextRoutePoint == -1) // ставим время, когдап надо начать идти к следующей ai.setNextRoutePoint(currentTime + getPatrolInterval()); // если уже пора к след. двигаться else if(currentTime > nextRoutePoint) { currentIndex += 1; if(route.length >= currentIndex) currentIndex = 0; // обновляем индекс точки ai.setRouteIndex(currentIndex); // получаем след. точку point = route[currentIndex]; // даем задание к ней идти ai.addMoveTask(point, true); // убераем время перехода к след точке ai.setNextRoutePoint(-1); } } /** * @return сработала ли указанная группа. */ protected boolean chance(SkillGroup group) { return Rnd.chance(groupChance[group.ordinal()]); } /** * @return радиус обращения внимаия на игроков. */ public int getNoticeRange() { return noticeRange; } /** * @return интервал между переходами между точек. */ public int getPatrolInterval() { return patrolInterval; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Equip_Item.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Inven_Changedslot; import tera.gameserver.network.serverpackets.S_User_External_Change; /** * Запрос на одевание предмета. * * @author Ronn */ public class C_Equip_Item extends ClientPacket { /** номер слота */ private int slot; /** ид итема снимаемого */ private int itemId; /** игрок */ private Player player; @Override public void finalyze() { itemId = 0; slot = 0; player = null; } @Override public boolean isSynchronized() { return false; } @Override public void readImpl() { player = owner.getOwner(); readInt(); readInt(); //номер слота slot = readInt(); if(slot < 40 && buffer.remaining() > 7) { readInt(); itemId = readInt(); } } @Override public void runImpl() { if(player != null){ player.getAI().startDressItem(slot, itemId); player.broadcastPacket(S_User_External_Change.getInstance(player)); } } } <file_sep>/java/game/tera/gameserver/events/EventUtils.java package tera.gameserver.events; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.EffectList; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAIClass; import tera.gameserver.model.npc.spawn.NpcSpawn; import tera.gameserver.model.npc.spawn.Spawn; import tera.gameserver.model.playable.Player; import tera.gameserver.tables.ConfigAITable; import tera.gameserver.tables.NpcTable; import tera.gameserver.templates.NpcTemplate; import tera.util.Location; /** * Набор полезных методов при создании эвентов. * * @author Ronn */ public abstract class EventUtils { private static final Array<Location> LOCATION_POOL = Arrays.toConcurrentArray(Location.class); private static final NpcTemplate GUARD; private static final ConfigAI GUARD_AI_CONFIG; static { NpcTable npcTable = NpcTable.getInstance(); GUARD = npcTable.getTemplate(1139, 63); ConfigAITable configTable = ConfigAITable.getInstance(); GUARD_AI_CONFIG = configTable.getConfig("DefaultFriendly"); } public static final int SLEEP_ID = 701100; public static final Spawn[] guards = { new NpcSpawn(GUARD, new Location(10607, 8118, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(10799, 8250, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11003, 8394, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11205, 8541, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11408, 8686, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11606, 8839, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11812, 8980, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12014, 9127, 976, 55235), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12438, 9098, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12584, 8895, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12729, 8691, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12874, 8488, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(13022, 8286, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(13170, 8085, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(13318, 7883, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(13466, 7682, 976, 38447), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(13332, 7335, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(13131, 7187, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12929, 7039, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12726, 6893, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12524, 6746, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12323, 6599, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(12120, 6453, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11919, 6304, 976, 23419), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11530, 6397, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11382, 6598, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11231, 6797, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(11080, 6997, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(10931, 7197, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(10782, 7397, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(10628, 7594, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), new NpcSpawn(GUARD, new Location(10478, 6304, 976, 6768), GUARD_AI_CONFIG, NpcAIClass.DEFAULT), }; /** * Завершение всех эффектов игрока. * * @param player игрок. */ public static void clearEffects(Player player) { EffectList list = player.getEffectList(); if(list == null || list.size() < 1) return; list.clear(); } /** * @param loc отработавший инстанс локации. */ public static final void putLocation(Location loc) { LOCATION_POOL.add(loc); } /** * @return новый инстанс локации. */ public static final Location takeLocation() { if(LOCATION_POOL.isEmpty()) return new Location(); LOCATION_POOL.writeLock(); try { Location loc = LOCATION_POOL.poll(); if(loc == null) loc = new Location(); return loc; } finally { LOCATION_POOL.writeUnlock(); } } } <file_sep>/java/game/tera/gameserver/templates/ResourseTemplate.java package tera.gameserver.templates; import rlib.util.VarTable; import tera.gameserver.IdFactory; import tera.gameserver.model.drop.ResourseDrop; import tera.gameserver.model.resourse.ResourseInstance; import tera.gameserver.model.resourse.ResourseType; /** * Модель темплейта ресурса. * * @author Ronn */ public final class ResourseTemplate { /** дроп с ресурса */ private ResourseDrop drop; /** тип ресурса */ private ResourseType type; /** ид ресурса */ private int id; /** уровень ресурса */ private int level; /** уровень навыка для сбора */ private int req; /** получаемый опыт */ private int exp; private int isExtractor; private int isDisabled; public ResourseTemplate(VarTable vars) { this.id = vars.getInteger("id"); this.level = vars.getInteger("level"); this.req = vars.getInteger("req"); this.exp = vars.getInteger("exp", 0); this.isExtractor = vars.getInteger("extractor"); this.isDisabled = 0; this.type = vars.getEnum("type", ResourseType.class); } /** * @return дроп с ресурсов. */ public final ResourseDrop getDrop() { return drop; } /** * @return кол-во опыта за ресурс. */ public int getExp() { return exp; } /** * @return ид темплейта. */ public final int getId() { return id; } /** * @return уровень ресурса. */ public final int getLevel() { return level; } /** * @return необходимый навык для сбора ресурса. */ public final int getReq() { return req; } public final int isDisabled() { return isDisabled; } public final int isExtractor() { return isExtractor; } /** * @return тип ресурса. */ public ResourseType getType() { return type; } /** * Получение нового экземпляра ресурсов. * * @return экземпляр ресурса. */ public ResourseInstance newInstance() { IdFactory idFactory = IdFactory.getInstance(); return newInstance(idFactory.getNextResourseId()); } /** * Получение нового экземпляра ресурсов с указанным ид. * * @param objectId уникальный ид. * @return экземпляр ресурса. */ public ResourseInstance newInstance(int objectId) { // создаем новый инстанс ResourseInstance resourse = type.newInstance(this); // запоминаем уникальный ид resourse.setObjectId(objectId); // возвращаем экземпляр return resourse; } /** * @param drop дроп с ресурсов. */ public final void setDrop(ResourseDrop drop) { this.drop = drop; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_View_My_Guild_War.java package tera.gameserver.network.clientpackets; import tera.gameserver.network.serverpackets.S_View_My_Guild_War; public class C_View_My_Guild_War extends ClientPacket { @Override protected void readImpl() { } @Override protected void runImpl() { getOwner().sendPacket(S_View_My_Guild_War.getInstance()); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/OwerturnedStrike.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.templates.SkillTemplate; /** * @author Ronn */ public class OwerturnedStrike extends Strike { /** * @param template темплейт скила. */ public OwerturnedStrike(SkillTemplate template) { super(template); } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { if(attacker.isOwerturned()) attacker.cancelOwerturn(); super.startSkill(attacker, targetX, targetY, targetZ); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Skill_Learn_List.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import rlib.util.array.Array; import rlib.util.table.IntKey; import rlib.util.table.Table; import tera.gameserver.model.SkillLearn; import tera.gameserver.model.npc.interaction.dialogs.SkillShopDialog; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, описывающий список изучаемых скилов. * * @author Ronn * @created 25.02.2012 */ public class S_Skill_Learn_List extends ServerPacket { private static final ServerPacket instance = new S_Skill_Learn_List(); public static S_Skill_Learn_List getInstance(Array<SkillLearn> skills, Player player) { S_Skill_Learn_List packet = (S_Skill_Learn_List) instance.newInstance(); ByteBuffer buffer = packet.getPrepare(); try { // получаем последний изучаемый скил SkillLearn last = skills.last(); packet.writeInt(buffer, 524422); // если изучаемых скилов нет, выходим if(player == null || skills.isEmpty() || last == null) return packet; int beginByte = 8; // получаем массив изучаемыхскилов SkillLearn[] array = skills.array(); // получаем таблицу изученных скилов Table<IntKey, Skill> currentSkills = player.getSkills(); // перебираем изучаемые скилы for(int i = 0, length = skills.size() - 1; i <= length; i++) { // получаем изучаемый скил SkillLearn skill = array[i]; // если его нет, пропускаем if(skill == null) continue; packet.writeShort(buffer, beginByte); if(skill == last) beginByte = 0; else beginByte += skill.getReplaceId() == 0? 26 : 35; packet.writeShort(buffer, beginByte);// если последний нуллим if(skill.getReplaceId() == 0) packet.writeInt(buffer, 0); else { packet.writeShort(buffer, 1); packet.writeShort(buffer, beginByte - 9); } packet.writeInt(buffer, 0); if(skill.getClassId() > 0) packet.writeInt(buffer, skill.getId()); else packet.writeInt(buffer, skill.getId());// ид скила packet.writeByte(buffer, skill.isPassive()? 0 : 1);// ативный 01, пассивный 00 packet.writeInt(buffer, skill.getPrice());// цена за изучение скила packet.writeInt(buffer, skill.getMinLevel());// минимальный лвл на изучение packet.writeByte(buffer, SkillShopDialog.isLearneableSkill(player, currentSkills, skill, false)? 1 : 0); //может изучать 1 или неможет 0 if(skill.getReplaceId() != 0) { packet.writeShort(buffer, beginByte - 9); packet.writeShort(buffer, 0); packet.writeInt(buffer, skill.getReplaceId());// ид заменяемого скила packet.writeByte(buffer, 1);// ативный 01, пассивный 00 заменяемый скилл } } return packet; } finally { buffer.flip(); } } /** промежуточный буффер */ private ByteBuffer prepare; public S_Skill_Learn_List() { // создаем промежуточный буфер this.prepare = ByteBuffer.allocate(8192).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SKILL_LEARN_LIST; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); // получаем промежуточный буффер ByteBuffer prepare = getPrepare(); // переносим данные buffer.put(prepare.array(), 0, prepare.limit()); } /** * @return подготовленный буфер. */ public ByteBuffer getPrepare() { return prepare; } } <file_sep>/java/game/tera/gameserver/model/skillengine/Effect.java package tera.gameserver.model.skillengine; import rlib.util.pools.Foldable; import tera.gameserver.model.Character; import tera.gameserver.model.EffectList; import tera.gameserver.model.skillengine.funcs.Func; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; /** * Интерфейс для реализации эффекта. * * @author Ronn * @created 13.04.2012 */ public interface Effect extends Foldable { /** * Завершение эффекта. */ public void exit(); /** * Складировать в пул. */ public void fold(); /** * @return шанс наложения эффекта. */ public int getChance(); /** * @return кол-во приминений эффекта. */ public int getCount(); /** * @return тот, на кого накладывают эффект. */ public Character getEffected(); /** * @return id эффекта. */ public int getEffectId(); /** * @return effectList эффект лист, в котором находится этот эффект. */ public EffectList getEffectList(); /** * @return тот, кто накладывает эффект. */ public Character getEffector(); /** * @return тип эффекта. */ public EffectType getEffectType(); /** * @return функции эффекта. */ public Func[] getFuncs(); /** * @return порядок в темплейте скила. */ public int getOrder(); /** * @return период эффекта. */ public int getPeriod(); /** * @return тип ресиста эффекта. */ public ResistType getResistType(); /** * @return класс ид скила эффекта. */ public int getSkillClassId(); /** * @return ид скила эффекта. */ public int getSkillId(); /** * @return скил эффекта. */ public SkillTemplate getSkillTemplate(); /** * @return стак тип эффекта. */ public String getStackType(); /** * @return время запуска эффекта. */ public long getStartTime(); /** * @return состояние эффекта. */ public EffectState getState(); /** * @return темплейт эффекта. */ public EffectTemplate getTemplate(); /** * @return сколько уже секунд висит. */ public int getTime(); /** * @return сколько времени осталось. */ public int getTimeEnd(); /** * @return время для пакета. */ public int getTimeForPacket(); /** * @return общее время эффекта. */ public int getTotalTime(); /** * @return сколько приминенний уже было. */ public int getUsingCount(); /** * @return имеет ли стак тип. */ public boolean hasStackType(); /** * @return является ли аурой. */ public boolean isAura(); /** * @return дебаф ли эффект. */ public boolean isDebuff(); /** * @return является ли эффектом. */ public boolean isEffect(); /** * @return завершается ли скил. */ public boolean isEnded(); /** * @return завершен ли эффект. */ public boolean isFinished(); /** * @return использован ли эффект. */ public boolean isInUse(); /** * @return снимается ли при атаке. */ public boolean isNoAttack(); /** * @return снимается ли при получении уроеа. */ public boolean isNoAttacked(); /** * @return снимается ли при опрокидывании. */ public boolean isNoOwerturn(); /** * Действие при завершении периода эффекта. * * @return нужно ли продолжать. */ public boolean onActionTime(); /** * Завершение эффекта. */ public void onExit(); /** * Подготовка к старту эффект. */ public void onStart(); /** * Обработка работы эффекта. */ public void scheduleEffect(); /** * @param count кол-во приминений. */ public void setCount(int count); /** * @param effected тот, на кого накладывают эффект. */ public void setEffected(Character effected); /** * @param effectList эффект лист, в котором находится этот эффект. */ public void setEffectList(EffectList effectList); /** * @param effector тот, кто накладывает эффект. */ public void setEffector(Character effector); /** * @param value запустить ли скил. */ public void setInUse(boolean value); /** * @param period перидо эффекта. */ public void setPeriod(int period); /** * @param startTime стартовое время эффекта. */ public void setStartTime(long startTime); /** * @param state состояние эффекта. */ public void setState(EffectState state); /** * @return динамический ли каунтер эффекта. */ public boolean isDynamicCount(); /** * @return динамическое ли время эффекта. */ public boolean isDynamicTime(); } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Party_Member_Buff_Update.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import rlib.util.array.Array; import tera.gameserver.config.MissingConfig; import tera.gameserver.model.Character; import tera.gameserver.model.EffectList; import tera.gameserver.model.skillengine.Effect; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с информацией о эффектах члена группы. * * @author Ronn */ public class S_Party_Member_Buff_Update extends ServerPacket { private static final ServerPacket instance = new S_Party_Member_Buff_Update(); public static S_Party_Member_Buff_Update getInstance(Character character) { S_Party_Member_Buff_Update packet = (S_Party_Member_Buff_Update) instance.newInstance(); // получаем эффект лист игрока EffectList effectList = character.getEffectList(); // если его нет, выходим if(effectList == null) return packet; ByteBuffer buffer = packet.getPrepare(); effectList.lock(); try { int bytes = 20; int lenght = (effectList.size() * 20 + bytes); packet.writeShort(buffer, effectList.size()); packet.writeShort(buffer, bytes); packet.writeShort(buffer, 0); packet.writeShort(buffer, lenght); packet.writeInt(buffer, MissingConfig.SERVER_ID); // SERVER ID packet.writeInt(buffer, character.getObjectId()); // получаем список эффектов Array<Effect> effects = effectList.getEffects(); // получаем массив эффектов Effect[] array = effects.array(); // перебираем эффекты for(int i = 0, length = effects.size(); i < length; i++) { // получаем эффект Effect effect = array[i]; // если его нет либо он завершился, пропускаем if(effect == null || effect.isEnded()) continue; packet.writeShort(buffer, bytes); bytes += 20; if(lenght < bytes) bytes = 0; packet.writeShort(buffer, bytes); packet.writeInt(buffer, effect.getEffectId()); packet.writeInt(buffer, effect.getTimeEnd() * 1000); packet.writeInt(buffer,0); packet.writeInt(buffer, effect.getCount()); } packet.writeShort(buffer, 0); } finally { effectList.unlock(); } buffer.flip(); return packet; } /** подготовленный буффер */ private final ByteBuffer prepare; public S_Party_Member_Buff_Update() { this.prepare = ByteBuffer.allocate(1024).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_PARTY_MEMBER_BUFF_UPDATE; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); // получаем промежуточный буффер ByteBuffer prepare = getPrepare(); // переносим данные buffer.put(prepare.array(), 0, prepare.limit()); } /** * @return подготовленный буфер. */ public ByteBuffer getPrepare() { return prepare; } } <file_sep>/java/game/tera/remotecontrol/handlers/StaticInfoHandler.java package tera.remotecontrol.handlers; import rlib.Monitoring; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Сборщик статичной инфы о сервере * * @author Ronn * @created 25.04.2012 */ public class StaticInfoHandler implements PacketHandler { @Override public Packet processing(Packet packet) { return new Packet(PacketType.REQUEST_STATIC_INFO, Monitoring.getSystemArch(), Monitoring.getSystemName(), Monitoring.getSystemVersion(), Monitoring.getJavaVersion(), Monitoring.getVMName(), Monitoring.getProcessorCount(), Monitoring.getStartDate()); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Despawn_Bonfire.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.worldobject.WorldObject; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с инфой об удалении объекта. * * @author Ronn */ public class S_Despawn_Bonfire extends ServerPacket { private static final ServerPacket instance = new S_Despawn_Bonfire(); public static S_Despawn_Bonfire getInstance(WorldObject object) { S_Despawn_Bonfire packet = (S_Despawn_Bonfire) instance.newInstance(); packet.objectId = object.getObjectId(); packet.subId = object.getSubId(); return packet; } /** обджект ид объекта */ private int objectId; /** саб ид объекта */ private int subId; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_DESPAWN_BONFIRE; } @Override protected void writeImpl() { writeOpcode(); writeInt(objectId);//4A 50 0C 00 обжект ид writeInt(subId);//00 80 0E 00 саб ид writeByte(1);//01 } } <file_sep>/java/game/tera/gameserver/model/PegasInfo.java package tera.gameserver.model; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.util.Location; /** * Модель информации для системы пигасов, необходимых для ее работы. * * @author Ronn */ public final class PegasInfo { /** координаты портала */ private final Location portal; /** координаты точки посадки */ private final Location landing; /** время полета от портала до посадки */ private final int toLanding; /** время полета от взлета до портала */ private final int toPortal; /** время локального перелета */ private final int local; public PegasInfo(Node node, int continentId) { this.landing = new Location(); this.portal = new Location(); VarTable vars = VarTable.newInstance(node); this.toLanding = vars.getInteger("landing"); this.toPortal = vars.getInteger("portal"); this.local = vars.getInteger("local"); for(Node nd = node.getFirstChild(); nd != null; nd = nd.getNextSibling()) if(nd.getNodeType() == Node.ELEMENT_NODE) { vars.parse(nd); float x = vars.getFloat("x"); float y = vars.getFloat("y"); float z = vars.getFloat("z"); if("portal".equals(nd.getNodeName())) { // обновляем координаты portal.setXYZ(x, y, z); // устанавливаем ид континент а portal.setContinentId(continentId); } else if("landing".equals(nd.getNodeName())) { // обновляем координаты landing.setXYZ(x, y, z); // устанавливаем ид континент а landing.setContinentId(continentId); } } } /** * @return точка посадки. */ public final Location getLanding() { return landing; } /** * @return время локального палета. */ public final int getLocal() { return local; } /** * @return точка портала. */ public final Location getPortal() { return portal; } /** * @return время полета из портала. */ public final int getToLanding() { return toLanding; } /** * @return время полета к порталу. */ public final int getToPortal() { return toPortal; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/NameChange.java package tera.gameserver.network.clientpackets; import tera.Config; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.network.model.UserClient; import tera.gameserver.network.serverpackets.PlayerNameResult; /** * Клиентский пакет, запрашивающий проверку на доступность нового имени * * @author Ronn */ public class NameChange extends ClientPacket { /** новое имя */ private String name; @Override public void finalyze() { name = null; } @Override public void readImpl() { readShort(); name = readString(); } @Override public void runImpl() { // получаем менеджер БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем клиент игрока UserClient owner = getOwner(); if(dbManager.getAccountSize(owner.getAccount().getName()) >= 8) owner.sendPacket(PlayerNameResult.getInstance(PlayerNameResult.FAILED), true); else if(!Config.checkName(name)) owner.sendPacket(PlayerNameResult.getInstance(PlayerNameResult.FAILED), true); else if(!dbManager.isFreeName(name)) owner.sendPacket(PlayerNameResult.getInstance(PlayerNameResult.FAILED), true); else owner.sendPacket(PlayerNameResult.getInstance(PlayerNameResult.SUCCESSFUL), true); } }<file_sep>/java/game/tera/gameserver/model/skillengine/classes/ChargeSingleShot.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.shots.FastShot; import tera.gameserver.network.serverpackets.StartFastShot; import tera.gameserver.templates.SkillTemplate; /** * Модель быстро стреляющего скила. * * @author Ronn */ public class ChargeSingleShot extends ChargeDam { /** * @param template темплейт скила. */ public ChargeSingleShot(SkillTemplate template) { super(template); } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { super.startSkill(attacker, targetX, targetY, targetZ); attacker.broadcastPacket(StartFastShot.getInstance(attacker, this, castId, targetX, targetY, targetZ)); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { setImpactX(character.getX()); setImpactY(character.getY()); setImpactZ(character.getZ()); FastShot.startShot(character, this, targetX, targetY, targetZ); } } <file_sep>/java/game/tera/gameserver/model/listeners/TerritoryListener.java package tera.gameserver.model.listeners; import tera.gameserver.model.TObject; import tera.gameserver.model.territory.Territory; /** * Прослушиватель входа/выхода объектов на территорию. * * @author Ronn */ public interface TerritoryListener { /** * Событие входа объекта на территорию. * * @param territory территория. * @param object вошедший объект. */ public void onEnter(Territory territory, TObject object); /** * Событие выхода из территории объекта. * * @param territory территория. * @param object вышедший объект с территории. */ public void onExit(Territory territory, TObject object); } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Delete_Quest.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.quests.QuestState; import tera.gameserver.network.ServerPacketType; /** * Пакет выполнения квеста. * * @author Ronn */ public class S_Delete_Quest extends ServerPacket { private static final ServerPacket instance = new S_Delete_Quest(); public static S_Delete_Quest getInstance(QuestState quest, boolean canceled) { S_Delete_Quest packet = (S_Delete_Quest) instance.newInstance(); packet.questId = quest.getQuestId(); packet.objectId = quest.getObjectId(); packet.canceled = canceled? 1 : 0; return packet; } /** ид квеста */ private int questId; /** ид состояния квеста */ private int objectId; /** отменен ли квест */ private int canceled; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_DELETE_QUEST; } @Override protected void writeImpl() { writeOpcode(); writeInt(questId);//16 05 00 00 writeInt(objectId);//FE DF 89 00 writeShort(canceled);//00 00 0 - выполнен, 1 - отменен writeFloat(1); writeFloat(1); writeInt(-1); writeByte(0); } } <file_sep>/java/game/tera/gameserver/model/skillengine/lambdas/FloatSub.java package tera.gameserver.model.skillengine.lambdas; /** * Отнимающий вещественный модификатор. * * @author Ronn * @created 28.02.2012 */ public final class FloatSub extends LambdaFloat { public FloatSub(float value) { super(value); } @Override public float calc(float val) { return val - value; } } <file_sep>/java/game/tera/gameserver/model/playable/PlayerDetails2.java package tera.gameserver.model.playable; import java.lang.reflect.Field; import rlib.logging.Loggers; import rlib.util.ReflectionUtils; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; /** * Модель опиÑ�аниÑ� внешноÑ�ти игрока. * * @author <NAME> */ public class PlayerDetails2 implements Foldable, Cloneable { private static final FoldablePool<PlayerDetails2> pool = Pools.newConcurrentFoldablePool(PlayerDetails2.class); public static final PlayerDetails2 getInstance(int objectId) { PlayerDetails2 detailsappearance = pool.take(); if(detailsappearance == null) detailsappearance = new PlayerDetails2(); detailsappearance.setObjectId(objectId); return detailsappearance; } /** уникальный ид игрока */ private int objectId; private int[] details2; public int[] getDetails2() { return details2; } public void setDetails2(int[] details2) { this.details2 = details2; } /** * @return objectId */ public final int getObjectId() { return objectId; } /** * @param objectId задаваемое objectId */ public final void setObjectId(int objectId) { this.objectId = objectId; } @Override public void finalyze(){} @Override public void reinit(){} public void fold() { pool.put(this); } public static String toXML(PlayerDetails2 detailsappearance, String id) { StringBuilder builder = new StringBuilder(); builder.append("<detailsappearance id=\"").append(id).append("\" >\n"); Array<Field> fields = ReflectionUtils.getAllFields(detailsappearance.getClass(), Object.class, true, "pool", "objectId"); try { for(Field field : fields) { String name = field.getName(); boolean old = field.isAccessible(); field.setAccessible(true); String value = String.valueOf(field.get(detailsappearance)); builder.append(" <set name=\"").append(name).append("\" value=\"") .append(value).append("\" />").append("\n"); field.setAccessible(old); } } catch(IllegalArgumentException | IllegalAccessException e) { Loggers.warning(detailsappearance.getClass(), e); } builder.append("</detailsappearance>"); return builder.toString(); } public static <T extends PlayerDetails2> T fromXML(T detailsappearance, VarTable vars) { Array<Field> fields = ReflectionUtils.getAllFields(detailsappearance.getClass(), Object.class, true, "pool", "objectId"); try { for(Field field : fields) { boolean old = field.isAccessible(); field.setAccessible(true); field.setInt(detailsappearance, vars.getInteger(field.getName(), field.getInt(detailsappearance))); field.setAccessible(old); } } catch(IllegalArgumentException | IllegalAccessException e) { Loggers.warning(detailsappearance.getClass(), e); } return detailsappearance; } /** * @return копирование внешноÑ�ти. */ public PlayerDetails2 copy() { try { return (PlayerDetails2) clone(); } catch(CloneNotSupportedException e) { return null; } } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_Unmount_Vehicle.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Пакет слезания с маунта. * * @author Ronn */ public class S_Unmount_Vehicle extends ServerPacket { private static final ServerPacket instance = new S_Unmount_Vehicle(); public static final S_Unmount_Vehicle getInstance(Player player, int skillId) { S_Unmount_Vehicle packet = (S_Unmount_Vehicle) instance.newInstance(); packet.objectId = player.getObjectId(); packet.subId = player.getSubId(); packet.skillId = skillId; return packet; } /** уникальный ид игрока */ private int objectId; /** саб ид игрока */ private int subId; /** ид скила, которым он сел */ private int skillId; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_UNMOUNT_VEHICLE; } @Override protected final void writeImpl() { writeOpcode(); writeInt(objectId);//91 0B 00 10 обжект ид наш writeInt(subId);//00 80 00 13 саб ид наш writeInt(skillId);//07 B2 01 00 ид скила } }<file_sep>/java/game/tera/gameserver/network/serverpackets/GuildLoadIcon.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с информацией о клане. * * @author Ronn */ public class GuildLoadIcon extends ServerPacket { private static final ServerPacket instance = new GuildLoadIcon(); public static GuildLoadIcon getInstance() { return (GuildLoadIcon) instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.GUILD_LOAD_ICON; } @Override protected void writeImpl() { writeOpcode(); } } <file_sep>/java/game/tera/gameserver/model/World.java package tera.gameserver.model; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import rlib.util.Strings; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.Config; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Chat; import tera.gameserver.network.serverpackets.S_Despawn_Npc; import tera.util.Location; /** * Модель мира Tera-Online. * * @author Ronn */ public abstract class World { /** Параметры карты */ public static final int MAP_MIN_X = -294912; // Координаты от фанаря, нужно мерять в игре!!! public static final int MAP_MAX_X = 229375; // Координаты от фанаря, нужно мерять в игре!!! public static final int MAP_MIN_Y = -229376; // Координаты от фанаря, нужно мерять в игре!!! public static final int MAP_MAX_Y = 294911; // Координаты от фанаря, нужно мерять в игре!!! public static final int MAP_MIN_Z = -32768; // Координаты от фанаря, нужно мерять в игре!!! public static final int MAP_MAX_Z = 32767; // Координаты от фанаря, нужно мерять в игре!!! public static final int WORLD_SIZE_X = (MAP_MAX_X - MAP_MIN_X + 1) / 32768; public static final int WORLD_SIZE_Y = (MAP_MAX_Y - MAP_MIN_Y + 1) / 32768; /** размер регионов */ public static final int REGION_WIDTH = Config.WORLD_WIDTH_REGION; public static final int REGION_HEIGHT = Config.WORLD_HEIGHT_REGION; /** рассчет смещения */ public static final int OFFSET_X = Math.abs(MAP_MIN_X / REGION_WIDTH); public static final int OFFSET_Y = Math.abs(MAP_MIN_Y / REGION_WIDTH); public static final int OFFSET_Z = Math.abs(MAP_MIN_Z / REGION_HEIGHT); /** Размерность массива регионов */ private static final int REGIONS_X = MAP_MAX_X / REGION_WIDTH + OFFSET_X; private static final int REGIONS_Y = MAP_MAX_Y / REGION_WIDTH + OFFSET_Y; private static final int REGIONS_Z = MAP_MAX_Z / REGION_HEIGHT + OFFSET_Z; /** массив регионов */ private static final WorldRegion[][][][] worldRegions = new WorldRegion[Config.WORLD_CONTINENT_COUNT][REGIONS_X + 1][REGIONS_Y + 1][REGIONS_Z + 1]; /** блокировщик */ private static final Lock lock = Locks.newLock(); /** список активных регионов */ private static final Array<WorldRegion> activeRegions = Arrays.toConcurrentArray(WorldRegion.class); /** список онлаин игроков по никам */ private static final Map<String, Player> playerNames = new HashMap<String, Player>(); /** просто список онлаин игроков */ private static final Array<Player> players = Arrays.toConcurrentArray(Player.class); /** таблица игроков */ private static final Table<IntKey, Player> playerTable = Tables.newIntegerTable(); /** счетчики */ private static volatile long droppedItems; private static volatile long spawnedNpcs; private static volatile long killedNpcs; private static volatile long killedPlayers; /** * @param region активировшийся регион. */ public static void addActiveRegion(WorldRegion region) { activeRegions.add(region); } /** * Добавление к счетчику. */ public static final void addDroppedItems() { droppedItems += 1; } /** * Добавление к счетчику. */ public static final void addKilledNpc() { killedNpcs += 1; } /** * Добавление к счетчику. */ public static final void addKilledPlayers() { killedPlayers += 1; } /** * Добавляем нового игрока в список онлаин. * * @param player вошедший игрок. */ public static void addNewPlayer(Player player) { players.writeLock(); try { // получаем массив текущих онлаин игроков Player[] array = players.array(); // перебираем их for(int i = 0, length = players.size(); i < length; i++) { // получаем игрока Player target = array[i]; // получаем его список друзей FriendList friendList = target.getFriendList(); // если пуст, пропускаем if(friendList.size() < 1) continue; // уведомляем о входе в игру этого игрока friendList.onEnterGame(player); } playerNames.put(player.getName(), player); players.add(player); playerTable.put(player.getObjectId(), player); } finally { players.writeUnlock(); } } /** * Добавление к счетчику. */ public static final void addSpawnedNpc() { spawnedNpcs += 1; } /** * Проверяет, сменился ли регион в котором находится обьект Если сменился - удаляет обьект из старого региона и добавляет в новый. * * @param object обьект для проверки. */ public static void addVisibleObject(TObject object) { if(object == null || !object.isVisible()) return; WorldRegion region = getRegion(object); WorldRegion currentRegion = object.getCurrentRegion(); // если регион не нашли if(region == null) { // ставим его в центр мира object.setXYZ(0, 0, 0); return; } // активируем ловушки региона region.activateTrap(object); if(currentRegion != null && currentRegion == region) return; region.addObject(object); object.setCurrentRegion(region); // Убираем из старых регионов обьект if(currentRegion == null) // Новый обьект (пример - игрок вошел в мир, заспаунился моб, дропнули вещь) { // Показываем обьект в текущем и соседних регионах // Если обьект игрок, показываем ему все обьекты в текущем и соседних регионах WorldRegion[] newNeighbors = region.getNeighbors(); for(int i = 0, length = newNeighbors.length; i < length; i++) newNeighbors[i].addToPlayers(object); } else // Обьект уже существует, перешел из одного региона в другой { // Показываем обьект, но в отличие от первого случая - только для новых соседей. // Убираем обьект из старых соседей. WorldRegion[] oldNeighbors = currentRegion.getNeighbors(); WorldRegion[] newNeighbors = region.getNeighbors(); for(int i = 0, length = oldNeighbors.length; i < length; i++) { WorldRegion neighbor = oldNeighbors[i]; if(!Arrays.contains(newNeighbors, neighbor)) neighbor.removeFromPlayers(object, S_Despawn_Npc.DISAPPEARS); } for(int i = 0, length = newNeighbors.length; i < length; i++) { WorldRegion neighbor = newNeighbors[i]; if(!Arrays.contains(oldNeighbors, neighbor)) neighbor.addToPlayers(object); } currentRegion.removeObject(object); } } /** * Очищает мир от всего. */ public static final void clear() { // удаляем старые регионы for(WorldRegion[][][] regionsss : worldRegions) for(WorldRegion[][] regionss : regionsss) for(WorldRegion[] regions : regionss) Arrays.clear(regions); // очищаем активные регионы activeRegions.clear(); // очищаем таблицу игроков playerNames.clear(); } /** * Проверка на нахождение онлаин игрока с указанным именем. * * @param name имя игрока. * @return есть ли онлаин игрок с таким ником. */ public static boolean containsPlayer(String name) { players.readLock(); try { return playerNames.containsKey(name); } finally { players.readUnlock(); } } /** * @return список активных регионов. */ public static Array<WorldRegion> getActiveRegions() { return activeRegions; } /** * Добавляем в указанный список объекты указанного класса расположенных вокруг указанного объекта. * * @param array список объектов. * @param type тип искомых объектов. * @param object объект, вокруг которого исщем. * @return список объектов. */ public static <T extends TObject, V extends T> Array<T> getAround(Array<T> array, Class<V> type, TObject object) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null || !currentRegion.isActive()) return array; WorldRegion[] regions = currentRegion.getNeighbors(); int objectId = object.getObjectId(); int subId = object.getSubId(); for(int i = 0, length = regions.length; i < length; i++) regions[i].addObject(array, type, objectId, subId); return array; } /** * Получаем список объектов указанного класса вокруг указанного объекта. * * @param type тип искомых объектов. * @param array список объекто. * @param object объект, вокруг которого ищем. * @return список объектов. */ public static <T extends TObject> Array<T> getAround(Class<T> type, Array<T> array, TObject object) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null) return array; WorldRegion[] regions = currentRegion.getNeighbors(); int objectId = object.getObjectId(); int subId = object.getSubId(); for(int i = 0, length = regions.length; i < length; i++) regions[i].addObject(array, type, objectId, subId); return array; } /** * Получаем список объектов указанного класса вокруг указанной точки. * * @param type тип искомых объектов. * @param continentId ид континента. * @param x координата. * @param y координата. * @param z координата. * @param objectId исключающийся объект. * @param subId саб ид объекта. * @param radius радиус поиска. * @param height высота описка. * @return список объектов. */ public static <T extends TObject> Array<T> getAround(Class<T> type, int continentId, float x, float y, float z, int objectId, int subId, float radius) { WorldRegion[] regions = getRegion(continentId, x, y, z).getNeighbors(); Array<T> array = Arrays.toArray(type); for(int i = 0, length = regions.length; i < length; i++) regions[i].addObjects(array, type, objectId, subId, x, y, z, radius); return array; } /** * Получаем список объектов указанного класса вокруг указанной точки. * * @param type тип искомых объектов. * @param loc точка, вокруг которой поиск. * @param objectId исключаемый объект. * @param subId саб ид объекта. * @param radius радиус поиска. * @param height высота поиска. * @return список объектов. */ public static <T extends TObject> Array<T> getAround(Class<T> type, Location loc, int objectId, int subId, float radius) { return getAround(type, loc.getContinentId(), loc.getX(), loc.getY(), loc.getZ(), objectId, subId, radius); } /** * Получаем список объектов указанного класса вокруг указанного объекта. * * @param type тип искомых объектов. * @param object объект, вокруг которого ищем. * @return список объектов. */ public static <T extends TObject> Array<T> getAround(Class<T> type, TObject object) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null) return Arrays.toArray(type, 0); WorldRegion[] regions = currentRegion.getNeighbors(); Array<T> array = Arrays.toArray(type); int objectId = object.getObjectId(); int subId = object.getSubId(); for(int i = 0, length = regions.length; i < length; i++) regions[i].addObject(array, type, objectId, subId); return array; } /** * Получаем список объектов указанного класса вокруг указанного объекта в указанном радиусе и высоте. * * @param type тип искомых объектов. * @param object объект, вокруг которого поиск. * @param radius радиус поиска. * @return список объектов. */ public static <T extends TObject> Array<T> getAround(Class<T> type, TObject object, float radius) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null) return Arrays.toArray(type, 0); WorldRegion[] regions = currentRegion.getNeighbors(); Array<T> array = Arrays.toArray(type); int objectId = object.getObjectId(); int subId = object.getSubId(); for(int i = 0, length = regions.length; i < length; i++) regions[i].addObjects(array, type, objectId, subId, object.getX(), object.getY(), object.getZ(), radius); return array; } /** * Получения кол-во искомых объектов. * * @param type тип искомых объектов. * @param object объект, вокруг которого поиск. * @param radius радиус поиска. * @return кол-во объектов. */ public static <T extends TObject> int getAroundCount(Class<T> type, TObject object, float radius) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null) return 0; WorldRegion[] regions = currentRegion.getNeighbors(); int objectId = object.getObjectId(); int subId = object.getSubId(); int counter = 0; for(int i = 0, length = regions.length; i < length; i++) counter += regions[i].getObjectCount( type, objectId, subId, object.getX(), object.getY(), object.getZ(), radius); return counter; } /** * Получаем список объектов указанного класса вокруг указанной точки. * * @param type тип искомых объектов. * @param array список персонажей. * @param continentId ид континента. * @param x координата. * @param y координата. * @param z координата. * @param objectId исключающийся объект. * @param subId саб ид исключаемого. * @param radius радиус поиска. * @param height высота описка. * @return список объектов. */ public static <T extends TObject, V extends T> Array<T> getAround(Class<V> type, Array<T> array, int continentId, float x, float y, float z, int objectId, int subId, float radius) { WorldRegion curreentRegion = getRegion(continentId, x, y, z); if(curreentRegion == null) return array; WorldRegion[] regions = curreentRegion.getNeighbors(); for(int i = 0, length = regions.length; i < length; i++) regions[i].addObjects(array, type, objectId, subId, x, y, z, radius); return array; } /** * Получаем список объектов указанного класса вокруг указанного объекта в указанном радиусе и высоте. * * @param type тип искомых объектов. * @param array список объектов. * @param object объект, вокруг которого поиск. * @param radius радиус поиска. * @param height высота описка. * @return список объектов. */ public static <T extends TObject, V extends T> Array<T> getAround(Class<V> type, Array<T> array, TObject object, float radius) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null) return array; WorldRegion[] regions = currentRegion.getNeighbors(); int objectId = object.getObjectId(); int subId = object.getSubId(); for(int i = 0, length = regions.length; i < length; i++) regions[i].addObjects(array, type, objectId, subId, object.getX(), object.getY(), object.getZ(), radius); return array; } /** * Получение списка потенциальных препядствий для движения во время каста скила. * * @param array список препядствий. * @param caster кастующий скил персонаж. * @param distance дистанция, на которую персонаж сместится. */ public static void getAroundBarriers(Array<Character> array, Character caster, float distance) { WorldRegion currentRegion = caster.getCurrentRegion(); if(currentRegion == null) return; WorldRegion[] regions = currentRegion.getNeighbors(); float x = caster.getX(); float y = caster.getY(); float z = caster.getZ(); for(int i = 0, length = regions.length; i < length; i++) regions[i].addBarriers(array, caster, x, y, z, distance); } /** * Возврашает объект с указанным ид в регионе где находится object. * * @param type тип искомых объектов. * @param object объект, вокруг которого ищем. * @param targetId ид искомого объекта. * @param targetSubId саб ид искомого объекта. * @return список объектов. */ public static <T extends TObject> T getAroundById(Class<T> type, TObject object, int targetId, int targetSubId) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null || !currentRegion.isActive()) return null; WorldRegion[] regions = currentRegion.getNeighbors(); for(int i = 0, length = regions.length; i < length; i++) { TObject target = regions[i].getObject(targetId, targetSubId); if(target != null && type.isInstance(target)) return type.cast(target); } return null; } /** * Возврашает объект с указанным именем в регионе где находится object. * * @param type тип искомого объекта. * @param object объект, вокруг которого идет поиск. * @param name имя искомого объекта. * @return искомый объект. */ public static <T extends TObject> T getAroundByName(Class<T> type, TObject object, String name) { WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion == null || !currentRegion.isActive()) return null; WorldRegion[] regions = currentRegion.getNeighbors(); for(WorldRegion region : regions) { TObject target = region.getObject(name); if(target != null && type.isInstance(target)) return type.cast(target); } return null; } /** * @return кол-во дропнутых вещей. */ public static final long getDroppedItems() { return droppedItems; } /** * @return кол-во убитых нпс. */ public static final long getKilledNpcs() { return killedNpcs; } /** * @return кол-во убитых игроков. */ public static final long getKilledPlayers() { return killedPlayers; } /** * Список регионов вокруг координат объекта. * * @param continentId ид континента. * @param x координата х. * @param y координата у. * @param minZ минимальная высота. * @param maxZ максимальная высота. * @return список регионов. */ public static Array<WorldRegion> getNeighbors(int continentId, float x, float y, float minZ, float maxZ) { Array<WorldRegion> array = Arrays.toArray(WorldRegion.class, 27); int newX = (int) (x / REGION_WIDTH + OFFSET_X); int newY = (int) (y / REGION_WIDTH + OFFSET_Y); int newMinZ = (int) (minZ / REGION_HEIGHT + OFFSET_Z); int newMaxZ = (int) (maxZ / REGION_HEIGHT + OFFSET_Z); for(int a = -1; a <= 1; a++) for(int b = -1; b <= 1; b++) for(int c = newMinZ; c <= newMaxZ; c++) if(validRegion(newX + a, newY + b, c)) { if(worldRegions[continentId][newX + a][newY + b][c] == null) { lock.lock(); try { if(worldRegions[continentId][newX + a][newY + b][c] == null) worldRegions[continentId][newX + a][newY + b][c] = new WorldRegion(continentId, newX + a, newY + b, c); } finally { lock.unlock(); } } array.add(worldRegions[continentId][newX + a][newY + b][c]); } return array; } /** * Список регионов вокруг координат объекта. * * @param continentId ид континента. * @param x координата х. * @param y координата у. * @param z координата. * @return список регионов. */ public static WorldRegion[] getNeighbors(int continentId, int x, int y, int z) { Array<WorldRegion> array = Arrays.toArray(WorldRegion.class, 27); for(int a = -1; a <= 1; a++) for(int b = -1; b <= 1; b++) for(int c = -1; c <= 1; c++) if(validRegion(x + a, y + b, z + c)) { if(worldRegions[continentId][x + a][y + b][z + c] == null) { lock.lock(); try { if(worldRegions[continentId][x + a][y + b][z + c] == null) worldRegions[continentId][x + a][y + b][z + c] = new WorldRegion(continentId, x + a, y + b, z + c); } finally { lock.unlock(); } } array.add(worldRegions[continentId][x + a][y + b][z + c]); } array.trimToSize(); return array.array(); } /** * Получение онлаин игрока по уникальному ид. * * @param objectId уникальный ид игрока. * @return игрок. */ public static Player getPlayer(int objectId) { players.readLock(); try { return playerTable.get(objectId); } finally { players.readUnlock(); } } /** * Получение онлаин игрока по имени. * * @param name имя игрока. * @return онлаин игрок. */ public static Player getPlayer(String name) { players.readLock(); try { return playerNames.get(name); } finally { players.readUnlock(); } } /** * @return список игроков онлайн. */ public static final Array<Player> getPlayers() { return players; } /** * @param continentId ид континента. * @param x координата. * @param y координата. * @param z координата. * @return регион, в котором находятся указанные координаты. */ public static WorldRegion getRegion(int continentId, float x, float y, float z) { if(continentId > 2) return null; int newX = (int) x / REGION_WIDTH + OFFSET_X; int newY = (int) y / REGION_WIDTH + OFFSET_Y; int newZ = (int) z / REGION_HEIGHT + OFFSET_Z; // еси коррдинаты корректные if(validRegion(newX, newY, newZ)) { // получаем регион WorldRegion region = worldRegions[continentId][newX][newY][newZ]; // если его нет if(region == null) { lock.lock(); try { // получаем еще раз region = worldRegions[continentId][newX][newY][newZ]; // если его всеравно нет if(region == null) { // создаем новый region = new WorldRegion(continentId, newX, newY, newZ); // вносим worldRegions[continentId][newX][newY][newZ] = region; } } finally { lock.unlock(); } } // возвращаем регион return region; } return null; } /** * @param continentId ид континента. * @param x координата. * @param y координата. * @param z координата. * @return регион, в котором находятся координаты. */ public static WorldRegion getRegion(int continentId, int x, int y, int z) { int newX = x / REGION_WIDTH + OFFSET_X; int newY = y / REGION_WIDTH + OFFSET_Y; int newZ = z / REGION_HEIGHT + OFFSET_Z; // еси коррдинаты корректные if(validRegion(newX, newY, newZ)) { // получаем регион WorldRegion region = worldRegions[continentId][newX][newY][newZ]; // если его нет if(region == null) { lock.lock(); try { // получаем еще раз region = worldRegions[continentId][newX][newY][newZ]; // если его всеравно нет if(region == null) { // создаем новый region = new WorldRegion(continentId, newX, newY, newZ); // вносим worldRegions[continentId][newX][newY][newZ] = region; } } finally { lock.unlock(); } } // возвращаем регион return region; } return null; } /** * @return регион, в котором находится указанная точка. */ public static WorldRegion getRegion(Location location) { return getRegion(location.getContinentId(), location.getX(), location.getY(), location.getZ()); } /** * @param object объект. * @return регион, в котором находится указанный объект. */ public static WorldRegion getRegion(TObject object) { return getRegion(object.getContinentId(), object.getX(), object.getY(), object.getZ()); } /** * @return массив регионов. */ public static WorldRegion[][][][] getRegions() { return worldRegions; } /** * Подсчет регионов с указанной активность. * * @param active активность региона. * @return кол-во регионов. */ public static long getRegionsCount(boolean active) { long counter = 0; for(WorldRegion[][][] first : worldRegions) { if(first == null) continue; for(WorldRegion[][] second : first) { if(second == null) continue; for(WorldRegion[] thrid : second) { if(thrid == null) continue; for(WorldRegion four : thrid) { if(four == null) continue; if(four.isActive() != active) continue; counter++; } } } } return counter; } /** * @return кол-во отспавненых нпс. */ public static final long getSpawnedNpcs() { return spawnedNpcs; } /** * @return текущий онлаин. */ public static int online() { return playerNames.size(); } /** * Возвращает регион по указанным индексам. * * @param continentId ид континента. * @param i индекс региона. * @param j индекс региона. * @param k индекс региона. * @return соответствующий регион. */ public static WorldRegion region(int continentId, int i, int j, int k) { WorldRegion region = worldRegions[continentId][i][j][k]; if(region == null) { lock.lock(); try { region = worldRegions[continentId][i][j][k]; if(region == null) { region = new WorldRegion(continentId, i, j, k); worldRegions[continentId][i][j][k] = region; } } finally { lock.unlock(); } } return region; } /** * @param region удаляемый из активных регион. */ public static void removeActiveRegion(WorldRegion region) { activeRegions.fastRemove(region); } /** * Удаляет из онлайна старого игрока. * * @param player удаляемый игрок. */ public static void removeOldPlayer(Player player) { players.writeLock(); try { playerNames.remove(player.getName()); players.fastRemove(player); playerTable.remove(player.getObjectId()); // получаем массив текущих онлаин игроков Player[] array = players.array(); // перебираем их for(int i = 0, length = players.size(); i < length; i++) { // получаем игрока Player target = array[i]; // получаем его список друзей FriendList friendList = target.getFriendList(); // если пуст, пропускаем if(friendList.size() < 1) continue; // уведомляем о выходе в игру этого игрока friendList.onExitGame(player); } } finally { players.writeUnlock(); } } /** * Удаляет обьект из текущего региона. * * @param object удаляемый объект. */ public static void removeVisibleObject(TObject object, int type) { if(object == null || object.isVisible()) return; WorldRegion currentRegion = object.getCurrentRegion(); if(currentRegion != null) { currentRegion.removeObject(object); // TODO for(WorldRegion neighbor : currentRegion.getNeighbors()) neighbor.removeFromPlayers(object, type); object.setCurrentRegion(null); } } /** * @param text текст аннонса. */ public static void sendAnnounce(String text) { S_Chat packet = S_Chat.getInstance(Strings.EMPTY, text, SayType.NOTICE_CHAT, 0, 0); players.readLock(); try { Player[] array = players.array(); for(int i = 0, length = players.size(); i < length; i++) packet.increaseSends(); for(int i = 0, length = players.size(); i < length; i++) array[i].sendPacket(packet, false); } finally { players.readUnlock(); } } /** * Проверка на корректность индексов региона. * * @param x индекс региона. * @param y индекс региона. * @param z индекс региона. * @return корректные ли индексы региона. */ public static boolean validRegion(int x, int y, int z) { return x >= 0 && x < REGIONS_X && y >= 0 && y < REGIONS_Y && z >= 0 && z < REGIONS_Z; } }<file_sep>/java/game/tera/gameserver/model/regenerations/PlayerRegenHp.java package tera.gameserver.model.regenerations; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.playable.Player; /** * Модель регенерации хп у игрока. * * @author Ronn * @created 11.04.2012 */ public class PlayerRegenHp extends AbstractRegen<Player> { public PlayerRegenHp(Player actor) { super(actor); } @Override public boolean checkCondition() { // получаем игрока Player actor = getActor(); // можно только не в боевой стойки и если не фул хп return !actor.isBattleStanced() && actor.getCurrentHp() < actor.getMaxHp(); } @Override public void doRegen() { // получаем игрока Player actor = getActor(); // применяем реген actor.setCurrentHp(actor.getCurrentHp() + actor.getRegenHp()); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // обновляем отображение хп eventManager.notifyHpChanged(actor); } } <file_sep>/java/game/tera/gameserver/tables/ItemTable.java package tera.gameserver.tables; import java.io.File; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Files; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.Config; import tera.gameserver.document.DocumentItem; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.templates.ItemTemplate; /** * Таблица шаблонов итемов. * * @author Ronn */ public final class ItemTable { private static final Logger log = Loggers.getLogger(ItemTable.class); private static ItemTable instance; /** * Создает массив итемов с указанным кол-вом и указаным итем ид. * * @param templateId ид шаблона итема. * @param count кол-во итемов. * @return итоговый массив итемов. */ public static final ItemInstance[] createItem(int templateId, int count) { // проверяем отношение итема к донату if(Arrays.contains(Config.WORLD_DONATE_ITEMS, templateId)) { log.warning(new Exception("not create donate item for id " + templateId)); return null; } if(count < 1) return new ItemInstance[0]; // получаем таблицу итемов ItemTable table = getInstance(); // получаем шаблон ItemTemplate template = table.getItem(templateId); // если шаблона нет if(template == null) // возавращаем пустой массив return new ItemInstance[0]; // создаем массив итемов ItemInstance[] items = new ItemInstance[template.isStackable()? 1 : count]; // заполняем экземплярами for(int i = 0; i < items.length; i++) { items[i] = template.newInstance(); if(items[i] == null) return new ItemInstance[0]; if(template.isStackable()) items[i].setItemCount(count); } // возвращаем массив итемов return items; } /** * Создает итем с указанным кол-вом и указаным итем ид. * * @param templateId ид шаблона итема. * @param count кол-во итемов. * @return итоговый массив итемов. */ public static final ItemInstance createItem(int templateId, long count) { // проверяем отношение итема к донату if(Arrays.contains(Config.WORLD_DONATE_ITEMS, templateId)) { log.warning(new Exception("not create donate item for id " + templateId)); return null; } if(count < 1) return null; // получаем таблицу итемов ItemTable table = getInstance(); // получаем шаблон ItemTemplate template = table.getItem(templateId); // если шаблона нет, выходим if(template == null) return null; // создаем новый экземпляр итема ItemInstance item = template.newInstance(); // если не получилось if(item == null) return null; // устанавливаем по возможностит нужное кол-во item.setItemCount(item.isStackable()? count : 1); // возвращаем return item; } public static ItemTable getInstance() { if(instance == null) instance = new ItemTable(); return instance; } /** * Извлекает ид шаблона из итема. * * @param item итем. * @return итем ид итема. */ public static final int templateId(ItemInstance item) { if(item == null) return 0; return item.getItemId(); } /** таблица всех темплейтв */ private Table<IntKey, ItemTemplate> items; private ItemTable() { // созадем таблицу скилов items = Tables.newIntegerTable(); // получаем файлы с итемами File[] files = Files.getFiles(new File(Config.SERVER_DIR + "/data/items")); // перебираем файлы for(File file : files) { if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file.getAbsolutePath()); continue; } if(file.getName().startsWith("example")) continue; // перебираем отпарсенные шаблоны файла for(ItemTemplate item : new DocumentItem(file).parse()) { // если стоимость продажи выше стоимости покупки if(item.getSellPrice() != 0 && item.getSellPrice() > item.getBuyPrice()) { // уведомляем log.warning("found incorrect price for item " + item + " in file " + file); // зануляем стоимость продажи item.setSellPrice(0); } if(items.containsKey(item.getItemId())) log.warning("found duplicate item " + item); // вносим в таблицу items.put(item.getItemId(), item); } } log.info("loaded " + items.size() + " items."); } /** * Получение шаблона темплейта. * * @param type тип шаблона. * @param id ид шаблона итема. * @return соответствующий шаблон. */ public final <T extends ItemTemplate> T getItem(Class<T> type, int id) { ItemTemplate item = items.get(id); if(item == null || !type.isInstance(item)) return null; return type.cast(item); } /** * Получение шаблона темплейта. * * @param id ид шаблона итема. * @return соотвествующий шаблон. */ public final ItemTemplate getItem(int id) { return items.get(id); } /** * Обновляет текуще итемы и добавляет новые. */ public synchronized void reload() { // создаем новую таблицу шаблонов Table<IntKey, ItemTemplate> newTemplates = Tables.newIntegerTable(); // получаем файлы для парса File[] files = Files.getFiles(new File(Config.SERVER_DIR + "/data/items")); // перебираем файлы for(File file : files) { if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file.getAbsolutePath()); continue; } if(file.getName().startsWith("example")) continue; // парсим файл for(ItemTemplate template : new DocumentItem(file).parse()) // вносим в таблицу новые шаблоны newTemplates.put(template.getItemId(), template); } // перебираем новые шаблоны for(ItemTemplate template : newTemplates) { // поопускаем пустые if(template == null) continue; // получаем старый шаблон ItemTemplate old = items.get(template.getItemId()); // если его нет if(old == null) { // вносим новый items.put(template.getItemId(), template); continue; } // обновляем старый old.reload(template); } log.info("reloaded items."); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Cancel_Return_To_Lobby.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Cancel_Return_To_Lobby extends ServerPacket { private static final ServerPacket instance = new S_Cancel_Return_To_Lobby(); public static S_Cancel_Return_To_Lobby getInstance() { return (S_Cancel_Return_To_Lobby) instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_CANCEL_RETURN_TO_LOBBY; } @Override protected void writeImpl() { writeOpcode(); writeByte(0x00); // 00 - Successful. } }<file_sep>/java/game/tera/gameserver/model/skillengine/classes/SummonAttack.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.model.npc.summons.Summon; import tera.gameserver.templates.SkillTemplate; /** * @author Ronn */ public class SummonAttack extends AbstractSkill { public SummonAttack(SkillTemplate template) { super(template); } @Override public boolean checkCondition(Character attacker, float targetX, float targetY, float targetZ) { if(attacker.getSummon() == null) { attacker.sendMessage("У вас нет вызванных питомцев."); return false; } return super.checkCondition(attacker, targetX, targetY, targetZ); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { super.useSkill(character, targetX, targetY, targetZ); Character target = character.getTarget(); Summon summon = character.getSummon(); if(target == null || summon == null) return; summon.getAI().startAttack(target); character.setTarget(null); } } <file_sep>/java/game/tera/gameserver/model/ai/npc/thinkaction/SummonReturnAction.java package tera.gameserver.model.ai.npc.thinkaction; import org.w3c.dom.Node; import tera.gameserver.model.Character; import tera.gameserver.model.NpcAIState; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.util.LocalObjects; /** * Реализация генерации действий суммона в режиме возвращения домой. * * @author Ronn */ public class SummonReturnAction extends DefaultReturnAction { public SummonReturnAction(Node node) { super(node); } @Override public <A extends Npc> void think(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime) { // если нпс мертв if(actor.isDead()) { // очищаем задания ai.clearTaskList(); // очищаем агр лист actor.clearAggroList(); // переводим в режим ожидания ai.setNewState(NpcAIState.WAIT); // выходим return; } // если нпс щас что-то делает, выходим if(actor.isTurner() || actor.isCastingNow() || actor.isMoving() || actor.isStuned() || actor.isOwerturned()) return; // очищаем агро лист actor.clearAggroList(); // очищаем задания ai.clearTaskList(); // получаем владельца суммона Character owner = actor.getOwner(); // если НПС уже на точке респа if(owner == null || actor.isInRange(owner, getDistanceToSpawnLoc())) { // переключаемся в режим ожидания ai.setNewState(NpcAIState.WAIT); // выходим return; } // если нужно телепортнуть if(owner.getContinentId() != actor.getContinentId() || !owner.isInRange(actor, getDistanceToTeleport()) || actor.getRunSpeed() < 10) { actor.teleToLocation(owner.getContinentId(), owner.getX(), owner.getY(), owner.getZ(), 0); return; } // есть ли на очереди задания if(ai.isWaitingTask()) { // выполняем задание ai.doTask(actor, currentTime, local); // выходим return; } // добавляем новые задания ai.getCurrentFactory().addNewTask(ai, actor, local, config, currentTime); // если есть ожидающиеся задания if(ai.isWaitingTask()) // выполняем ai.doTask(actor, currentTime, local); } } <file_sep>/java/game/tera/gameserver/model/actions/classes/PlayerAction.java package tera.gameserver.model.actions.classes; import tera.gameserver.model.playable.Player; /** * Базовый акшен между 2мя игроками. * * @author Ronn */ public abstract class PlayerAction extends AbstractAction<Player> { @Override protected final synchronized void clear() { // получаем цель акщена Player target = getTarget(); // если она есть if(target != null) // зануляем ей акшен target.setLastAction(null); super.clear(); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Party_Member_Stat_Update.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.config.MissingConfig; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Пакет с информацией о члене группы. * * @author Ronn * @created 26.04.2012 */ public class S_Party_Member_Stat_Update extends ServerPacket { private static final ServerPacket instance = new S_Party_Member_Stat_Update(); public static S_Party_Member_Stat_Update getInstance(Player member) { member.stopBattleStance(); S_Party_Member_Stat_Update packet = (S_Party_Member_Stat_Update) instance.newInstance(); packet.objectId = member.getObjectId(); packet.currentHp = member.getCurrentHp(); packet.currentMp = member.getCurrentMp(); packet.maxHp = member.getMaxHp(); packet.maxMp = member.getMaxMp(); packet.level = member.getLevel(); packet.stamina = member.getStamina(); packet.dead = member.isDead() ? 0 : 1; packet.inBattle = member.isBattleStanced() ? 0 : 1; packet.vitality = packet.stamina/30; return packet; } /** уникальный ид игрока */ private int objectId; /** текущее состояние хп */ private int currentHp; /** текущее состояние мп */ private int currentMp; /** максимальное кол-во хп */ private int maxHp; /** максимальное кол-во мп */ private int maxMp; /** текущий уровень */ private int level; /** стамина */ private int stamina; /** мертв ли */ private int dead; private int inBattle; private int vitality; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_PARTY_MEMBER_STAT_UPDATE; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, MissingConfig.SERVER_ID); // SERVER ID writeInt(buffer, objectId);//DE 2C 0B 00 //айди используемого в пати writeInt(buffer, currentHp);//2D 08 00 00 //хп сколько было writeInt(buffer, currentMp);//3C 05 00 00 /мп сколько было writeInt(buffer, maxHp);//2D 08 00 00 //хп сколько всего writeInt(buffer, maxMp);//3C 05 00 00 /мп сколько всего writeShort(buffer, level);//02 00 //уровень writeShort(buffer, inBattle);//02 00 //уровень writeShort(buffer, vitality);//04 00 лвл стамины writeByte(buffer, dead);//01 writeInt(buffer, stamina);//78 00 00 00 writeInt(buffer, 0);//current RE writeInt(buffer, 0);//Max RE writeInt(buffer, 0); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/ChargeManaHeal.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель заряжающегося восстановителя МП. * * @author Ronn */ public class ChargeManaHeal extends ChargeDam { public ChargeManaHeal(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { // хилим МП target.effectHealMp(getPower(), attacker); // получаем локальные объекты LocalObjects local = LocalObjects.get(); return local.getNextAttackInfo(); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/ServerConstPacket.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import rlib.util.Util; /** * Модель константного серверного пакета. * * @author Ronn */ public abstract class ServerConstPacket extends ServerPacket { @Override public final boolean isSynchronized() { return false; } @Override public final void write(ByteBuffer buffer) { try { writeImpl(buffer); } catch(Exception e) { log.warning(this, e); log.warning(this, "Buffer " + buffer + "\n" + Util.hexdump(buffer.array(), buffer.position())); } } @Override protected final void writeImpl() { super.writeImpl(); } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionQuestCancel.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.manager.QuestManager; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; /** * Акшен для запуска квеста. * * @author Ronn */ public class ActionQuestCancel extends AbstractQuestAction { /** ид запускаемого квеста */ private int id; public ActionQuestCancel(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); VarTable vars = VarTable.newInstance(node); this.id = vars.getInteger("id", 0); } @Override public void apply(QuestEvent event) { // если ид небыл указан, запускаем квест акшена if(id == 0) quest.cancel(event, false); else { // олучаем менеджер квестов QuestManager questManager = QuestManager.getInstance(); // получаем нужный квест Quest quest = questManager.getQuest(id); // если квеста нет, выходим if(quest == null) { log.warning(this, "not found quest"); return; } // запускаем квест quest.cancel(event, false); } } @Override public String toString() { return "ActionQuestStart id = " + id; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestGuildLoadIcon.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.npc.interaction.dialogs.Dialog; import tera.gameserver.model.npc.interaction.dialogs.DialogType; import tera.gameserver.model.npc.interaction.dialogs.LoadGuildIcon; import tera.gameserver.model.playable.Player; /** * Загрузка иконки гильдии. * * @author Ronn */ public class RequestGuildLoadIcon extends ClientPacket { /** игрок */ private Player player; /** загрузка картинки на сервер */ private byte[] icon; @Override public void finalyze() { player = null; } @Override protected void readImpl() { player = owner.getOwner(); readShort(); int size = readShort(); if(size > buffer.remaining()) { log.warning(this, "incorrect load guild icon, size " + size + ", remaining " + buffer.remaining()); return; } icon = new byte[size]; buffer.get(icon); } @Override protected void runImpl() { if(player == null) return; if(icon == null || icon.length < 5) { player.sendMessage("Загрузка произошла неудачно."); return; } Dialog dialog = player.getLastDialog(); if(dialog == null || dialog.getType() != DialogType.GUILD_LOAD_ICON) return; LoadGuildIcon load = (LoadGuildIcon) dialog; load.setIcon(icon); load.apply(); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Reign_Info.java package tera.gameserver.network.clientpackets; import tera.gameserver.network.serverpackets.S_Reign_Info; public class C_Reign_Info extends ClientPacket { private int unk; @Override protected void readImpl() { unk = readInt(); } @Override protected void runImpl() { getOwner().sendPacket(S_Reign_Info.getInstance(unk, (short)0, (short)0)); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Daily_Quest_Complete_Count.java package tera.gameserver.network.serverpackets; import tera.gameserver.config.MissingConfig; import tera.gameserver.network.ServerPacketType; public class S_Daily_Quest_Complete_Count extends ServerPacket { private static final ServerPacket instance = new S_Daily_Quest_Complete_Count(); public static S_Daily_Quest_Complete_Count getInstance() { return (S_Daily_Quest_Complete_Count) instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_DAILY_QUEST_COMPLETE_COUNT; } @Override protected final void writeImpl() { writeOpcode(); writeShort(0);//total did writeShort(MissingConfig.DAILY_QUEST_MAX_COUNT);//total writeByte(0); } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/replyes/ReplyShop.java package tera.gameserver.model.npc.interaction.replyes; import org.w3c.dom.Node; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.gameserver.model.inventory.Bank; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.TaxationNpc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.npc.interaction.dialogs.Dialog; import tera.gameserver.model.npc.interaction.dialogs.ShopDialog; import tera.gameserver.model.playable.Player; import tera.gameserver.tables.ItemTable; import tera.gameserver.templates.ItemTemplate; /** * Модель ссылки на обычный магазин. * * @author Ronn */ public final class ReplyShop extends AbstractReply { /** массив секций с итемами */ private ItemTemplate[][] sections; /** все итемы доступные на продажу */ private Table<IntKey, ItemTemplate> availableItems; /** ид первой секции */ private int sectionId; public ReplyShop(Node node) { super(node); VarTable vars = VarTable.newInstance(node); // получаем ид секции sectionId = vars.getInteger("sectionId"); // подготавливаем таблицу секций Array<Array<ItemTemplate>> sectionList = Arrays.toArray(Array.class); // получаем таблицу скилов ItemTable itemTable = ItemTable.getInstance(); // перебираем внутренние элементы for(Node section = node.getFirstChild(); section != null; section = section.getNextSibling()) { if(section.getNodeType() != Node.ELEMENT_NODE) continue; // если это секция if("section".equals(section.getNodeName())) { Array<ItemTemplate> items = Arrays.toArray(ItemTemplate.class); // перебираем итемы входящие в секцию for(Node item = section.getFirstChild(); item != null; item = item.getNextSibling()) { if(item.getNodeType() != Node.ELEMENT_NODE) continue; // если это описание итема if("item".equals(item.getNodeName())) { // парсим атрибуты vars.parse(item); // получаем ид итема int id = vars.getInteger("id"); // получаем темплейт итема ItemTemplate template = itemTable.getItem(id); // если его нет, пропускаем if(template == null) { log.warning("not itemId " + id + " in item table."); continue; } // добавляем в список items.add(template); } } // одбавляем новую секцию sectionList.add(items); } } // создаем таблицу секций sections = new ItemTemplate[sectionList.size()][]; // получаем список секций Array<ItemTemplate>[] array = sectionList.array(); // заполняем таблицу секций for(int i = 0, length = sectionList.size(); i < length; i++) sections[i] = array[i].trimToSize().array(); // счетчик всех итемов int counter = 0; // подсчитываем общее кол-во итемов for(ItemTemplate[] items : sections) counter += items.length; // если нет не одного, прерываемся if(counter < 1) throw new IllegalArgumentException("no items"); // создаем таблицу доступных итемов availableItems = Tables.newIntegerTable(); // заполняем таблицу for(ItemTemplate[] items : sections) for(ItemTemplate item : items) availableItems.put(item.getItemId(), item); } @Override public void reply(Npc npc, Player player, Link link) { // ссылка на банк для отчилсений Bank bank = null; // итоговый налог float resultTax = 1; // если НПС имеет налог if(npc instanceof TaxationNpc) { TaxationNpc taxation = (TaxationNpc) npc; // получаем банк для отчисления bank = taxation.getTaxBank(); // рассчитываем итоговый налог resultTax = 1 + (taxation.getTax() / 100F); } // создаем диалог магазина Dialog dialog = ShopDialog.newInstance(npc, sections, availableItems, player, bank, sectionId, resultTax); // если неудачно инициализировался, закрываем if(!dialog.init()) dialog.close(); } } <file_sep>/java/game/tera/gameserver/tables/MinionTable.java package tera.gameserver.tables; import java.io.File; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Files; import rlib.util.array.Array; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.Config; import tera.gameserver.document.DocumentMinion; import tera.gameserver.model.MinionData; import tera.gameserver.templates.NpcTemplate; /** * Таблица данных о минионах. * * @author Ronn * @created 14.03.2012 */ public final class MinionTable { private static final Logger log = Loggers.getLogger(MinionTable.class); private static MinionTable instance; public static MinionTable getInstance() { if(instance == null) instance = new MinionTable(); return instance; } /** таблица минионов */ private Table<IntKey, Table<IntKey, MinionData>> minions; private MinionTable() { minions = Tables.newIntegerTable(); // получаем таблицу НПС NpcTable npcTable = NpcTable.getInstance(); int counter = 0; // получаем файлы для парса File[] files = Files.getFiles(new File(Config.SERVER_DIR + "/data/minions")); // перебираем файлы for(File file : files) { if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file.getAbsolutePath()); continue; } if(file.getName().startsWith("example")) continue; // парсим файл Array<MinionData> parsed = new DocumentMinion(file).parse(); // перебираем результат for(MinionData minion : parsed) { // получаем подтаблицу Table<IntKey, MinionData> table = minions.get(minion.getLeaderId()); // если ее нету if(table == null) { // создаем новую table = Tables.newIntegerTable(); // вносим в основную таблицу minions.put(minion.getLeaderId(), table); } // вносим в таблицу информацию о минионах table.put(minion.getType(), minion); // квеличиваем счетчик counter += minion.size(); // получаем темплейт лидера NpcTemplate template = npcTable.getTemplate(minion.getLeaderId(), minion.getType()); if(template == null) { log.warning("not found npc template for " + minion); continue; } // применяем минионов template.setMinions(minion); } } log.info("loaded " + counter + " minions for " + minions.size() + " npcs."); } } <file_sep>/java/game/tera/gameserver/model/skillengine/effects/Heal.java package tera.gameserver.model.skillengine.effects; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; /** * Модеэлт эффекта хила. * * @author Ronn */ public class Heal extends AbstractEffect { public Heal(EffectTemplate template, Character effector, Character effected, SkillTemplate skill) { super(template, effector, effected, skill); } @Override public boolean onActionTime() { Character effected = getEffected(); Character effector = getEffector(); if(effected == null || effector == null) return false; if(effected.getCurrentHp() >= effected.getMaxHp()) return true; //сила хила скила int power = template.getPower(); // увеличиваем на процентный бонус хилера power = (int) (power * effector.calcStat(StatType.HEAL_POWER_PERCENT, 1, null, null)); // добавляем статичный бонус хилера power += effector.calcStat(StatType.HEAL_POWER_STATIC, 0, null, null); if(power < 1) return true; effected.effectHealHp(power, effector); return true; } } <file_sep>/java/game/tera/gameserver/document/DocumentSnifferOpcode.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; /** * Парсер конфига с xml. * * @author Ronn * @created 12.03.2012 */ public final class DocumentSnifferOpcode extends AbstractDocument<VarTable> { /** * @param file отпрасиваемый фаил. */ public DocumentSnifferOpcode(File file) { super(file); } @Override protected VarTable create() { return VarTable.newInstance(); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node protocol = list.getFirstChild(); protocol != null; protocol = protocol.getNextSibling()) if("protocol".equals(protocol.getNodeName())) for(Node packet = protocol.getFirstChild(); packet != null; packet = packet.getNextSibling()) { if("packet".equals(packet.getNodeName())) { NamedNodeMap attrs = packet.getAttributes(); Integer id = Integer.decode(attrs.getNamedItem("id").getNodeValue()); String type = attrs.getNamedItem("class").getNodeValue(); String name = attrs.getNamedItem("name").getNodeValue(); result.set(type + "_" + name, id); } } } } <file_sep>/java/game/tera/gameserver/document/DocumentBattlefield.java package tera.gameserver.document; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import tera.gameserver.model.battlefields.BattlefieldList; import java.io.File; public class DocumentBattlefield extends AbstractDocument<Void> { public DocumentBattlefield(File file) { super(file); } @Override protected Void create() { return null; } @Override protected void parse(Document document) { VarTable vars = VarTable.newInstance(); for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node child = list.getFirstChild(); child != null; child = child.getNextSibling()) if(child.getNodeType() == Node.ELEMENT_NODE && "battlefield".equals(child.getNodeName())) { vars.parse(child); BattlefieldList battlefield = new BattlefieldList(); battlefield.setBattleFieldId(vars.getInteger("id")); battlefield.setMinLevel(vars.getInteger("minLevel")); battlefield.setMaxLevel(vars.getInteger("maxLevel")); battlefield.setName(vars.getString("name")); } } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Equip_Item.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; public class S_Equip_Item extends ServerPacket { private static final ServerPacket instance = new S_Equip_Item(); public static S_Equip_Item getInstance(Player player, int itemId) { S_Equip_Item packet = (S_Equip_Item) instance.newInstance(); packet.player = player; packet.itemId = itemId; return packet; } private Player player; private int itemId; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_EQUIP_ITEM; } @Override protected final void writeImpl() { writeOpcode(); writeInt(player.getObjectId()); writeInt(player.getSubId()); writeByte(1); writeInt(itemId); writeInt(0); } } <file_sep>/java/game/tera/gameserver/templates/CrystalTemplate.java package tera.gameserver.templates; import rlib.util.VarTable; import tera.gameserver.model.items.CrystalType; import tera.gameserver.model.items.StackType; /** * Модель шаблона кристала. * * @author Ronn */ public class CrystalTemplate extends ItemTemplate { /** тип стыковки кристалов */ private StackType stackType; /** запрещено ли больше 1 однотипного кристала */ private boolean noStack; public CrystalTemplate(CrystalType type, VarTable vars) { super(type, vars); try { stackType = StackType.valueOfXml(vars.getString("stackType", "none")); noStack = vars.getBoolean("noStack", true); } catch(Exception e) { e.printStackTrace(); } } @Override public int getClassIdItemSkill() { return -10; } /** * @return тип стыковки. */ public StackType getStackType() { return stackType; } @Override public CrystalType getType() { return (CrystalType) type; } /** * @return запрещено ли больше 1 однотипного кристала. */ public final boolean isNoStack() { return noStack; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Skill_List.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.ServerPacketType; /** * Список скилов игрока. * * @author Ronn */ public final class S_Skill_List extends ServerPacket { private static final ServerPacket instance = new S_Skill_List(); public static S_Skill_List getInstance(Player player) { S_Skill_List packet = (S_Skill_List) instance.newInstance(); // получаем подготавливаемый буффер ByteBuffer buffer = packet.getPrepare(); try { // получаем скилы игрока Table<IntKey, Skill> table = player.getSkills(); // получаем список скилов Array<Skill> skills = table.values(packet.getSkills()); // получаем массив скилов Skill[] array = skills.array(); int counter = 0; int index = 8; // подсчитываем кол-во скилов в книге for(int i = 0, length = skills.size(); i < length; i++) { Skill skill = array[i]; if(skill.getLevel() < 2 && skill.isVisibleOnSkillList()) counter++; } // если есть скилы if(counter > 0) { // запись классовых активных скилов for(int i = 0, length = skills.size(); i < length; i++) { Skill skill = array[i]; if(skill.getLevel() < 2 && skill.isVisibleOnSkillList()) { counter--; packet.writeShort(buffer, index); if(counter == 0) index = 0; else index += 10; packet.writeShort(buffer, index); packet.writeInt(buffer, skill.getId()); packet.writeByte(buffer, skill.isActive()? 1 : 0); packet.writeByte(buffer, 0);//union } } } return packet; } finally { buffer.flip(); } } /** список скилов игрока */ private final Array<Skill> skills; /** промежуточный буффер */ private final ByteBuffer prepare; public S_Skill_List() { this.skills = Arrays.toArray(Skill.class); this.prepare = ByteBuffer.allocate(4096).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); skills.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SKILL_LIST; } /** * @return подготовленный буфер. */ public ByteBuffer getPrepare() { return prepare; } /** * @return список скилов. */ public Array<Skill> getSkills() { return skills; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 0x00080007); // получаем промежуточный буффер ByteBuffer prepare = getPrepare(); // переносим данные buffer.put(prepare.array(), 0, prepare.limit()); } }<file_sep>/java/game/tera/gameserver/model/ai/npc/MessagePackage.java package tera.gameserver.model.ai.npc; import rlib.util.Rnd; /** * Пачка сообщений для АИ НПС. * * @author Ronn */ public final class MessagePackage { /** название пакета */ private String name; /** набор сообщений пакета */ private String[] messages; /** лимит массива сообщений */ private int limit; public MessagePackage(String name, String[] messages) { this.name = name; this.messages = messages; this.limit = messages.length - 1; } /** * @return название пакета. */ public final String getName() { return name; } /** * @return случайное сообщение. */ public final String getRandomMessage() { return messages[Rnd.nextInt(0, limit)]; } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/AbstractAutoShot.java package tera.gameserver.model.skillengine.shots; import java.util.concurrent.ScheduledFuture; import rlib.logging.Logger; import rlib.logging.Loggers; import tera.Config; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Базовая модель новодяхчихся выстрелов. * * @author Ronn */ public abstract class AbstractAutoShot implements Shot { protected static final Logger log = Loggers.getLogger(Shot.class); /** кастер */ protected Character caster; /** цель */ protected Character target; /** скил */ protected Skill skill; /** скорость */ protected int speed; /** радиус */ protected int radius; /** время вылета */ protected long startTime; /** стартовая точка */ protected float startX; protected float startY; protected float startZ; /** таск выстрела */ protected ScheduledFuture<?> task; @Override public void finalyze() { caster = null; target = null; skill = null; } /** * @return the caster */ protected final Character getCaster() { return caster; } @Override public int getObjectId() { return 0; } /** * @return the radius */ protected final int getRadius() { return radius; } /** * @return скил выстрела. */ public Skill getSkill() { return skill; } /** * @return the speed */ protected final int getSpeed() { return speed; } /** * @return the startTime */ protected final long getStartTime() { return startTime; } /** * @return the startX */ protected final float getStartX() { return startX; } /** * @return the startY */ protected final float getStartY() { return startY; } /** * @return the startZ */ protected final float getStartZ() { return startZ; } @Override public int getSubId() { return Config.SERVER_SHOT_SUB_ID; } @Override public Character getTarget() { return target; } @Override public float getTargetX() { return target == null? 0 : target.getX(); } @Override public float getTargetY() { return target == null? 0 : target.getY(); } @Override public float getTargetZ() { return target == null? 0 : target.getZ(); } /** * @return the task */ protected final ScheduledFuture<?> getTask() { return task; } @Override public boolean isAuto() { return true; } @Override public void reinit(){} @Override public synchronized void run() { try { // текущая цель Character target = getTarget(); // текущий скил Skill skill = getSkill(); // если что-то пошло не так, прекращаем обработку if(target == null || skill == null) { log.warning(this, new Exception("not found target or skill")); stop(); return; } // текущее время long now = System.currentTimeMillis(); // пройденное расстояние float donedist = (now - getStartTime()) * getSpeed() / 1000F; float startX = getStartX(); float startY = getStartY(); float startZ = getStartZ(); // расстояние от места выстрела до цели float alldist = target.getDistance(startX, startY, startZ); // получаем радиус float radius = getRadius(); // если выстрел догнал цель if(target.getDistance(startX, startY, startZ) <= donedist + radius) { // и цель может быть подвержена удару if(!target.isDead() && !target.isInvul() && !target.isEvasioned() && caster.checkTarget(target)) // ударяем skill.applySkill(caster, target); // завершаем работу выстрела stop(); return; } float done = donedist / alldist; // если путь выстрел весь прошел и почему-то не ударил, всеравно завершаем if(done >= 1F) stop(); } catch(Exception e) { log.warning(this, e); } } /** * @param caster the caster to set */ protected final void setCaster(Character caster) { this.caster = caster; } /** * @param radius the radius to set */ protected final void setRadius(int radius) { this.radius = radius; } /** * @param skill the skill to set */ protected final void setSkill(Skill skill) { this.skill = skill; } /** * @param speed the speed to set */ protected final void setSpeed(int speed) { this.speed = speed; } /** * @param startTime the startTime to set */ protected final void setStartTime(long startTime) { this.startTime = startTime; } /** * @param startX the startX to set */ protected final void setStartX(float startX) { this.startX = startX; } /** * @param startY the startY to set */ protected final void setStartY(float startY) { this.startY = startY; } /** * @param startZ the startZ to set */ protected final void setStartZ(float startZ) { this.startZ = startZ; } /** * @param target the target to set */ protected final void setTarget(Character target) { this.target = target; } /** * @param task the task to set */ protected final void setTask(ScheduledFuture<?> task) { this.task = task; } @Override public synchronized void start() { // получаем стреляющего Character caster = getCaster(); // если его нет, выходим if(caster == null) { log.warning(this, new Exception("not found caster")); return; } // вносим стартовые координаты setStartX(caster.getX()); setStartY(caster.getY()); setStartZ(caster.getZ() + caster.getGeom().getHeight() - 5F); // получаем скил Skill skill = getSkill(); // если его нет, выходим if(skill == null) { log.warning(this, new Exception("not found skill")); return; } // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); setSpeed(skill.getSpeed()); setRadius(skill.getRadius()); setStartTime( System.currentTimeMillis()); setTask(executor.scheduleMoveAtFixedRate(this, 0, 100)); } @Override public synchronized void stop() { if(task != null) { task.cancel(false); task = null; } } } <file_sep>/java/game/tera/gameserver/model/regenerations/NpcRegenHp.java package tera.gameserver.model.regenerations; import tera.gameserver.model.Character; /** * Модель регенерации хп у НПС. * * @author Ronn * @created 11.04.2012 */ public class NpcRegenHp extends AbstractRegen<Character> { public NpcRegenHp(Character actor) { super(actor); } @Override public boolean checkCondition() { Character actor = getActor(); if(actor.isBattleStanced()) return false; return actor.getCurrentHp() < actor.getMaxHp(); } @Override public void doRegen() { Character actor = getActor(); actor.setCurrentHp(actor.getCurrentHp() + actor.getRegenHp()); actor.updateHp(); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Spawn_Collection.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.resourse.ResourseInstance; import tera.gameserver.network.ServerPacketType; import tera.util.Location; /** * Серверный пакет с информацией об ресурсе. * * @author Ronn */ public class S_Spawn_Collection extends ServerPacket { private static final ServerPacket instance = new S_Spawn_Collection(); public static S_Spawn_Collection getInstance(ResourseInstance resourse) { S_Spawn_Collection packet = (S_Spawn_Collection) instance.newInstance(); packet.objectId = resourse.getObjectId(); packet.subId = resourse.getSubId(); packet.templateId = resourse.getTemplateId(); packet.extractor = resourse.getTemplate().isExtractor(); packet.disabled = resourse.getTemplate().isDisabled(); resourse.getLoc(packet.loc); return packet; } /** обджект ид нпс */ private int objectId; /** саб ид нпс */ private int subId; /** ид темплейта */ private int templateId; private int extractor; private int disabled; /** координаты нпс */ private Location loc; public S_Spawn_Collection() { super(); this.loc = new Location(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SPAWN_COLLECTION; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, objectId);//EF F7 04 00 обжект ид writeInt(buffer, subId);//00 80 04 00 саб ид writeInt(buffer, templateId);//90 01 00 00 ид растения/камня writeInt(buffer, 1);//amount writeFloat(buffer, loc.getX());//D1 6A 13 C6 writeFloat(buffer, loc.getY());//F4 99 05 C6 writeFloat(buffer, loc.getZ());//20 97 10 44 writeByte(buffer, extractor);//is extractor writeByte(buffer, disabled);//extractor disabled writeInt(buffer, 0);//extractor disabled time remaining } } <file_sep>/java/game/tera/gameserver/document/DocumentSkillLearn.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.SkillLearn; /** * Парсер изучений скилов с xml. * * @author Ronn */ public class DocumentSkillLearn extends AbstractDocument<Array<SkillLearn>> { public DocumentSkillLearn(File file) { super(file); } @Override protected Array<SkillLearn> create() { return Arrays.toArray(SkillLearn.class); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node playerClass = list.getFirstChild(); playerClass != null; playerClass = playerClass.getNextSibling()) if("class".equals(playerClass.getNodeName())) parseClass(playerClass); } /** * @param node структура скилов класса. */ private void parseClass(Node node) { // получаем атрибуты класса VarTable vars = VarTable.newInstance(node); // получаем ид класса int classId = vars.getInteger("id"); // перебираем доступные скилы классу for(Node skills = node.getFirstChild(); skills != null; skills = skills.getNextSibling()) if("skill".equals(skills.getNodeName())) { // получаем атрибуты скила vars.parse(skills); // получаем ид скила int id = vars.getInteger("id"); // получаем минимальный ур. скила int minLevel = vars.getInteger("minLevel"); // получаем цену скила int price = vars.getInteger("price"); // флаг пассивности/активности boolean passive = vars.getBoolean("passive", false); // создаем изучающийся скил SkillLearn current = new SkillLearn(id, price, 0, minLevel, classId, passive); // добавляем в результат result.add(current); // перебираем прокачку скила for(Node next = skills.getFirstChild(); next != null; next = next.getNextSibling()) if("next".equals(next.getNodeName())) { // получаем атрибуты след. уровня скила vars.parse(next); // получаем ид скила id = vars.getInteger("id"); // мин ур. minLevel = vars.getInteger("minLevel"); // цену price = vars.getInteger("price"); // создаем новый ур. скила current = new SkillLearn(id, price, current.getId(), minLevel, classId, passive); // добавляем в результат result.add(current); } } } } <file_sep>/java/game/tera/gameserver/model/ai/npc/classes/EpicBattleAI.java package tera.gameserver.model.ai.npc.classes; import rlib.util.Rnd; import tera.gameserver.model.Character; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.npc.playable.EventEpicBattleNpc; /** * Модель АИ для ивента эпичных битв. * * @author Ronn */ public final class EpicBattleAI extends AbstractNpcAI<EventEpicBattleNpc> { public EpicBattleAI(EventEpicBattleNpc actor, ConfigAI config) { super(actor, config); } @Override public void notifyClanAttacked(Character attackedMember, Character attacker, int damage) { super.notifyClanAttacked(attackedMember, attacker, 1); } @Override public boolean checkAggression(Character target) { // получаем НПС EventEpicBattleNpc actor = getActor(); // если его нет или нет цели, или цель не в оне агра if(actor == null || target == null || !target.isInRange(actor, actor.getAggroRange())) return false; // если НПС может атаковать цель if(actor.checkTarget(target) && Rnd.chance(25)) { // добавляем агр поинт actor.addAggro(target, (long) (actor.getMaxHp() * 0.05F), true); return true; } return false; } } <file_sep>/java/game/tera/gameserver/model/skillengine/conditions/ConditionTargetPlayer.java package tera.gameserver.model.skillengine.conditions; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Условие выполнение проверки цели на игрока. * * @author Ronn */ public class ConditionTargetPlayer extends AbstractCondition { /** значение флага */ private boolean value; /** * @param value флаг. */ public ConditionTargetPlayer(boolean value) { this.value = value; } @Override public boolean test(Character attacker, Character attacked, Skill skill, float val) { if(attacker == null || attacked == null) return false; return attacked.isPlayer() == value; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/UserInfo.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.network.ServerPacketType; import tera.gameserver.templates.PlayerTemplate; /** * Пакет с информацией о игроке. * * @author Ronn */ public class UserInfo extends ServerPacket { private static final ServerPacket instance = new UserInfo(); public static UserInfo getInstance(Player player) { UserInfo packet = (UserInfo) instance.newInstance(); // получаем подготавливаемый буффер ByteBuffer buffer = packet.getPrepare(); try { // получаем шаблон игрока PlayerTemplate template = player.getTemplate(); int attack = player.getAttack(null, null); int baseAttack = player.getBaseAttack(); int defense = player.getDefense(null, null); int baseDefense = player.getBaseDefense(); int impact = player.getImpact(null, null); int baseImpact = player.getBaseImpact(); int balance = player.getBalance(null, null); int baseBalance = player.getBaseBalance(); float weakResist = player.calcStat(StatType.WEAK_RECEPTIVE, 0, 0x20, null, null); float stunResist = player.calcStat(StatType.STUN_RECEPTIVE, 0, 0x20, null, null); float dmgResist = player.calcStat(StatType.DAMAGE_RECEPTIVE, 0, 0x20, null, null); packet.writeInt(buffer, player.getCurrentHp()); // ХП сколько есть packet.writeInt(buffer, player.getCurrentMp()); // МП сколько есть packet.writeInt(buffer, 0); packet.writeInt(buffer, player.getMaxHp()); packet.writeInt(buffer, player.getMaxMp()); packet.writeInt(buffer, template.getPowerFactor()); packet.writeInt(buffer, template.getDefenseFactor()); packet.writeShort(buffer, template.getImpactFactor()); packet.writeShort(buffer, template.getBalanceFactor()); packet.writeShort(buffer, template.getRunSpd()); // базовая скорость бега packet.writeShort(buffer, template.getAtkSpd()); packet.writeFloat(buffer, template.getCritRate()); // шанс крита packet.writeFloat(buffer, template.getCritRcpt()); // защита от крита (пока не ясно кд или шанс режет) packet.writeFloat(buffer, 2); // крит дамаг packet.writeInt(buffer, baseAttack); // базовая атака мин packet.writeInt(buffer, baseAttack); // базовая атака макс packet.writeInt(buffer, baseDefense); packet.writeShort(buffer, baseImpact); packet.writeShort(buffer, baseBalance); packet.writeFloat(buffer, weakResist);// (Hex)Сопротивление к Ядам 38 packet.writeFloat(buffer, dmgResist);// (Hex)Сопротивление к повреждениям 38 packet.writeFloat(buffer, stunResist);// (Hex)Сопротивление к обиздвиживанию 38 packet.writeInt(buffer, player.getPowerFactor() - template.getPowerFactor()); // бонус к повер фактору packet.writeInt(buffer, player.getDefenseFactor() - template.getDefenseFactor()); // бонус к дефенс фактору packet.writeShort(buffer, player.getImpactFactor() - template.getImpactFactor()); // бонус к импакт фактору packet.writeShort(buffer, player.getBalanceFactor() - template.getBalanceFactor()); // бонус к баланс фактору packet.writeShort(buffer, player.getRunSpeed() - template.getRunSpd()); // Бонус к скорости бега... packet.writeShort(buffer, player.getAtkSpd() - template.getAtkSpd()); // бонус к атак спиду packet.writeFloat(buffer, player.getCritRate(null, null) - template.getCritRate()); // крит рейт бонус packet.writeFloat(buffer, player.getCritRateRcpt(null, null) - template.getCritRcpt()); // крит ресист бонус packet.writeFloat(buffer, player.getCritDamage(null, null) - 2); // крит мощность бонус packet.writeInt(buffer, attack - baseAttack); // бонус к атаке мин packet.writeInt(buffer, attack - baseAttack); // бонус к атаке макс packet.writeInt(buffer, defense - baseDefense); // бонус к защите packet.writeShort(buffer, impact - baseImpact); // бонус к импакту packet.writeShort(buffer, balance - baseBalance); // бонус к балансу packet.writeFloat(buffer, player.calcStat(StatType.WEAK_RECEPTIVE, 0, null, null) - weakResist); packet.writeFloat(buffer, player.calcStat(StatType.DAMAGE_RECEPTIVE, 0, null, null) - dmgResist); packet.writeFloat(buffer, player.calcStat(StatType.STUN_RECEPTIVE, 0, null, null) - stunResist); packet.writeShort(buffer, player.getLevel()); packet.writeShort(buffer, player.isBattleStanced() ? 1 : 0); packet.writeShort(buffer, 4); packet.writeByte(buffer, 1); packet.writeInt(buffer, player.getMaxHp() - player.getBaseMaxHp()); packet.writeInt(buffer, player.getMaxMp() - player.getBaseMaxMp()); packet.writeInt(buffer, player.getStamina()); packet.writeInt(buffer, player.getMaxStamina()); packet.writeInt(buffer, 0); packet.writeInt(buffer, 0); packet.writeInt(buffer, 0); packet.writeInt(buffer, player.getKarma());// карма packet.writeInt(buffer, 0);// item level (with inventory) packet.writeInt(buffer, 0);// item level (without inventory) packet.writeLong(buffer, 150); packet.writeInt(buffer, 8000); packet.writeInt(buffer, 1); return packet; } finally { buffer.flip(); } } /** промежуточный буффер */ private ByteBuffer prepare; public UserInfo() { this.prepare = ByteBuffer.allocate(20480).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.USER_INFO; } public ByteBuffer getPrepare() { return prepare; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); // получаем промежуточный буффер ByteBuffer prepare = getPrepare(); // переносим данные buffer.put(prepare.array(), 0, prepare.limit()); } }<file_sep>/java/game/tera/gameserver/model/listeners/DamageListener.java package tera.gameserver.model.listeners; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Интерфейс для реализации слушателя получаемого урона. * * @author Ronn */ public interface DamageListener { /** * @param attacker атакующий. * @param attacked атакуемый. * @param info инфа об атаке. * @param skill атакующий скил. */ public void onDamage(Character attacker, Character attacked, AttackInfo info, Skill skill); } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestNpcSubSellShop.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.npc.interaction.dialogs.Dialog; import tera.gameserver.model.npc.interaction.dialogs.DialogType; import tera.gameserver.model.npc.interaction.dialogs.ShopDialog; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.ShopTradePacket; /** * Клиентский пакет указывающий на удаляемый продаваемый итем * * @author Ronn * @created 25.02.2012 */ public class RequestNpcSubSellShop extends ClientPacket { /** игрок */ private Player player; /** обджект ид итема */ private int objectId; /** ид итема */ private int itemId; /** кол-во итемов */ private int count; @Override public void finalyze() { player = null; } @Override public boolean isSynchronized() { return false; } @Override protected void readImpl() { player = owner.getOwner(); readLong(); //наш обжест ид с саб идом readInt(); //обжект ид вещи itemId = readInt(); //итем ид вещи count = readInt(); //кол-во вещей objectId = readInt(); //обжект ид вещи } @Override protected void runImpl() { if(player == null) return; Dialog dialog = player.getLastDialog(); if(dialog == null || dialog.getType() != DialogType.SHOP_WINDOW) return; ShopDialog trade = (ShopDialog) dialog; if(trade.subSellItem(itemId, count, objectId)) player.sendPacket(ShopTradePacket.getInstance(trade), true); } } <file_sep>/java/game/tera/gameserver/scripts/commands/Command.java package tera.gameserver.scripts.commands; import tera.gameserver.model.playable.Player; /** * Интерфейс для реализации обработчика команд. * * @author Ronn * @created 13.04.2012 */ public interface Command { /** * Процесс использования команды игроком. * * @param command введенная команда. * @param player игрок, который использует команду. * @param values надор параметров для команды. */ public void execution(String command, Player player, String values); /** * @return минимальный уровень доступа для обработчика. */ public int getAccess(); /** * @return массив команд, обрабатываемых этим обработчиком. */ public String[] getCommands(); } <file_sep>/java/game/tera/gameserver/network/serverpackets/SeverDeveloperPacket.java package tera.gameserver.network.serverpackets; import java.util.List; import tera.gameserver.network.ServerPacketType; /** * @author Ronn */ public class SeverDeveloperPacket extends ServerPacket { private static final ServerPacket instance = new SeverDeveloperPacket(); public static SeverDeveloperPacket getInstance(List<Short> list) { SeverDeveloperPacket packet = (SeverDeveloperPacket) instance.newInstance(); packet.list = list; return packet; } private List<Short> list; @Override public ServerPacketType getPacketType() { return ServerPacketType.DEVELOPER_PACKET; } @Override protected void writeImpl() { for(short val : list) writeByte(val); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestConfirmServer.java package tera.gameserver.network.clientpackets; import tera.gameserver.network.serverpackets.ConfirmServer; /** * Пакет клиентский, для проверки сервера * * @author Ronn * @created 25.03.2012 */ public class RequestConfirmServer extends ClientPacket { /** присылаемое значение */ public int index; @Override public boolean isSynchronized() { return false; } @Override public void readImpl() { index = readInt(); } @Override public void runImpl() { owner.sendPacket(ConfirmServer.getInstance(index), true); } }<file_sep>/java/game/tera/gameserver/model/BuyableItem.java package tera.gameserver.model; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.Config; import tera.gameserver.templates.ItemTemplate; /** * Модель покупаемого итема. * * @author Ronn */ public final class BuyableItem implements Foldable { /** пул не используемых итемов */ private static final FoldablePool<BuyableItem> pool = Pools.newConcurrentFoldablePool(BuyableItem.class); /** * Создание нового экземпляра оболочки продаваемого итема. * * @param item продаваемый итем. * @param count кол-во продаваемых итемов. * @return новая оболочка. */ public static final BuyableItem newInstance(ItemTemplate item, long count) { BuyableItem buy = pool.take(); if(buy == null) buy = new BuyableItem(); buy.item = item; buy.count = count; return buy; } /** покупаемый итем */ private ItemTemplate item; /** кол-во */ private long count; /** * @param count добавленное кол-во итемов. */ public void addCount(long count) { this.count += count; } @Override public void finalyze() { item = null; } /** * Положить в пул. */ public void fold() { pool.put(this); } /** * @return итоговая цена на итемы */ public long getBuyPrice() { return (long) (count * item.getBuyPrice() * Config.WORLD_SHOP_PRICE_MOD); } /** * @return кол-во покупаемых итемов. */ public long getCount() { return count; } /** * @return покупаемый итем. */ public ItemTemplate getItem() { return item; } /** * @return ид покупаемого итема. */ public int getItemId() { return item.getItemId(); } @Override public void reinit(){} /** * @param count кол-во покупаемых итемов. */ public void setCount(int count) { this.count = count; } /** * @param item покупаемый итем. */ public void setItem(ItemTemplate item) { this.item = item; } /** * @param count кол-во на которое нужно уменьшить покупаемых итемов. */ public void subCount(int count) { this.count -= count; } } <file_sep>/java/game/tera/gameserver/events/EventTeam.java package tera.gameserver.events; import rlib.util.Strings; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.model.playable.Player; /** * Модель команды на ивенте. * * @author Ronn */ public class EventTeam implements Foldable { private static final FoldablePool<EventTeam> pool = Pools.newConcurrentFoldablePool(EventTeam.class); public static EventTeam newInstance() { EventTeam team = pool.take(); if(team == null) team = new EventTeam(); return team; } /** список игроков в команде */ private final Array<EventPlayer> players; /** название команды */ private String name; /** уровень команды */ private int level; private EventTeam() { this.name = Strings.EMPTY; this.players = Arrays.toConcurrentArray(EventPlayer.class); } /** * @param eventPlayer добавляемый игрок. */ public final void addPlayer(EventPlayer eventPlayer) { players.add(eventPlayer); if(players.isEmpty()) setName(Strings.EMPTY); players.readLock(); try { EventPlayer[] array = players.array(); StringBuilder builder = new StringBuilder("{"); for(int i = 0, length = players.size(); i < length; i++) { Player player = array[i].getPlayer(); builder.append(player.getName()); if(i != length - 1) builder.append('-'); } builder.append('}'); setName(builder.toString()); } finally { players.readUnlock(); } } /** * понижение уровня команды. */ public void decreaseLevel() { level--; } @Override public void finalyze() { if(!players.isEmpty()) { EventPlayer[] array = players.array(); for(int i = 0, length = players.size(); i < length; i++) array[i].fold(); players.clear(); } } public void fold() { pool.put(this); } /** * @return уровень команды. */ public int getLevel() { return level; } /** * @return название команды. */ public final String getName() { return name; } /** * @return список игроков в команде. */ public final EventPlayer[] getPlayers() { return players.array(); } /** * Увеличение уровня команды. */ public void increaseLevel() { level++; } /** * @return мертва ли вся команда. */ public final boolean isDead() { if(players.isEmpty()) return true; players.readLock(); try { EventPlayer[] array = players.array(); for(int i = 0, length = players.size(); i < length; i++) { Player player = array[i].getPlayer(); if(!player.isDead()) return false; } return true; } finally { players.readUnlock(); } } @Override public void reinit() { level = 0; } public void removePlayer(EventPlayer player) { players.fastRemove(player); } /** * @param name название команды. */ public final void setName(String name) { this.name = name; } /** * @return кол-во игроков в команде. */ public final int size() { return players.size(); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Reign_Info.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; import java.nio.ByteBuffer; public class S_Reign_Info extends ServerPacket { public static final ServerPacket instance = new S_Reign_Info(); //Region id ? private int unk1; //Region status ? private short unk2; //Region status ? private short unk3; public static S_Reign_Info getInstance(int unk1, short unk2, short unk3){ S_Reign_Info packet = (S_Reign_Info) instance.newInstance(); packet.unk1 = unk1; packet.unk2 = unk2; packet.unk3 = unk3; return packet; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_REIGN_INFO; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer){ writeOpcode(buffer); writeShort(buffer, 12);//pos writeShort(buffer, 14);//pos writeInt(buffer, unk1); writeShort(buffer, unk2); writeShort(buffer, unk3); } } <file_sep>/java/game/tera/gameserver/parser/StatFuncParser.java package tera.gameserver.parser; import java.io.File; import org.w3c.dom.Node; import rlib.util.VarTable; import rlib.util.array.Arrays; import rlib.util.table.Table; import tera.gameserver.model.skillengine.Condition; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.model.skillengine.funcs.Func; import tera.gameserver.model.skillengine.funcs.stat.FuncFactory; /** * Парсер функций статов. * * @author Ronn */ public final class StatFuncParser { private static final String[] STAT_FUNC_NAMES = { "add", "sub", "mul", "set", "div", }; private static StatFuncParser instance; public static StatFuncParser getInstance() { if(instance == null) instance = new StatFuncParser(); return instance; } /** * Определяет, является ли данная функция, функцией статов. * * @param name название функции. * @return является ли финкцией статов. */ public static boolean isStatFunc(String name) { return Arrays.contains(STAT_FUNC_NAMES, name); } /** * Получаем значние параметра. * * @param order номер в таблице. * @param table таблица значений. * @param value значение параметра. * @param skill скил, для которого получаем значение. * @param file фаил, в котором находится скил. * @return значение параметра. */ private String getValue(int order, Table<String, String[]> table, String value, int skill, File file) { // итоговое значение String val = null; // если это не таблица, его же и принимаем if(!value.startsWith("#")) val = value; else { // иначе извлекаем массив из таблицы String[] array = table.get(value); // берем нужное значение value = array[Math.min(array.length -1, order)]; } // возвращаем результат return val; } /** * Парс функции стата с хмл. * * @param order номер в таблице. * @param table таблица значений. * @param node данные с хмл. * @param skill скилл, для которого парсится функция. * @param file фаил, в котором находится скилл. * @return новая функция. */ public Func parseFunc(int order, Table<String, String[]> table, Node node, int skill, File file) { // получаем атрибуты функции VarTable vars = VarTable.newInstance(node); // определяем стат StatType stat = StatType.valueOfXml(vars.getString("stat")); // определяем порядок int ordinal = Integer.decode(vars.getString("order")); // получаем значение функции String value = getValue(order, table, vars.getString("val"), skill, file); // подготавливаем условие Condition cond = null; // получаем парсер условий ConditionParser parser = ConditionParser.getInstance(); // перебираем возможные условия for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { // проопускаем ненужные элементы if(child.getNodeType() != Node.ELEMENT_NODE) continue; // парсим условие cond = parser.parseCondition(child, skill, file); // если кондишен был отпарсен, выходим из цикла if(cond != null) break; } // получаем фабрику функций статов FuncFactory funcFactory = FuncFactory.getInstance(); // создаем новую функцию return funcFactory.createFunc(node.getNodeName(), stat, ordinal, cond, value); } /** * Парс функции стата с хмл. * * @param node данные с хмл. * @return новая функция. */ public Func parseFunc(Node node, File file) { // парсим атрибуты VarTable vars = VarTable.newInstance(node); // определяем стат StatType stat = StatType.valueOfXml(vars.getString("stat")); // определяем ордер int ordinal = Integer.decode(vars.getString("order")); // подготавливаем условие Condition cond = null; // получаем парсер условий ConditionParser parser = ConditionParser.getInstance(); // перебираем возможные условия for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { // проопускаем ненужные элементы if(child.getNodeType() != Node.ELEMENT_NODE) continue; // парсим условие cond = parser.parseCondition(child, 0, file); // если кондишен был отпарсен, выходим из цикла if(cond != null) break; } // получаем фабрику функций статов FuncFactory funcFactory = FuncFactory.getInstance(); // создаем новую функцию return funcFactory.createFunc(node.getNodeName(), stat, ordinal, cond, vars.getString("val")); } } <file_sep>/java/game/tera/gameserver/model/items/WeaponInstance.java package tera.gameserver.model.items; import tera.gameserver.templates.ItemTemplate; import tera.gameserver.templates.WeaponTemplate; /** * Модель оружия. * * @author Ronn */ public final class WeaponInstance extends GearedInstance { /** атака оружия */ private int attack; /** сила оружия */ private int impact; /** * @param objectId уник ид оружия. * @param template темплейт оружия. */ public WeaponInstance(int objectId, ItemTemplate template) { super(objectId, template); } @Override public boolean checkCrystal(CrystalInstance crystal) { if (crystals == null || crystal.getType() != CrystalType.WEAPON) return false; if (crystal.getItemLevel() > template.getItemLevel()) return false; return crystals.hasEmptySlot(); } @Override public WeaponTemplate getTemplate() { return (WeaponTemplate) template; } @Override public WeaponInstance getWeapon() { return this; } @Override public boolean isWeapon() { return true; } @Override protected void updateEnchantStats() { int attack = super.getAttack(); int impact = super.getImpact(); float mod = 3F * getEnchantLevel() / 100F + 1; attack *= mod; mod = 7F * getEnchantLevel() / 100F + 1; impact *= mod; setAttack(attack); setImpact(impact); } private void setAttack(int attack) { this.attack = attack; } private void setImpact(int impact) { this.impact = impact; } @Override public int getImpact() { return impact; } @Override public int getAttack() { return attack; } }<file_sep>/java/game/tera/gameserver/network/clientpackets/C_View_Union_Info.java package tera.gameserver.network.clientpackets; import tera.gameserver.network.serverpackets.S_View_Union_Info; public class C_View_Union_Info extends ClientPacket { private String name; private int guildId; @Override protected void readImpl() { readShort(); name = readString(); readInt(); guildId = readInt(); } @Override protected void runImpl() { owner.getOwner().sendPacket(S_View_Union_Info.getInstance(owner.getOwner()), true); } } <file_sep>/java/game/tera/gameserver/model/ai/npc/classes/AbstractNpcAI.java package tera.gameserver.model.ai.npc.classes; import java.util.concurrent.ScheduledFuture; import rlib.geom.Angles; import rlib.geom.Coords; import rlib.util.Rnd; import rlib.util.Strings; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.manager.GeoManager; import tera.gameserver.model.Character; import tera.gameserver.model.MoveType; import tera.gameserver.model.NpcAIState; import tera.gameserver.model.TObject; import tera.gameserver.model.World; import tera.gameserver.model.ai.AbstractCharacterAI; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.ai.npc.Task; import tera.gameserver.model.ai.npc.TaskType; import tera.gameserver.model.ai.npc.taskfactory.TaskFactory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.npc.Minion; import tera.gameserver.model.npc.MinionLeader; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.model.resourse.ResourseInstance; import tera.gameserver.model.skillengine.Effect; import tera.gameserver.model.skillengine.Formulas; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.TargetType; import tera.util.LocalObjects; import tera.util.Location; /** * Базовая модель АИ нпс. * * @author Ronn */ public abstract class AbstractNpcAI<T extends Npc> extends AbstractCharacterAI<T> implements NpcAI<T>, Runnable { private static final Integer[] ATTACK_HEADINGS = { Integer.valueOf(-12000), Integer.valueOf(-9000), Integer.valueOf(-6000), Integer.valueOf(-3000), Integer.valueOf(0), Integer.valueOf(3000), Integer.valueOf(6000), Integer.valueOf(9000), Integer.valueOf(12000), }; /** пул заданий */ protected final FoldablePool<Task> taskPool; /** список заданий */ protected final Array<Task> taskList; /** текущая цель */ protected Character target; /** текущее состояние АИ */ protected NpcAIState currentState; /** конфиг АИ */ protected ConfigAI config; /** ссылка на таск работы АИ */ private volatile ScheduledFuture<? extends AbstractNpcAI<T>> schedule; /** направление атаки */ private volatile Integer attackHeading; /** статус работы АИ */ private volatile int running; /** время очистки агр листа */ protected long clearAggro; /** время следующего рандомного движения */ protected long nextRandomWalk; /** время последней атаки */ protected long lastAttacked; /** время отправки последней осведомляющей иконки */ protected long lastNotifyIcon; /** время последнего сообщения */ protected long lastMessage; /** время перехода к след. точке маршрута */ protected long nextRoutePoint; /** счетчик аттак на НПС */ protected int attackedCount; /** счетчик догонений */ protected int followCounter; /** индекс позиции на маршруте */ protected int routeIndex; public AbstractNpcAI(T actor, ConfigAI config) { super(actor); this.config = config; this.taskList = Arrays.toConcurrentArray(Task.class); this.taskPool = Pools.newFoldablePool(Task.class); this.currentState = NpcAIState.WAIT; if(config == null) { log.warning(this, new IllegalArgumentException("not found config.")); throw new IllegalArgumentException("not found config."); } } @Override public long getNextRoutePoint() { return nextRoutePoint; } @Override public void setNextRoutePoint(long nextRoutePoint) { this.nextRoutePoint = nextRoutePoint; } @Override public int getRouteIndex() { return routeIndex; } @Override public void setRouteIndex(int routeIndex) { this.routeIndex = routeIndex; } @Override public void setLastMessage(long time) { this.lastMessage = time; } @Override public long getLastMessage() { return lastMessage; } /** * @return список задач АИ. */ public Array<Task> getTaskList() { return taskList; } @Override public void addCastMoveTask(float x, float y, float z, Skill skill, Character target) { // получаем список задач Array<Task> taskList = getTaskList(); taskList.writeLock(); try { Task newTask = taskPool.take(); if(newTask == null) newTask = new Task(); newTask.setType(TaskType.MOVE_ON_CAST); newTask.setSkill(skill); newTask.setTarget(target); newTask.setX(x).setY(y).setZ(z); taskList.add(newTask); } finally { taskList.writeUnlock(); } } @Override public void addCastTask(Skill skill, Character target) { addCastTask(skill, target, Strings.EMPTY); } @Override public void addCastTask(Skill skill, Character target, int heading) { addCastTask(skill, target, heading, Strings.EMPTY); } @Override public void addCastTask(Skill skill, Character target, int heading, String message) { // получаем список задач Array<Task> taskList = getTaskList(); taskList.writeLock(); try { Task newTask = taskPool.take(); if(newTask == null) newTask = new Task(); newTask.setType(TaskType.CAST_ON_HEADING); newTask.setTarget(target); newTask.setSkill(skill); newTask.setHeading(heading); newTask.setMessage(message); taskList.add(newTask); } finally { taskList.writeUnlock(); } } @Override public void addCastTask(Skill skill, Character target, String message) { // получаем список задач Array<Task> taskList = getTaskList(); taskList.writeLock(); try { Task newTask = taskPool.take(); if(newTask == null) newTask = new Task(); newTask.setType(TaskType.CAST); newTask.setTarget(target); newTask.setSkill(skill); newTask.setMessage(message); taskList.add(newTask); } finally { taskList.writeUnlock(); } } @Override public void addMoveTask(float x, float y, float z, boolean update) { addMoveTask(x, y, z, update, Strings.EMPTY); } @Override public void addMoveTask(float x, float y, float z, boolean update, String message) { // получаем список задач Array<Task> taskList = getTaskList(); taskList.writeLock(); try { Task newTask = taskPool.take(); if(newTask == null) newTask = new Task(); newTask.setType(update? TaskType.MOVE_UPDATE_HEADING : TaskType.MOVE_NOT_UPDATE_HEADING); newTask.setX(x).setY(y).setZ(z); newTask.setMessage(message); taskList.add(newTask); } finally { taskList.writeUnlock(); } } @Override public void addMoveTask(float x, float y, float z, Skill skill, Character target) { addMoveTask(x, y, z, skill, target, Strings.EMPTY); } @Override public void addMoveTask(float x, float y, float z, Skill skill, Character target, String message) { // получаем список задач Array<Task> taskList = getTaskList(); taskList.writeLock(); try { Task newTask = taskPool.take(); if(newTask == null) newTask = new Task(); newTask.setType(TaskType.MOVE_ON_CAST); newTask.setX(x).setY(y).setZ(z); newTask.setTarget(target); newTask.setSkill(skill); newTask.setMessage(message); taskList.add(newTask); } finally { taskList.writeUnlock(); } } @Override public void addMoveTask(Location loc, boolean update) { addMoveTask(loc, update, Strings.EMPTY); } @Override public void addMoveTask(Location loc, boolean update, String message) { addMoveTask(loc.getX(), loc.getY(), loc.getZ(), update, message); } @Override public void addNoticeTask(Character target, boolean fast) { addNoticeTask(target, fast, Strings.EMPTY); } @Override public void addNoticeTask(Character target, boolean fast, String message) { // получаем список задач Array<Task> taskList = getTaskList(); taskList.writeLock(); try { Task newTask = taskPool.take(); if(newTask == null) newTask = new Task(); newTask.setType(fast? TaskType.NOTICE_FAST : TaskType.NOTICE); newTask.setTarget(target); newTask.setMessage(message); taskList.add(newTask); } finally { taskList.writeUnlock(); } } @Override public void addTask(Task task) { taskList.add(task); } @Override public boolean checkAggression(Character target) { // получаем НПС T actor = getActor(); // если его нет или нет цели, или цель не в оне агра if(actor == null || target == null || !target.isInRange(actor, actor.getAggroRange())) return false; // если НПС может атаковать цель if(actor.checkTarget(target)) { // если цель не игрок if(!target.isPlayer()) { // добавляем агр поинт actor.addAggro(target, 1, true); return true; } // если цель не ГМ else if(!target.getPlayer().isGM()) { // добавляем агр поинт actor.addAggro(target, 1, true); return true; } } return false; } /** * @return пул использованных задач. */ public FoldablePool<Task> getTaskPool() { return taskPool; } @Override public void clearTaskList() { // получаем список задач Array<Task> taskList = getTaskList(); // если пуст, выходим if(taskList.isEmpty()) return; // получаем пул использованных задач FoldablePool<Task> taskPool = getTaskPool(); taskList.writeLock(); try { Task[] array = taskList.array(); // вносим старые задачи в пул for(int i = 0, length = taskList.size(); i < length; i++) taskPool.put(array[i]); // очищаем таск лист taskList.clear(); } finally { taskList.writeUnlock(); } } /** * Форс очищение списка заданий. */ protected void forceClearTaskList() { taskList.clear(); } @Override public boolean doTask(T actor, long currentTime, LocalObjects local) { // если актор мертв, выходим if(actor.isDead()) return false; // получаем список задач Array<Task> taskList = getTaskList(); // если заданий нет, выходим if(taskList.isEmpty()) return true; // получаем следующее задание Task currentTask = taskList.poll(); // тип задания TaskType type = currentTask.getType(); // если типа нету о_О if(type == null) { // уведомляемd log.warning(this, "not found type for task " + currentTask); // очищаем список заданий forceClearTaskList(); // выходим return false; } // определяем метод исполнения switch(type) { // придти в указаную точку с установкой направления в соответсвии точки case MOVE_UPDATE_HEADING: { // если перемещаться запрещено, удаляем задание и выходим if(actor.isMovementDisabled()) return maybeNextTask(currentTask, false, true); // определям дистанцию до целевой точки float distance = actor.getDistance(currentTask.getX(), currentTask.getY(), currentTask.getZ()); // если она меньше 30, то удаляем задание и выходим if(distance < 30F) return maybeNextTask(currentTask, false, true); // рассчитываем направлении в соответсвии с целевой точкой actor.setHeading(actor.calcHeading(currentTask.getX(), currentTask.getY())); // если есть сообщение if(currentTask.getMessage() != Strings.EMPTY) // выдаем его actor.sayMessage(currentTask.getMessage()); // указываем идти туда startMove(actor.getHeading(), MoveType.RUN, currentTask.getX(), currentTask.getY(), currentTask.getZ(), true, false); // удаляем задание и выходим return maybeNextTask(currentTask, false, true); } //придти в указаную точку без рассчета направления case MOVE_NOT_UPDATE_HEADING: { //если перемещение запрещено, удаляем задание и выходим if(actor.isMovementDisabled()) return maybeNextTask(currentTask, false, true); //определяем дистанцию до целевой точки float distance = actor.getDistance(currentTask.getX(), currentTask.getY(), currentTask.getZ()); //если дистанция меньше 30, удаляем задание и выходим if(distance < 30F) return maybeNextTask(currentTask, false, true); //указываем идти туда startMove(actor.getHeading(), MoveType.RUN, currentTask.getX(), currentTask.getY(), currentTask.getZ(), true, false); //удаляем задание и выходим return maybeNextTask(currentTask, false, true); } // сфокусироваться на указанном персонаже case NOTICE_FAST: case NOTICE: { // определяем цель фокуса Character target = currentTask.getTarget(); if(target == actor) { // очищаем задания forceClearTaskList(); // выходим return false; } // определяем тип разворота boolean fast = type == TaskType.NOTICE_FAST; // если цель не перед лицом if(target != null && !actor.isInFront(target)) { // если быстрый режим if(fast) // мгновенно разворачиваем actor.setHeading(actor.calcHeading(target.getX(), target.getY())); else // иначе ставим плавный разворот actor.nextTurn(actor.calcHeading(target.getX(), target.getY())); } // обновляем боевую стойку actor.startBattleStance(target); // обновляем фокус таргет setTarget(target); // если есть сообщение if(currentTask.getMessage() != Strings.EMPTY) // выдаем его actor.sayMessage(currentTask.getMessage()); // удаляем задание и выходим return maybeNextTask(currentTask, false, true); } // скастовать скил на цель case CAST_ON_HEADING: case CAST: { // получаем цель скила Character target = currentTask.getTarget(); // получаем скил, который будем кастить Skill skill = currentTask.getSkill(); // если чего-то нет, удаляем таск if(target == null || skill == null) { // очищаем задания clearTaskList(); // возвращаем необоходимость создания новых return false; } // нацелен ли скил на себя же boolean self = actor == target || skill.getTargetType() == TargetType.TARGET_SELF; // получаем зону воздействия скила int maxDist = skill.getCastMaxRange(); int minDist = skill.getCastMinRange(); // определяем текущее расстояние до цели int currentDistance = self? 0 : (int) (target.getDistance(actor.getX(), actor.getY(), target.getZ())); // если цель не входит в зону действия скила if(!self && (currentDistance > maxDist || currentDistance < minDist)) { // получаем счетчик попыток догона int followCounter = getFollowCounter(); // TODO вынести в параметр если превысили лимит if(followCounter > 3) { // зануляем setFollowCounter(0); // зануляем направление setAttackHeading(null); // выходим return maybeNextTask(currentTask, false, true); } // получаем рекамендуемое кастовое расстояние int newDist = target.isRangeClass()? maxDist / 2 : (int) (maxDist - actor.getGeomRadius()) * 2 / 3; // делаем поправку на минимально допустимое расстояние newDist = Math.max(newDist, (int) (actor.getGeomRadius() + target.getGeomRadius())); newDist = Math.min(maxDist, newDist); // получаем направление атаки Integer attackHeading = getAttackHeading(); // если направления атаки нет if(attackHeading == null) { // получаем новое attackHeading = getNextAttackHeading(); // запоминаем его setAttackHeading(attackHeading); } // расчитываем направление подхода к цели int heading = target.calcHeading(actor.getX(), actor.getY()) + attackHeading.intValue(); // рассчитываем целевую точку float newX = Coords.calcX(target.getX(), newDist, heading); float newY = Coords.calcY(target.getY(), newDist, heading); // получаем менеджера геодаты GeoManager geoManager = GeoManager.getInstance(); // определяем высоту в той точке float newZ = geoManager.getHeight(actor.getContinentId(), newX, newY, target.getZ()); // добавляем задание доганять addMoveTask(newX, newY, newZ, true); // ставим его после задания догнать addTask(currentTask); // увеличиваем счетчик приследований setFollowCounter(followCounter + 1); // выходим return doTask(actor, currentTime, local); } // запоминаем цель actor.setTarget(getTarget()); // зануяем направление атаки setAttackHeading(null); // если есть сообщение if(currentTask.getMessage() != Strings.EMPTY) // выдаем его actor.sayMessage(currentTask.getMessage()); // получаем точку удара в плоскости float targetX = target.getX(); float targetY = target.getY(); // получаем скорость скила int speed = skill.getSpeed(); // если цель не актор и она в движении if(target != actor && target.isMoving()) { // получаем формулы Formulas formulas = Formulas.getInstance(); // время удара до цели float time = 0F; // если скил стреляющий if(speed > 1) // расчитываемся время полета time += ((float) currentDistance / speed); // расчитываем время каста до удара time += (formulas.castTime(skill.getDelay(), actor) / 1000F); // рассчитываем расстояние смещение цели за время полета скила int newDist = (int) (target.getRunSpeed() * time) + skill.getRadius(); // получаем направление цели float radians = Angles.headingToRadians(target.getHeading()); // перерасчитываем точку удара в плоскости targetX = Coords.calcX(targetX, newDist, radians); targetY = Coords.calcY(targetY, newDist, radians); } // определяем выоту удара float targetZ = target.getZ() + (target.getGeomHeight() / 2); // указываем исполнить каст if(type == TaskType.CAST_ON_HEADING) startCast(skill, currentTask.getHeading(), targetX, targetY, targetZ); else startCast(skill, actor.calcHeading(targetX, targetY), targetX, targetY, targetZ); // удаляем задание и выходим return maybeNextTask(currentTask, false, true); } default: { log.warning(this, "not supported task type " + type); break; } } return true; } /** * @param followCounter счетчик попыток догнать цель. */ public void setFollowCounter(int followCounter) { this.followCounter = followCounter; } /** * @return счетчик попыток догнать цель. */ public int getFollowCounter() { return followCounter; } @Override public void removeTask(Task task) { taskList.slowRemove(task); } @Override public int getAttackedCount() { return attackedCount; } @Override public long getClearAggro() { return clearAggro; } @Override public TaskFactory getCurrentFactory() { return config.getFactory(currentState); } @Override public NpcAIState getCurrentState() { return currentState; } @Override public long getLastAttacked() { return lastAttacked; } @Override public long getLastNotifyIcon() { return lastNotifyIcon; } @Override public final long getNextRandomWalk() { return nextRandomWalk; } @Override public Character getTarget() { return target; } @Override public boolean isGlobalAI() { return config.isGlobal(); } @Override public boolean isWaitingTask() { return !taskList.isEmpty(); } /** * Определить нужно ли новое задание. * * @param task предыдущее задание. * @return нужно ли определить новое задание. */ protected boolean maybeNextTask(Task task) { return maybeNextTask(task, true, true); } /** * Определить нужно ли новое задание. * * @param task предыдущее задание. * @param remove удалять ли его из списка. * @return нужно ли определить новое задание. */ protected boolean maybeNextTask(Task task, boolean remove, boolean pool) { // получаем список задач Array<Task> taskList = getTaskList(); // если таск есть if(task != null) { taskList.writeLock(); try { if(remove) taskList.slowRemove(task); if(pool) taskPool.put(task); } finally { taskList.writeUnlock(); } } // есть ли еще задания return taskList.isEmpty(); } @Override public void notifyAttacked(Character attacker, Skill skill, int damage) { // получаем НПС T actor = getActor(); // если НПС нет, выходим if(actor == null) return; // если АИ почему-то выключен if(running < 1) // запускаем startAITask(); // получаем текущее состояние NpcAIState currentState = getCurrentState(); // если НПС в ожидании if(currentState == NpcAIState.WAIT || currentState == NpcAIState.PATROL) { // если НПС в движении if(actor.isMoving()) // останавливаем actor.stopMove(); } // если мертв, выходим if(attacker == null) return; // добавляем дмг в аггро actor.addAggro(attacker, damage, true); if(skill != null) // добавляем хейт в аггро actor.addAggro(attacker, skill.getAggroPoint(), false); // увеличиваем счетчик setAttackedCount(attackedCount + 1); // запоминаем время последней атаки setLastAttacked(System.currentTimeMillis()); // получаем радиус фракции int range = actor.getFractionRange(); // если радиус есть if(range > 0) { // получаем название фракции String fraction = actor.getFraction(); // если название есть if(fraction != Strings.EMPTY) { LocalObjects local = LocalObjects.get(); // перебераем окружающих нпс Array<Npc> npcs = World.getAround(Npc.class, local.getNextNpcList(), actor, range); if(!npcs.isEmpty()) { // получаем массив нпс Npc[] array = npcs.array(); // перебираем окружающих нпс for(int i = 0, length = npcs.size(); i < length; i++) { // получаем нпс Npc npc = array[i]; // если нпс не подходит, пропускаем if(npc == null || npc == actor || !fraction.equals(npc.getFraction())) continue; // уведомляем нпс о нападении npc.getAI().notifyClanAttacked(actor, attacker, damage); } } } } // получаем лидера группы MinionLeader leader = actor.getMinionLeader(); // если это группа НПС if(leader != null) { // получаем минионов Array<Minion> minions = leader.getMinions(); // если они есть if(!minions.isEmpty()) { minions.readLock(); try { // получаем массив минионов Npc[] array = minions.array(); // перебираем доступных минионов for(int i = 0, length = minions.size(); i < length; i++) { // получаем миниона Npc minion = array[i]; // если это атакуемый, пропускаем if(minion == null || minion == actor) continue; // уведомляем о нападении minion.getAI().notifyPartyAttacked(actor, attacker, damage); } } finally { minions.readUnlock(); } } // если это не лидера атаковали if(leader != actor) // уведомляем его об этом leader.getAI().notifyPartyAttacked(actor, attacker, damage); } } @Override public void notifyClanAttacked(Character attackedMember, Character attacker, int damage) { // получаем НПС T actor = getActor(); // если нпс нету или мертв, выходим if(actor == null || actor.isDead()) return; // добавляем дмг в аггро actor.addAggro(attacker, damage, true); } @Override public void notifyPartyAttacked(Character attackedMember, Character attacker, int damage) { // получаем НПС T actor = getActor(); // если нпс нету или мертв, выходим if(actor == null || actor.isDead()) return; // добавляем дмг в аггро actor.addAggro(attacker, damage, true); } @Override public void run() { // получаем актора T actor = getActor(); // если его нет, выходим if(actor == null) { log.warning(this, new Exception("not found actor")); return; } // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем текущее время long currentTime = System.currentTimeMillis(); try { // думаем свое след. действие config.getThink(currentState).think(this, actor, local, config, currentTime); } catch(Exception exc) { log.warning(this, exc); } } @Override public void setAttackedCount(int count) { this.attackedCount = count; } @Override public void setClearAggro(long clearAggro) { this.clearAggro = clearAggro; } /** * @param config конфиг АИ. */ public void setConfig(ConfigAI config) { this.config = config; } /** * @param currentState текущее состояние АИ. */ protected void setCurrentState(NpcAIState currentState) { this.currentState = currentState; } @Override public void setLastAttacked(long lastAttacked) { this.lastAttacked = lastAttacked; } @Override public void setLastNotifyIcon(long lastNotifyIcon) { this.lastNotifyIcon = lastNotifyIcon; } @Override public void setNewState(NpcAIState state) { // если новое состояние уже применено, выходим if(currentState == state) return; synchronized(this) { // если новое состояние уже применено, выходим if(currentState == state) return; // если АИ активно if(schedule != null) // отменяем предыдущий таск schedule.cancel(false); // изменяем состояние setCurrentState(state); // подготавливаем новое состояние config.getThink(currentState).prepareState(this, actor, LocalObjects.get(), config, System.currentTimeMillis()); // получаем интервал новой работы int interval = config.getInterval(state); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // запускаем новый таск schedule = executor.scheduleAiAtFixedRate(this, interval, interval); } } @Override public final void setNextRandomWalk(long nextRandomWalk) { this.nextRandomWalk = nextRandomWalk; } @Override public void setTarget(Character target) { this.target = target; } @Override public synchronized void startAITask() { if(!config.isRunnable()) return; // если уже работает, выходим if(running > 0) return; // ставим флаг что работает running += 1; // получаем интервал работы int interval = config.getInterval(currentState); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // запускаем АИ schedule = executor.scheduleAiAtFixedRate(this, interval, interval); } @Override public synchronized void stopAITask() { if(!config.isRunnable()) return; // если уже остановлен, выходим if(running < 1) return; running -= 1; // если есть ссылка на таск, отменяем if(schedule != null) schedule.cancel(false); // ставим стадию ожидания setCurrentState(NpcAIState.WAIT); // получаем управленци T actor = getActor(); // если он есть if(actor != null) // очищаем агр лист actor.clearAggroList(); // очищаем задачи clearTaskList(); // зануляем schedule = null; } @Override public Integer getAttackHeading() { return attackHeading; } @Override public void setAttackHeading(Integer attackHeading) { this.attackHeading = attackHeading; } /** * @return следующее направление для атаки. */ protected Integer getNextAttackHeading() { return ATTACK_HEADINGS[Rnd.nextInt(0, ATTACK_HEADINGS.length - 1)]; } @Override public void notifySpawn(){} @Override public void notifyStartDialog(Player player){} @Override public void notifyStopDialog(Player player){} @Override public void notifyArrived(){} @Override public void notifyAgression(Character attacker, long aggro){} @Override public void notifyAttack(Character attacked, Skill skill, int damage){} @Override public void notifyDead(Character killer){} @Override public void notifyAppliedEffect(Effect effect){} @Override public void notifyArrivedBlocked(){} @Override public void notifyArrivedTarget(TObject target){} @Override public void notifyCollectResourse(ResourseInstance resourse){} @Override public void notifyFinishCasting(Skill skill){} @Override public void notifyPickUpItem(ItemInstance item){} @Override public void notifyStartCasting(Skill skill){} @Override public boolean isActiveDialog() { return false; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Exit.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Exit extends ServerPacket { private static final ServerPacket instance = new S_Exit(); public static S_Exit getInstance(int state) { S_Exit packet = (S_Exit) instance.newInstance(); packet.state = state; return packet; } private int state; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_EXIT; } @Override protected final void writeImpl() { writeOpcode(); if(state == 1) writeInt(0x0A000000); } }<file_sep>/java/game/tera/gameserver/tasks/TurnTask.java package tera.gameserver.tasks; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import rlib.util.SafeTask; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.Character; import tera.gameserver.templates.CharTemplate; /** * Модель обработки разворота нпс. * * @author Ronn */ public class TurnTask extends SafeTask { private static final int HALF = Short.MAX_VALUE; /** обрабатываемый нпс */ private final Character actor; /** скорость разворота */ private final int turnSpeed; /** ссылка на таск */ private volatile ScheduledFuture<TurnTask> schedule; /** стартовый разворот */ private int startHeading; /** конечный разворот */ private int endHeading; /** время данное для разворота */ private int time; /** разница в разворотах */ private int diff; public TurnTask(Character actor) { this.actor = actor; CharTemplate template = actor.getTemplate(); this.turnSpeed = template.getTurnSpeed() * 4; } /** * Отмена разворота. */ public void cancel() { // получаем ссылку на задачу разворота ScheduledFuture<TurnTask> schedule = getSchedule(); // если такая есть if(schedule != null) { synchronized(this) { // повторно получаем schedule = getSchedule(); // если всеже такая есть if(schedule != null) { // получаем оставшееся время int res = (int) schedule.getDelay(TimeUnit.MILLISECONDS); // останавливаем задачу schedule.cancel(false); // зануляем ссылку setSchedule(null); // получвем отведенное время int time = getTime(); // получаем процент выполненности разворота float done = (time - res) * 1F / time; // получаем сколько разворота прошли int result = (int) (getDiff() * done); // рассчитываем итоговый текущий разворот result = isPositive()? getStartHeading() + result : getStartHeading() - result; // применяем его actor.setHeading(result); } } } } /** * @return позетивный ли разворот. */ public boolean isPositive() { return startHeading < endHeading; } /** * @return разница в разворотах. */ public int getDiff() { return diff; } /** * @return стартовый разворот. */ public int getStartHeading() { return startHeading; } /** * @return время необоходимое для разворота. */ public int getTime() { return time; } /** * @param diff разница в разворотах. */ public void setDiff(int diff) { this.diff = diff; } /** * @return ссылка на задачу разворота. */ public ScheduledFuture<TurnTask> getSchedule() { return schedule; } /** * @param schedule ссылка на задачу разворота. */ public void setSchedule(ScheduledFuture<TurnTask> schedule) { this.schedule = schedule; } /** * @return конечный разворот. */ public final int getEndHeading() { if(endHeading > 65536) endHeading -= 65536; return endHeading; } /** * @return находится ли нпс в процессе разворота. */ public boolean isTurner() { return schedule != null; } /** * @return разворачиваемый персонаж. */ public Character getActor() { return actor; } /** * Развернуть нпс до указанного направления. * * @param newHeading новое направление. */ public void nextTurn(int newHeading) { // отменяем предыдущий равороот cancel(); // получаем разворачиваемого персонажа Character actor = getActor(); // получаем стартовый разворот int startHeading = actor.getHeading(); // получаем целевой разворот int endHeading = newHeading; synchronized(this) { // определяем разницу в развороте int diff = Math.abs(startHeading - endHeading); // вносим поправки в разницу if(diff > HALF) { if(startHeading < endHeading) startHeading += 65536; else endHeading += 65536; diff = Math.abs(startHeading - endHeading); } // обновляем разницу setDiff(diff); // увеличиваем разницу для рассчета требуемого времени в милисекундах diff *= 1000; // определяем требуемое время int time = diff / turnSpeed; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // ставим на исполнеие setSchedule(executor.scheduleGeneral(this, time + 700)); // обновляем время setTime(time); // отображаем разворот PacketManager.showTurnCharacter(actor, endHeading, time * 80 / 100); } // обновляем стартовый разворот setStartHeading(startHeading); // обновляем конечный разворот setEndHeading(endHeading); } /** * @param time время отведенное на разворот. */ public void setTime(int time) { this.time = time; } /** * @param startHeading стартовый разворот. */ public void setStartHeading(int startHeading) { this.startHeading = startHeading; } /** * @param endHeading конечный разворот. */ public void setEndHeading(int endHeading) { this.endHeading = endHeading; } @Override protected void runImpl() { // применяем целевой разворот actor.setHeading(endHeading); // зануляем ссылку на задачу setSchedule(null); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Delete_User.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с результатом попытки удаления персонажа. * * @author Ronn * @created 31.03.2012 */ public class S_Delete_User extends ServerPacket { /** успешно удален */ public static final int SUCCESSFUL = 1; /** не успешно удален */ public static final int FAILED = 0; private static final ServerPacket instance = new S_Delete_User(); public static S_Delete_User getInstance(int result) { S_Delete_User packet = (S_Delete_User) instance.newInstance(); packet.result = result; return packet; } /** результат удаления */ private int result; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_DELETE_PLAYER; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeByte(buffer, result); } }<file_sep>/java/game/tera/gameserver/model/quests/QuestEvent.java package tera.gameserver.model.quests; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.playable.Player; import tera.gameserver.model.resourse.ResourseInstance; /** * Контейнер инфы об событии. * * @author Ronn */ public final class QuestEvent { /** тип события */ private QuestEventType type; /** нажатая ссылка */ private Link link; /** квест */ private Quest quest; /** игрок */ private Player player; /** нпс */ private Npc npc; /** итем */ private ItemInstance item; /** ресурс */ private ResourseInstance resourse; /** значение чего-нибудь */ private int value; /** * Очистка. */ public QuestEvent clear() { link = null; player = null; quest = null; type = null; item = null; resourse = null; value = 0; return this; } /** * @return итем. */ public ItemInstance getItem() { return item; } /** * @return нажатая ссылка. */ public Link getLink() { return link; } /** * @return нпс. */ public Npc getNpc() { return npc; } /** * @return игрок. */ public Player getPlayer() { return player; } /** * @return квест. */ public Quest getQuest() { return quest; } /** * @return ресурс. */ public final ResourseInstance getResourse() { return resourse; } /** * @return тип события. */ public QuestEventType getType() { return type; } /** * @return значение чего-нибудь. */ public final int getValue() { return value; } /** * @param item итем. */ public void setItem(ItemInstance item) { this.item = item; } /** * @param link нажатая ссылка. */ public void setLink(Link link) { this.link = link; } /** * @param npc нпс. */ public void setNpc(Npc npc) { this.npc = npc; } /** * @param player игрок. */ public void setPlayer(Player player) { this.player = player; } /** * @param quest квест. */ public void setQuest(Quest quest) { this.quest = quest; } /** * @param resourse ресурс. */ public final void setResourse(ResourseInstance resourse) { this.resourse = resourse; } /** * @param type тип события. */ public void setType(QuestEventType type) { this.type = type; } /** * @param value значение чего-нибудь. */ public final void setValue(int value) { this.value = value; } @Override public String toString() { return "QuestEvent type = " + type + ", link = " + link + ", quest = " + quest + ", player = " + player + ", npc = " + npc + ", item = " + item + ", resourse = " + resourse; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Get_User_List.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import rlib.util.Strings; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.model.equipment.Equipment; import tera.gameserver.model.equipment.SlotType; import tera.gameserver.model.playable.PlayerAppearance; import tera.gameserver.model.playable.PlayerDetails2; import tera.gameserver.model.playable.PlayerPreview; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет со списком игроков на аккаунте * * @author Ronn */ public class S_Get_User_List extends ServerPacket { private static final ServerPacket instance = new S_Get_User_List(); public static S_Get_User_List getInstance(String accountName) { S_Get_User_List packet = (S_Get_User_List) instance.newInstance(); // получаем подготовительный буффер ByteBuffer buffer = packet.getPrepare(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем список персонажей на аккаунте Array<PlayerPreview> playerList = packet.getPlayerList(); // загружаем персонажей dbManager.restorePlayerList(playerList, accountName); int size = playerList.size(); int sizeTo = 0; if(size > 0) { packet.writeShort(buffer, size); // кол-во персонажей packet.writeShort(buffer, 39); packet.writeLong(buffer, 1); packet.writeByte(buffer, 0); packet.writeInt(buffer, 8); // Max character Allowed packet.writeInt(buffer, 1); packet.writeShort(buffer, 0); packet.writeInt(buffer, 40); packet.writeInt(buffer, 0); packet.writeInt(buffer, 24); // получаем массив превью PlayerPreview[] array = playerList.array(); // получаем последнее превью PlayerPreview last = playerList.last(); for(int i = 0; i < size; i++) { sizeTo = buffer.position() + 4; // reading amount of already written bytes... packet.writeShort(buffer, sizeTo); // amount of bytes which was written before this byte.. PlayerPreview current = array[i]; if(current == last) // last character sends 0x00 packet.writeShort(buffer, 0); else packet.writeShort(buffer, sizeTo + 401 + Strings.length(current.getName())); // need to update this from 283 to new packet.writeInt(buffer, 0); packet.writeShort(buffer, sizeTo += 304); // amount of bytes before char name starts... // same here needs update to packet.writeShort(buffer, sizeTo + Strings.length(current.getName())); //details1 packet.writeShort(buffer, 32); // packet.writeShort(buffer, sizeTo + 32 + Strings.length(current.getName())); // new details2 shif packet.writeShort(buffer, 64); // shift the right amount // ------------------------------------------------------------------ packet.writeInt(buffer, current.getObjectId()); packet.writeInt(buffer, current.getSex()); packet.writeInt(buffer, current.getRaceId()); packet.writeInt(buffer, current.getClassId()); packet.writeInt(buffer, current.getLevel()); packet.writeInt(buffer, current.getHp()); // AD040000 packet.writeInt(buffer, current.getMp()); // AD040000 packet.writeInt(buffer, 0);// 1 packet.writeInt(buffer, 0);// 2 packet.writeInt(buffer, 0);// 7 packet.writeInt(buffer, 0x00007E8F);//last online packet.writeByte(buffer, 0); packet.writeInt(buffer, 0); packet.writeInt(buffer, 0xB060614E); packet.writeInt(buffer, 0); packet.writeInt(buffer, 0xB060614E); // =========================== Экиперовка ================================// // получаем экиперовку игрока Equipment equipment = current.getEquipment(); packet.writeInt(buffer, equipment.getItemId(SlotType.SLOT_WEAPON)); packet.writeInt(buffer, 0); packet.writeInt(buffer, 0); packet.writeInt(buffer, equipment.getItemId(SlotType.SLOT_ARMOR)); packet.writeInt(buffer, equipment.getItemId(SlotType.SLOT_GLOVES)); packet.writeInt(buffer, equipment.getItemId(SlotType.SLOT_BOOTS)); packet.writeInt(buffer, 0); packet.writeInt(buffer, 0); packet.writeInt(buffer, 0); packet.writeInt(buffer, equipment.getItemId(SlotType.SLOT_HAT)); packet.writeInt(buffer, equipment.getItemId(SlotType.SLOT_MASK)); packet.writeInt(buffer, 0);// new // ============================================================\\ // получаем внешность игрока PlayerAppearance appearance = current.getAppearance(); PlayerDetails2 detailsappearance = current.getdetails2(); packet.writeByte(buffer, 65); // temp[9] packet.writeByte(buffer, appearance.getFaceColor()); packet.writeByte(buffer, appearance.getFaceSkin()); packet.writeByte(buffer, appearance.getAdormentsSkin()); packet.writeByte(buffer, appearance.getFeaturesSkin()); packet.writeByte(buffer, appearance.getFeaturesColor()); packet.writeByte(buffer, appearance.getVoice()); packet.writeByte(buffer, 0); // temp[14] // ============================================================\\ packet.writeLong(buffer, 0); //8 packet.writeInt(buffer, 0); // 4 packet.writeShort(buffer, 0); // 2 packet.writeInt(buffer, 0); // BF1857B0 packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); packet.writeLong(buffer, 0); //new packet.writeLong(buffer, 0); //new packet.writeLong(buffer, 0); //new packet.writeInt(buffer, 0); // new packet.writeInt(buffer, 0);//current rested xp? packet.writeInt(buffer, 0);//max restedxp ? packet.writeByte(buffer, 1); if(current.getOnlineTime() > 15000) packet.writeByte(buffer, 0);// 01 показываем промо 00 нет else packet.writeByte(buffer, 1); packet.writeByte(buffer, 0); packet.writeShort(buffer, 0); packet.writeByte(buffer, 0); packet.writeByte(buffer, 1); // new packet.writeInt(buffer, 0); packet.writeInt(buffer, 0);//guild id packet.writeInt(buffer, 0);//unknow array packet.writeString(buffer, current.getName()); packet.writeByte(buffer, appearance.getBoneStructureBrow()); packet.writeByte(buffer, appearance.getBoneStructureCheekbones()); packet.writeByte(buffer, appearance.getBoneStructureJaw()); packet.writeByte(buffer, appearance.getBoneStructureJawJut()); packet.writeByte(buffer, appearance.getEarsRotation()); packet.writeByte(buffer, appearance.getEarsExtension()); packet.writeByte(buffer, appearance.getEarsTrim()); packet.writeByte(buffer, appearance.getEarsSize()); packet.writeByte(buffer, appearance.getEyesWidth()); packet.writeByte(buffer, appearance.getEyesHeight()); packet.writeByte(buffer, appearance.getEyesSeparation()); packet.writeByte(buffer, 0); // temp[17] packet.writeByte(buffer, appearance.getEyesAngle()); packet.writeByte(buffer, appearance.getEyesInnerBrow()); packet.writeByte(buffer, appearance.getEyesOuterBrow()); packet.writeByte(buffer, 0); // temp[18] packet.writeByte(buffer, appearance.getNoseExtension()); packet.writeByte(buffer, appearance.getNoseSize()); packet.writeByte(buffer, appearance.getNoseBridge()); packet.writeByte(buffer, appearance.getNoseNostrilWidth()); packet.writeByte(buffer, appearance.getNoseTipWidth()); packet.writeByte(buffer, appearance.getNoseTip()); packet.writeByte(buffer, appearance.getNoseNostrilFlare()); packet.writeByte(buffer, appearance.getMouthPucker()); packet.writeByte(buffer, appearance.getMouthPosition()); packet.writeByte(buffer, appearance.getMouthWidth()); packet.writeByte(buffer, appearance.getMouthLipThickness()); packet.writeByte(buffer, appearance.getMouthCorners()); packet.writeByte(buffer, appearance.getEyesShape()); packet.writeByte(buffer, appearance.getNoseBend()); packet.writeByte(buffer, appearance.getBoneStructureJawWidth()); packet.writeByte(buffer, appearance.getMothGape()); int[] jp = detailsappearance.getDetails2(); for(int r = 0; r < 64; ++r){ packet.writeByte(buffer,jp[r]); } packet.writeByte(buffer, 0); } // скадируем превьюхи for(int i = 0; i < size; i++) array[i].fold(); } else { packet.writeShort(buffer, size); // кол-во персонажей packet.writeShort(buffer, 0); packet.writeLong(buffer, 1); packet.writeByte(buffer, 0); packet.writeInt(buffer, 8); // Max character Allowed packet.writeInt(buffer, 1); packet.writeShort(buffer, 0); packet.writeInt(buffer, 40); packet.writeInt(buffer, 0); packet.writeInt(buffer, 24); } return packet; } /** список игроков на аккаунте */ private final Array<PlayerPreview> playerList; /** промежуточный буффер пакета */ private final ByteBuffer prepare; public S_Get_User_List() { this.playerList = Arrays.toArray(PlayerPreview.class); this.prepare = ByteBuffer.allocate(4096).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { playerList.clear(); prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_GET_USER_LIST; } /** * @return список игроков. */ public Array<PlayerPreview> getPlayerList() { return playerList; } /** * @return подготовительный буффер. */ public ByteBuffer getPrepare() { return prepare; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); prepare.flip(); buffer.put(prepare); } }<file_sep>/java/game/tera/gameserver/model/geom/AbstractGeom.java package tera.gameserver.model.geom; import tera.gameserver.model.Character; /** * Фундаментальная модель геометрии персонажа. * * @author Ronn */ public abstract class AbstractGeom<E extends Character> implements Geom { /** персонаж */ protected E character; /** радиус модели */ protected float radius; /** высота модели */ protected float height; /** * @param character персонаж. * @param height высота модели. * @param radius радиус модели. */ public AbstractGeom(E character, float height, float radius) { this.character = character; this.height = height; this.radius = radius; } /** * @return владелец геометрии. */ protected E getCharacter() { return character; } @Override public float getHeight() { return height; } @Override public float getRadius() { return radius; } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/ObjectShot.java package tera.gameserver.model.skillengine.shots; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.IdFactory; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.StartObjectShot; import tera.gameserver.network.serverpackets.CharObjectDelete; /** * Модель объектных выстрелов. * * @author Ronn */ public class ObjectShot extends AbstractShot { /** пул выстрелов */ private static FoldablePool<ObjectShot> pool = Pools.newConcurrentFoldablePool(ObjectShot.class); /** * @param caster стреляющий персонаж. * @param skill стреляющий скил. * @param targetX координата точки полета. * @param targetY координата точки полета. * @param targetZ координата точки полета. */ public static void startShot(Character caster, Skill skill, float targetX, float targetY, float targetZ) { // вытаскиваем с пула ObjectShot shot = pool.take(); // если нету if(shot == null) // создаем shot = new ObjectShot(); // подготавливаем shot.prepare(caster, skill, targetX, targetY, targetZ); // запускаем shot.start(); } /** уникальный ид выстрела */ protected int objectId; public ObjectShot() { setType(ShotType.SLOW_SHOT); } @Override public int getObjectId() { return objectId; } @Override public synchronized void start() { super.start(); // получаем фабрику ИД IdFactory idFactory = IdFactory.getInstance(); // получаем новый ид setObjectId(idFactory.getNextShotId()); // отправляем пакет caster.broadcastPacket(StartObjectShot.getInstance(caster, skill, this)); } @Override public synchronized void stop() { super.stop(); // отправляем пакет удаления caster.broadcastPacket(CharObjectDelete.getInstance(objectId, getSubId())); // ложим в пул pool.put(this); } /** * @param objectId уникальный ид скила. */ public void setObjectId(int objectId) { this.objectId = objectId; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/CreatePlayerResult.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, говорящий об результате попытки создании персонажа. * * @author Ronn */ public class CreatePlayerResult extends ServerConstPacket { private static final CreatePlayerResult instance = new CreatePlayerResult(); public static CreatePlayerResult getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.PLAYER_CREATE_RESULT; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeByte(buffer, 1); } }<file_sep>/java/game/tera/gameserver/tables/PlayerTable.java package tera.gameserver.tables; import java.io.File; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.array.Array; import tera.Config; import tera.gameserver.document.DocumentPlayer; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.base.Race; import tera.gameserver.model.base.Sex; import tera.gameserver.templates.PlayerTemplate; /** * Таблица шаблонов игроков. * * @author Ronn */ public final class PlayerTable { private static final Logger log = Loggers.getLogger(PlayerTable.class); private static PlayerTable instance; public static PlayerTable getInstance() { if(instance == null) instance = new PlayerTable(); return instance; } /** таблица всех темплейтов */ private PlayerTemplate[][][] templates; private PlayerTable() { templates = new PlayerTemplate[Sex.SIZE][Race.SIZE][PlayerClass.length]; int counter = 0; Array<PlayerTemplate> parsed = new DocumentPlayer(new File(Config.SERVER_DIR + "/data/player_templates.xml")).parse(); for(PlayerTemplate temp : parsed) templates[temp.getSex().ordinal()][temp.getRace().ordinal()][temp.getPlayerClass().ordinal()] = temp; for(PlayerTemplate[][] matrix : templates) for(PlayerTemplate[] array : matrix) for(PlayerTemplate template : array) if(template != null) counter++; log.info("loaded " + counter + " player templates."); } /** * Получение темплейта игрока. * * @param playerClass класс игрока. * @param race раса игрока. * @param sex пол игрока. * @return соответствующий темплейт. */ public final PlayerTemplate getTemplate(PlayerClass playerClass, Race race, Sex sex) { return templates[sex.ordinal()][race.ordinal()][playerClass.getId()]; } } <file_sep>/java/game/tera/gameserver/model/skillengine/EffectType.java package tera.gameserver.model.skillengine; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.effects.AuraManaDamOverTime; import tera.gameserver.model.skillengine.effects.Buff; import tera.gameserver.model.skillengine.effects.CancelEffect; import tera.gameserver.model.skillengine.effects.CharmBuff; import tera.gameserver.model.skillengine.effects.DamOverTime; import tera.gameserver.model.skillengine.effects.DamOverTimePercent; import tera.gameserver.model.skillengine.effects.DamageAbsorption; import tera.gameserver.model.skillengine.effects.DamageTransfer; import tera.gameserver.model.skillengine.effects.Debuff; import tera.gameserver.model.skillengine.effects.Heal; import tera.gameserver.model.skillengine.effects.HealMod; import tera.gameserver.model.skillengine.effects.HealOverTime; import tera.gameserver.model.skillengine.effects.Invul; import tera.gameserver.model.skillengine.effects.ManaHealOverTime; import tera.gameserver.model.skillengine.effects.ManaHealOverTimePercent; import tera.gameserver.model.skillengine.effects.NoBattleEffect; import tera.gameserver.model.skillengine.effects.NoOwerturnEffect; import tera.gameserver.model.skillengine.effects.PercentHealOverTime; import tera.gameserver.model.skillengine.effects.Pheonix; import tera.gameserver.model.skillengine.effects.Root; import tera.gameserver.model.skillengine.effects.SkillBlocking; import tera.gameserver.model.skillengine.effects.Stun; import tera.gameserver.model.skillengine.effects.Turn; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; /** * Перечисление типов эффекта. * * @author Ronn */ public enum EffectType { /** баф */ BUFF(Buff.class), CHARM_BUFF(CharmBuff.class), /** хилещий эффект */ HEAL(Heal.class), /** хил с модифицированым бонусом хила */ HEAL_MOD(HealMod.class), /** хил в течении времени эффекта */ HEAL_OVER_TIME(HealOverTime.class), /** процентный хил в течении времени */ PERCENT_HEAL_OVER_TIME(PercentHealOverTime.class), /** дебафф */ DEBUFF(Debuff.class), /** эффект оглушения */ STUN(Stun.class), /** эффект блокирования скилов */ SKILL_BLOCKING(SkillBlocking.class), /** эффект, наносящий урон в процессе работы */ DAM_OVER_TIME(DamOverTime.class), /** эффект, который наносит процентный урон в процессе работы */ DAM_OVER_TIME_PERCENT(DamOverTimePercent.class), /** эффект, прерывающиийся при входе в бой */ NO_BATTLE_EFFECT(NoBattleEffect.class), /** эффект, прерывающиийся при опрокидывании */ NO_OWERTURN_EFFECT(NoOwerturnEffect.class), /** эффект, периодического рестора мп */ MANA_HEAL_OVER_TIME(ManaHealOverTime.class), /** эффект, который процентно ресторит мп */ MANA_HEAL_OVER_TIME_PERCENT(ManaHealOverTimePercent.class), /** ара баф на поддержание которого требуется мп */ AURA_MANA_DAM_OVER_TIME(AuraManaDamOverTime.class), /** эффект обездвиживания */ ROOT(Root.class), /** поглощающий урон эффект */ DAMAGE_ABSORPTION(DamageAbsorption.class), /** эффект самовоскрешения */ PHEONIX(Pheonix.class), /** эффект неуязвимости */ INVUL(Invul.class), /** эффект разворота */ TURN(Turn.class), /** эффект трансфера урона */ DAMAGE_TRANSFER(DamageTransfer.class), /** эффект кансела эффектов */ CANCEL_EFFECT(CancelEffect.class); /** конструктор для создания эффекта */ private Constructor<? extends Effect> constructor; /** * @param constructor конструктор эффекта. */ private EffectType(Class<? extends Effect> effectClass) { try { this.constructor = effectClass.getConstructor(EffectTemplate.class, Character.class, Character.class, SkillTemplate.class); } catch(NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException(); } } /** * Создание нового эффекта. * * @param template темплейт эффекта. * @param effector тот, кто накладывает эффект. * @param effected тот, на кого накладывают эффект. * @param skill скил, которым накладывают эффект. * @return новый экземпляр эффекта. */ public Effect newInstance(EffectTemplate template, Character effector, Character effected, SkillTemplate skill) { try { return constructor.newInstance(template, effector, effected, skill); } catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { return null; } } } <file_sep>/java/game/tera/gameserver/manager/DebugManager.java package tera.gameserver.manager; import rlib.geom.Coords; import tera.gameserver.tables.ItemTable; import tera.gameserver.templates.ItemTemplate; import tera.util.Location; /** * Менеджер по отображению дебага. * * @author Ronn */ public abstract class DebugManager { public static void showAreaDebug(int continentId, float targetX, float targetY, float targetZ, float radius) { Location[] locs = Coords.circularCoords(Location.class, targetX, targetY, targetZ, (int) radius, 10); ItemTable itemTable = ItemTable.getInstance(); ItemTemplate template = itemTable.getItem(8007); // перебираем точки for(int i = 0; i < 10; i++) { // получаем точку Location loc = locs[i]; // вносим континент loc.setContinentId(continentId); // спавним template.newInstance().spawnMe(loc); } template.newInstance().spawnMe(new Location(targetX, targetY, targetZ)); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestDialogCancel.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.actions.Action; import tera.gameserver.model.actions.dialogs.ActionDialog; import tera.gameserver.model.npc.interaction.dialogs.Dialog; import tera.gameserver.model.playable.Player; /** * Клиентский пакет, уведомляющий о закрытии диалогового окна * * @author Ronn * @created 24.02.2012 */ public class RequestDialogCancel extends ClientPacket { /** игрок */ private Player player; @Override public void finalyze() { player = null; } @Override protected void readImpl() { player = owner.getOwner(); } @Override protected void runImpl() { if(player == null) return; Action action = player.getLastAction(); if(action != null) action.cancel(player); Dialog dialog = player.getLastDialog(); if(dialog != null) dialog.close(); ActionDialog actionDialog = player.getLastActionDialog(); if(actionDialog != null) actionDialog.cancel(player); } } <file_sep>/java/game/tera/gameserver/model/resourse/QuestResourse.java package tera.gameserver.model.resourse; import tera.gameserver.model.playable.Player; import tera.gameserver.templates.ResourseTemplate; /** * Модель квестовых ресурсов. * * @author Ronn */ public class QuestResourse extends ResourseInstance { public QuestResourse(int objectId, ResourseTemplate template) { super(objectId, template); } @Override public boolean checkCondition(Player collector) { return true; } @Override public int getChanceFor(Player player) { return 100; } @Override public void increaseReq(Player player){} } <file_sep>/java/game/tera/gameserver/tasks/SkillMoveTask.java package tera.gameserver.tasks; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import rlib.geom.Angles; import rlib.geom.Coords; import rlib.util.SafeTask; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.manager.GeoManager; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.skillengine.Formulas; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.MoveSkill; import tera.gameserver.network.serverpackets.S_Action_End; /** * Модель обрбаотки движения скила. * * @author Ronn * @created 12.03.2012 */ public final class SkillMoveTask extends SafeTask { /** блокировщик */ private final Lock lock; /** кастер */ private final Character caster; /** список возможных помех */ private final Array<Character> barriers; /** скил, который перемещает */ private Skill skill; /** кол-во смещений */ private int counter; /** полная дистанция */ private float alldist; /** выполненый */ private float done; /** шаг */ private float step; /** точка старта */ private float startX; /** точка старта */ private float startY; /** точка старта */ private float startZ; /** точка конца */ private float targetX; /** точка конца */ private float targetY; /** точка конца */ private float targetZ; /** направление */ private float radians; /** игнорирует ли препядствия скил */ private boolean ignore; /** ссылка на таск */ private volatile ScheduledFuture<SkillMoveTask> schedule; /** * @param caster кастующий скил персонаж. */ public SkillMoveTask(Character caster) { this.caster = caster; this.lock = Locks.newLock(); this.barriers = Arrays.toArray(Character.class); } /** * Применить скил. */ public void applySkill() { lock.lock(); try { // получаем текущий активный скил Skill skill = getSkill(); // если его нет, выходим if(skill == null) return; // активируем его caster.nextUse(skill); // зануляем скил setSkill(null); } finally { lock.unlock(); } } /** * Прерывание таска. */ public void cancel(boolean force) { lock.lock(); try { // зануляем текущий активный скил setSkill(null); // отменяем таск обработки if(schedule != null) { schedule.cancel(false); schedule = null; } // убераем флаг перемещения при касте скила caster.setSkillMoved(false); // если есть препядствия if(!barriers.isEmpty()) // очищаем от них barriers.clear(); } finally { lock.unlock(); } } /** * Завершение таска. */ public void done() { lock.lock(); try { // получаем текущий активный скил Skill skill = getSkill(); // если он есть и активируется при сталкновении if(skill != null && skill.isCastToMove()) // применяем applySkill(); // убераем флаг перемещения скилом caster.setSkillMoved(false); // отменяем таск if(schedule != null) { schedule.cancel(false); schedule = null; } // если есть препядствия if(!barriers.isEmpty()) // очищаем от них barriers.clear(); } finally { lock.unlock(); } } /** * @return alldist */ public final float getAlldist() { return alldist; } /** * @return done */ public final float getDone() { return done; } /** * @return radians */ public final float getRadians() { return radians; } /** * @return скил таска. */ public Skill getSkill() { return skill; } /** * @return startX */ public final float getStartX() { return startX; } /** * @return startY */ public final float getStartY() { return startY; } /** * @return startZ */ public final float getStartZ() { return startZ; } /** * @return targetX */ public final float getTargetX() { return targetX; } /** * @return targetY */ public final float getTargetY() { return targetY; } /** * @return targetZ */ public final float getTargetZ() { return targetZ; } /** * Запустить обработку скила. * * @param skill скил, который нужно обработать. */ public void nextTask(Skill skill, float targetX, float targetY, float targetZ) { // отменяем предыдущий скил cancel(false); Formulas formulas = Formulas.getInstance(); // определяем время перемещения int time = skill.isStaticCast()? skill.getMoveTime() : formulas.castTime(skill.getMoveTime(), caster); // определяем дистанцию int moveDistance = skill.getMoveDistance(); // если дистанции нет, отменяем if(moveDistance == 0 && !skill.isRush()) return; lock.lock(); try { // обновляем скил setSkill(skill); // зануляем пройденное расстояние setDone(0); // запоминаем точку старта setStartX(caster.getX()); setStartY(caster.getY()); setStartZ(caster.getZ()); // получаем менеджера геодаты GeoManager geoManager = GeoManager.getInstance(); // если скил раш if(skill.isRush()) { // рассчитываем дистанцию setAlldist(caster.getDistance(targetX, targetY, targetZ)); // если она больше допустимой if(getAlldist() > moveDistance) { // рассчитываем направление setRadians(Angles.headingToRadians(caster.getHeading() + skill.getMoveHeading())); // меняем дистанцию setAlldist(moveDistance); // перерассчитываем целевую точку setTargetX(Coords.calcX(startX, moveDistance, radians)); setTargetY(Coords.calcY(startY, moveDistance, radians)); setTargetZ(geoManager.getHeight(caster.getContinentId(), getTargetX(), getTargetY(), getStartZ())); } // иначе else { // применяем целевую точку setTargetX(targetX); setTargetY(targetY); setTargetZ(targetZ); // рассчитываем направление setRadians(Angles.headingToRadians(caster.calcHeading(targetX, targetY) + skill.getMoveHeading())); } } // иначе else { // рассчитываем направление setRadians(Angles.headingToRadians(caster.getHeading() + skill.getMoveHeading())); // применяем дистанцию setAlldist(moveDistance); // рассчитываем целевюу точку setTargetX(Coords.calcX(getStartX(), moveDistance, getRadians())); setTargetY(Coords.calcY(getStartY(), moveDistance, getRadians())); setTargetZ(geoManager.getHeight(caster.getContinentId(), getTargetX(), getTargetY(), getStartZ())); } // определяем, игнорирует ли барьеры ignore = skill.isIgnoreBarrier(); // определяем кол-во перемещений counter = Math.round(Math.max(1, (int) Math.sqrt(Math.abs(alldist)))); // определяем размер шага step = alldist / counter; // ставим флаг движения во время скила caster.setSkillMoved(true); // если идет учет препядствий, получаем их список if(!ignore || (skill != null && skill.isCastToMove())) World.getAroundBarriers(barriers, caster, skill.getMoveDistance() * 3); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // запускаем обработку schedule = executor.scheduleSkillMoveAtFixedRate(this, skill.isStaticCast()? skill.getMoveDelay() : formulas.castTime(skill.getMoveDelay(), caster), time / counter); } finally { lock.unlock(); } } /** * @return кастующий персонаж. */ public Character getCaster() { return caster; } @Override protected void runImpl() { // если закончили перемещаться, выходим if(counter < 1) { done(); return; } // получаем кастера Character caster = getCaster(); // уменьшаем счетчик counter -= 1; // получаем текущий обрабатываемый скил Skill skill = getSkill(); // если перемещение не игнорирует барьеры, проверяем на помехи if((!ignore || (skill != null && skill.isCastToMove())) && !caster.checkBarriers(barriers, (int) step + 1, radians)) { // если есть скил if(skill != null) { // если скил срабатывает при колизии if(skill.isCastToMove()) // активируем applySkill(); // если скил раш if(skill.isRush()) // отправляем пакет об столкновении caster.broadcastPacket(MoveSkill.getInstance(caster, caster)); // если кастер нпс if(caster.isBroadcastEndSkillForCollision()) // обрываем анимацию перемещения caster.broadcastPacket(S_Action_End.getInstance(caster, 0, skill.getIconId())); // если скил раш или кастер нпс if(skill.isRush() || caster.isBroadcastEndSkillForCollision()) // завершаем работу таска done(); } return; } // увеличиваем пройденное расстояние done += step; // смотрит результат float result = done / alldist; // если все прошли if(result >= 1F) { // завершаем работу таска done(); return; } // рассчитываем новые координаты float newX = startX + ((targetX - startX) * result); float newY = startY + ((targetY - startY) * result); float newZ = startZ + ((targetZ - startZ) * result); // смещаем caster.setXYZ(newX, newY, newZ); } /** * @param alldist задаваемое alldist */ public final void setAlldist(float alldist) { this.alldist = alldist; } /** * @param done задаваемое done */ public final void setDone(float done) { this.done = done; } /** * @param radians задаваемое radians */ public final void setRadians(float radians) { this.radians = radians; } /** * @param skill скил таска. */ public void setSkill(Skill skill) { this.skill = skill; } /** * @param startX задаваемое startX */ public final void setStartX(float startX) { this.startX = startX; } /** * @param startY задаваемое startY */ public final void setStartY(float startY) { this.startY = startY; } /** * @param startZ задаваемое startZ */ public final void setStartZ(float startZ) { this.startZ = startZ; } /** * @param targetX задаваемое targetX */ public final void setTargetX(float targetX) { this.targetX = targetX; } /** * @param targetY задаваемое targetY */ public final void setTargetY(float targetY) { this.targetY = targetY; } /** * @param targetZ задаваемое targetZ */ public final void setTargetZ(float targetZ) { this.targetZ = targetZ; } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionAddReward.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.Reward; /** * Акшен выдачи награды квеста. * * @author Ronn */ public class ActionAddReward extends AbstractQuestAction { public ActionAddReward(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); } @Override public void apply(QuestEvent event) { // если это нужный квест if(event.getQuest() == quest) { // получаем награду за квест Reward reward = quest.getReward(); // если ее нет, выходим if(reward == null) { log.warning(this, new Exception("not found reward")); return; } // выдаем награду reward.giveReward(event); } } } <file_sep>/java/game/tera/gameserver/model/regenerations/NpcRegenMp.java package tera.gameserver.model.regenerations; import tera.gameserver.model.Character; /** * Модель регенерации мп у НПС. * * @author Ronn * @created 11.04.2012 */ public class NpcRegenMp extends AbstractRegen<Character> { public NpcRegenMp(Character actor) { super(actor); } @Override public boolean checkCondition() { Character actor = getActor(); return actor.getCurrentMp() < actor.getMaxMp(); } @Override public void doRegen() { Character actor = getActor(); actor.setCurrentMp(actor.getCurrentMp() + actor.getRegenMp()); actor.updateMp(); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/TeleportPoints.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import tera.gameserver.model.TeleportRegion; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.model.territory.LocalTerritory; import tera.gameserver.network.ServerPacketType; import tera.util.Location; /** * Серверный пакет с доступными точками для телепорта. * * @author Ronn * @created 26.02.2012 */ public class TeleportPoints extends ServerPacket { private static final ServerPacket instance = new TeleportPoints(); public static TeleportPoints getInstance(Npc npc, Player player, TeleportRegion[] regions) { TeleportPoints packet = (TeleportPoints) instance.newInstance(); ByteBuffer buffer = packet.getPrepare(); try { packet.writeShort(buffer, regions.length);// 02 00 кол-во точек телепорта int bytes = 24; packet.writeShort(buffer, bytes);// 18 00 packet.writeFloat(buffer, npc.getX());// 00 29 83 47 packet.writeFloat(buffer, npc.getY());// 80 33 9B C7 packet.writeFloat(buffer, npc.getZ());// 00 B0 39 C5 packet.writeInt(buffer, 1);// 01 00 00 00 for(int i = 0, length = regions.length; i < length; i++) { TeleportRegion region = regions[i]; LocalTerritory local = region.getRegion(); Location loc = local.getTeleportLoc(); packet.writeShort(buffer, bytes);// 18 00 if(i == length -1) bytes = 0; else bytes += 29; packet.writeShort(buffer, bytes);// 35 00 packet.writeInt(buffer, region.getIndex());// индекс маршрута region.getIndex() packet.writeFloat(buffer, loc.getX());// 00 29 83 47 packet.writeFloat(buffer, loc.getY());// 80 33 9B C7 packet.writeFloat(buffer, loc.getZ());// 00 B0 39 C5 packet.writeInt(buffer, region.getPrice());// цена packet.writeInt(buffer, 0);// packet.writeByte(buffer, player.isWhetherIn(local)? 1 : 0); // можно ли использовать } return packet; } finally { buffer.flip(); } } private ByteBuffer prepare; public TeleportPoints() { this.prepare = ByteBuffer.allocate(1024).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.TELEPORT_POINTS; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); // получаем промежуточный буффер ByteBuffer prepare = getPrepare(); // переносим данные buffer.put(prepare.array(), 0, prepare.limit()); } /** * @return подготовленный буфер. */ public ByteBuffer getPrepare() { return prepare; } } <file_sep>/java/game/tera/gameserver/scripts/commands/NpcCommands.java package tera.gameserver.scripts.commands; import rlib.logging.Loggers; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.World; import tera.gameserver.model.ai.npc.NpcAIClass; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.IconType; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.npc.interaction.LinkType; import tera.gameserver.model.npc.interaction.links.NpcLink; import tera.gameserver.model.npc.spawn.NpcSpawn; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.*; import tera.gameserver.tables.ConfigAITable; import tera.gameserver.tables.NpcTable; import tera.gameserver.tables.SpawnTable; import tera.gameserver.templates.NpcTemplate; import tera.util.Location; /** * Список команд, для работы с нпс. * * @author Ronn */ public class NpcCommands extends AbstractCommand { /** * @param access * @param commands */ public NpcCommands(int access, String[] commands) { super(access, commands); } @Override public void execution(String command, Player player, String values) { SpawnTable spawnTable = SpawnTable.getInstance(); switch(command) { case "stop_spawns": spawnTable.stopSpawns(); break; case "start_spawns": spawnTable.startSpawns(); break; case "send_dialog": { Array<Link> array = Arrays.toArray(Link.class); int id = Integer.parseInt(values); for(int i = id, length = id + 10; i < length; i++) array.add(new NpcLink("@npc:" + i, LinkType.DIALOG, IconType.DIALOG, null)); player.sendPacket(S_Dialog.getInstance(null, player, array), true); break; } case "npc_cast": { int skillId = Integer.parseInt(values); Array<Npc> npcs = World.getAround(Npc.class, player, 300F); for(final Npc npc : npcs) { Skill skill = npc.getSkill(skillId); if(skill == null) continue; if(npc.isCastingNow()) npc.abortCast(true); npc.setTarget(player); npc.getAI().startCast(skill, npc.calcHeading(player.getX(), player.getY()), player.getX(), player.getY(), player.getZ()); } break; } case "around_npc_spawn": { Array<Npc> npcs = World.getAround(Npc.class, player, 100F); StringBuilder text = new StringBuilder("Spawns:"); for(Npc npc : npcs) { if(npc == null || !(npc.getSpawn() instanceof NpcSpawn)) continue; NpcSpawn spawn = (NpcSpawn) npc.getSpawn(); text.append(" [id = ").append(spawn.getTemplateId()).append(", ").append(spawn.getLocation()).append("], "); } if(text.length() > 7) { text.replace(text.length() - 2, text.length(), "."); player.sendMessage(text.toString()); } else player.sendMessage("no npcs."); break; } case "reload_spawns": { try { spawnTable.reload(); player.sendMessage("NPC spanws have been reloaded."); } catch(Exception e) { Loggers.warning(getClass(), e); } break; } case "around_npc_cast": { final int id = Integer.decode(values); Array<Npc> npcs = World.getAround(Npc.class, player, 150F); for(final Npc npc : npcs) { npc.broadcastPacket(S_Action_Stage.getInstance(npc, id, 1, 0)); player.sendMessage("cast " + id + " to " + npc); Runnable run = new Runnable() { @Override public void run() { npc.broadcastPacket(S_Action_End.getInstance(npc, 1, id)); } }; ExecutorManager executor = ExecutorManager.getInstance(); executor.scheduleGeneral(run, 1000); } break; } case "around_npc_long_cast": { final int id = Integer.parseInt(values); Array<Npc> npcs = World.getAround(Npc.class, player, 100F); for(final Npc npc : npcs) { npc.broadcastPacket(S_Action_Stage.getInstance(npc, id, 0, 0)); Runnable run = new Runnable() { @Override public void run() { npc.broadcastPacket(S_Action_End.getInstance(npc, 0, id)); } }; ExecutorManager executor = ExecutorManager.getInstance(); executor.scheduleGeneral(run, 4000); } break; } case "reload_npcs": { NpcTable npcTable = NpcTable.getInstance(); npcTable.reload(); player.sendMessage("NPCs have been reloaded."); break; } case "spawn": { String vals[] = values.split(" "); int id = Integer.parseInt(vals[0]); int type = Integer.parseInt(vals[1]); NpcTable npcTable = NpcTable.getInstance(); NpcTemplate template = npcTable.getTemplate(id, type); if(template == null) { player.sendMessage("Target NPC doesn't exist."); return; } String aiConfig = vals.length > 2 ? vals[2] : "DefaultMonster"; ConfigAITable configTable = ConfigAITable.getInstance(); NpcSpawn spawn = new NpcSpawn(null, null, template, player.getLoc(), 45, 0, 120, 0, configTable.getConfig(aiConfig), NpcAIClass.DEFAULT); int respawnTime = Integer.MAX_VALUE / 2000; spawn.setRespawnTime(respawnTime); spawn.start(); break; } case "go_to_npc": { String[] vals = values.split(" "); Location loc = spawnTable.getNpcSpawnLoc(Integer.parseInt(vals[0]), Integer.parseInt(vals[1])); if(loc != null) player.teleToLocation(loc); break; } case "around_npc": { try { Array<Npc> npcs = World.getAround(Npc.class, player, 150F); StringBuilder text = new StringBuilder("Npcs:"); for(Npc npc : npcs) { if(npc == null) continue; text.append(" id = ").append(npc.getTemplateId()).append(", type = ").append(npc.getTemplateType()).append(", objectId = ").append(npc.getObjectId()).append(", "); // text.append(" id = ").append(npc.getNpcId()).append(npc.getSpawnLoc()); npc.broadcastPacket(S_Npc_Status.getInstance(player, npc, 1)); } if(text.length() > 5) { text.replace(text.length() - 2, text.length(), "."); player.sendMessage(text.toString()); } else player.sendMessage("no npcs."); } catch(Exception e) { Loggers.warning(getClass(), "error " + command + " vals " + values + " " + e.getMessage()); } break; } } } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Request_Guild_Info_Before_Apply_Guild.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Request_Guild_Info_Before_Apply_Guild extends ServerPacket { private static final ServerPacket instance = new S_Request_Guild_Info_Before_Apply_Guild(); private String guildName; public static S_Request_Guild_Info_Before_Apply_Guild getInstance(String guildName) { S_Request_Guild_Info_Before_Apply_Guild packet = (S_Request_Guild_Info_Before_Apply_Guild) instance.newInstance(); packet.guildName = guildName; return packet; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_REQUEST_GUILD_INFO_BEFORE_APPLY_GUILD; } @Override protected final void writeImpl() { writeOpcode(); writeShort(11); writeInt(0); writeByte(1); writeString(guildName); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/MoveSkill.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет уведомляющий о старте бегущего скила * * @author Ronn * @created 31.03.2012 */ public class MoveSkill extends ServerPacket { private static final ServerPacket instance = new MoveSkill(); public static MoveSkill getInstance(Character caster, Character target) { MoveSkill packet = (MoveSkill) instance.newInstance(); packet.caster = caster; packet.target = target; return packet; } public static MoveSkill getInstance(Character caster, float targetX, float targetY, float targetZ) { MoveSkill packet = (MoveSkill) instance.newInstance(); packet.caster = caster; packet.targetX = targetX; packet.targetY = targetY; packet.targetZ = targetZ; return packet; } /** тот кто кастует */ private Character caster; /** цели атакующего */ private Character target; /** целевая точка перемещения */ private float targetX; private float targetY; private float targetZ; @Override public void finalyze() { caster = null; target = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.SKILL_MOVE; } @Override protected final void writeImpl() { writeOpcode(); if(target != null) { writeInt(caster.getObjectId()); writeInt(caster.getSubId()); writeInt(target.getObjectId()); writeInt(target.getSubId()); writeFloat(target.getX()); writeFloat(target.getY()); writeFloat(target.getZ()); writeShort(caster.calcHeading(caster == target? caster.getHeading() : target.getX(), target.getY()));//FD4 A0 } else { writeInt(caster.getObjectId()); writeInt(caster.getSubId()); writeInt(0); writeInt(0); writeFloat(targetX); writeFloat(targetY); writeFloat(targetZ); writeShort(caster.calcHeading(targetX, targetY));//FD4 A0 } } }<file_sep>/java/game/tera/gameserver/network/serverpackets/ActionDialogCancel.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет закрытия диалога акшена. * * @author Ronn */ public class ActionDialogCancel extends ServerPacket { private static final ServerPacket instance = new ActionDialogCancel(); /** * @param actor инициатор диалога. * @param enemy опонент инициатора. * @param id ид диалога. * @param objectId обджект ид диалога. */ public static ActionDialogCancel getInstance(Player actor, Player enemy, int id, int objectId) { ActionDialogCancel packet = (ActionDialogCancel) instance.newInstance(); packet.actorId = actor.getObjectId(); packet.actorSubId = actor.getSubId(); packet.enemyId = enemy.getObjectId(); packet.enemySubId = enemy.getSubId(); packet.id = id; packet.objectId = objectId; return packet; } /** ид инициатора */ private int actorId; /** саб ид инициатора */ private int actorSubId; /** ид опонента */ private int enemyId; /** саб ид опонента */ private int enemySubId; /** ид акшена */ private int id; /** обджект ид акшена */ private int objectId; @Override public ServerPacketType getPacketType() { return ServerPacketType.CLOSE_TRADE; } @Override protected void writeImpl() { writeOpcode(); writeInt(actorId);//BD 07 00 10 обжект ид 1го writeInt(actorSubId);//00 80 00 13 саб ид writeInt(enemyId);//C7 07 00 10 обжект ид 2го writeInt(enemySubId);//00 80 00 13 саб ид writeInt(id);//03 00 00 00 ид экшена writeInt(objectId);//93 EE 06 00 обжект ид экшена } } <file_sep>/java/game/tera/gameserver/model/base/PlayerGeomTable.java package tera.gameserver.model.base; /** * Таблицп размеров моделей игроков. * * @author Ronn * @created 20.03.2012 */ public abstract class PlayerGeomTable { /** таблица роста */ private static final float[][] tableHeight = { //HUMAN {45F, 45F}, //ELF {45F, 45F}, //AMAN {50F, 50F}, //CASTANIC {45F, 45F}, //POPORI {33F, 33F}, //BARAKA {55F, 55F}, }; /** таблица ширины */ private static final float[][] tableRadius = { //HUMAN {10F, 10F}, //ELF {10F, 10F}, //AMAN {15F, 10F}, //CASTANIC {10F, 10F}, //POPORI {13F, 8F}, //BARAKA {20F, 20F}, }; /** * Высота модели указанной расы и пола. * * @param race ид расы. * @param sex пол. * @return высота. */ public static float getHeight(int race, int sex) { return tableHeight[race][sex]; } /** * Радиус модели указанной расы и пола. * * @param race ид расы. * @param sex пол. * @return радиус. */ public static float getRadius(int race, int sex) { return tableRadius[race][sex]; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/MultiShop.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; import tera.gameserver.templates.ItemTemplate; /** * Серверный пакет с содержанием мультиселла. * * @author Ronn */ public class MultiShop extends ServerPacket { private static final ServerPacket instance = new MultiShop(); public static MultiShop getInstance(Player player, ItemTemplate[] items, int[] price, int priceId) { MultiShop packet = (MultiShop) instance.newInstance(); ByteBuffer buffer = packet.prepare; packet.writeShort(buffer, 2);// 02 00 int bytes = 32; packet.writeShort(buffer, 32);// 20 00 packet.writeInt(buffer, player.getObjectId());// 51 63 0D 00 packet.writeInt(buffer, player.getSubId());// 00 80 00 01 packet.writeInt(buffer, 923335);// C7 16 0E 00 packet.writeInt(buffer, 154);// 9A 00 00 00 кол-во итемов в магазине packet.writeInt(buffer, 0);// 00 00 00 00 packet.writeInt(buffer, 25);// 19 00 00 00 Ид итемов за которые будет всё покупаться packet.writeShort(buffer, bytes);// 20 00 packet.writeInt(buffer, 8390188);// хз что это 2C 06 80 00 bytes += 12; packet.writeShort(buffer, bytes);// 2C 00 packet.writeInt(buffer, 1541);// 05 06 00 00 int last = items.length - 1; for(int i = 0, length = items.length; i < length; i++) { packet.writeShort(buffer, bytes);// 2C 00 if(i == last) bytes = 0; else bytes += 12;// если последний нуллим packet.writeShort(buffer, bytes);// 38 00 packet.writeInt(buffer, items[i].getItemId());// B9 2D 00 00 Ид packet.writeInt(buffer, price[i]);// 05 00 00 00 цена в итемах } return packet; } /** подготовленный буффер */ private ByteBuffer prepare; public MultiShop() { super(); this.prepare = ByteBuffer.allocate(16384).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.MULTI_SHOP; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); prepare.flip(); buffer.put(prepare); //System.out.println(Util.hexdump(buffer.array(), buffer.position())); } } <file_sep>/java/game/tera/gameserver/model/skillengine/Calculator.java package tera.gameserver.model.skillengine; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.funcs.StatFunc; /** * Модель рассчет статовперсонажей. * * @author Ronn */ public final class Calculator { /** список функций */ private Array<StatFunc> funcs; public Calculator() { this.funcs = Arrays.toSortedArray(StatFunc.class, 1); } /** * Добавить функцию в калькулятор. * * @param func добавляемая функция. */ public void addFunc(StatFunc func) { funcs.add(func); } /** * Процесс расчета значения стата у персонажа. * * @param attacker тот, у кого находится эта функция. * @param attacked целевой персонаж. * @param skill кастуемый скил. * @param value базовое значение. * @return конечное значение. */ public float calc(Character attacker, Character attacked, Skill skill, float value) { StatFunc[] array = funcs.array(); for(int i = 0, length = funcs.size(); i < length; i++) value = array[i].calc(attacker, attacked, skill, value); return value; } /** * Процесс расчета значения стата у персонажа. * * @param attacker тот, у кого находится эта функция. * @param attacked целевой персонаж. * @param skill кастуемый скил. * @param value базовое значение. * @param order максимальный ордер для функции. * @return конечное значение. */ public float calcToOrder(Character attacker, Character attacked, Skill skill, float value, int order) { StatFunc[] array = funcs.array(); for(int i = 0, length = funcs.size(); i < length; i++) { StatFunc func = array[i]; if(func.getOrder() > order) break; value = func.calc(attacker, attacked, skill, value); } return value; } /** * @return список функций. */ public Array<StatFunc> getFuncs() { return funcs; } /** * @return есть ли фукции в калькуляторе. */ public boolean isEmpty() { return funcs.isEmpty(); } /** * Удалить функцию с калькулятора. * * @param func удаляемая функция. */ public void removeFunc(StatFunc func) { funcs.slowRemove(func); } /** * @param funcs список функций. */ public void setFuncs(Array<StatFunc> funcs) { this.funcs = funcs; } /** * @return size кол-во функций. */ public int size() { return funcs.size(); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Spawn_Npc.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; import tera.gameserver.templates.NpcTemplate; /** * Серверный пакет с информацией об НПС. * * @author Ronn */ public class S_Spawn_Npc extends ServerPacket { private static final ServerPacket instance = new S_Spawn_Npc(); public static S_Spawn_Npc getInstance(Npc npc, Player player) { S_Spawn_Npc packet = (S_Spawn_Npc) instance.newInstance(); packet.objectId = npc.getObjectId(); packet.subId = npc.getSubId(); packet.x = npc.getX(); packet.y = npc.getY(); packet.z = npc.getZ(); // получаеим темплейт НПС NpcTemplate template = npc.getTemplate(); packet.heading = npc.getHeading(); packet.npcId = template.getIconId(); packet.npcType = npc.getTemplateType(); packet.spawned = npc.isSpawned()? 1 : 0; packet.isFriend = npc.isFriend(player)? 1 : 0; return packet; } /** обджект ид нпс */ private int objectId; /** саб ид нпс */ private int subId; /** координаты нпс */ private float x; private float y; private float z; /** разворот нпс */ private int heading; /** ид нпс */ private int npcId; /** тип нпс */ private int npcType; /** дружественный ли */ private int isFriend; /** отспавнен ли уже нпс */ private int spawned; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SPAWN_NPC; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 0);//00 00 00 00 8 writeShort(buffer, 114);// 6D 00 10 writeInt(buffer, objectId);// A3 D4 0C 00 обжект ид 14 writeInt(buffer, subId);// 00 80 0B 00 саб ид 18 writeLong(buffer, 0);//target writeFloat(buffer, x);// FC 90 A6 47 x 30 writeFloat(buffer, y);// 1F 16 A5 C7 y 34 writeFloat(buffer, z);// 00 00 94 C5 z 38 writeShort(buffer, heading);// 10 17 heading 40 writeInt(buffer, 12);//relation writeInt(buffer, npcId);// templateId writeShort(buffer, npcType);//Hunting zone id writeShort(buffer, 60);// walk speed writeShort(buffer, 110);// run speed writeShort(buffer, 0);//status writeShort(buffer, 0);//mode writeShort(buffer, 5);//hp level writeShort(buffer, 0);//questinfo writeByte(buffer, 1);//visible writeByte(buffer, isFriend);//is villager writeInt(buffer, spawned); writeLong(buffer, 0); writeInt(buffer, 0); writeInt(buffer, 0); writeByte(buffer, 0);//aggressive writeLong(buffer,0); writeLong(buffer,0); writeLong(buffer,0); writeInt(buffer,0); writeByte(buffer,0); writeString(buffer, "");//npcname } } <file_sep>/java/game/tera/gameserver/model/items/ItemLocation.java package tera.gameserver.model.items; /** * Перечисление видов расположения итема. * * @author Ronn */ public enum ItemLocation { INVENTORY, EQUIPMENT, BANK, GUILD_BANK, CRYSTAL, NONE; public static final ItemLocation[] VALUES = values(); public static ItemLocation valueOf(int index) { return VALUES[index]; } } <file_sep>/java/game/tera/gameserver/network/crypt/CryptorState.java package tera.gameserver.network.crypt; /** * Перечисление состояний криптора. * * @author Ronn */ public enum CryptorState { /** в ожидании первого клиент ключа */ WAIT_FIRST_CLIENT_KEY, /** в ожидании первого серверного ключа */ WAIT_FIRST_SERVER_KEY, /** в ожидании второго клиент ключа */ WAIT_SECOND_CLIENT_KEY, /** в ожидании второго серверного ключа */ WAIT_SECOND_SERCER_KEY, /** подготовлен */ PREPARED, /** готов к работе */ READY_TO_WORK; } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestDuelCancel.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.Duel; import tera.gameserver.model.playable.Player; /** * Отмена дуэли. * * @author Ronn */ public class RequestDuelCancel extends ClientPacket { /** игрок */ private Player player; @Override public void finalyze() { player = null; } @Override protected void readImpl() { player = owner.getOwner(); } @Override protected void runImpl() { if(player == null) return; // получаем дуль игрока Duel duel = player.getDuel(); // если такая есть if(duel != null) // отменяем duel.cancel(true, false); } } <file_sep>/java/game/tera/gameserver/model/ai/npc/thinkaction/NoWaitAction.java package tera.gameserver.model.ai.npc.thinkaction; import org.w3c.dom.Node; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.util.LocalObjects; /** * Пустой генератор действий в режиме ожидания. * * @author Ronn */ public class NoWaitAction extends AbstractThinkAction { public NoWaitAction(Node node) { super(node); } @Override public <A extends Npc> void startAITask(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime){} @Override public <A extends Npc> void think(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime){} } <file_sep>/java/game/tera/gameserver/model/ai/npc/TaskType.java package tera.gameserver.model.ai.npc; /** * Типы заданий для АИ * @author Ronn */ public enum TaskType { /** движение c обновлением разворота */ MOVE_UPDATE_HEADING, /** движение без обновления разворота */ MOVE_NOT_UPDATE_HEADING, /** движение для каста скила */ MOVE_ON_CAST, /** каст скила */ CAST, /** каст с применением указанного направления */ CAST_ON_HEADING, /** наблюдение */ NOTICE, /** ускоренный фокус */ NOTICE_FAST, } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Visit_New_Section.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Пакет ответа на запрос проверки сервера * * @author Ronn * @created 25.03.2012 */ public class S_Visit_New_Section extends ServerPacket { private static final ServerPacket instance = new S_Visit_New_Section(); public static S_Visit_New_Section getInstance(int[] vals) { S_Visit_New_Section packet = (S_Visit_New_Section) instance.newInstance(); packet.vals[0] = vals[0]; packet.vals[1] = vals[1]; packet.vals[2] = vals[2]; return packet; } /** индекс подтверждения */ private int[] vals; public S_Visit_New_Section() { this.vals = new int[3]; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_VISIT_NEW_SECTION; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeByte(buffer, 0);//00 writeInt(buffer, vals[0]);//01 00 00 00 число 1 writeInt(buffer, vals[1]);//05 00 00 00 число 2 writeInt(buffer, vals[2]);//2C 00 00 00 число 3 } }<file_sep>/java/game/tera/gameserver/model/npc/interaction/conditions/ConditionPlayerHeart.java package tera.gameserver.model.npc.interaction.conditions; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; /** * Проверка на уровень стамины. * * @author Ronn */ public class ConditionPlayerHeart extends AbstractCondition { /** нужное кол-во стамины */ private int heart; public ConditionPlayerHeart(Quest quest, int heart) { super(quest); this.heart = heart; } @Override public boolean test(Npc npc, Player player) { if(player == null) return false; return player.getStamina() >= heart; } @Override public String toString() { return "ConditionPlayerHeart heart = " + heart; } } <file_sep>/java/game/tera/gameserver/model/quests/QuestEventType.java package tera.gameserver.model.quests; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.w3c.dom.Node; import rlib.logging.Loggers; import tera.gameserver.model.quests.events.AcceptedQuestListener; import tera.gameserver.model.quests.events.AddNpcListener; import tera.gameserver.model.quests.events.CanceledQuestListener; import tera.gameserver.model.quests.events.CollectResourseListener; import tera.gameserver.model.quests.events.EmptyListener; import tera.gameserver.model.quests.events.FinishedQuestListener; import tera.gameserver.model.quests.events.InventoryAddItemListener; import tera.gameserver.model.quests.events.InventoryRemoveItemListener; import tera.gameserver.model.quests.events.KillNpcListener; import tera.gameserver.model.quests.events.LinkSelectListener; import tera.gameserver.model.quests.events.PickUpItemListener; import tera.gameserver.model.quests.events.QuestMovieListener; import tera.gameserver.model.quests.events.SkillLearnListener; import tera.gameserver.model.quests.events.UseItemListener; /** * Перечисление типов ивентов. * * @author Ronn */ public enum QuestEventType { /** завершение квеста */ FINISHED_QUEST(FinishedQuestListener.class), /** взятие квеста */ ACCEPTED_QUEST(AcceptedQuestListener.class), /** отмена квеста */ CANCELED_QUEST(CanceledQuestListener.class), /** окончания просмотра мувика */ QUEST_MOVIE_ENDED(QuestMovieListener.class), /** убийство моба */ KILL_NPC(KillNpcListener.class), /** сбор ресурса */ COLLECT_RESOURSE(CollectResourseListener.class), /** изменение стамины */ CHANGED_HEART(EmptyListener.class), /** использование итема */ USE_ITEM(UseItemListener.class), /** нажатие на кнопку */ SELECT_BUTTON(LinkSelectListener.class), /** слушатель поднятий итемов */ PICK_UP_ITEM(PickUpItemListener.class), /** слушатель добавлений в инвентарь */ INVENTORY_ADD_ITEM(InventoryAddItemListener.class), /** слушатель удаление из инвенторя */ INVENTORY_REMOVE_ITEM(InventoryRemoveItemListener.class), /** вход игрока в мир */ PLAYER_SPAWN(EmptyListener.class), /** добовление отображения нпс игроку */ ADD_NPC(AddNpcListener.class), /** событие изучение скила игроком */ SKILL_LEARNED(SkillLearnListener.class), /** событие нажатия на ссылку */ SELECT_LINK(LinkSelectListener.class); /** конструктор квеста */ private Constructor<? extends QuestEventListener> constructor; /** * @param eventClass класс обработчик ивента. */ private QuestEventType(Class<? extends QuestEventListener> eventClass) { try { constructor = eventClass.getConstructor(getClass(), QuestAction[].class, Quest.class, Node.class); } catch(NoSuchMethodException | SecurityException e) { Loggers.warning(this, e); throw new IllegalArgumentException(); } } /** * Создание нового слушателя под указанный квест. * * @param quest целевой квест. * @param actions набор акшенов ивента. * @param node набор параметров с хмл. * @return новый слушатель. */ public QuestEventListener newInstance(Quest quest, QuestAction[] actions, Node node) { try { return constructor.newInstance(this, actions, quest, node); } catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { return null; } } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Union_Summary.java package tera.gameserver.network.serverpackets; import rlib.util.Strings; import tera.gameserver.manager.AllianceManager; import tera.gameserver.model.Alliance; import tera.gameserver.network.ServerPacketType; import java.nio.ByteBuffer; public class S_Union_Summary extends ServerPacket { private static final ServerPacket instance = new S_Union_Summary(); public static S_Union_Summary getInstance(){ S_Union_Summary packet = (S_Union_Summary) instance.newInstance(); return packet; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_UNION_SUMMARY; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer){ String[] names = new String[3]; names[0] = "Lancer1"; names[1] = "Lancer2"; names[2] = "Lancer3"; int[] unk1 = new int[3]; unk1[0] = 1249; unk1[1] = 2827; unk1[2] = 1542; int[] bonuses = new int[3]; bonuses[0] = 10; bonuses[1] = 62; bonuses[2] = 27; int[] strength = new int[3]; strength[0] = 2; strength[1] = 11; strength[2] = 7; writeOpcode(buffer); writeShort(buffer, 3);//nbr of union writeShort(buffer, 12); writeInt(buffer, 0); int pos = 12; for(int i = 0; i < 3; i++) { Alliance alliance = AllianceManager.getInstance().getAlliance(i+1); int namePos = pos + 53; writeShort(buffer, pos);//current pos pos = 67 * (i+1) + Strings.length(alliance.getLeaderName()); if(i == 1) pos += 2; if(i == 2) writeShort(buffer, 0); else writeShort(buffer, pos);//next writeShort(buffer, namePos); writeShort(buffer, namePos + Strings.length(alliance.getLeaderName())); writeInt(buffer, i+1); writeInt(buffer, alliance.getStrength()); writeInt(buffer, alliance.getTaxRate());//tax rate if(i == 2) writeByte(buffer, 1);//vault access else writeByte(buffer, 0); writeInt(buffer, alliance.getBonus()); writeInt(buffer, 0);//bonuses activation time writeInt(buffer, unk1[i]);//E1 04 writeInt(buffer, 0);//previous exarch number writeLong(buffer, 0); writeByte(buffer, 0); writeInt(buffer, 168750);// 2E 93 02 00 writeShort(buffer, 0); writeByte(buffer,0); writeString(buffer, alliance.getLeaderName()); writeShort(buffer, 0); } } } <file_sep>/java/game/tera/gameserver/templates/ArmorTemplate.java package tera.gameserver.templates; import rlib.util.VarTable; import tera.gameserver.model.items.ArmorKind; import tera.gameserver.model.items.ArmorType; import tera.gameserver.model.playable.Player; /** * Модель шаблона брони и бижутерии. * * @author Ronn */ public final class ArmorTemplate extends GearedTemplate { /** тип брони */ protected ArmorKind armorKind; public ArmorTemplate(ArmorType type, VarTable vars) { super(type, vars); try { armorKind = ArmorKind.valueOfXml(vars.getString("kind", "other")); slotType = type.getSlot(); } catch(Exception e) { e.printStackTrace(); throw e; } } @Override public boolean checkClass(Player player) { return armorKind.checkClass(player); } /** * @return тип материала брони. */ public final ArmorKind getArmorKind() { return armorKind; } @Override public ArmorType getType() { return (ArmorType) type; } @Override public String toString() { return "ArmorTemplate armorKind = " + armorKind + ", requiredLevel = " + requiredLevel + ", attack = " + attack + ", impact = " + impact + ", defence = " + defence + ", balance = " + balance + ", sockets = " + sockets + ", extractable = " + extractable + ", enchantable = " + enchantable + ", remodelable = " + remodelable + ", dyeable = " + dyeable + ", bindType = " + bindType + ", name = " + name + ", itemId = " + itemId + ", itemLevel = " + itemLevel + ", buyPrice = " + buyPrice + ", sellPrice = " + sellPrice + ", slotType = " + slotType + ", rank = " + rank + ", itemClass = " + itemClass + ", stackable = " + stackable + ", sellable = " + sellable + ", bank = " + bank + ", guildBank = " + guildBank + ", tradable = " + tradable + ", deletable = " + deletable + ", type = " + type; } } <file_sep>/java/game/tera/gameserver/model/ReuseSkill.java package tera.gameserver.model; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; /** * Модель отката скилов. * * @author Ronn */ public final class ReuseSkill implements Foldable { private static final FoldablePool<ReuseSkill> pool = Pools.newConcurrentFoldablePool(ReuseSkill.class); /** * Срздает новый экземпляр отката скила. * * @param skillId ид откатываемого скила. * @param reuse время отката скила. * @return новый откат скила. */ public static final ReuseSkill newInstance(int skillId, long reuse) { ReuseSkill reuseSkill = pool.take(); if(reuseSkill == null) reuseSkill = new ReuseSkill(); reuseSkill.skillId = skillId; reuseSkill.endTime = System.currentTimeMillis() + reuse; return reuseSkill; } /** скил ид */ private int skillId; /** ид итема */ private int itemId; /** время окончания реюза */ private long endTime; @Override public void finalyze() { itemId = 0; skillId = 0; endTime = 0; } /** * Сложить в пул. */ public void fold() { pool.put(this); } /** * @return возвращает кол-во милисек оставшихся для отката скила. */ public long getCurrentDelay() { long rest = endTime - System.currentTimeMillis(); if(rest > 0) return rest; return 0; } /** * @return время окончания отката. */ public long getEndTime() { return endTime; } /** * @return ид откатываемого итема. */ public int getItemId() { return itemId; } /** * @return ид откатываемого скила. */ public int getSkillId() { return skillId; } /** * @return является ли откат откатом итема. */ public boolean isItemReuse() { return itemId > 0; } /** * @return откатился ли уже скил. */ public boolean isUse() { return System.currentTimeMillis() < endTime; } @Override public void reinit(){} /** * @param endTime дата завершения отката скила. */ public void setEndTime(long endTime) { this.endTime = endTime; } /** * @param itemId ид откатываемого итема. */ public ReuseSkill setItemId(int itemId) { this.itemId = itemId; return this; } /** * @param skillId ид откатываемого скила. */ public void setSkillId(int skillId) { this.skillId = skillId; } @Override public String toString() { return "ReuseSkill skillId = " + skillId + ", itemId = " + itemId + ", endTime = " + endTime; } } <file_sep>/java/game/tera/gameserver/model/regenerations/PlayerRegenFatigability.java package tera.gameserver.model.regenerations; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.Account; import tera.gameserver.model.playable.Player; import java.util.Date; import java.util.concurrent.TimeUnit; public class PlayerRegenFatigability extends AbstractRegen<Player> { public PlayerRegenFatigability(Player actor) { super(actor); } private Account account; @Override public boolean checkCondition() { account = getActor().getAccount(); if(account == null) { return false; } long diff = Math.abs((new Date()).getTime() - account.getLastFatigabilityCheck().getTime()); return (account != null && account.getFatigability() < 4000 && TimeUnit.MILLISECONDS.toMinutes(diff) >= 5); } @Override public void doRegen() { account.setFatigability(account.getFatigability() + 5); account.setLastFatigabilityCheck(new Date()); ObjectEventManager eventManager = ObjectEventManager.getInstance(); // обновляем отображение хп eventManager.notifyFatigabilityChanged(getActor()); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/Leash.java package tera.gameserver.model.skillengine.classes; import rlib.geom.Coords; import rlib.util.Rnd; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.MoveType; import tera.gameserver.network.serverpackets.SkillLeash; import tera.gameserver.network.serverpackets.S_Action_Stage; import tera.gameserver.templates.SkillTemplate; /** * @author Ronn */ public class Leash extends Strike { public Leash(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { AttackInfo info = super.applySkill(attacker, target); if(!info.isBlocked() && !target.isLeashImmunity()) { boolean result = Rnd.chance(80); if(result) { target.stopMove(); target.abortCast(true); int distance = (int) (attacker.getGeomRadius() + target.getGeomRadius()); float newX = Coords.calcX(attacker.getX(), distance, attacker.getHeading()); float newY = Coords.calcY(attacker.getY(), distance, attacker.getHeading()); target.setXYZ(newX, newY, attacker.getZ()); target.broadcastMove(target.getX(), target.getY(), target.getZ(), target.getHeading(), MoveType.STOP, target.getX(), target.getY(), target.getZ(), true); } attacker.broadcastPacket(SkillLeash.getInstance(attacker.getObjectId(), attacker.getSubId(), target.getObjectId(), target.getSubId(), result)); } return info; } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { super.useSkill(character, targetX, targetY, targetZ); character.broadcastPacket(S_Action_Stage.getInstance(character, template.getIconId(), castId, 1)); } } <file_sep>/java/game/tera/gameserver/model/quests/events/SkillLearnListener.java package tera.gameserver.model.quests.events; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestAction; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestEventType; /** * Прослушка изучения скилов. * * @author Ronn */ public class SkillLearnListener extends AbstractQuestEventListener { /** целевой скил */ private int skillId; public SkillLearnListener(QuestEventType type, QuestAction[] actions, Quest quest, Node node) { super(type, actions, quest, node); try { VarTable vars = VarTable.newInstance(node); this.skillId = vars.getInteger("skillId", 0); } catch(Exception e) { log.warning(this, e); } } @Override public void notifyQuest(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // если его нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } if(skillId == 0 || skillId == event.getValue()) super.notifyQuest(event); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestActionDialogCancel.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.actions.dialogs.ActionDialog; import tera.gameserver.model.playable.Player; /** * Клиентский пакет с отменой приглашения на акшен * * @author Ronn * @created 07.03.2012 */ public class RequestActionDialogCancel extends ClientPacket { /** потвердивший игрок */ private Player player; @Override protected void readImpl() { player = owner.getOwner(); } @Override protected void runImpl() { ActionDialog dialog = player.getLastActionDialog(); if(dialog != null) dialog.cancel(player); } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/replyes/ReplyHeroPointToGold.java package tera.gameserver.model.npc.interaction.replyes; import org.w3c.dom.Node; import tera.Config; import tera.gameserver.events.EventConstant; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.playable.Player; /** * Модель для перевода очков славы в деньги. * * @author Ronn */ public class ReplyHeroPointToGold extends AbstractReply { public ReplyHeroPointToGold(Node node) { super(node); } @Override public void reply(Npc npc, Player player, Link link) { synchronized(player) { // получаем текущее кол-во очков int points = player.getVar(EventConstant.VAR_NANE_HERO_POINT, 0); // если их нет, выходим if(points < 1) { player.sendMessage("You don't have Fame points."); return; } // забираем 1 очко player.setVar(EventConstant.VAR_NANE_HERO_POINT, points - 1); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // на всякий случай сохраняем в БД dbManager.updatePlayerVar(player.getObjectId(), EventConstant.VAR_NANE_HERO_POINT, String.valueOf(points - 1)); } // рассчитываем итоговое кол-во денег int reward = (int) (1 * Config.EVENT_HERO_POINT_TO_GOLD * Config.SERVER_RATE_MONEY); // если награды нет, выходим if(reward < 1) return; // получаем инвентарь Inventory inventory = player.getInventory(); // выдаем деньги inventory.addMoney(reward); // отображаем выдачу денег PacketManager.showAddGold(player, reward); } } <file_sep>/java/game/tera/gameserver/model/traps/Trap.java package tera.gameserver.model.traps; import java.util.concurrent.ScheduledFuture; import rlib.geom.Coords; import rlib.util.array.Array; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.Config; import tera.gameserver.IdFactory; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Character; import tera.gameserver.model.TObject; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.CharObjectDelete; import tera.gameserver.network.serverpackets.TrapInfo; import tera.util.LocalObjects; /** * Модель ловушки в тере. * * @author Ronn */ public class Trap extends TObject implements Foldable, Runnable { private static final FoldablePool<Trap> pool = Pools.newConcurrentFoldablePool(Trap.class); /** * Создание новой ловукши. * * @param owner создатель и владелец. * @param skill скил, который создает. * @param lifeTime время жизни. * @param radius ражиус активации. * @return новая ловука. */ public static Trap newInstance(Character owner, Skill skill, int range, int lifeTime, int radius) { Trap trap = pool.take(); if(trap == null) { IdFactory idFactory = IdFactory.getInstance(); trap = new Trap(idFactory.getNextTrapId()); } trap.setContinentId(owner.getContinentId()); trap.spawnMe(owner, skill, range, lifeTime, radius); return trap; } /** владелец ловушки */ protected Character owner; /** атакующий скил */ protected Skill skill; /** время жизни */ protected ScheduledFuture<? extends Runnable> lifeTask; /** радиус активации */ protected int radius; public Trap(int objectId) { super(objectId); } /** * Обработка активации ловушки. * * @param object объект, который изменил свое положение. */ public boolean activate(TObject object) { if(!object.isCharacter()) return false; Character owner = getOwner(); Character target = object.getCharacter(); if(owner == null || owner == target || !owner.checkTarget(target)) { return false; } float dist = target.getGeomDistance(x, y); if(dist > radius) { return false; } if(lifeTask != null) { lifeTask.cancel(false); lifeTask = null; } ExecutorManager executor = ExecutorManager.getInstance(); executor.scheduleGeneral(this, 100); return true; } @Override public void addMe(Player player) { player.sendPacket(TrapInfo.getInstance(this), true); } @Override public synchronized void deleteMe() { if(deleted) { return; } super.deleteMe(); fold(); } @Override public void finalyze() { this.owner = null; this.skill = null; this.lifeTask = null; } /** * Складировать. */ public void fold() { pool.put(this); } /** * @return владелец ловушки. */ public Character getOwner() { return owner; } /** * @return атакующий скил. */ public Skill getSkill() { return skill; } @Override public int getSubId() { return Config.SERVER_TRAP_SUB_ID; } /** * @return ид темплейта ловушки. */ @Override public int getTemplateId() { return skill != null ? skill.getIconId() : 0; } @Override public Trap getTrap() { return this; } @Override public boolean isTrap() { return true; } @Override public void reinit() { IdFactory idFactory = IdFactory.getInstance(); this.objectId = idFactory.getNextTrapId(); } @Override public void removeMe(Player player, int type) { player.sendPacket(CharObjectDelete.getInstance(this), true); } @Override public void run() { Skill skill = getSkill(); if(skill != null && lifeTask == null) skill.useSkill(owner, x, y, z); deleteMe(); } /** * Спавн в мир ловушку. * * @param owner владелец. * @param skill скил ловушки. * @param lifeTime время жизни. * @param radius радиус активации. */ public void spawnMe(Character owner, Skill skill, int range, int lifeTime, int radius) { this.owner = owner; this.skill = skill; this.radius = radius; spawnMe(Coords.calcX(owner.getX(), range, owner.getHeading()), Coords.calcY(owner.getY(), range, owner.getHeading()), owner.getZ(), 0); LocalObjects local = LocalObjects.get(); Array<Character> chars = World.getAround(Character.class, local.getNextCharList(), this, radius); ExecutorManager executor = ExecutorManager.getInstance(); if(chars.isEmpty()) this.lifeTask = executor.scheduleGeneral(this, lifeTime * 1000); else { Character[] array = chars.array(); for(int i = 0, length = chars.size(); i < length; i++) { Character target = array[i]; if(owner.checkTarget(target)) { executor.scheduleGeneral(this, 100); return; } } this.lifeTask = executor.scheduleGeneral(this, lifeTime * 1000); } } } <file_sep>/java/game/tera/gameserver/events/global/regionwars/RegionWars.java package tera.gameserver.events.global.regionwars; import java.io.File; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.Config; import tera.gameserver.document.DocumentRegionWar; import tera.gameserver.events.EventType; import tera.gameserver.events.global.AbstractGlobalEvent; import tera.gameserver.model.Guild; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.playable.Player; /** * Модель ивента битв за территорию. * * @author Ronn */ public class RegionWars extends AbstractGlobalEvent { public static final String BATTLE_POINT = "region_war_battle_point"; public static final int REWARD_INTERVAL = 300000; private static final String EVENT_NANE = "Region Wars"; /** все зарегестрированные гильдии */ private final Array<Guild> registerGuilds; /** все гильдии владельцы */ private final Array<Guild> ownerGuilds; /** список учавствующих регионов */ private Region[] regions; public RegionWars() { this.registerGuilds = Arrays.toConcurrentArraySet(Guild.class); this.ownerGuilds = Arrays.toConcurrentArraySet(Guild.class); } @Override public void addLinks(Array<Link> links, Npc npc, Player player) { // получаем все зарегестрированные региона Region[] regions = getRegions(); // спрашиваем у всех доступные ссылки for(int i = 0, length = regions.length; i < length; i++) regions[i].addLinks(links, npc, player); } /** * Добавления гильдии в список владеющих регионом. * * @param guild владелющая регионом гильдия. */ public void addOwnerGuild(Guild guild) { ownerGuilds.add(guild); } /** * Добавление в зарегестрированные гильдии на битву за регион. * * @param guild регистрируемая гильдия. */ public void addRegisterGuild(Guild guild) { // получаем список зарегестрированных гильдий Array<Guild> registerGuilds = getRegisterGuilds(); // если такая гильдия еще не внесена if(!registerGuilds.contains(guild)) // вносим registerGuilds.add(guild); } /** * @return список зарегестрированных гильдий. */ public Array<Guild> getRegisterGuilds() { return registerGuilds; } @Override public String getName() { return EVENT_NANE; } public Region[] getRegions() { return regions; } @Override public EventType getType() { return EventType.REGION_WARS; } /** * @return являетсял и гильдия владельцем какого-нибудь региона. */ public boolean isOwnerGuild(Guild guild) { return ownerGuilds.contains(guild); } /** * @return зарегестрированна ли уже эта гильдия на какую-нибудь битву. */ public boolean isRegisterGuild(Guild guild) { return registerGuilds.contains(guild); } @Override public boolean onLoad() { // создаем список регионов Array<Region> regions = Arrays.toArray(Region.class); // парсим регионы regions.addAll(new DocumentRegionWar(new File(Config.SERVER_DIR + "/data/events/region_wars/region_wars.xml"), this).parse()); // сжимаем список regions.trimToSize(); // вносим в ивент setRegions(regions.array()); // подготавливаем регионы for(Region region : regions) region.prepare(); return true; } /** * Удаление из списка владеющих регионами гильдии. * * @param guild удаляемая гильдия. */ public void removeOwnerGuild(Guild guild) { ownerGuilds.fastRemove(guild); } /** * Удаление из списка харегестрированных на битву гильдий. * * @param guild удаляемая гильдия. */ public void removeRegisterGuild(Guild guild) { registerGuilds.fastRemove(guild); } /** * @param regions список действующих регионов. */ private void setRegions(Region[] regions) { this.regions = regions; } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/Mount.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.S_Mount_Vehicle; import tera.gameserver.templates.SkillTemplate; /** * Модель скила для усадки на маунта. * * @author Ronn */ public class Mount extends AbstractSkill { public Mount(SkillTemplate template) { super(template); } @Override public boolean checkCondition(Character attacker, float targetX, float targetY, float targetZ) { // получаем игрока Player player = attacker.getPlayer(); // если игрок на маунте if(player != null && player.isOnMount()) { // получаем скил, которым он сел на маунта Skill skill = player.getMountSkill(); // если это не этот, выходим if(skill != this) return false; } return super.checkCondition(attacker, targetX, targetY, targetZ); } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { // получаем игрока Player player = attacker.getPlayer(); // если игрока нет ,выходим if(player == null) return; // если игрок на маунте if(player.isOnMount()) { // получаем скил, которым он сел на маунта Skill skill = player.getMountSkill(); // если это не этот, выходим if(skill != this) return; // слезаем с маунта player.getOffMount(); return; } super.startSkill(attacker, targetX, targetY, targetZ); // если игрок на маунте if(!player.isOnMount()) { // выдаем пассивные бонусы template.addPassiveFuncs(player); // запоминаем ид маунта player.setMountId(template.getMountId()); // запоминаем маунт скил player.setMountSkill(this); // отправляем пакет посадки на маунта player.broadcastPacket(S_Mount_Vehicle.getInstance(player, getIconId())); // обновляем статы player.updateInfo(); } } } <file_sep>/java/game/tera/gameserver/model/npc/spawn/MinionSpawn.java package tera.gameserver.model.npc.spawn; import rlib.geom.Coords; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Rnd; import rlib.util.array.Array; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAIClass; import tera.gameserver.model.npc.Minion; import tera.gameserver.model.npc.MinionLeader; import tera.gameserver.model.npc.Npc; import tera.gameserver.templates.NpcTemplate; import tera.util.Location; /** * Модель информации о минионах. * * @author Ronn * @created 12.04.2012 */ public final class MinionSpawn implements Spawn { private static final Logger log = Loggers.getLogger(MinionSpawn.class); /** пул минионов */ private final FoldablePool<Minion> pool; /** шаблон нпс */ private final NpcTemplate template; /** параметры для АИ */ private ConfigAI config; /** конструктор для АИ */ private NpcAIClass aiClass; /** кол-во отспавниваемых минионов. */ private int count; /** радиус спавна от точки */ private int radius; /** * @param template темплейт нпс. */ public MinionSpawn(NpcTemplate template) { this.template = template; this.pool = Pools.newConcurrentFoldablePool(Minion.class); } @Override public void doDie(Npc npc) { pool.put((Minion) npc); } /** * @return кол-во отспавниваемых минионов. */ public final int getCount() { return count; } @Override public Location getLocation() { throw new IllegalArgumentException("unsupported method."); } /** * @return радиус спавна. */ public int getRadius() { return radius; } /** * @return темплейт нпс. */ public NpcTemplate getTemplate() { return template; } @Override public int getTemplateId() { return template.getTemplateId(); } @Override public int getTemplateType() { return template.getTemplateType(); } /** * @param count кол-во отспавниваемых минионов. */ public final void setCount(int count) { this.count = count; } @Override public void setLocation(Location location) { throw new IllegalArgumentException("unsupported method."); } /** * @param radius радиус спавна минионов от лидера. */ public final void setRadius(int radius) { this.radius = radius; } @Override public void start() { log.warning(new Exception("unsupported method")); } /** * Спавн минионов. * * @param leader лидер минионов. * @param array список минионов. */ public void start(MinionLeader leader, Array<Minion> array) { // получаем координаты лидера float x = leader.getX(); float y = leader.getY(); float z = leader.getZ(); // получаем ид континента int continentId = leader.getContinentId(); // получаем пул инстансов FoldablePool<Minion> pool = getPool(); // получаем шаблон миниона NpcTemplate template = getTemplate(); // спавним нужное кол-во минионов for(int i = 0, length = getCount(); i < length; i++) { // извлекаем миниона из пула Minion newNpc = pool.take(); // если его нету if(newNpc == null) { // создаем нового newNpc = (Minion) template.newInstance(); // запоминаем спавн newNpc.setSpawn(this); // ссылка на точку спавна Location spawnLoc = null; // если радиус есть if(radius > 0) // рассчитываем рандомную точку spawnLoc = Coords.randomCoords(new Location(), x, y, z, 0, radius); else // иначе делаем статичную spawnLoc = new Location(x, y, z, Rnd.nextInt(32000)); // вносим ид континента spawnLoc.setContinentId(continentId); // создаем и вносим АИ newNpc.setAi(aiClass.newInstance(newNpc, getConfig())); // спавним newNpc.spawnMe(spawnLoc, leader); // добавляем в список array.add((Minion) newNpc); } else { // получаем прошлую точку спавна Location spawnLoc = newNpc.getSpawnLoc(); // если радиус есть if(radius > 0) // рассчитываем новую spawnLoc = Coords.randomCoords(spawnLoc, x, y, z, 0, radius); else // иначе спавним в статичной spawnLoc.setXYZH(x, y, z, Rnd.nextInt(32000)); // вносим ид континента spawnLoc.setContinentId(continentId); // спавним newNpc.spawnMe(spawnLoc, leader); // добавляем в список array.add(newNpc); } } } @Override public void stop() { log.warning(new Exception("unsupported method")); } /** * @return пул минионов. */ public FoldablePool<Minion> getPool() { return pool; } /** * @param aiClass класс АИ. */ public void setAiClass(NpcAIClass aiClass) { this.aiClass = aiClass; } /** * @param config конфиг АИ. */ public void setConfig(ConfigAI config) { this.config = config; } /** * @return класс АИ. */ public NpcAIClass getAiClass() { return aiClass; } /** * @return конфиг АИ. */ public ConfigAI getConfig() { return config; } @Override public Location[] getRoute() { return null; } } <file_sep>/java/game/tera/gameserver/model/ai/npc/thinkaction/AbstractThinkAction.java package tera.gameserver.model.ai.npc.thinkaction; import org.w3c.dom.Node; import rlib.logging.Logger; import rlib.logging.Loggers; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.util.LocalObjects; /** * Базовая модель генератора действий. * * @author Ronn */ public abstract class AbstractThinkAction implements ThinkAction { protected static final Logger log = Loggers.getLogger(ThinkAction.class); public AbstractThinkAction(Node node){} @Override public <A extends Npc> void prepareState(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime){} @Override public <A extends Npc> void startAITask(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime){} } <file_sep>/java/game/tera/remotecontrol/ServerPackets.java package tera.remotecontrol; public class ServerPackets { } <file_sep>/java/game/tera/gameserver/model/npc/interaction/dialogs/AbstractDialog.java package tera.gameserver.model.npc.interaction.dialogs; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; /** * Базовая модель диалога с нпс. * * @author Ronn * @created 24.02.2012 */ public abstract class AbstractDialog implements Dialog, Foldable { protected static final Logger log = Loggers.getLogger(AbstractDialog.class); /** тип диалогового окна */ protected DialogType type; /** нпс, с которым заговорили */ protected Npc npc; /** игрок с которым говорим */ protected Player player; public AbstractDialog() { this.type = getType(); } @Override public boolean apply() { return false; } @Override public synchronized boolean close() { // игрок, ведущий диалог Player player = getPlayer(); // получаем нпс этого диалога Npc npc = getNpc(); // если игрока нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return false; } if(npc == null) log.warning(this, new Exception("not found npc")); else { // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // уведомляем о закрытии диалога eventManager.notifyStopDialog(npc, player); } // зануляем диалог игроку player.setLastDialog(null); // получаем пул диалогов FoldablePool<Dialog> pool = type.getPool(); // ложим в пул pool.put(this); return true; } @Override public void finalyze() { npc = null; player = null; } @Override public final Npc getNpc() { return npc; } @Override public final Player getPlayer() { return player; } @Override public abstract DialogType getType(); @Override public boolean init() { // получаем игрока Player player = getPlayer(); // если его нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return false; } // получаем последний диалог Dialog old = player.getLastDialog(); // если он есть if(old != null) // закрываем его old.close(); // получаем нпс Npc npc = getNpc(); if(npc == null) log.warning(this, new Exception("not found npc")); else { // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // уведомляем о открытии диалога eventManager.notifyStartDialog(npc, player); } // запоминаем диалог у игрока player.setLastDialog(this); return true; } @Override public void reinit(){} @Override public String toString() { return getClass().getSimpleName(); } } <file_sep>/java/game/tera/remotecontrol/handlers/UpdatePlayerStatInfoHandler.java package tera.remotecontrol.handlers; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.StatType; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Запрос основной информации об игроке. * * @author Ronn */ public class UpdatePlayerStatInfoHandler implements PacketHandler { public static final UpdatePlayerStatInfoHandler instance = new UpdatePlayerStatInfoHandler(); @Override public Packet processing(Packet packet) { Player player = World.getPlayer(packet.nextString()); if(player == null) return null; int attack = player.getAttack(null, null); int defense = player.getDefense(null, null); int impact = player.getImpact(null, null); int balance = player.getBalance(null, null); int critRcpt = (int) player.getCritRateRcpt(null, null); int critRate = (int) player.getCritRate(null, null); int powerFactor = player.getPowerFactor(); int defenseFactor = player.getDefenseFactor(); int impactFactor = player.getImpactFactor(); int balanceFactor = player.getBalanceFactor(); int attackSpeed = player.getAtkSpd(); int moveSpeed = player.getRunSpeed(); int weakRcpt = (int) player.calcStat(StatType.WEAK_RECEPTIVE, 0, null, null); int damageRcpt = (int) player.calcStat(StatType.DAMAGE_RECEPTIVE, 0, null, null); int stunRcpt = (int) player.calcStat(StatType.STUN_RECEPTIVE, 0, null, null); float critDmg = player.getCritDamage(null, null); return new Packet(PacketType.RESPONSE, attack, defense, impact, balance, critRcpt, critRate, critDmg, powerFactor, defenseFactor, impactFactor, balanceFactor, attackSpeed, moveSpeed, weakRcpt, damageRcpt, stunRcpt); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Union_Change.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; public class S_Union_Change extends ServerPacket { private static final ServerPacket instance = new S_Union_Change(); public static S_Union_Change getInstance(Player player) { S_Union_Change packet = (S_Union_Change) instance.newInstance(); packet.player = player; return packet; } /** кол-во ожидания секунд */ private Player player; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_UNION_CHANGE; } @Override protected final void writeImpl() { writeOpcode(); writeInt(player.getObjectId()); writeInt(player.getSubId()); writeInt(player.getGuild().getAllianceId()); writeLong(player.getAllianceClass()); writeByte(1); } } <file_sep>/java/game/tera/gameserver/tasks/ResourseCollectTask.java package tera.gameserver.tasks; import java.util.concurrent.ScheduledFuture; import rlib.util.Rnd; import rlib.util.SafeTask; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.EmotionType; import tera.gameserver.model.playable.Player; import tera.gameserver.model.resourse.ResourseInstance; import tera.gameserver.network.serverpackets.S_SOCIAL; import tera.gameserver.network.serverpackets.S_Collection_Progress; import tera.gameserver.network.serverpackets.S_Collection_Pickend; import tera.gameserver.network.serverpackets.S_Collection_Pickstart; /** * Модель обработки сбора ресурсов. * * @author Ronn */ public final class ResourseCollectTask extends SafeTask { /** кастер скила */ private Player collector; /** собираемый ресурс */ private ResourseInstance resourse; /** текущий шанс сбора */ private int chance; /** кол-во проходов до завершени сбора */ private int counter; /** ссылка на таск */ private volatile ScheduledFuture<ResourseCollectTask> schedule; public ResourseCollectTask(Player collector) { this.collector = collector; } /** * Отмена каста скила. */ public synchronized void cancel(boolean force) { // получаем собераемый ресурс ResourseInstance resourse = getResourse(); synchronized(this) { // если работает таск if(schedule != null) { // отстанавливаем schedule.cancel(false); // зануляем schedule = null; } // если есть скил if(resourse != null) { // зануляем скил setResourse(null); } } // если ресурс был if(resourse != null) { // если отмена формирована if(force) // отправляем пакет остановки сбора collector.broadcastPacket(S_Collection_Pickend.getInstance(collector, resourse, S_Collection_Pickend.INTERRUPTED)); // иначе это фейл else // отправляем пакет остановки сбора collector.broadcastPacket(S_Collection_Pickend.getInstance(collector, resourse, S_Collection_Pickend.FAILED)); // выполняем отмену сбора resourse.onCollected(collector, true); } } /** * @return собираемый ресурс. */ protected final ResourseInstance getResourse() { return resourse; } /** * @return запущен ли. */ public boolean isRunning() { return schedule != null && !schedule.isDone(); } /** * @param resourse собираемый ресурс. */ public void nextTask(ResourseInstance resourse) { // отменяем предыдущий таск cancel(true); synchronized(this) { this.counter = 3; // запоминаем ресурс this.resourse = resourse; // рассчитываем шанс сбора this.chance = resourse.getChanceFor(collector); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // запускаем новый this.schedule = executor.scheduleGeneralAtFixedRate(this, 1000, 1000); } // отсылаем пакет со стартом анимации collector.broadcastPacket(S_Collection_Pickstart.getInstance(collector, resourse)); } @Override protected void runImpl() { collector.getAccount().setFatigability(collector.getAccount().getFatigability() - 10); // отправляем пакет с погрессом collector.sendPacket(S_Collection_Progress.getInstance((100 - 25 * counter)), true); ResourseInstance resourse = null; boolean cancel = false; synchronized(this) { //TODO обновление прогресса // если еще не завершен сбор if(counter > 0) { // рассчитываем не сфейлился ли он if(Rnd.chance(chance)) { // уменьшаем счетчик проходов и ыходим counter -= 1; return; } // ставим флаг прерывания cancel = true; } else { // если есть ссылка на таск if(schedule != null) { // авершаем schedule.cancel(false); // зануляем ссылку на таск schedule = null; } // вытаскиваем ресурс resourse = getResourse(); // зануляем ресурс setResourse(null); } } // если фейл if(cancel) { // отменяем сбор cancel(false); // отправляем пакет с эмоцией collector.broadcastPacket(S_SOCIAL.getInstance(collector, EmotionType.FAIL)); } else if(resourse != null) { // отправляем пакет остановки сбора collector.broadcastPacket(S_Collection_Pickend.getInstance(collector, resourse, S_Collection_Pickend.SUCCESSFUL)); // завершаем сбор resourse.onCollected(collector, false); // отправляем пакет с эмоцией collector.broadcastPacket(S_SOCIAL.getInstance(collector, EmotionType.BOASTING)); } } /** * @param resourse собираемый ресурс. */ protected final void setResourse(ResourseInstance resourse) { this.resourse = resourse; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Clear_Quest_Info.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * @author Ronn */ public class S_Clear_Quest_Info extends ServerPacket { private static final ServerPacket instance = new S_Clear_Quest_Info(); public static S_Clear_Quest_Info getInstance() { return (S_Clear_Quest_Info) instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_CLEAR_QUEST_INFO; } @Override protected void writeImpl() { writeOpcode(); } } <file_sep>/java/game/tera/gameserver/document/DocumentRaceAppearance.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import tera.gameserver.model.base.Race; import tera.gameserver.model.playable.PlayerAppearance; /** * Парсер стандартных внешностей рас игроков с xml. * * @author Ronn */ public final class DocumentRaceAppearance extends AbstractDocument<Void> { public DocumentRaceAppearance(File file) { super(file); } @Override protected Void create() { return null; } @Override protected void parse(Document doc) { VarTable vars = VarTable.newInstance(); for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node child = list.getFirstChild(); child != null; child = child.getNextSibling()) if(child.getNodeType() == Node.ELEMENT_NODE && "appearance".equals(child.getNodeName())) { // парсим атрибуты vars.parse(child); // получаем расу внешности Race race = vars.getEnum("race", Race.class); // получаем пол внености String sex = vars.getString("sex"); // парсим параметры внешности vars.parse(child, "set", "name", "value"); // парсим внешность PlayerAppearance appearance = PlayerAppearance.fromXML(PlayerAppearance.getInstance(0), vars); switch(sex) { case "male": race.setMale(appearance); continue; case "female" : race.setFemale(appearance); continue; case "all" : { race.setFemale(appearance); race.setMale(appearance); } } } } }<file_sep>/java/game/tera/gameserver/document/DocumentRegionWar.java package tera.gameserver.document; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.Config; import tera.gameserver.events.global.regionwars.Region; import tera.gameserver.events.global.regionwars.RegionWars; import tera.gameserver.model.npc.spawn.Spawn; import tera.gameserver.model.skillengine.funcs.Func; import tera.gameserver.model.territory.RegionTerritory; import tera.gameserver.parser.FuncParser; import tera.gameserver.tables.TerritoryTable; /** * Парсер территорий с xml. * * @author Ronn * @created 09.03.2012 */ public final class DocumentRegionWar extends AbstractDocument<Array<Region>> { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); /** ивент владелец регионов */ private RegionWars event; /** * @param file отпрасиваемый фаил. */ public DocumentRegionWar(File file, RegionWars event) { super(file); this.event = event; } @Override protected Array<Region> create() { return Arrays.toArray(Region.class); } @Override protected void parse(Document doc) { // получаем таблицу территорий TerritoryTable territoryTable = TerritoryTable.getInstance(); for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node node = list.getFirstChild(); node != null; node = node.getNextSibling()) if("region".equals(node.getNodeName())) { // парси атрибуты VarTable vars = VarTable.newInstance(node); // парсим ид территории int id = vars.getInteger("id"); // получаем территорию RegionTerritory territory = (RegionTerritory) territoryTable.getTerritory(id); // если территории нету, пропускаем регион if(territory == null) { log.warning(this, "not found territory for " + id); continue; } // создаем регион Region region = new Region(event, territory); // устанавливаем интервал region.setInterval(vars.getLong("interval") * 60 * 60 * 1000); // устанавливаем время битвы region.setBattleTime(vars.getLong("battleTime") * 60 * 1000); // устанавливаем точку отсчета try { region.setStartTime(DATE_FORMAT.parse(vars.getString("startTime")).getTime()); } catch(ParseException e) { log.warning(this, e); } // устанавливаем налог region.setTax(vars.getInteger("tax")); for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if(child.getNodeType() != Node.ELEMENT_NODE) continue; String name = child.getNodeName(); switch(name) { case "spawns": parseSpawns(region, child); break; } } // парсим функции parseFuncs(region, node); // вносим в список result.add(region); } } private void parseFuncs(Region region, Node node) { Array<Func> positive = Arrays.toArray(Func.class); Array<Func> negative = Arrays.toArray(Func.class); // получаем парсер функций FuncParser parser = FuncParser.getInstance(); for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if(child.getNodeType() != Node.ELEMENT_NODE) continue; if("positive".equals(child.getNodeName())) parser.parse(child, positive, file); else if("negative".equals(child.getNodeName())) parser.parse(child, negative, file); } positive.trimToSize(); negative.trimToSize(); region.setNegative(negative.array()); region.setPositive(positive.array()); } private void parseSpawns(Region region, Node node) { Array<Spawn> defense = Arrays.toArray(Spawn.class); Array<Spawn> barriers = Arrays.toArray(Spawn.class); Array<Spawn> control = Arrays.toArray(Spawn.class); Array<Spawn> manager = Arrays.toArray(Spawn.class); Array<Spawn> shops = Arrays.toArray(Spawn.class); VarTable vars = VarTable.newInstance(); for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if(child.getNodeType() != Node.ELEMENT_NODE || !"spawn".equals(child.getNodeName())) continue; vars.parse(child); File file = new File(Config.SERVER_DIR + vars.getString("filepath")); switch(vars.getString("name")) { case "control": control.addAll(new DocumentNpcSpawn(file).parse()); break; case "defense": defense.addAll(new DocumentNpcSpawn(file).parse()); break; case "barriers": barriers.addAll(new DocumentNpcSpawn(file).parse()); break; case "manager": manager.addAll(new DocumentNpcSpawn(file).parse()); break; case "shops": shops.addAll(new DocumentNpcSpawn(file).parse()); break; } } defense.trimToSize(); control.trimToSize(); manager.trimToSize(); barriers.trimToSize(); shops.trimToSize(); region.setControl(control.array()); region.setDefense(defense.array()); region.setManager(manager.array()); region.setBarriers(barriers.array()); region.setShops(shops.array()); } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_Start_Pegasus.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет для посадки персонажа на пегас * * @author Ronn */ public class S_Start_Pegasus extends ServerPacket { private static final ServerPacket instance = new S_Start_Pegasus(); public static S_Start_Pegasus getInstance(Character actor) { S_Start_Pegasus packet = (S_Start_Pegasus) instance.newInstance(); packet.actor = actor; return packet; } /** персонаж, который нужно посадить */ private Character actor; @Override public void finalyze() { actor = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_START_PEGASUS; } @Override protected void writeImpl() { writeOpcode(); writeInt(actor.getObjectId()); // наш ид writeInt(actor.getSubId());//саб ид перса writeInt(1); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/AbstractSkill.java package tera.gameserver.model.skillengine.classes; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.MessageType; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.skillengine.Condition; import tera.gameserver.model.skillengine.Effect; import tera.gameserver.model.skillengine.Formulas; import tera.gameserver.model.skillengine.OperateType; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.SkillName; import tera.gameserver.model.skillengine.SkillRangeType; import tera.gameserver.model.skillengine.SkillType; import tera.gameserver.model.skillengine.TargetType; import tera.gameserver.network.serverpackets.MoveSkill; import tera.gameserver.network.serverpackets.S_Action_End; import tera.gameserver.network.serverpackets.S_Action_Stage; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; /** * Базовая модель скила. * * @author Ronn * @created 12.04.2012 */ public abstract class AbstractSkill implements Skill { public static final Skill[] EMPTY_SKILLS = new Skill[0]; /** ид каста скила */ protected int castId; /** номер приминения в течении каста */ protected int applyOrder; /** целевые координаты */ protected float impactX; protected float impactY; protected float impactZ; /** темплейт скила */ protected SkillTemplate template; /** * @param set набор параметров скила. * @param effectTemplates набор эффектов скила. * @param condition условие использования скила. * @param funcs набор функций скила. */ public AbstractSkill(SkillTemplate template) { this.template = template; } /** * Добавление агр поинты кастующему для нпс, которые в агр листе у таргета. * * @param caster кастующий. * @param target цель кастующего. * @param aggro кол-во агр поинтов. */ protected void addAggroTo(Character caster, Character target, int aggro) { // список НПС, сагренных на персонажа Array<Npc> hateList = target.getLocalHateList(); // если не пуст if(!hateList.isEmpty()) { Npc[] array = hateList.array(); // перебираем сагренные НПС for(int i = 0, length = hateList.size(); i < length; i++) array[i].addAggro(caster, aggro, false); } } /** * Применение эффектов скила. * * @param caster тот, кто кастует скил. */ protected void addEffects(Character caster) { // список возможных эффектов от скила EffectTemplate[] effectTemplates = template.getEffectTemplates(); // если таких нет if(effectTemplates == null || effectTemplates.length == 0) return; // получаем формулы Formulas formulas = Formulas.getInstance(); // перебор for(int i = 0, length = effectTemplates.length; i < length; i++) { EffectTemplate temp = effectTemplates[i]; // если эффект не только на кастующего или шанс не сработал if(!temp.isOnCaster() || formulas.calcEffect(caster, caster, temp, this) < 0) continue; // активируем эффект runEffect(temp.newInstance(caster, caster, template), caster); } return; } /** * Применение эффектов скила. * * @param effector тот, кто накладывает эффекты. * @param effected тот, на кого накладывают эффекты. */ protected void addEffects(Character effector, Character effected) { // список возможных эффектов от скила EffectTemplate[] effectTemplates = template.getEffectTemplates(); // если таких нет if(effectTemplates == null || effectTemplates.length == 0) return; // получаем формулы Formulas formulas = Formulas.getInstance(); // перебираем темплейты for(int i = 0, length = effectTemplates.length; i < length; i++) { // получаем темплейт EffectTemplate temp = effectTemplates[i]; // если эффект только на кастующего, пропускаем if(temp.isOnCaster()) continue; // получаем модификатор шанса float mod = formulas.calcEffect(effector, effected, temp, this); // если эффект не прошел, пропускаем if(mod < 0) continue; // создаем эффект Effect effect = temp.newInstance(effector, effected, template); // если у него динамическое время if(effect.isDynamicTime()) // применяем модификатор времени effect.setPeriod((int) Math.max(temp.getTime() * Math.min(mod, 1), 1)); // если динамический каунтер if(effect.isDynamicCount()) // применяем модификатор effect.setCount((int) Math.max(temp.getCount() * Math.min(mod, 1), 1)); // активируем эффект runEffect(effect, effected); } } @Override public void addTargets(Array<Character> targets, Character attacker, float targetX, float targetY, float targetZ) { getTargetType().getTargets(targets, this, targetX, targetY, targetZ, attacker); } @Override public AttackInfo applySkill(Character attacker, Character target) { return null; } @Override public int blockMpConsume(int damage) { return 0; } @Override public boolean checkCondition(Character attacker, float targetX, float targetY, float targetZ) { // если скил в откате, то нельзя его юзать if(attacker.isSkillDisabled(this)) return false; // если атакующий в корнях if(attacker.isRooted() && (isEvasion() || getMoveDistance() != 0)) { //attacker.sendMessage("Нельзя использовать в обездвиженном состоянии."); attacker.sendMessage(MessageType.YOU_CANNOT_USE_THAT_SKILL_AT_THE_MOMENT); return false; } Skill activate = attacker.getActivateSkill(); // если есть активированный скил, и этот скил не имеет принудительного каста if(!isForceCast() && activate != null && activate != this) { attacker.sendMessage(MessageType.YOU_CANNOT_USE_THAT_SKILL_AT_THE_MOMENT); return false; } // если недостаточно мп if(attacker.getCurrentMp() < template.getMpConsume()) { attacker.sendMessage(MessageType.NOT_ENOUGH_MP); return false; } // если недостаточно хп if(attacker.getCurrentHp() <= template.getHpConsume() + 1) { attacker.sendMessage("Not enought HP"); return false; } // если есть потребляемые итемы if(template.getItemIdConsume() != 0) { Inventory inventory = attacker.getInventory(); // если ет инвенторя if(inventory == null) return false; // кол-во необходимых итемов int count = inventory.getItemCount(template.getItemIdConsume()); // если итемов не хватает if(template.getItemCountConsume() > count) { attacker.sendMessage("У вас недостаточно необходимых вещей в инвенторе."); return false; } } // условие выполнения скила Condition condition = template.getCondition(); // если оно не выполняется if(condition != null && !condition.test(attacker, null, this, 0)) return false; return true; } @Override public void endSkill(Character attacker, float targetX, float targetY, float targetZ, boolean force) { // отображаем анимацию завершения каста скила attacker.broadcastPacket(S_Action_End.getInstance(attacker, castId, template.getIconId())); // удаляем функции, которые добавлялись на время каста template.removeCastFuncs(attacker); // добавляем эффекты на кастера addEffects(attacker); } @Override public void finalyze(){} @Override public void fold() { template.put(this); } @Override public int getAggroPoint() { return template.getAggroPoint(); } @Override public int getCastCount() { return template.getCastCount(); } @Override public int getCastHeading() { int[] heading = template.getCastHeading(); return heading[Math.min(applyOrder, heading.length - 1)]; } @Override public int getCastId() { return castId; } @Override public int getCastMaxRange() { return template.getCastMaxRange(); } @Override public int getCastMinRange() { return template.getCastMinRange(); } @Override public int getChance() { return template.getChance(); } @Override public int getClassId() { return template.getClassId(); } @Override public Condition getCondition() { return template.getCondition(); } @Override public int getDamageId() { return template.getDamageId(); } @Override public int getDegree() { int[] degrees = template.getDegree(); return degrees[Math.min(applyOrder, degrees.length - 1)]; } @Override public int getDelay() { return template.getDelay(); } @Override public EffectTemplate[] getEffectTemplates() { return template.getEffectTemplates(); } @Override public String getGroup() { return template.getGroup(); } @Override public int getHeading() { int[] heading = template.getHeading(); return heading[Math.min(applyOrder, heading.length - 1)]; } @Override public int getHitTime() { return template.getHitTime(); } @Override public int getHpConsume() { return template.getHpConsume(); } @Override public int getIconId() { return template.getIconId(); } @Override public int getId() { return template.getId(); } /** * @return целевая координата. */ public final float getImpactX() { return impactX; } /** * @return целевая координата. */ public final float getImpactY() { return impactY; } /** * @return целевая координата. */ public final float getImpactZ() { return impactZ; } @Override public int getInterval() { int[] intervals = template.getInterval(); return intervals[Math.min(applyOrder, intervals.length - 1)]; } @Override public int getItemCount() { return template.getItemCount(); } @Override public long getItemCountConsume() { return template.getItemCountConsume(); } @Override public int getItemId() { return template.getItemId(); } @Override public int getItemIdConsume() { return template.getItemIdConsume(); } @Override public int getLevel() { return template.getLevel(); } @Override public int getMaxTargets() { return template.getMaxTargets(); } @Override public int getMinRange() { return template.getMinRange(); } @Override public int getMoveDelay() { return template.getMoveDelay(); } @Override public int getMoveDistance() { return template.getMoveDistance(); } @Override public int getMoveHeading() { return template.getMoveHeding(); } @Override public int getMoveTime() { return template.getMoveTime(); } @Override public int getMpConsume() { return template.getMpConsume(); } @Override public String getName() { return template.getName(); } @Override public OperateType getOperateType() { return template.getOperateType(); } @Override public float getOwerturnMod() { return template.getOwerturnMod(); } @Override public int getPower() { int[] powers = template.getPower(); return powers[Math.min(applyOrder, powers.length - 1)]; } @Override public int getRadius() { int[] redius = template.getRadius(); return redius[Math.min(applyOrder, redius.length - 1)]; } @Override public int getRange() { int[] ranges = template.getRange(); return ranges[Math.min(applyOrder, ranges.length - 1)]; } @Override public SkillRangeType getRangeType() { return template.getRangeType(); } @Override public int getReuseDelay(Character caster) { if(isStaticReuseDelay()) return template.getReuseDelay(); // получаем тип скила по дальности приминения SkillRangeType rangeType = getRangeType(); return (int) (template.getReuseDelay() * caster.calcStat(rangeType.getReuseStat(), 1, null, null) * rangeType.getReuseMod()); } @Override public int getReuseId() { return template.getReuseId(); } @Override public int[] getReuseIds() { return template.getReuseIds(); } @Override public SkillName getSkillName() { return template.getSkillName(); } @Override public SkillType getSkillType() { return template.getSkillType(); } @Override public int getSpeed() { return template.getSpeed(); } @Override public int getStage() { int[] stages = template.getStage(); return stages[Math.min(applyOrder, stages.length - 1)]; } @Override public TargetType getTargetType() { TargetType[] types = template.getTargetType(); return types[Math.min(applyOrder, types.length - 1)]; } @Override public final SkillTemplate getTemplate() { return template; } @Override public int getTransformId() { return template.getTransformId(); } @Override public int getWidth() { int[] widths = template.getWidth(); return widths[Math.min(applyOrder, widths.length - 1)]; } @Override public int hashCode() { return template.getId(); } @Override public boolean hasPrevSkillName(SkillName skillName) { return Arrays.contains(template.getPrevSkillNames(), skillName); } @Override public boolean isActive() { OperateType operateType = template.getOperateType(); return operateType == OperateType.ACTIVE || operateType == OperateType.ACTIVATE || operateType == OperateType.CHARGE || operateType == OperateType.LOCK_ON; } @Override public boolean isAltCast() { return template.isAltCast(); } @Override public boolean isApply() { boolean[] apply = template.isApply(); return apply[Math.min(applyOrder, apply.length - 1)]; } @Override public boolean isBlockingMove() { return template.isBlockingMove(); } @Override public boolean isCanceable() { return true; } @Override public boolean isCanOwerturn() { return template.isCanOwerturn(); } @Override public boolean isCastToMove() { return template.isCastToMove(); } @Override public boolean isEvasion() { return template.isEvasion(); } @Override public boolean isForceCast() { return template.isForceCast(); } @Override public boolean isHasFast() { return template.isHasFast(); } @Override public boolean isIgnoreBarrier() { return template.isIgnoreBarrier(); } @Override public boolean isImplemented() { return template.isImplemented(); } @Override public boolean isNoCaster() { return template.isNoCaster(); } @Override public boolean isOffensive() { switch(template.getSkillType()) { case TRANSFORM: case TELEPORT_JUMP: case SPAWN_ITEM: case SPAWN_BONFIRE: case RESURRECT: case RESTART_BONFIRE: case PREPARE_MANAHEAL: case PARTY_SUMMON: case MANAHEAL_PERCENT: case HEAL_PERCENT: case HEAL: case ITEM_BUFF: case JUMP: case DEFENSE: case LANCER_DEFENSE: case MANAHEAL: case CLEAR_DEBUFF: case CANCEL_OWERTURN: case CHARGE_MANA_HEAL: return false; default: break; } return true; } @Override public boolean isOneTarget() { switch(getTargetType()) { case TARGET_BACK_RAIL: case TARGET_RAIL: case TARGET_ONE: case TARGET_AREA: return true; default : return false; } } @Override public boolean isPassive() { return template.getOperateType() == OperateType.PASSIVE; } @Override public boolean isRush() { return template.isRush(); } @Override public boolean isShieldIgnore() { return template.isShieldIgnore(); } @Override public boolean isShortSkill() { return template.isShortSkill(); } @Override public boolean isStaticCast() { return template.isStaticCast(); } @Override public boolean isStaticInterval() { return template.isStaticInterval(); } @Override public boolean isToggle() { return template.isToggle(); } @Override public boolean isTrigger() { return template.isTrigger(); } @Override public boolean isVisibleOnSkillList() { return template.isVisibleOnSkillList(); } @Override public boolean isWaitable() { return true; } @Override public void reinit(){} /** * Метод запускающий эффект. * * @param effect запускаемый эффект. * @param effected тот, на кого будет наложен эффект. */ protected void runEffect(Effect effect, Character effected) { // если эффект не мгновеный, добавляем в эффект лист if(effect.getPeriod() != 0) effected.addEffect(effect); // иначе тупо сразу применяем else { // метод старта effect.onStart(); // приминение эффекта effect.onActionTime(); // метод завершения effect.onExit(); // складываем в пул effect.fold(); } } /** * @param impactX целевая координата. */ public final void setImpactX(float impactX) { this.impactX = impactX; } /** * @param impactY целевая координата. */ public final void setImpactY(float impactY) { this.impactY = impactY; } /** * @param impactZ целевая координата. */ public final void setImpactZ(float impactZ) { this.impactZ = impactZ; } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { // выдаем функции, которые работают в течении каста скила template.addCastFuncs(attacker); // обнуляем порядок каста applyOrder = 0; // получаем ид каста castId = attacker.nextCastId(); // отображаем начало каста attacker.broadcastPacket(S_Action_Stage.getInstance(attacker, template.getIconId(), castId, 0)); // если скил раш, отображаем рывок if(isRush()) { // цель рывка Character target = attacker.getTarget(); // если цель есть, отображаем рывок за целью if(target != null) attacker.broadcastPacket(MoveSkill.getInstance(attacker, target)); else // иначе рывок в точку attacker.broadcastPacket(MoveSkill.getInstance(attacker, targetX, targetY, targetZ)); } } @Override public String toString() { return getClass().getSimpleName() + " template = " + template; } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { applyOrder++; } @Override public boolean isStaticReuseDelay() { return template.isStaticReuseDelay(); } @Override public int getSpeedOffset() { return template.getSpeedOffset(); } @Override public boolean isCorrectableTarget() { return template.isCorrectableTarget(); } @Override public boolean isTargetSelf() { return getTargetType() == TargetType.TARGET_SELF; } } <file_sep>/java/game/tera/gameserver/model/quests/QuestAction.java package tera.gameserver.model.quests; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; /** * Интерфейс для реализации квестовых акшенов. * * @author Ronn */ public interface QuestAction { /** * Применить акшен с учетом события. * * @param event событие. */ public void apply(QuestEvent event); /** * @return тип акшена. */ public QuestActionType getType(); /** * Проверка на условия для отображения ссылки. * * @param npc нпс, у которого находится ссылка. * @param player игрок, запрашиваемый ссылки нпс. * @return нужно ли отображать ссылку. */ public boolean test(Npc npc, Player player); } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Check_Version.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Check_Version extends ServerPacket { public static final int SUCCESSFUL = 1; public static final int INCORRECT = 2; private static final ServerPacket instance = new S_Check_Version(); public static S_Check_Version getInstance(int result) { S_Check_Version packet = (S_Check_Version) instance.newInstance(); packet.result = result; return packet; } /** результат */ private int result; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_CHECK_VERSION; } @Override protected void writeImpl() { writeOpcode(); writeByte((result == SUCCESSFUL) ? 1 : 0); } }<file_sep>/java/game/tera/gameserver/scripts/commands/UserCommand.java package tera.gameserver.scripts.commands; import java.text.SimpleDateFormat; import java.util.Date; import rlib.util.Files; import rlib.util.table.IntKey; import rlib.util.table.Table; import tera.Config; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.EventManager; import tera.gameserver.manager.OnlineManager; import tera.gameserver.manager.PlayerManager; import tera.gameserver.model.Account; import tera.gameserver.model.MessageType; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.S_Skill_List; /** * Список команд, доступных для всех игроков. * * @author Ronn */ public class UserCommand extends AbstractCommand { private static final SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); private static final String CHANGE_APPEARANCE_VAR = "CHANGE_APPEARANCE_VAR"; private static final String CHANGE_RACE_VAR = "CHANGE_RACE_VAR"; private static final int CHANGE_APPEARANCE_LIMIT = 3; private static final int CHANGE_RACE_LIMIT = 3; private static final Date date = new Date(); private static String help; public UserCommand(int access, String[] commands) { super(access, commands); help = Files.read(Config.SERVER_DIR + "/data/help.txt"); } @Override public void execution(String command, Player player, String values) { switch(command) { case "event_reg": { if(values == null) { return; } EventManager eventManager = EventManager.getInstance(); eventManager.registerPlayer(values, player); break; } case "restore_characters": { PlayerManager playerManager = PlayerManager.getInstance(); playerManager.restoreCharacters(player); break; } case "help": player.sendMessage(help); break; case "time": { synchronized(date) { date.setTime(System.currentTimeMillis()); player.sendMessage(timeFormat.format(date)); } break; } case "end_pay": { Account account = player.getAccount(); long time = account.getEndPay(); if(System.currentTimeMillis() > time) player.sendMessage("You don't have premium account."); else { synchronized(date) { date.setTime(time); player.sendMessage("End of premium account: " + timeFormat.format(date)); } } break; } case "restore_skills": { Table<IntKey, Skill> current = player.getSkills(); DataBaseManager dbManager = DataBaseManager.getInstance(); for(Skill skill : current) { if(skill.getClassId() == -15) continue; player.removeSkill(skill, false); dbManager.deleteSkill(player, skill); skill.fold(); } current.clear(); player.getTemplate().giveSkills(player); player.sendPacket(S_Skill_List.getInstance(player), true); break; } case "kill_me": { if(player.isBattleStanced()) { player.sendMessage("Can't be used in battle."); return; } synchronized(player) { player.setCurrentHp(0); player.doDie(player); } break; } case "version": player.sendMessage("Current server's version: " + Config.SERVER_VERSION); break; case "online": { OnlineManager onlineManager = OnlineManager.getInstance(); player.sendMessage("Online since: " + onlineManager.getCurrentOnline()); break; } case "player_info": { if(player.getName().equals(values)) return; Player target = World.getAroundByName(Player.class, player, values); if(target == null) target = World.getPlayer(values); if(target == null) { player.sendMessage(MessageType.THAT_CHARACTER_ISNT_ONLINE); return; } StringBuilder builder = new StringBuilder("\n--------\nPlayer: \"").append(target.getName()).append("\":\n"); builder.append("attack:").append(target.getAttack(null, null)).append(";\n"); builder.append("defense:").append(target.getDefense(null, null)).append(";\n"); builder.append("impact:").append(target.getImpact(null, null)).append(";\n"); builder.append("balance:").append(target.getBalance(null, null)).append(";\n"); builder.append("max hp:").append(target.getMaxHp()).append(".\n"); builder.append("--------"); player.sendMessage(builder.toString()); break; } } } } <file_sep>/java/game/tera/gameserver/scripts/commands/AbstractCommand.java package tera.gameserver.scripts.commands; import java.util.Arrays; /** * Фундамент для реализации обработчика команд. * * @author Ronn * @created 13.04.2012 */ public abstract class AbstractCommand implements Command { /** список команд, которые выполняются этим обработчиком */ private String[] commands; /** уровень прав доступа игрока, для выполнения команды */ private int access; /** * @param access минимальный кровень доступа. * @param commands список обрабатываемых команд. */ public AbstractCommand(int access, String[] commands) { this.commands = commands; this.access = access; } @Override public int getAccess() { return access; } @Override public String[] getCommands() { return commands; } @Override public String toString() { return getClass().getSimpleName() + " " + (commands != null ? "commands = " + Arrays.toString(commands) + ", " : "") + "access = " + access; } } <file_sep>/java/game/tera/gameserver/model/items/Rank.java package tera.gameserver.model.items; /** * Перечисление ранков итемов. * * @author Ronn */ public enum Rank { COMMON("common"), UNCOMMON("uncommon"), RARE("rare"), EPIC("epic"), UNKNOWN("unknown"), UNKNOW("unknow"); /** * Получение нужного ранка по названию в xml. * * @param name название в xml. * @return соответствующий ранк. */ public static Rank valueOfXml(String name) { for(Rank type : values()) if(type.getXmlName().equals(name)) return type; throw new IllegalArgumentException(name); } /** хмл название */ private String xmlName; private Rank(String xmlName) { this.xmlName = xmlName; } /** * @return xml название. */ public final String getXmlName() { return xmlName; } } <file_sep>/java/game/tera/gameserver/model/npc/BattleGuard.java package tera.gameserver.model.npc; import tera.gameserver.model.Character; import tera.gameserver.templates.NpcTemplate; /** * Модель дружественного нпс. * * @author Ronn */ public class BattleGuard extends Guard { public BattleGuard(int objectId, NpcTemplate template) { super(objectId, template); } @Override public boolean checkTarget(Character target) { if(target.isPlayer() || target.isSummon()) return false; if(target.isNpc()) { Npc npc = target.getNpc(); return npc.isMonster() || npc.isRaidBoss(); } return false; } @Override public boolean isInvul() { return false; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestCancelQuest.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestState; import tera.util.LocalObjects; /** * Клиентский пакет обновление квеста на панели. * * @author Ronn */ public class RequestCancelQuest extends ClientPacket { /** игрок */ private Player player; /** уник ид квеста */ private int objectId; @Override public void finalyze() { player = null; } @Override public void readImpl() { if(buffer.remaining() < 12) return; player = owner.getOwner(); readInt(); readInt(); objectId = readInt(); } @Override public void runImpl() { // если игрока нет, выходим if(player == null) return; // получаем его список квестов QuestList questList = player.getQuestList(); // если списка нет, выходим if(questList == null) { log.warning(this, new Exception("not found quest list for player " + player.getName())); return; } // получаем нужный квест QuestState state = questList.getQuestState(objectId); // если его нету, выходим if(state == null) return; // получаем сам квест Quest quest = state.getQuest(); // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем ивент QuestEvent event = local.getNextQuestEvent(); // вносим игрока event.setPlayer(player); // вносим квест event.setQuest(quest); // отменяем квест quest.cancel(event, false); } }<file_sep>/java/game/tera/gameserver/model/actions/dialogs/ActionDialogType.java package tera.gameserver.model.actions.dialogs; import rlib.logging.Loggers; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; /** * Перечисление типов диалогов акшенов. * * @author Ronn */ public enum ActionDialogType { NULL(null), NULL1(null), NULL2(null), /** диалог трейда */ TRADE_DIALOG(TradeDialog.class), /** диалог зачоравания вещей */ ENCHANT_ITEM_DIALOG(EnchantItemDialog.class); /** пул диалогов */ private final FoldablePool<ActionDialog> pool; /** тип диалога */ private final Class<? extends ActionDialog> type; private ActionDialogType(Class<? extends ActionDialog> type) { this.pool = Pools.newConcurrentFoldablePool(ActionDialog.class); this.type = type; } /** * @return пул диалогов. */ public FoldablePool<ActionDialog> getPool() { return pool; } /** * @return новый инстанс диалога. */ public ActionDialog newInstance() { ActionDialog dialog = pool.take(); if (dialog == null) try { dialog = type.newInstance(); } catch (InstantiationException | IllegalAccessException e) { Loggers.warning(this, e); } return dialog; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Toggle_Task_Info_Window.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.quests.QuestState; import tera.gameserver.network.ServerPacketType; /** * @author Ronn */ public class S_Toggle_Task_Info_Window extends ServerPacket { private static final ServerPacket instance = new S_Toggle_Task_Info_Window(); public static S_Toggle_Task_Info_Window getInstance(QuestState quest) { S_Toggle_Task_Info_Window packet = (S_Toggle_Task_Info_Window) instance.newInstance(); packet.questId = quest.getQuestId(); packet.objectId = quest.getObjectId(); packet.state = quest.getState(); return packet; } /** ид квеста */ private int questId; /** ид состояния квеста */ private int objectId; /** стадия квеста */ private int state; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_TOGGLE_TASK_INFO_WINDOW; } @Override protected void writeImpl() { writeOpcode(); writeInt(questId); //29 05 00 00 //NPC ID writeInt(objectId); //C4 E0 89 00 //обжект ид writeByte(state); //01//номер квеста } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/TeleportJump.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.network.serverpackets.S_Action_Stage; import tera.gameserver.templates.SkillTemplate; /** * Модель скила, служащего только для активирования бафа. * * @author Ronn */ public class TeleportJump extends Jump { /** * @param template темплейт скила. */ public TeleportJump(SkillTemplate template) { super(template); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { character.broadcastPacket(S_Action_Stage.getInstance(character, template.getIconId(), castId, 1)); } } <file_sep>/java/game/tera/gameserver/model/skillengine/Formulas.java package tera.gameserver.model.skillengine; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.VarTable; import rlib.util.random.Random; import tera.Config; import tera.gameserver.manager.RandomManager; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.equipment.Equipment; import tera.gameserver.model.equipment.Slot; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.funcs.StatFunc; import tera.gameserver.model.skillengine.funcs.stat.MathFunc; import tera.gameserver.templates.EffectTemplate; /** * Набор формул и функций. * * @author Ronn */ public final class Formulas { private static final Logger log = Loggers.getLogger(Formulas.class); private static Formulas instance; public static Formulas getInstance() { if(instance == null) instance = new Formulas(); return instance; } /** модификаторы базовых статов */ private final float[] ATTACK = new float[200]; private final float[] DEFENSE = new float[200]; private final float[] IMPACT = new float[200]; private final float[] BALANCE = new float[200]; /** модификатор уровня хп от уровня стамины */ private final float[] HEART = new float[200]; /** модификатор для скорости каста */ private final float[] CAST_MOD = new float[300]; /** таблица бонуса к макс. хп для игроков */ private float[][] HP_MOD; /** функции для игрока */ private StatFunc STAMINA_HP; private StatFunc STAMINA_MP; private StatFunc LEVEL_MOD_HP_PLAYER; private StatFunc LEVEL_MOD_REGEN_HP_PLAYER; private StatFunc ATTACK_PLAYER; private StatFunc IMPACT_PLAYER; private StatFunc DEFENSE_PLAYER; private StatFunc BALANCE_PLAYER; /** функции для НПС */ private StatFunc BATTLE_WALK_NPC; private Formulas() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File(Config.SERVER_DIR + "/data/base_stats.xml"); try { Document doc = factory.newDocumentBuilder().parse(file); for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) { for(Node node = list.getFirstChild(); node != null; node = node.getNextSibling()) { if(node.getNodeType() != Node.ELEMENT_NODE || !"set".equals(node.getNodeName())) continue; // парсим атрибуты VarTable vars = VarTable.newInstance(node); // получаем тип параметра String type = vars.getString("type"); // позиция пораметра int order = vars.getInteger("order"); // значение параметра float value = vars.getFloat("value"); switch(type) { case "heart": HEART[order] = value; break; } } } for(int i = 1, length = ATTACK.length; i < length; i++) ATTACK[i] = 0.01F * i + 3; for(int i = 1, length = DEFENSE.length; i < length; i++) DEFENSE[i] = 0.01F * i + 0.5F; for(int i = 0, length = IMPACT.length; i < length; i++) IMPACT[i] = 0.01F * i; for(int i = 0, length = BALANCE.length; i < length; i++) BALANCE[i] = 0.01F * i; for(int i = 0, length = HEART.length; i < length; i++) if(HEART[i] == 0F) HEART[i] = 1F; } catch(SAXException | IOException | ParserConfigurationException e) { Loggers.warning(Formulas.class, e); } HP_MOD = new float[PlayerClass.values().length][Config.WORLD_PLAYER_MAX_LEVEL + 1]; for(PlayerClass cs : PlayerClass.values()) for(int i = 1; i < HP_MOD[cs.getId()].length; i++) HP_MOD[cs.getId()][i] = (float) Math.pow(cs.getHpMod(), i - 1); for(int i = 0; i < CAST_MOD.length; i++) CAST_MOD[i] = 18000F / (Math.max(i, 1) + 180) / 10; ATTACK_PLAYER = new MathFunc(StatType.ATTACK, 0x10, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { float total = 0F; if(attacker.isPlayer()) { Equipment equipment = attacker.getEquipment(); if(equipment != null) { Slot[] slots = equipment.getSlots(); for(int i = 0, length = slots.length; i < length; i++) { ItemInstance item = slots[i].getItem(); if(item != null) total += item.getAttack(); } } } return val + ATTACK[attacker.getPowerFactor()] * total; } }; IMPACT_PLAYER = new MathFunc(StatType.IMPACT, 0x10, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { float total = 0F; if(attacker.isPlayer()) { Equipment equipment = attacker.getEquipment(); if(equipment != null) { Slot[] slots = equipment.getSlots(); for(int i = 0, length = slots.length; i < length; i++) { ItemInstance item = slots[i].getItem(); if(item != null) total += item.getImpact(); } } } return val + total * IMPACT[attacker.getImpactFactor()]; } }; DEFENSE_PLAYER = new MathFunc(StatType.DEFENSE, 0x10, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { float total = 0F; if(attacker.isPlayer()) { Equipment equipment = attacker.getEquipment(); if(equipment != null) { Slot[] slots = equipment.getSlots(); for(int i = 0, length = slots.length; i < length; i++) { ItemInstance item = slots[i].getItem(); if(item != null) total += item.getDefence(); } } } return val + total * DEFENSE[attacker.getDefenseFactor()]; } }; BALANCE_PLAYER = new MathFunc(StatType.BALANCE, 0x10, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { float total = 0F; if(attacker.isPlayer()) { Equipment equipment = attacker.getEquipment(); if(equipment != null) { Slot[] slots = equipment.getSlots(); for(int i = 0, length = slots.length; i < length; i++) { ItemInstance item = slots[i].getItem(); if(item != null) total += item.getBalance(); } } } return val + total * BALANCE[attacker.getBalanceFactor()]; } }; STAMINA_HP = new MathFunc(StatType.MAX_HP, 0x50, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { if(!attacker.isPlayer()) return val; Player player = attacker.getPlayer(); return val * HEART[player.getStamina()]; } }; STAMINA_MP = new MathFunc(StatType.MAX_MP, 0x50, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { if(!attacker.isPlayer()) return val; Player player = (Player) attacker; return val * HEART[player.getStamina()]; } }; LEVEL_MOD_HP_PLAYER = new MathFunc(StatType.MAX_HP, 0x10, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { if(!attacker.isPlayer()) return val; Player player = (Player) attacker; return val * HP_MOD[player.getClassId()][player.getLevel()]; } }; LEVEL_MOD_REGEN_HP_PLAYER = new MathFunc(StatType.REGEN_HP, 0x10, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { if(!attacker.isPlayer()) return val; Player player = (Player) attacker; return val * HP_MOD[player.getClassId()][player.getLevel()]; } }; BATTLE_WALK_NPC = new MathFunc(StatType.RUN_SPEED, 0x50, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { if(!attacker.isNpc()) return val; if(!attacker.isBattleStanced()) val = attacker.isSummon() ? val * 2 : val / 2; return val; } }; log.info("initialized."); } /** * @param character персонаж, которому нужно добавить базовые функции. */ public void addFuncsToNewCharacter(Character character) { // TODO } /** * @param npc нпс, которому нужно добавить базовые функции. */ public void addFuncsToNewNpc(Character npc) { BATTLE_WALK_NPC.addFuncTo(npc); } /** * @param player игрок, которому нужно добавить базовые функции. */ public void addFuncsToNewPlayer(Player player) { ATTACK_PLAYER.addFuncTo(player); IMPACT_PLAYER.addFuncTo(player); DEFENSE_PLAYER.addFuncTo(player); BALANCE_PLAYER.addFuncTo(player); STAMINA_HP.addFuncTo(player); STAMINA_MP.addFuncTo(player); LEVEL_MOD_HP_PLAYER.addFuncTo(player); LEVEL_MOD_REGEN_HP_PLAYER.addFuncTo(player); } /** * Рассчет атаки персонажа скилом. * * @param info контейнер инфы об атаке. * @param skill атакующий скил. * @param attacker атакующий персонаж. * @param attacked атакуемый персонаж. * @return результат атаки. */ public AttackInfo calcDamageSkill(AttackInfo info, Skill skill, Character attacker, Character attacked) { // получаем менеджер рандома RandomManager randomManager = RandomManager.getInstance(); // получаем рандоминайзер для критов Random rand = randomManager.getCritRandom(); // вносим атаку атакующего info.addDamage(attacker.getAttack(attacked, skill)); // умножаем на силу скила info.mulDamage(skill.getPower() / skill.getCastCount()); // делим на защиту info.divDamage(Math.max(1, attacked.getDefense(attacker, skill))); // рассчитывает крит удар { // получаем шанс float chance = attacker.getCritRate(attacked, skill); // получаем ресист float resist = (100F - attacked.getCritRateRcpt(attacker, skill)) / 100F; // рассчитываем крит info.setCrit(rand.chance(chance * resist / 5F)); } // устанавливаем урон info.setDamage(Math.max(info.getDamage(), 1)); // пропуск по слушателям attacked.onDamage(attacker, skill, info); attacked.onShield(attacker, skill, info); // если крит, умножаем на крит повер if(info.isCrit()) info.mulDamage(attacker.getCritDamage(attacked, skill)); // проверка на неуязвимость if(attacked.isInvul()) info.setDamage(0); // получаем рандоминайзер для урона rand = randomManager.getDamageRandom(); // если есть урон if(!info.isNoDamage()) // делаем рандомную модификацию info.setDamage(info.getDamage() * 100 / rand.nextInt(95, 105)); // рассчитываем опрокидывание info.setOwerturn(!info.isBlocked() && skill.isCanOwerturn() && calcOwerturn(attacker, attacked, skill)); return info; } /** * Рассчет прохождения эффекта. * * @param attacker атакующий. * @param attacked атакуемый. * @param effect эффект. * @return проходит ли эффект. */ public float calcEffect(Character attacker, Character attacked, EffectTemplate effect, Skill skill) { // получаем базовый шанс эффекта int chance = effect.getChance(); // если шанс -1, то он 100% if(chance == -1) return 1; // получаем ресист ResistType resistType = effect.getResistType(); // проверяем, есть ли иммунитет if(!resistType.checkCondition(attacker, attacked)) return -1; // рассчитываем силу дэбафа float power = attacker.calcStat(resistType.getPowerStat(), 1, attacked, skill) * attacker.getLevel() / Math.max(attacked.getLevel(), 1); // рассчитываем защиту от дебафа float resist = Math.max(1, 100 - attacked.calcStat(resistType.getRcptStat(), 0, attacker, skill)) / 100F; // считаем модификатор шанса float mod = 1F * power * resist; // рассчитываем итоговый шанс chance = Math.min((int) (chance * mod), 95); // получаем менеджер рандома RandomManager randomManager = RandomManager.getInstance(); // получаем рандоминайзер Random rand = randomManager.getEffectRandom(); if(rand.chance(chance)) { attacker.sendMessage("Шанс эффекта " + chance + " %. Успех!"); return mod; } else { attacker.sendMessage("Шанс эффекта " + chance + " %. Провал!"); return -1; } } /** * Рассчет опракидывания. * * @param attacker атакующий. * @param attacked атакуемый. * @param skill ударный скил. * @return опрокинул ли. */ public boolean calcOwerturn(Character attacker, Character attacked, Skill skill) { ResistType resistType = ResistType.owerturnResist; if(!resistType.checkCondition(attacker, attacked)) return false; float chance = attacker.getImpact(attacked, skill) * 2F / Math.max(attacked.getBalance(attacker, skill), 1); float power = skill.getOwerturnMod() * attacker.calcStat(resistType.getPowerStat(), 1, attacked, skill) * attacker.getLevel() / Math.max(attacked.getLevel(), 1); float resist = Math.max(1, 100 - attacked.calcStat(resistType.getRcptStat(), 0, attacker, skill)); // получаем менеджер рандома RandomManager randomManager = RandomManager.getInstance(); // получаем рандоминайзер для опрокидывания Random rand = randomManager.getOwerturnRandom(); // рассчитываем опрокидывание return rand.chance(Math.min(chance * power * resist / 100F, 80F)); } /** * Рассчет времени каста. * * @param hitTime базовое время каста. * @param caster тот, кто кастует. * @return итоговое время каста. */ public int castTime(int hitTime, Character caster) { if(hitTime < 1) return 0; return hitTime * 70 / Math.max(caster.getAtkSpd(), 1); } /** * Рассчет шанса сбора ресурса. * * @param req требуемый уровень ресурса. * @param level текущий уровень игрока. * @return шанс сбора. */ public int getChanceCollect(int req, int level) { return Math.max(65 + req - level, 95); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Action_Stage.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; import tera.util.Location; /** * Серверный пакет уведомляющий о старте каста скила * * @author Ronn * @created 31.03.2012 */ public class S_Action_Stage extends ServerPacket { private static final ServerPacket instance = new S_Action_Stage(); public static S_Action_Stage getInstance(Character caster, int skillId, int castId, int state) { S_Action_Stage packet = (S_Action_Stage) instance.newInstance(); if(caster == null) log.warning(packet, new Exception("not found caster")); packet.casterId = caster.getObjectId(); packet.casterSubId = caster.getSubId(); packet.modelId = caster.getModelId(); packet.atkSpd = caster.getAtkSpd() / 100F; packet.skillId = skillId; packet.state = state; packet.castId = castId; caster.getLoc(packet.loc); return packet; } /** позиция кастующего */ private final Location loc; /** ид кастующего */ private int casterId; /** под ид кастующего */ private int casterSubId; /** ид модели кастующего */ private int modelId; /** ид скила */ private int skillId; /** состояние скила */ private int state; /** ид каста */ private int castId; /** скорость атаки кастующего */ private float atkSpd; public S_Action_Stage() { super(); this.loc = new Location(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_ACTION_STAGE; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 0); writeInt(buffer, casterId); writeInt(buffer, casterSubId); writeFloat(buffer, loc.getX()); writeFloat(buffer, loc.getY()); writeFloat(buffer, loc.getZ()); writeShort(buffer, loc.getHeading()); writeInt(buffer, modelId); writeInt(buffer, skillId); writeInt(buffer, state); writeFloat(buffer, atkSpd); /*writeShort(buffer, 0); writeByte(buffer, atkSpd); writeByte(buffer, 0x3F);*/ writeInt(buffer, castId); /* * writeUid(skillProcessor.creature) * writeF(skillProcessor.args.startPosition.x) writeF(skillProcessor.args.startPosition.y) writeF(skillProcessor.args.startPosition.z) writeH(skillProcessor.args.startPosition.heading) writeD(skillProcessor.creature.templateId) writeD(skillProcessor.args.skillId + 0x4000000) writeD(skillProcessor.stage) writeF(skillProcessor.speed) writeD(skillProcessor.uid) */ /*if(true) { writeInt(buffer, 0); // 11 57 30 04 тут бывает какойто скилл ид writeInt(buffer, 50); writeInt(buffer, 200); // 200-2100 у однотипных мобов вроде одинакого writeInt(buffer, 0x6666a63F);// бывает ноль и разные цифры writeShort(buffer, 0); writeByte(buffer, atkSpd); writeByte(buffer, 0x3F); }*/ } }<file_sep>/java/game/tera/gameserver/model/quests/actions/ActionSetQuestState.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestState; /** * Акшен для изминение стадии квеста. * * @author Ronn */ public class ActionSetQuestState extends AbstractQuestAction { /** нужный стейт */ private int state; public ActionSetQuestState(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); this.state = VarTable.newInstance(node).getInteger("state"); } @Override public void apply(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // если его неет, выходим if(player == null) return; // получаем список квестов QuestList questList = player.getQuestList(); // если списка нет, выходим if(questList == null) return; // получаем состояние квеста QuestState state = questList.getQuestState(quest); // если состояния нет, выходим if(state == null) return; // применяем новую стадию state.setState(getState()); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // обновляем в БД dbManager.updateQuest(state); } /** * @return стадия квеста. */ private final int getState() { return state; } @Override public String toString() { return "ActionSetQuestState state = " + state; } } <file_sep>/java/game/tera/gameserver/taskmanager/EffectTaskManager.java package tera.gameserver.taskmanager; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.SafeTask; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.EffectList; import tera.gameserver.model.skillengine.Effect; /** * Менеджер по обиспечению работы эффектов. * * @author Ronn */ @SuppressWarnings("unchecked") public final class EffectTaskManager extends SafeTask { private static final Logger log = Loggers.getLogger(EffectTaskManager.class); private static EffectTaskManager instance; public static EffectTaskManager getInstance() { if(instance == null) instance = new EffectTaskManager(); return instance; } /** блокировщик контейнеров */ private Lock lock; /** доступные контейнеры для эффектов */ private Array<Effect>[] containers; /** пул контейнеров */ private FoldablePool<Array<Effect>> pool; /** текущая позиция в массиве контейнеров */ private volatile int ordinal; private EffectTaskManager() { // создаем массив контейнеров containers = new Array[178000]; // синхронизатор lock = Locks.newLock(); // пул контейнеров pool = Pools.newFoldablePool(Array.class, 1000); // индекс текущего контейнера ordinal = 0; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // добавляем задание на исполнение executor.scheduleGeneralAtFixedRate(this, 1000, 1000); log.info("initialized."); } /** * Добавление в очередь эффект. * * @param effect эффект, который нужно добавить. * @param interval через сколько времени он должен обновится. */ public final void addTask(Effect effect, int interval) { // минимальный интервал if(interval < 1) interval = 1; // максимальный интервал if(interval >= containers.length) interval = containers.length - 1; // определяем целевую ячейку int cell = ordinal + interval; // смещаем, если превышает предел if(containers.length <= cell) cell -= containers.length; // контейнер ожидающих эффектов Array<Effect> container = null; lock.lock(); try { // получаем контейнер container = containers[cell]; // если его нету if(container == null) { // если нету в пуле if(pool.isEmpty()) container = Arrays.toArray(Effect.class); else // если есть, вынимаем container = pool.take(); // добавляем в массив контейнеров containers[cell] = container; } // добавляем эффект в контейнер container.add(effect); } finally { lock.unlock(); } } @Override protected void runImpl() { // контейнер эффектов Array<Effect> container; lock.lock(); try { // забираем с массива контейнер container = containers[ordinal]; // зануляем его в массиве containers[ordinal] = null; } finally { lock.unlock(); } // если контейнера нету if(container == null) { // увеличиваем позицию ordinal += 1; // если предельная позиция - обнуляем if(ordinal >= containers.length) ordinal = 0; // выходим return; } // если в контейнере есть эффекты if(!container.isEmpty()) { // получаем массив эффектов Effect[] array = container.array(); // перебераем эффекты for(int i = 0, length = container.size(); i < length; i++) { // получаем эффект Effect effect = array[i]; // если эффекта нету if(effect == null) { log.warning(new Exception("not found effect")); continue; } // если эффект уже завершен if(effect.isFinished()) { // складываем в пул effect.fold(); continue; } // получаем эффект лист EffectList effectList = effect.getEffectList(); // если его нет, пропускаем обработку эффекта if(effectList == null) { log.warning("not found effect list to " + effect); continue; } effectList.lock(); try { effect.scheduleEffect(); } finally { effectList.unlock(); } // если эффект завершен if(effect.isFinished()) { // ложим в пул effect.fold(); continue; } // добавляем эффект на очередь обработки addTask(effect, effect.getPeriod()); } } // смещаем ячейку ordinal += 1; // если ячейка превысила лимит, обнуляем if(ordinal >= containers.length) ordinal = 0; // очищаем контейнер container.clear(); // ложим контейнер в пул pool.put(container); } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/AbstractShot.java package tera.gameserver.model.skillengine.shots; import java.util.concurrent.ScheduledFuture; import rlib.geom.Geometry; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.Config; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.skillengine.Skill; /** * Базовая модель выстрела. * * @author Ronn */ public abstract class AbstractShot implements Shot { protected static final Logger log = Loggers.getLogger(Shot.class); /** возможные цели */ protected final Array<Character> targets; /** тип выстрела */ protected ShotType type; /** кастующий персонаж */ protected Character caster; /** кастуемый скил */ protected Skill skill; /** скорость */ protected int speed; /** радиус */ protected int radius; /** кол-во поражаемых целей */ protected int count; /** начало полета */ protected long startTime; /** стартовая точка */ protected float startX; protected float startY; protected float startZ; /** целевые координаты */ protected float targetX; protected float targetY; protected float targetZ; /** всего путь */ protected float alldist; /** таск выстрела */ protected volatile ScheduledFuture<?> task; public AbstractShot() { this.targets = Arrays.toArray(Character.class); } @Override public void finalyze() { targets.clear(); setCaster(null); setSkill(null); } /** * @return вся дистанция выстрела. */ protected final float getAlldist() { return alldist; } /** * @return стреляющий персонаж. */ protected final Character getCaster() { return caster; } /** * @return кол-во атакованных целей. */ protected final int getCount() { return count; } @Override public int getObjectId() { return 0; } /** * @return радиус выстрела. */ protected final int getRadius() { return radius; } /** * @return стреляющий скил. */ protected final Skill getSkill() { return skill; } /** * @return скорость выстрела. */ protected final int getSpeed() { return speed; } /** * @return стартовое время выстрела. */ protected final long getStartTime() { return startTime; } /** * @return стартовая координата выстрела. */ protected final float getStartX() { return startX; } /** * @return стартовая координата выстрела. */ protected final float getStartY() { return startY; } /** * @return стартовая координата выстрела. */ protected final float getStartZ() { return startZ; } @Override public int getSubId() { return Config.SERVER_SHOT_SUB_ID; } @Override public Character getTarget() { return null; } /** * @return список целей. */ protected final Array<Character> getTargets() { return targets; } @Override public float getTargetX() { return targetX; } @Override public float getTargetY() { return targetY; } @Override public float getTargetZ() { return targetZ; } /** * @return ссылка на задачу полета. */ protected final ScheduledFuture<?> getTask() { return task; } @Override public ShotType getType() { return type; } @Override public boolean isAuto() { return false; } /** * Реинициализация выстрела. * * @param caster стрелок. * @param skill стреляющий скил. * @param targetX целевая координата. * @param targetY целевая координата. * @param targetZ целевая координата. */ protected void prepare(Character caster, Skill skill, float targetX, float targetY, float targetZ) { // получаем стартовые координаты float startX = caster.getX(); float startY = caster.getY(); float startZ = caster.getZ() + caster.getGeomHeight() - 5F; // получаем дистанцию до цели float alldist = Geometry.getDistance(startX, startY, startZ, targetX, targetY, targetZ); // получаем максимальную дистанцию float range = skill.getRange(); // получаем % от максимальной дистанции float diff = range / alldist; // если целевая координата не является предельной if(diff > 1F) { targetX = startX + ((targetX - startX) * diff); targetY = startY + ((targetY - startY) * diff); targetZ = startZ + ((targetZ - startZ) * diff); } // считаем всю дистанцию setAlldist(range); if(Config.DEVELOPER_MAIN_DEBUG) caster.sendMessage("Shot: dist " + getAlldist()); // вносим стартовые координаты setStartX(startX); setStartY(startY); setStartZ(startZ); // вносим конечные координаты setTargetX(targetX); setTargetY(targetY); setTargetZ(targetZ); // получаем список целей Array<Character> targets = getTargets(); // собираем потенциальные цели World.getAround(Character.class, targets, caster, skill.getRange() * 2); // если есть потенциальные цели if(!targets.isEmpty()) { // получаем массив Character[] array = targets.array(); // перебираем цели for(int i = 0, length = targets.size(); i < length; i++) { // получаем цель Character target = array[i]; // если кастующий не может ударить его if(!caster.checkTarget(target)) { // удаляем из списка targets.fastRemove(i--); length--; continue; } } } setCaster(caster); setSkill(skill); setSpeed(skill.getSpeed()); setRadius(skill.getRadius()); } @Override public void reinit() { count = 0; } @Override public synchronized void run() { // получаем текущее время long now = System.currentTimeMillis(); // получаем пройденное расстояние float donedist = (now - getStartTime()) * getSpeed() / 1000F; // получаем список целей Array<Character> targets = getTargets(); // получаем стартовые координаты float startX = getStartX(); float startY = getStartY(); float startZ = getStartZ(); // получаем конечные координаты float targetX = getTargetX(); float targetY = getTargetY(); float targetZ = getTargetZ(); if(!targets.isEmpty()) { // получаем массив целей Character[] array = targets.array(); // перебираем for(int i = 0, length = targets.size(); i < length; i++) { // получаем цель Character target = array[i]; // если цели нет либо она дальше пройденного расстояния, пропускаем if(target == null || target.getDistance(startX, startY, startZ) > donedist + 100) continue; // удаляем цель из списка targets.fastRemove(i--); length--; // если цель в уклоне/неуязвимости либо мертва, попускаем if(target.isDead() || target.isInvul() || target.isEvasioned()) continue; // определяем попадает ли выстрел в цель if(target.isHit(startX, startY, startZ, targetX, targetY, targetZ, radius)) { // получаем скил Skill skill = getSkill(); // если скила нет, останавливаем выстрел if(skill == null) { stop(); return; } // применяем скил AttackInfo info = skill.applySkill(getCaster(), target); // увеличиваем счетчик count++; // если выстрел был заблокирован или он набрал лимит поражений, останавливаем if(info.isBlocked() || count >= skill.getMaxTargets()) { stop(); return; } } } } // если пройдено все расстояние, останавливаемся if(donedist >= getAlldist()) stop(); } /** * @param alldist вся дистанция полета. */ protected final void setAlldist(float alldist) { this.alldist = alldist; } /** * @param caster кастующицй персонаж. */ protected final void setCaster(Character caster) { this.caster = caster; } /** * @param count кол-во атакованнвых целей. */ protected final void setCount(int count) { this.count = count; } /** * @param radius радиус выстрела. */ protected final void setRadius(int radius) { this.radius = radius; } /** * @param skill стреляющий скил. */ protected final void setSkill(Skill skill) { this.skill = skill; } /** * @param speed скорость выстрела. */ protected final void setSpeed(int speed) { this.speed = speed; } /** * @param startTime время старта выстрела. */ protected final void setStartTime(long startTime) { this.startTime = startTime; } /** * @param startX стартовая координата. */ protected final void setStartX(float startX) { this.startX = startX; } /** * @param startY стартовая координата. */ protected final void setStartY(float startY) { this.startY = startY; } /** * @param startZ стартовая координата. */ protected final void setStartZ(float startZ) { this.startZ = startZ; } /** * @param targetX целевая координата. */ protected final void setTargetX(float targetX) { this.targetX = targetX; } /** * @param targetY целевая координата. */ protected final void setTargetY(float targetY) { this.targetY = targetY; } /** * @param targetZ целевая координата. */ protected final void setTargetZ(float targetZ) { this.targetZ = targetZ; } /** * @param task ссылка на задачу полета. */ protected final void setTask(ScheduledFuture<?> task) { this.task = task; } /** * @param typeтип выстрела. */ protected final void setType(ShotType type) { this.type = type; } @Override public synchronized void start() { // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // запоминаем время старта setStartTime(System.currentTimeMillis()); // запускаем таск полета setTask(executor.scheduleMoveAtFixedRate(this, 0, 100)); } @Override public synchronized void stop() { if(task != null) { task.cancel(false); task = null; } } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/IconType.java package tera.gameserver.model.npc.interaction; /** * Перечисление типов иконок для ссылок в диалогах. * * @author Ronn */ public enum IconType { /** * blue -> guild quest * red -> story quest * yellow -> zone quest * green -> daily quest * purple -> alliance quest */ NONE, //0 RED, //1 NONE2, //2 NONE3, //3 NONE4, //4 NONE5, //5 NONE6, //6 NONE7, //7 BLUE_STAR, //8 RED_STAR, //9 YELLOW_STAR, //10 GREEN_STAR, //11 PURPLE_STAR, //12 BLUE_QUESTION, //13 BLUE_QUESTION_SWITCH, //14 RED_QUESTION, //15 RED_QUESTION_SWITCH, //16 YELLOW_QUESTION, //17 YELLOW_QUESTION_SWITCH, //18 GREEN_QUESTION, //19 GREEN_QUESTION_SWITCH, //20 PURPLE_QUESTION, //21 PURPLE_QUESTION_SWITCH, //22 BLUE_NOTICE, //23 BLUE_NOTICE_SWITCH, //24 RED_NOTICE, //25 RED_NOTICE_SWITCH, //26 YELLOW_NOTICE, //27 YELLOW_NOTICE_SWITCH, //28 GREEN_NOTICE, //29 GREEN_NOTICE_SWITCH, //30 PURPLE_NOTICE, //31 PURPLE_NOTICE_SWITCH, //32 DIALOG, //33 NONE29, //34 NONE30, //35 GREEN, //36 } <file_sep>/java/game/tera/gameserver/model/skillengine/lambdas/LambdaFloat.java package tera.gameserver.model.skillengine.lambdas; /** * Вещественный модификатор. * * @author Ronn * @created 28.02.2012 */ public abstract class LambdaFloat implements Lambda { /** значение модификатора */ protected float value; public LambdaFloat(float value) { super(); this.value = value; } @Override public Object getValue() { return value; } } <file_sep>/java/game/tera/gameserver/model/npc/RegionWarControl.java package tera.gameserver.model.npc; import tera.gameserver.events.global.regionwars.Region; import tera.gameserver.events.global.regionwars.RegionWarNpc; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.Guild; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.S_Show_Hp; import tera.gameserver.templates.NpcTemplate; /** * Модель регионального контрола. * * @author Ronn */ public class RegionWarControl extends Monster implements RegionWarNpc { /** владеющая гильдия */ private Guild guild; /** регион, к которому принадлежит */ private Region region; public RegionWarControl(int objectId, NpcTemplate template) { super(objectId, template); } @Override public void setGuildOwner(Guild guild) { this.guild = guild; } @Override public void setRegion(Region region) { this.region = region; } @Override public Region getRegion() { return region; } @Override public Guild getGuildOwner() { return guild; } @Override public boolean isOwerturnImmunity() { return true; } @Override public boolean isStunImmunity() { return true; } @Override public boolean isSleepImmunity() { return true; } @Override public boolean isLeashImmunity() { return true; } @Override public void causingDamage(Skill skill, AttackInfo info, Character attacker) { // если атакуемый персонаж игрок if(attacker.isPlayer()) { // получаем гильдию атакующего Guild guild = attacker.getGuild(); // если это гильдия не зарегестрирована в этой битве, игнорируем атакующего if(!region.isRegister(guild) || getGuildOwner() == guild) return; } super.causingDamage(skill, info, attacker); } @Override public void updateHp() { super.updateHp(); // получаем владельца Guild owner = getGuildOwner(); // если он есть if(owner != null) // отправляем всем состояние хп owner.sendPacket(null, S_Show_Hp.getInstance(this, S_Show_Hp.BLUE)); } } <file_sep>/README.md # tera_2805 Tera Server emulator 28.05 <file_sep>/java/game/tera/gameserver/model/npc/TaxationNpc.java package tera.gameserver.model.npc; import tera.gameserver.model.inventory.Bank; /** * Интерфейс для реализации облаживаемого налогом магазина. * * @author Ronn */ public interface TaxationNpc { /** * @return налог. */ public int getTax(); /** * @return банк, в который перенаправлять вырученные средства. */ public Bank getTaxBank(); } <file_sep>/java/game/tera/gameserver/model/Bonfire.java package tera.gameserver.model; /** * Интерфейс-маркер говорящий о том, что класс есть костер для регена стамины. * * @author Ronn */ public interface Bonfire { } <file_sep>/java/game/tera/gameserver/tasks/AnnounceTask.java package tera.gameserver.tasks; import java.util.concurrent.ScheduledFuture; import rlib.util.SafeTask; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.World; /** * Модель периодического аннонса. * * @author Ronn * @created 29.03.2012 */ public class AnnounceTask extends SafeTask { /** отправляемый текст */ private final String text; /** интервал */ private final int interval; /** ссылка на таск */ private ScheduledFuture<AnnounceTask> schedule; public AnnounceTask(String text, int interval) { this.text = text; this.interval = interval; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); this.schedule = executor.scheduleGeneralAtFixedRate(this, interval, interval); } /** * Остановка аннонса. */ public synchronized void cancel() { if(schedule != null) schedule.cancel(true); } /** * @return интервал аннонса. */ public final int getInterval() { return interval; } /** * @return текст аннонса. */ public final String getText() { return text; } @Override protected void runImpl() { World.sendAnnounce(text); } } <file_sep>/java/game/tera/gameserver/model/DuelPlayer.java package tera.gameserver.model; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.playable.Player; /** * Контейнер состояние игрока для дуэли. * * @author Ronn */ public class DuelPlayer { /** список откатываемых скилов */ private Array<ReuseSkill> reuses; /** состояние хп перед дуэлью */ private int hp; /** состояние мп перед дуэлью */ private int mp; /** состояние стамины перед дуэлью */ private int stamina; public DuelPlayer() { this.reuses = Arrays.toArray(ReuseSkill.class); } /** * @return список скилов игрока в откате. */ public Array<ReuseSkill> getReuses() { return reuses; } /** * Восстановление состояния игрока. * * @param player восстанавливаемый игрок. */ public void restore(Player player) { // восстанавливаем стамину player.setStamina(stamina); // восстанавливаем состояние хп player.setCurrentHp(hp); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // уведомляем об этом eventManager.notifyHpChanged(player); // восстанавливаем состояние мп player.setCurrentMp(mp); // уведомляем об этом eventManager.notifyMpChanged(player); // получаем таблицу откатов скилов Table<IntKey, ReuseSkill> reuseTable = player.getReuseSkills(); // получаем список откатываемых скилов Array<ReuseSkill> reuses = getReuses(); // получаем текущее время long current = System.currentTimeMillis(); // перебираем текущую таблицу откатов for(ReuseSkill reuse : reuseTable) if(!reuse.isItemReuse() && reuse.getEndTime() > current && !reuses.contains(reuse)) player.enableSkill(player.getSkill(reuse.getSkillId())); // очищаем список reuses.clear(); } /** * Сохранение состояния игрока перед дуэлью. * * @param player сохраняемый игрок. */ public void save(Player player) { // запоминаем статы this.hp = player.getCurrentHp(); this.mp = player.getCurrentMp(); this.stamina = player.getStamina(); // получаем таблицу откатов скилов Table<IntKey, ReuseSkill> reuseTable = player.getReuseSkills(); // получаем список откатываемых скилов Array<ReuseSkill> reuses = getReuses(); // очищаем его reuses.clear(); // получаем текущее время long current = System.currentTimeMillis(); // перебираем текущую таблицу откатов for(ReuseSkill reuse : reuseTable) { // если скил в откате if(!reuse.isItemReuse() && reuse.getEndTime() > current) // вносим в список его reuses.add(reuse); } } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/ConterStrike.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.templates.SkillTemplate; /** * Модель контр удара после блокирования щитом. * * @author Ronn */ public class ConterStrike extends Strike { /** * @param template темплейт скила. */ public ConterStrike(SkillTemplate template) { super(template); } @Override public boolean checkCondition(Character attacker, float targetX, float targetY, float targetZ) { if(!attacker.isPlayer() || !attacker.isDefenseStance()) return false; long last = attacker.getPlayer().getLastBlock(); if(System.currentTimeMillis() - last > 1000) { attacker.sendMessage("Можно использовать только после успешного блока."); return false; } return super.checkCondition(attacker, targetX, targetY, targetZ); } @Override public boolean isWaitable() { return false; } } <file_sep>/java/game/tera/gameserver/model/actions/ActionType.java package tera.gameserver.model.actions; import rlib.logging.Loggers; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.model.actions.classes.BindItemAction; import tera.gameserver.model.actions.classes.DuelStartAction; import tera.gameserver.model.actions.classes.EnchantItemAction; import tera.gameserver.model.actions.classes.GuildCreateAction; import tera.gameserver.model.actions.classes.GuildInviteAction; import tera.gameserver.model.actions.classes.PartyInviteAction; import tera.gameserver.model.actions.classes.TradeStartAction; import tera.gameserver.model.playable.Player; /** * Перечисление типов акшенов. * * @author Ronn * @created 07.03.2012 */ public enum ActionType { NONE(null), NONE1(null), NONE2(null), TRADE(TradeStartAction.class), PARTY(PartyInviteAction.class), JOIN_PARTY(null), NONE6(null), NONE7(null), NONE8(null), NONE9(null), CREATE_GUILD(GuildCreateAction.class), INVITE_GUILD(GuildInviteAction.class), DUEL(DuelStartAction.class), NONE13(null), NONE14(null), NONE15(null), TELEPORT(null), NONE17(null), NONE18(null), NONE19(null), NONE20(null), NONE21(null), NONE22(null), NONE23(null), NONE24(null), NONE25(null), NONE26(null), NONE27(null), NONE28(null), NONE29(null), NONE30(null), NONE31(null), BIND_ITEM(BindItemAction.class), NONE32(null), ENCHANT_ITEM(EnchantItemAction.class) ; /** массив типов */ public static final ActionType[] ELEMENTS = values(); /** * Получение типа акшена по индексу. * * @param index индекс типа акшена. * @return тип акшена. */ public static ActionType valueOf(int index) { if (index < 0 || index >= ELEMENTS.length) return ActionType.NONE; return ELEMENTS[index]; } /** пул акшенов */ private FoldablePool<Action> pool; /** тип акшена */ private Class<? extends Action> type; private ActionType(Class<? extends Action> type) { this.type = type; this.pool = Pools.newConcurrentFoldablePool(Action.class); } /** * @return пул акшенов. */ public final FoldablePool<Action> getPool() { return pool; } /** * @return реализован ли такой акшен. */ public boolean isImplemented() { return type != null; } /** * Создание нового экземпляра акшена. * * @param actor инициатор акшена. * @param name имя цели. * @return новый акшен. */ public Action newInstance(Player actor, String name) { Action action = pool.take(); if (action == null) try { action = type.newInstance(); } catch (InstantiationException | IllegalAccessException e) { Loggers.warning(this, e); } action.init(actor, name); return action; } } <file_sep>/java/game/tera/gameserver/tasks/SkillUseTask.java package tera.gameserver.tasks; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import rlib.util.SafeTask; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Formulas; import tera.gameserver.model.skillengine.Skill; /** * Модель обработки приминения скила. * * @author Ronn */ public final class SkillUseTask extends SafeTask { /** блокировщик */ private final Lock lock; /** кастующий скилл */ private final Character caster; /** кастующийся скилл */ private Skill skill; /** целевая координата */ private float targetX; /** целевая координата */ private float targetY; /** целевая координата */ private float targetZ; /** кол-во приминений */ private int count; /** ссылка на таск */ private volatile ScheduledFuture<SkillUseTask> schedule; /** * @param caster кастующий персонаж. */ public SkillUseTask(Character caster) { this.lock = Locks.newLock(); this.caster = caster; } /** * Отмена приминения скила. * * @param force принудительная ли отмена. */ public void cancel(boolean force) { if(schedule != null) { lock.lock(); try { if(schedule != null) { schedule.cancel(false); schedule = null; } } finally { lock.unlock(); } } } /** * @return обрабатываемый скил. */ public Skill getSkill() { return skill; } /** * @param skill применяемый скил. */ public void nextUse(Skill skill) { cancel(true); Formulas formulas = Formulas.getInstance(); lock.lock(); try { this.skill = skill; this.count = skill.getCastCount(); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); this.schedule = executor.scheduleSkillCast(this, skill.isStaticCast()? skill.getDelay() : formulas.castTime(skill.getDelay(), caster)); } finally { lock.unlock(); } } /** * @param skill применяемый скил. * @param targetX целевая координата. * @param targetY целевая координата. * @param targetZ целевая координата. */ public void nextUse(Skill skill, float targetX, float targetY, float targetZ) { cancel(true); Formulas formulas = Formulas.getInstance(); lock.lock(); try { this.skill = skill; this.count = skill.getCastCount(); this.targetX = targetX; this.targetY = targetY; this.targetZ = targetZ; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); this.schedule = executor.scheduleSkillUse(this, skill.isStaticCast()? skill.getDelay() : formulas.castTime(skill.getDelay(), caster)); } finally { lock.unlock(); } } @Override protected void runImpl() { count -= 1; Skill skill = getSkill(); if(skill == null) return; // добавляем смещение направления каста caster.setHeading(caster.getHeading() + skill.getCastHeading()); // активируем приминение скила skill.useSkill(caster, targetX, targetY, targetZ); if(count > 0) { // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); Formulas formulas = Formulas.getInstance(); schedule = executor.scheduleSkillCast(this, skill.isStaticInterval()? skill.getInterval() : formulas.castTime(skill.getInterval(), caster)); } } /** * @param targetX целевая координата. * @param targetY целевая координата. * @param targetZ целевая координата. */ public void setTarget(float targetX, float targetY, float targetZ) { cancel(true); this.targetX = targetX; this.targetY = targetY; this.targetZ = targetZ; } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/ClearDebuff.java package tera.gameserver.model.skillengine.classes; import rlib.util.array.Array; import tera.gameserver.model.Character; import tera.gameserver.model.EffectList; import tera.gameserver.model.skillengine.Effect; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель скила, служащего только для активирования бафа. * * @author Ronn */ public class ClearDebuff extends AbstractSkill { /** * @param template темплейт скила. */ public ClearDebuff(SkillTemplate template) { super(template); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); Array<Character> targets = local.getNextCharList(); addTargets(targets, character, targetX, targetY, targetZ); Character[] array = targets.array(); for(int i = 0, length = targets.size(); i < length; i++) { Character target = array[i]; if(target.isDead() || target.isInvul()) continue; EffectList effectList = target.getEffectList(); if(effectList == null || effectList.size() < 1) continue; Array<Effect> effects = effectList.getEffects(); Effect[] effectArray = effects.array(); for(int g = 0, size = effects.size(); g < size; g++) { Effect effect = effectArray[g]; if(effect == null || effect.isAura() || !effect.isDebuff()) continue; effect.exit(); } } } } <file_sep>/java/game/tera/gameserver/manager/ObjectEventManager.java package tera.gameserver.manager; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.Character; import tera.gameserver.model.EffectList; import tera.gameserver.model.Guild; import tera.gameserver.model.Party; import tera.gameserver.model.SkillLearn; import tera.gameserver.model.TObject; import tera.gameserver.model.ai.AI; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.listeners.DeleteListener; import tera.gameserver.model.listeners.DieListener; import tera.gameserver.model.listeners.LevelUpListener; import tera.gameserver.model.listeners.PlayerSelectListener; import tera.gameserver.model.listeners.PlayerSpawnListener; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Playable; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestEventType; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestUtils; import tera.gameserver.model.resourse.ResourseInstance; import tera.gameserver.model.skillengine.ChanceType; import tera.gameserver.model.skillengine.Effect; import tera.gameserver.model.skillengine.Skill; import tera.util.LocalObjects; /** * Менеджер обработки событий игровых объектов в игре. * * @author Ronn */ public final class ObjectEventManager { private static final Logger log = Loggers.getLogger(ObjectEventManager.class); private static ObjectEventManager instance; public static ObjectEventManager getInstance() { if(instance == null) instance = new ObjectEventManager(); return instance; } /** слушатели убийств */ private final Array<DieListener> dieListeners; /** слушатели удаляемых объектов */ private final Array<DeleteListener> deleteListeners; /** набор слушателей лвл апов игроков */ private final Array<LevelUpListener> levelUpListeners; /** набор слушателей спавнов игроков */ private final Array<PlayerSpawnListener> playerSpawnListeners; /** набор слушателей выбора игрока для входа */ private final Array<PlayerSelectListener> playerSelectListeners; private ObjectEventManager() { dieListeners = Arrays.toConcurrentArray(DieListener.class); deleteListeners = Arrays.toConcurrentArray(DeleteListener.class); levelUpListeners = Arrays.toConcurrentArray(LevelUpListener.class); playerSpawnListeners = Arrays.toConcurrentArray(PlayerSpawnListener.class); playerSelectListeners = Arrays.toConcurrentArray(PlayerSelectListener.class); log.info("initialized."); } /** * @return список слушателей выбора игрока. */ public Array<PlayerSelectListener> getPlayerSelectListeners() { return playerSelectListeners; } /** * @param listener добавляемый слушатель. */ public final void addDeleteListener(DeleteListener listener) { deleteListeners.add(listener); } /** * @param listener добавляемый слушатель. */ public final void addDieListener(DieListener listener) { dieListeners.add(listener); } /** * Доабвление слушателей лвл апов. */ public final void addLevelUpListener(LevelUpListener listener) { levelUpListeners.add(listener); } /** * Доабвление слушателей спавнов игроков. */ public final void addPlayerSpawnListener(PlayerSpawnListener listener) { playerSpawnListeners.add(listener); } /** * Доабвление слушателей выбора игроков. */ public final void addPlayerSelectListener(PlayerSelectListener listener) { playerSelectListeners.add(listener); } /** * @return получаем слушателей по удалению объектов. */ public Array<DeleteListener> getDeleteListeners() { return deleteListeners; } /** * @return слушатели убийств. */ public Array<DieListener> getDieListeners() { return dieListeners; } /** * @return слушатели изменения уровней игроков. */ public Array<LevelUpListener> getLevelUpListeners() { return levelUpListeners; } /** * @return слушатели спавна игроков. */ public Array<PlayerSpawnListener> getPlayerSpawnListeners() { return playerSpawnListeners; } /** * Уведомление о добавлении НПС игроку. * * @param player игрок, которому добавился НПС. * @param npc добавляемый НПС. */ public void notifyAddNpc(Player player, Npc npc) { // высвечиваем доступный квест npc.updateQuestInteresting(player, false); // получаем список квестов игрока QuestList questList = player.getQuestList(); // если есть активные квесты if(questList != null && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем событие квеста QuestEvent event = local.getNextQuestEvent(); // запоминаем игрока event.setPlayer(player); // запоминаем нпс event.setNpc(npc); // запоминаем тип ивента event.setType(QuestEventType.ADD_NPC); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } /** * Уведомление об изменение уровня агрессии объекта по отношению к аткующему. * * @param object атакуемый. * @param attacker атакующий. * @param aggro кол-во добавленых агр очков. */ public final void notifyAgression(Character object, Character attacker, long aggro) { object.getAI().notifyAgression(attacker, aggro); } /** * Уведомление о наложении эффекта на персонажа. * *@param effected на кого наложили эффект. *@param effect наложенный эффект. */ public final void notifyAppliedEffect(Character effected, Effect effect) { effected.getAI().notifyAppliedEffect(effect); } /** * Уведомление об прибытии объекта в назначенную точку. * * @param object прибывший объект. */ public final void notifyArrived(Character object) { object.getAI().notifyArrived(); } /** * Уведомление об блокировке перемещения объекта. * * @param object заблокированный объект. */ public final void notifyArrivedBlocked(Character object) { object.getAI().notifyArrivedBlocked(); } /** * Уведомление о прибытии объекта к указанной цели. * * @param object прибывший объект. * @param target цель прибытия. */ public final void notifyArrivedTarget(Character object, TObject target) { object.getAI().notifyArrivedTarget(target); } /** * Уведомление о атаке объектом. * * @param attacker атакующий объект. * @param attacked атакуемый объект. * @param skill атакующий скилл. * @param damage кол-во урона. * @param crit является ли удар критическим. */ public final void notifyAttack(Character attacker, Character attacked, Skill skill, int damage, boolean crit) { // уведомляем АИ об этом attacker.getAI().notifyAttack(attacked, skill, damage); // получаем список эффектов EffectList effectList = attacker.getEffectList(); // завершаем эффекты, завершаемые при атаке кого-то effectList.exitNoAttackEffects(); // если атакуемый на пегасе if(attacker.isOnMount()) // слезаем с пегаса attacker.getOffMount(); // получаем владельца атакуемого Character owner = attacker.getOwner(); // если владелец есть if(owner != null) { // если он на пегасе if(owner.isOnMount()) // слазим с пегаса owner.getOffMount(); // запускаем боевую стойку owner.startBattleStance(attacker); } // запускаем боевую стойку attacker.startBattleStance(attacked); // запускаем шансовые функции attacker.applyChanceFunc(crit? ChanceType.ON_CRIT_ATTACK : ChanceType.ON_ATTACK, attacked, skill); } /** * Уведомление о атаке объекта. * * @param attacked атакуемый объект. * @param attacker атакующий объект. * @param skill атакующий скил. * @param damage кол-во урона. * @param crit является ли удар критическим. */ public final void notifyAttacked(Character attacked, Character attacker, Skill skill, int damage, boolean crit) { // увндомляем АИ об этом attacked.getAI().notifyAttacked(attacker, skill, damage); // получаем список эффектов персонажа EffectList effectList = attacked.getEffectList(); // завершаем эффекты, завершаемые при получении урона effectList.exitNoAttackedEffects(); // если атакуемый на пегасе if(attacked.isOnMount()) // слазим с пегаса attacked.getOffMount(); // получаем владельца атакуемого Character owner = attacked.getOwner(); // если владелец есть if(owner != null) { // если он на пегасе if(owner.isOnMount()) // слазим с пегаса owner.getOffMount(); // запускаем боевую стойку owner.startBattleStance(attacker); } // запускаем боевую стойку attacked.startBattleStance(attacker); // вызываем шансовые функции attacked.applyChanceFunc(crit? ChanceType.ON_CRIT_ATTACKED : ChanceType.ON_ATTACKED, attacker, skill); } /** * Уведомление об изминении уровня играющего. * * @param playable объект. */ public final void notifyChangedLevel(Playable playable) { // если персонаж игрока if(playable.isPlayer()) { // получаем игрока Player player = playable.getPlayer(); // получаем гильдию игрока Guild guild = playable.getGuild(); // если гильдия есть if(guild != null) // обновляем параметры игрока в ней guild.updateMember(player); // обновляем информацию о игроке player.updateInfo(); // получаем менеджера БД DataBaseManager manager = DataBaseManager.getInstance(); // обновляем уровень в БД manager.updatePlayerLevel(player); // получаем список слушателей Array<LevelUpListener> listeners = getLevelUpListeners(); // если слушателей нет, выходим if(listeners.isEmpty()) return; listeners.readLock(); try { LevelUpListener[] array = listeners.array(); for(int i = 0, length = listeners.size(); i < length; i++) array[i].onLevelUp(player); } finally { listeners.readUnlock(); } } } /** * Уведомление об изминении локации играющего. * * @param playable объект. */ public final void notifyChangedZoneId(Playable playable) { // если персонаж игрок if(playable.isPlayer()) { // получаем игрока Player player = playable.getPlayer(); // получаем гильдию Guild guild = playable.getGuild(); // если гильдия есть if(guild != null) // обновляем игрока в гильдии guild.updateMember(player); // получаем менеджера БД DataBaseManager manager = DataBaseManager.getInstance(); // обновляем зону в БД manager.updatePlayerZoneId(player); } } /** * Уведомление об сборе ресурса. * * @param resourse собранный ресурс. * @param collector персонаж, который собрал. */ public final void notifyCollect(ResourseInstance resourse, Character collector) { // если ресурса нет, выходим if(resourse == null) { log.warning(new Exception("not found resourse")); return; } // если собирателя нет, выходим if(collector == null) { log.warning(new Exception("not found collector")); return; } // получаем АИ сборщика AI ai = collector.getAI(); // если АИ есть if(ai != null) // его тоже уведомляем ai.notifyCollectResourse(resourse); // получаем игрока из сборщика Player player = collector.getPlayer(); // если игрок есть if(player != null) { // получаем его список квестов QuestList questList = player.getQuestList(); // если есть активные квесты if(questList != null && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем ивент QuestEvent event = local.getNextQuestEvent(); // запоминаем игрока event.setPlayer(player); // заносим тип ивента event.setType(QuestEventType.COLLECT_RESOURSE); // запоминаем ресурс event.setResourse(resourse); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } } /** * Уведомление о смерти персонажа. * * @param character умерший персонаж. * @param killer убийца персонажа. */ public final void notifyDead(Character character, Character killer) { // сообщаем АИ о смерти character.getAI().notifyDead(killer); // если убитый является НПС if(character.isNpc()) { // получаем НПС Npc npc = character.getNpc(); // получаем главного дэмагера Character damager = npc.getMostDamager(); // если есть топ демагер if(damager != null) { // определяем потенциального выполнителя квестов Character questor = damager.isSummon()? damager.getOwner() : damager; // определяем список квестов QuestList questList = questor == null? null : questor.getQuestList(); // если есть активные квесты if(questList != null && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // квестовый ивент QuestEvent event = local.getNextQuestEvent(); // вставляем нпс event.setNpc(npc); // вставляем игрока event.setPlayer(questor.getPlayer()); // тип ивента event.setType(QuestEventType.KILL_NPC); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); // получаем группу выполнителя Party party = questor.getParty(); // если группа есть if(party != null) { // получаем список членов группы Array<Player> members = party.getMembers(); members.readLock(); try { Player[] array = members.array(); for(int i = 0, length = members.size(); i < length; i++) { // получаем члена группы Player member = array[i]; // если его нет или это квестор, пропускаем if(member == null || member == questor) continue; // получаем список квестов члена группы questList = member.getQuestList(); // если есть активные квесты if(questList != null && questList.hasActiveQuest()) { // вставляем нпс event.setNpc(npc); // вставляем игрока event.setPlayer(member); // тип ивента event.setType(QuestEventType.KILL_NPC); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } } finally { members.readUnlock(); } } } } } // получаем список слушателей Array<DieListener> listeners = getDieListeners(); // если нет слушателей, выходим if(listeners.isEmpty()) return; listeners.readLock(); try { DieListener[] array = listeners.array(); // перебираем слушателей for(int i = 0, length = listeners.size(); i < length; i++) array[i].onDie(killer, character); } finally { listeners.readUnlock(); } } /** * Уведомление о удалении объекта. * * @param object удаленный объект. */ public final void notifyDelete(TObject object) { // получаем слушателей Array<DeleteListener> listeners = getDeleteListeners(); if(listeners.isEmpty()) return; listeners.readLock(); try { DeleteListener[] array = listeners.array(); for(int i = 0, length = listeners.size(); i < length; i++) array[i].onDelete(object); } finally { listeners.readUnlock(); } } /** * Уведомление об изминение экиперовки. * * @param owner владелец equipment. */ public final void notifyEquipmentChanged(Character owner) { if(owner == null) return; // если персонаж игрок if(owner.isPlayer()) { // обновляем его экиперовку //PacketManager.updateEquip(owner); // обновляем инвентарь PacketManager.updateInventory(owner.getPlayer()); } } /** * Уведомление о завершении каста скилла объектом. * * @param object кастующий объект. * @param skill кастуемый скил. */ public final void notifyFinishCasting(Character object, Skill skill) { // записываем название скила object.setLastSkillName(skill.getSkillName()); // записываем время завершения этого каста object.setLastCast(System.currentTimeMillis()); // уведомляем АИ об завершении каста скила object.getAI().notifyFinishCasting(skill); } /** * Уведомление о завершениисбора ресурса сборщиком. * * @param object собирающий ресурс. * @param resourse собираемый ресурс.. */ public final void notifyFinishCollect(Character object, ResourseInstance resourse) { // уведомляем АИ об завершении каста скила object.getAI().notifyCollectResourse(resourse); } /** * Уведомление об изминении банка. * * @param owner владелец банка. */ public final void notifyGuildBankChanged(Character owner, int startCell) { if(owner == null || !owner.isPlayer()) return; // обновляем банк гильдии PacketManager.updateGuildBank(owner.getPlayer(), startCell); } /** * Уведомление об изминение состояния хп. * * @param owner вперсонаж, у которого было изминение. */ public final void notifyHpChanged(Character owner) { owner.updateHp(); } public final void notifyFatigabilityChanged(Character owner) { owner.updateFatigability(); } /** * Уведомление о добавлении итема в инвентарь. * * @param object владелец инвенторя. * @param item добавленный итем. */ public final void notifyInventoryAddItem(Character object, ItemInstance item) { if(object == null || item == null) { log.warning(new Exception("not found object or item")); return; } // получаем список квестов QuestList questList = object.getQuestList(); // если есть активные квесты if(questList != null && object.isPlayer() && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем событие квеста QuestEvent event = local.getNextQuestEvent(); // вносим итем event.setItem(item); // вносим игрока event.setPlayer(object.getPlayer()); // меняем на тип добавления в инвентарь event.setType(QuestEventType.INVENTORY_ADD_ITEM); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } /** * Уведомление об изминении инвенторя. * * @param owner владелец инвенторя. */ public final void notifyInventoryChanged(Character owner) { if(owner == null || !owner.isPlayer()) return; PacketManager.updateInventory(owner.getPlayer()); } /** * Уведомление о удалении объектом итема. * * @param object владелец инвенторя. * @param item удаленный итем. */ public final void notifyInventoryRemoveItem(Character object, ItemInstance item) { if(object == null || item == null) { log.warning(new Exception("not found object or item")); return; } // получаем список квестов персонажа QuestList questList = object.getQuestList(); // если есть активные квесты if(questList != null && object.isPlayer() && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем событие квеста QuestEvent event = local.getNextQuestEvent(); // вносим итем event.setItem(item); // вносим игрока event.setPlayer(object.getPlayer()); // ставим тип поднятия итема event.setType(QuestEventType.INVENTORY_REMOVE_ITEM); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } /** * Уведомление об изминение состояния ьз. * * @param owner вперсонаж, у которого было изминение. */ public final void notifyMpChanged(Character owner) { owner.updateMp(); } /** * Уведомлении о том, что персонаж опрокинул кого-то. * * @param attacker тот кто опрокинул. * @param attacked опрокинутый. * @param skill используемый скил для удара. */ public final void notifyOwerturn(Character attacker, Character attacked, Skill skill) { attacker.applyChanceFunc(ChanceType.ON_OWERTURN, attacked, skill); } /** * Уведомлении о том, что персонаж был опрокинут. * * @param attacked опрокинутый. * @param attacker атакующий. * @param skill используемый скил для удара. */ public final void notifyOwerturned(Character attacked, Character attacker, Skill skill) { attacked.applyChanceFunc(ChanceType.ON_OWERTURNED, attacker, skill); } /** * Уведомление о поднятие объектом итем с земли. * * @param object поднявший итем объект. * @param item поднятый итем. */ public final void notifyPickUpItem(Character object, ItemInstance item) { if(object == null || item == null) { log.warning(new Exception("not found object or item")); return; } // уведоиляем АИ об поднятии итема object.getAI().notifyPickUpItem(item); // получаем список квестов QuestList questList = object.getQuestList(); // если есть активные квесты if(questList != null && object.isPlayer() && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем событие квеста QuestEvent event = local.getNextQuestEvent(); // вносим итем event.setItem(item); // вносим игрока event.setPlayer(object.getPlayer()); // ставим тип поднятия итема event.setType(QuestEventType.PICK_UP_ITEM); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } /** * Уведомление об изминении банка. * * @param owner владелец банка. */ public final void notifyPlayerBankChanged(Character owner, int startCell) { if(owner == null || !owner.isPlayer()) return; PacketManager.updatePlayerBank(owner.getPlayer(), startCell); } /** * Уведомление о завершение просмотра квестового мувика. * * @param character персонаж, который просматривал. * @param movieId ид мувика. * @param force принудительное ли завершение. */ public final void notifyQuestMovieEnded(Player character, int movieId, boolean force) { // получаем его список квестов QuestList questList = character.getQuestList(); // если списка нет, выходим if(questList == null) { log.warning(new Exception("not found quest list for player " + character.getName())); return; } // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем ивент QuestEvent event = local.getNextQuestEvent(); // вносим игрока event.setPlayer(character); // ставим тип окончания мувика event.setType(QuestEventType.QUEST_MOVIE_ENDED); // вносим ид мувика event.setValue(movieId); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } /** * Уведомлении о том, что персонаж заблокировал удар другого персонажа. * * @param attacked блокирующий. * @param attacker атакующий. * @param skill используемый скил для удара. */ public final void notifyShieldBlocked(Character attacked, Character attacker, Skill skill) { attacked.addDefenseCounter(); attacked.applyChanceFunc(ChanceType.ON_SHIELD_BLOCK, attacker, skill); } /** * Уведомление о изучении скила персонажем. * * @param character изучающий скил. * @param learn изучаемый скил. */ public final void notifySkillLearned(Character character, SkillLearn learn) { if(character == null || learn == null) { log.warning(new Exception("not found object or item")); return; } // получаем квестовый лист объекта QuestList questList = character.getQuestList(); // если это игрок с активными квестами if(questList != null && character.isPlayer() && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем свободный ивент квеста QuestEvent event = local.getNextQuestEvent(); // вносим игрока event.setPlayer(character.getPlayer()); // ставим тип поднятия итема event.setType(QuestEventType.SKILL_LEARNED); // ставим ид скила event.setValue(learn.getId()); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } /** * Уведомление об спавне объекта. * * @param object отспавненный объект. */ public final void notifySpawn(TObject object) { // если объекта нет, выходим if(object == null) return; // получаем АИ объекта AI ai = object.getAI(); // если АИ есть if(ai != null) // его тоже уведомляем ai.notifySpawn(); // получаем игрока с объекта Player player = object.getPlayer(); // если игрок есть if(player != null) { // получаем его квест лист QuestList questList = player.getQuestList(); // если квест лист есть и есть активные квесты if(questList != null && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем ивент QuestEvent event = local.getNextQuestEvent(); // запоминаем игрока event.setPlayer(player); // заносим тип ивента event.setType(QuestEventType.PLAYER_SPAWN); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } // получаем списки слушателей Array<PlayerSpawnListener> listeners = getPlayerSpawnListeners(); if(listeners.isEmpty()) return; listeners.readLock(); try { // получаем массив слушателей PlayerSpawnListener[] array = listeners.array(); for(int i = 0, length = listeners.size(); i < length; i++) array[i].onSpawn(player); } finally { listeners.readUnlock(); } } } /** * Уведомление о выборе игрока для входа в игру. * * @param player выбранный игрок. */ public final void notifyPlayerSelect(Player player) { // получаем список слушателей выбора Array<PlayerSelectListener> listeners = getPlayerSelectListeners(); // если их нет, выходим if(listeners.isEmpty()) return; listeners.readLock(); try { PlayerSelectListener[] array = listeners.array(); // перебираем и обрабатываем событие for(int i = 0, length = listeners.size(); i < length; i++) array[i].onSelect(player); } finally { listeners.readUnlock(); } } /** * Уведомление об изминение состояния усталости. * * @param owner вперсонаж, у которого было изминение. */ public final void notifyStaminaChanged(Character owner) { // обнловляем стамину owner.updateStamina(); // получаем список квестов QuestList questList = owner.getQuestList(); // если список есть, персонаж игрок и у него есть активные квесты if(questList != null && owner.isPlayer() && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем событие квеста QuestEvent event = local.getNextQuestEvent(); // вносим игрока event.setPlayer(owner.getPlayer()); // вносим тип события event.setType(QuestEventType.CHANGED_HEART); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } /** * Уведомление о начале каста скила объектом. * * @param object кастующий объект. * @param skill кастуемый скил. */ public final void notifyStartCasting(Character object, Skill skill) { // если объекта нету ,выходим if(object == null) return; // получаем АИ объекта AI ai = object.getAI(); // если АИ объекта есть if(ai != null) // уведомляем его ai.notifyStartCasting(skill); } /** * Уведомление об начале диалога объекта с игроком. * * @param object разговариемый объект. * @param player разговариваемый игрок. */ public final void notifyStartDialog(Character object, Player player) { // если объекта нет, выходим if(object == null) return; // получаем АИ объекта AI ai = object.getAI(); // если АИ есть if(ai != null) // уведомляем ai.notifyStartDialog(player); } /** * Уведомление об изминение статов игрока. * * @param owner игрок. */ public final void notifyStatChanged(Character owner) { if(owner == null) return; owner.updateInfo(); } /** * Уведомление об завершении диалога объекта с игроком. * * @param object разговариемый объект. * @param player разговариваемый игрок. */ public final void notifyStopDialog(Character object, Player player) { // если объекта нет, выходим if(object == null) return; // получаем АИ объекта AI ai = object.getAI(); // если АИ есть if(ai != null) // уведомляем ai.notifyStopDialog(player); } /** * Уведомление об использовании итема. * * @param item используемый итем. * @param owner вперсонаж, который использовал итем. */ public final void notifyUseItem(ItemInstance item, Character owner) { // получаем список квестов QuestList questList = owner.getQuestList(); // если есть активные квесты if(owner.isPlayer() && questList.hasActiveQuest()) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем событие квеста QuestEvent event = local.getNextQuestEvent(); // вносим итем event.setItem(item); // вносим игрока event.setPlayer(owner.getPlayer()); // вносим тип события event.setType(QuestEventType.USE_ITEM); // уведомляем квесты QuestUtils.notifyQuests(questList.getActiveQuests(), event); } } /** * @param listener удаляемый листенер. */ public final void removeDeleteListener(DeleteListener listener) { deleteListeners.fastRemove(listener); } /** * @param listener удаляемый листенер. */ public final void removeDieListener(DieListener listener) { dieListeners.fastRemove(listener); } /** * Удаление слушателя лвл апов. */ public void removeLevelUpListener(LevelUpListener listener) { levelUpListeners.fastRemove(listener); } /** * Удаление слушателя спавнов игроков. */ public void removePlayerSpawnListener(PlayerSpawnListener listener) { playerSpawnListeners.fastRemove(listener); } /** * Удаление слушателя спавнов игроков. */ public void removePlayerSelectListener(PlayerSelectListener listener) { playerSelectListeners.fastRemove(listener); } } <file_sep>/java/game/tera/gameserver/model/skillengine/effects/NoBattleEffect.java package tera.gameserver.model.skillengine.effects; import tera.gameserver.model.Character; import tera.gameserver.templates.EffectTemplate; import tera.gameserver.templates.SkillTemplate; /** * Модель эффекта, прерываемого при входе в бой. * * @author Ronn */ public class NoBattleEffect extends AbstractEffect { /** * @param template темплейт эффекта. * @param effector тот кто наложил эффект. * @param effected тот на кого наложили эффект. * @param skill скил, которым наложили. */ public NoBattleEffect(EffectTemplate template, Character effector, Character effected, SkillTemplate skill) { super(template, effector, effected, skill); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Ask_Interactive.java package tera.gameserver.network.clientpackets; import tera.gameserver.network.serverpackets.S_Answer_Interactive; public class C_Ask_Interactive extends ClientPacket { private String name; @Override protected void readImpl() { readShort(); readInt(); readInt();//serverId name = readString(); } @Override protected void runImpl() { getOwner().sendPacket(S_Answer_Interactive.getInstance(name), true); } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionShowQuestInfo.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.network.serverpackets.QuestInfo; /** * Акшен отображение инфы об квесте. * * @author Ronn */ public class ActionShowQuestInfo extends AbstractQuestAction { /** название ссылки */ private String button; /** ид диалога */ private int dialogId; /** номер страницы */ private int page; public ActionShowQuestInfo(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); try { VarTable vars = VarTable.newInstance(node); this.button = vars.getString("button"); this.dialogId = vars.getInteger("id"); this.page = vars.getInteger("page", 2); } catch(Exception e) { log.warning(this, e); } } @Override public void apply(QuestEvent event) { // получаем нпс Npc npc = event.getNpc(); // получаем игрока Player player = event.getPlayer(); // получаем квест Quest quest = event.getQuest(); // если игрока нет, выходим if(player == null) { log.warning(this, "not found player"); return; } // если нпс нет, выходим if(npc == null) { log.warning(this, "not found npc"); return; } // если квеста нет, выходим if(quest == null) { log.warning(this, "not found quest"); return; } // отправляем пакет player.sendPacket(QuestInfo.getInstance(npc, player, quest, dialogId, page, button), true); } @Override public String toString() { return "ActionShowQuestInfo button = " + button + ", dialogId = " + dialogId; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Play_Movie.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * @author Ronn */ public class S_Play_Movie extends ServerPacket { private static final ServerPacket instance = new S_Play_Movie(); public static S_Play_Movie getInstance(int id) { S_Play_Movie packet = (S_Play_Movie) instance.newInstance(); packet.id = id; return packet; } /** ид ролика */ private int id; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_PLAY_MOVIE; } @Override protected void writeImpl() { writeOpcode(); writeInt(id);//02 00 00 00 Номер Ролика } } <file_sep>/java/game/tera/gameserver/model/quests/events/AddNpcListener.java package tera.gameserver.model.quests.events; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestAction; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestEventType; /** * Просулшка добавление в отображение нпс игроку. * * @author Ronn */ public class AddNpcListener extends AbstractQuestEventListener { /** ид нпс */ private int id; /** тип нпс */ private int type; public AddNpcListener(QuestEventType type, QuestAction[] actions, Quest quest, Node node) { super(type, actions, quest, node); try { VarTable vars = VarTable.newInstance(node); this.id = vars.getInteger("id"); this.type = vars.getInteger("type"); } catch(Exception e) { log.warning(this, e); } } @Override public void notifyQuest(QuestEvent event) { // получаем нпс Npc npc = event.getNpc(); // если нпс есть и ид подходит if(npc != null && npc.getTemplateId() == id && npc.getTemplateType() == type) super.notifyQuest(event); } } <file_sep>/java/game/tera/gameserver/model/ai/npc/taskfactory/SummonWaitTaskFactory.java package tera.gameserver.model.ai.npc.taskfactory; import org.w3c.dom.Node; import rlib.geom.Angles; import rlib.geom.Coords; import rlib.util.Rnd; import rlib.util.Strings; import rlib.util.VarTable; import tera.gameserver.manager.GeoManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.Character; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.MessagePackage; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.gameserver.network.serverpackets.S_User_Status.NotifyType; import tera.gameserver.tables.MessagePackageTable; import tera.util.LocalObjects; /** * Модель реализации фабрики заданий для суммона в режиме ожидания. * * @author Ronn */ public class SummonWaitTaskFactory extends AbstractTaskFactory { /** сообщения брождения */ protected final MessagePackage walkMessage; /** сообщения догонки */ protected final MessagePackage followMessage; /** минимальный радиус случайного брождения */ protected final int randomWalkMinRange; /** максимальный радиус случайного брождения */ protected final int randomWalkMaxRange; /** минимальный интервал случайного движения */ protected final int randomWalkMinDelay; /** максимальный интервал случайного движения */ protected final int randomWalkMaxDelay; /** интервал сообщений */ protected final int messageInterval; public SummonWaitTaskFactory(Node node) { super(node); try { // парсим параметры VarTable vars = VarTable.newInstance(node, "set", "name", "val"); this.messageInterval = vars.getInteger("messageInterval", 120000); this.randomWalkMinRange = vars.getInteger("randomWalkMinRange", ConfigAI.DEFAULT_RANDOM_MIN_WALK_RANGE); this.randomWalkMaxRange = vars.getInteger("randomWalkMaxRange", ConfigAI.DEFAULT_RANDOM_MAX_WALK_RANGE); this.randomWalkMinDelay = vars.getInteger("randomWalkMinDelay", ConfigAI.DEFAULT_RANDOM_MIN_WALK_DELAY); this.randomWalkMaxDelay = vars.getInteger("randomWalkMaxDelay", ConfigAI.DEFAULT_RANDOM_MAX_WALK_DELAY); // получаем таблицу сообщений MessagePackageTable messageTable = MessagePackageTable.getInstance(); this.followMessage = messageTable.getPackage(vars.getString("followMessage", Strings.EMPTY)); this.walkMessage = messageTable.getPackage(vars.getString("walkMessage", Strings.EMPTY)); } catch(Exception e) { log.warning(this, e); throw new IllegalArgumentException(e); } } @Override public <A extends Npc> void addNewTask(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime) { // получаем владельца суммона Character owner = actor.getOwner(); // если его нет, выходим if(owner == null) return; if(actor.isBattleStanced()) actor.stopBattleStance(); // получаем расстояние максимально допустимое для расхождения int randomWalkMaxRange = getRandomWalkMaxRange(); // если владелец далеко отошел if(!owner.isInRange(actor, randomWalkMaxRange)) { // определяем минимальное расстояние до владельца int minDist = (int) (actor.getGeomRadius() + owner.getGeomRadius()) + 20; // определяем сторону у которой стоять хотим float radians = Angles.headingToRadians(Rnd.nextInt(65000)); // определяем целевую точку на плоскости float newX = Coords.calcX(owner.getX(), minDist, radians); float newY = Coords.calcY(owner.getY(), minDist, radians); // получаем менеджера геодаты GeoManager geoManager = GeoManager.getInstance(); // определяем высоту в том месте float newZ = geoManager.getHeight(actor.getContinentId(), newX, newY, actor.getZ()); // заготовка сообщения String message = Strings.EMPTY; // получаем пакет сообщений MessagePackage followMessage = getFollowMessage(); // если пакет есть и интервал выполнен if(followMessage != null && currentTime - ai.getLastMessage() > getMessageInterval()) { // получаем сообщение message = followMessage.getRandomMessage(); // обновляем время ai.setLastMessage(currentTime + getMessageInterval()); } // добавляем задание придти туда ai.addMoveTask(newX, newY, newZ, true, message); return; } // если нпс должен бродить и наступило время следующего хождения if(randomWalkMaxRange > 0 && currentTime > ai.getNextRandomWalk()) { // если последний раз иконка блистала более 5 сек назад if(currentTime - ai.getLastNotifyIcon() > 5000) { // отображаем иконку думания PacketManager.showNotifyIcon(actor, NotifyType.NOTICE_THINK); // обновляем время ai.setLastNotifyIcon(currentTime); } // обновляем время следующего ai.setNextRandomWalk(currentTime + Rnd.nextInt(getRandomWalkMinDelay(), getRandomWalkMaxDelay())); // расчитываем расстояние брождения int distance = Rnd.nextInt(getRandomWalkMinRange(),getRandomWalkMaxRange()); // рассчитываем случацное направление int newHeading = Rnd.nextInt(65000); // рассчитываем целевую точку float newX = Coords.calcX(owner.getX(), distance, newHeading); float newY = Coords.calcY(owner.getY(), distance, newHeading); // получаем менеджер геодаты GeoManager geoManager = GeoManager.getInstance(); float newZ = geoManager.getHeight(actor.getContinentId(), newX, newY, owner.getZ()); // заготовка сообщения String message = Strings.EMPTY; // получаем пакет сообщений MessagePackage walkMessage = getWalkMessage(); // если пакет есть и интервал выполнен if(walkMessage != null && currentTime - ai.getLastMessage() > getMessageInterval()) { // получаем сообщение message = walkMessage.getRandomMessage(); // обновляем время ai.setLastMessage(currentTime + getMessageInterval()); } // добавляем задание придти туда ai.addMoveTask(newX, newY, newZ, true, message); } } /** * @return максимальный период брождения. */ protected final int getRandomWalkMaxDelay() { return randomWalkMaxDelay; } /** * @return максимальный радиус брождения. */ protected final int getRandomWalkMaxRange() { return randomWalkMaxRange; } /** * @return минимальный период брождения. */ protected final int getRandomWalkMinDelay() { return randomWalkMinDelay; } /** * @return минимальный радиус брождения. */ protected final int getRandomWalkMinRange() { return randomWalkMinRange; } /** * @return пакет движения при догонке. */ public MessagePackage getFollowMessage() { return followMessage; } /** * @return интервал сообщений. */ public int getMessageInterval() { return messageInterval; } /** * @return пакет сообщений при брождении. */ public MessagePackage getWalkMessage() { return walkMessage; } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/Charge.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.RequestSkillStart; import tera.gameserver.network.serverpackets.S_Action_End; import tera.gameserver.network.serverpackets.S_Action_Stage; import tera.gameserver.templates.SkillTemplate; /** * Модель зарядки скила. * * @author Ronn */ public class Charge extends AbstractSkill { /** степень зарядки */ private int charge; /** * @param template темплейт скила. */ public Charge(SkillTemplate template) { super(template); } @Override public void endSkill(Character attacker, float targetX, float targetY, float targetZ, boolean force) { template.removeCastFuncs(attacker); // если принудительное завершение if(force || attacker.isAttackBlocking() || attacker.isOwerturned()) { // отображаем пакет завершения каста attacker.broadcastPacket(S_Action_End.getInstance(attacker, castId, template.getId())); // зануляем заряжаемый скил attacker.setChargeSkill(null); return; } attacker.setCastId(castId); attacker.setChargeLevel(getCharge()); attacker.sendPacket(RequestSkillStart.getInstance(template.getId() + template.getOffsetId()), true); } @Override public boolean isWaitable() { return false; } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { super.startSkill(attacker, targetX, targetY, targetZ); // указываем стартовый заряд setCharge(template.getStartState()); // указываем текущий заряжаемый скил attacker.setChargeSkill(this); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { setCharge(getCharge() + 1); Skill skill = character.getSkill(template.getId() + getCharge()); if(skill == null || !skill.checkCondition(character, targetX, targetY, targetZ)) { character.abortCast(false); return; } character.broadcastPacket(S_Action_Stage.getInstance(character, template.getId(), castId, getCharge())); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); //есть ли мп потребление у скила if(skill.getMpConsume() > 0) { //потребляем мп int resultMp = character.getCurrentMp() - skill.getMpConsume(); character.setCurrentMp(resultMp); //обновляем мп игроку eventManager.notifyMpChanged(character); } //есть ли хп потребление у скила if(skill.getHpConsume() > 0) { //потребляем хп int resultHp = character.getCurrentHp() - skill.getHpConsume(); character.setCurrentHp(resultHp); //обновляем хп игроку eventManager.notifyHpChanged(character); } } /** * @return уровень зарядки. */ public int getCharge() { return charge; } /** * @param charge уровень зарядки. */ public void setCharge(int charge) { this.charge = charge; } } <file_sep>/java/game/tera/gameserver/model/AttackInfo.java package tera.gameserver.model; /** * Контейнер с информацией об атаке персонажа на персонажа. * * @author Ronn */ public final class AttackInfo { /** урон */ private int damage; /** крит ли */ private boolean crit; /** блок ли */ private boolean blocked; /** опрокидование ли */ private boolean owerturn; public AttackInfo() { super(); } /** * @param damage нанесенный урон. */ public AttackInfo(int damage) { this.damage = damage; } /** * Добавить урона. * * @param damage кол-во добавления к урону. */ public void addDamage(int damage) { this.damage += damage; } /** * Очистка информации. */ public AttackInfo clear() { this.damage = 0; this.owerturn = false; this.crit = false; this.blocked = false; return this; } /** * Поделить урон. * * @param mod на сколько делить урон. */ public void divDamage(float mod) { damage /= mod; } /** * Поделить урон. * * @param mod на сколько делить урон. */ public void divDamage(int mod) { damage /= mod; } /** * @return кол-во нанесенного урона. */ public int getDamage() { return damage; } /** * @return урон конвектированный в урон по мп при блокировке удара. */ public int getDamageMp() { return damage / 3; } /** * @return заблокирована ли атака. */ public boolean isBlocked() { return blocked; } /** * @return критическая ли атака. */ public boolean isCrit() { return crit; } /** * @return отсутствует ли урон у атаки. */ public boolean isNoDamage() { return damage < 1; } /** * @return опрокидывающая ли атака. */ public boolean isOwerturn() { return owerturn; } /** * Умножение урона. * * @param mod во сколько раз умножить урон. */ public void mulDamage(float mod) { damage *= mod; } /** * Умножение урона. * * @param mod во сколько раз умножить урон. */ public void mulDamage(int mod) { damage *= mod; } /** * @param blocked заблокирован ли удар. */ public void setBlocked(boolean blocked) { this.blocked = blocked; } /** * @param crit критичиский ли удар. */ public void setCrit(boolean crit) { this.crit = crit; } /** * @param damage сколько урона нанесено. */ public void setDamage(int damage) { this.damage = damage; } /** * @param owerturn опракидывающий ли удар. */ public void setOwerturn(boolean owerturn) { this.owerturn = owerturn; } @Override public String toString() { return "AttackInfo damage = " + damage + ", crit = " + crit + ", blocked = " + blocked + ", owerturn = " + owerturn; } } <file_sep>/java/game/tera/gameserver/model/skillengine/lambdas/FloatSet.java package tera.gameserver.model.skillengine.lambdas; /** * Устанавливающий вещественный модификатор. * * @author Ronn * @created 28.02.2012 */ public final class FloatSet extends LambdaFloat { public FloatSet(float value) { super(value); } @Override public float calc(float val) { return value; } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/FastShot.java package tera.gameserver.model.skillengine.shots; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Модель быстрых выстрелов. * * @author Ronn */ public class FastShot extends AbstractShot { /** пул выстрелов */ private static FoldablePool<FastShot> shotPool = Pools.newConcurrentFoldablePool(FastShot.class); /** * @param caster стреляющий персонаж. * @param skill стреляющий скил. * @param targetX координата точки полета. * @param targetY координата точки полета. * @param targetZ координата точки полета. */ public static void startShot(Character caster, Skill skill, float targetX, float targetY, float targetZ) { // извлекаем из пула выстрел FastShot shot = shotPool.take(); // если его нет if(shot == null) // создаем shot = new FastShot(); // подготавливаем shot.prepare(caster, skill, targetX, targetY, targetZ); // запускаем shot.start(); } public FastShot() { setType(ShotType.FAST_SHOT); } @Override public synchronized void stop() { super.stop(); // складываем в пул shotPool.put(this); } } <file_sep>/java/game/tera/gameserver/model/ai/npc/classes/RegionWarDefenseAI.java package tera.gameserver.model.ai.npc.classes; import tera.gameserver.model.Character; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.npc.RegionWarDefense; /** * Модель АИ защитника региона. * * @author Ronn */ public class RegionWarDefenseAI extends AbstractNpcAI<RegionWarDefense> { public RegionWarDefenseAI(RegionWarDefense actor, ConfigAI config) { super(actor, config); } @Override public boolean checkAggression(Character target) { // получаем НПС RegionWarDefense actor = getActor(); // если НПС нету, выходим if(actor == null) { log.warning(this, "not found actor."); return false; } // может ли НПС атаковать эту цель return actor.checkTarget(target); } @Override public void notifyClanAttacked(Character attackedMember, Character attacker, int damage) { // срезаем урон, что бы срабатывало как уведомление, но не переагриивало damage = 1; // обрабатываем super.notifyClanAttacked(attackedMember, attacker, damage); } @Override public boolean isGlobalAI() { return true; } } <file_sep>/java/game/tera/gameserver/model/skillengine/StatType.java package tera.gameserver.model.skillengine; import java.util.NoSuchElementException; /** * Перечисление видов параметров персонажей. * * @author Ronn */ public enum StatType { /**-----------------------------основные в статусе-----------------------------------*/ MAX_HP("maxHp"), MAX_MP("maxMp"), ATTACK("atk"), DEFENSE("def"), IMPACT("impact"), BALANCE("balance"), CRITICAL_DAMAGE("cAtk"), CRITICAL_RATE("rCrit"), CRIT_CHANCE_RECEPTIVE("critChanceRcpt"), ATTACK_SPEED("atkSpd"), RUN_SPEED("runSpd"), BASE_HEART("heart"), /**----------------------------------------------------------------------------------------- */ /**------------------------------------базовые------------------------------------------*/ POWER_FACTOR("powerFactor"), DEFENSE_FACTOR("defenseFactor"), IMPACT_FACTOR("impactFactor"), BALANCE_FACTOR("balanceFactor"), /**-------------------------------------------------------------------------------------------*/ /** -------------типы воздействий мощность/сопротивление-------------- */ WEAK_RECEPTIVE("weakRcpt"), DAMAGE_RECEPTIVE("dmgRcpt"), STUN_RECEPTIVE("stunRcpt"), OWERTURN_RECEPTIVE("owerturnRcpt"), WEAK_POWER("weakPower"), DAMAGE_POWER("dmgPower"), STUN_POWER("stunPower"), OWERTURN_POWER("owerturnPower"), /**--------------------------------------------------------------------------------------------*/ /**-------------------------------------статы сбора--------------------------------------*/ COLLECTING_ORE("collectingOre"), COLLECTING_PLANT("collectingPlant"), COLLECTING_OTHER("collectingOther"), /**--------------------------------------------------------------------------------------------*/ /**-------------------------------------остальные----------------------------------------*/ AGGRO_MOD("agrMod"), SHORT_SKILL_REUSE("shortReuse"), RANGE_SKILL_REUSE("rangeReuse"), OTHER_SKILL_REUSE("otherReuse"), SHORT_SKILL_POWER("shortPower"), RANGE_SKILL_POWER("rangePower"), OTHER_SKILL_POWER("otherPower"), SHORT_SKILL_RECEPTIVE("shortRcpt"), RANGE_SKILL_RECEPTIVE("rangeRcpt"), OTHER_SKILL_RECEPTIVE("otherReuse"), REGEN_HP("regHp"), REGEN_MP("regMp"), MIN_HEART("minHeart"), MIN_HEART_PERCENT("minHeartPercent"), ABSORPTION_HP("absHp"), ABSORPTION_MP("absMp"), GAIN_MP("gainMp"), ATTACK_ABSORPTION_MP("atkAbsMp"), DEFENSE_ABSORPTION_MP("defAbsMp"), ABSORPTION_HP_POWER("absHpPower"), ABSORPTION_MP_POWER("absMpPower"), ABSORPTION_MP_ON_MAX("absMpOnMax"), HEAL_POWER_PERCENT("healPowerPercent"), HEAL_POWER_STATIC("healPowerStatic"), MAX_DAMAGE_DEFENSE("maxDamDef"), FALLING_DAMAGE("fallDam"); /** ------------------------------------------------------------------------------------*/ /** кол-во видов параметров */ public static final int SIZE = values().length; /** * Получить тип параметра по названию в хмл. * * @param name название в хмл. * @return тип параметра. */ public static StatType valueOfXml(String name) { for(StatType stat : values()) if(stat.xmlName.equals(name)) return stat; throw new NoSuchElementException("Unknown name '" + name + "' for enum Stats"); } /** название в хмл */ private String xmlName; /** * @param xmlName название параметра в хмл. */ private StatType(String xmlName) { this.xmlName = xmlName; } /** * @return название параметра в хмл. */ public String getValue() { return xmlName; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/Test35.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; public class Test35 extends ServerPacket { private static final ServerPacket instance = new Test35(); public static Test35 getInstance(Player player) { Test35 packet = (Test35) instance.newInstance(); packet.objectId = player.getObjectId(); return packet; } private int objectId; @Override public ServerPacketType getPacketType() { return ServerPacketType.TEST_35; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, objectId); writeInt(buffer, 0x13008000); writeInt(buffer, 0x0000C47C); writeInt(buffer, 0xFFFFFF01); writeByte(buffer, 0x7F); } }<file_sep>/java/game/tera/gameserver/model/skillengine/classes/Effect.java package tera.gameserver.model.skillengine.classes; import rlib.util.array.Array; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.network.serverpackets.S_Each_Skill_Result; import tera.gameserver.templates.SkillTemplate; import tera.util.LocalObjects; /** * Модель скила, служащего только для активирования бафа. * * @author Ronn */ public class Effect extends AbstractSkill { /** * @param template темплейт скила. */ public Effect(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // инфа об атаке AttackInfo info = local.getNextAttackInfo(); // рассчет блокировки щитом info.setBlocked(target.isBlocked(attacker, impactX, impactY, this)); // отображем анимацию target.broadcastPacket(S_Each_Skill_Result.getInstance(attacker, target, template.getDamageId(), getPower(), false, false, S_Each_Skill_Result.EFFECT)); return info; } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // контейнер для целей Array<Character> targets = local.getNextCharList(); // добавляем цели addTargets(targets, character, targetX, targetY, targetZ); Character[] array = targets.array(); // перечисляем цели for(int i = 0, length = targets.size(); i < length; i++) { Character target = array[i]; // если цель мертва или в инву, пропускаем if(target.isDead() || target.isInvul()) continue; // применяем скил applySkill(character, target); } } } <file_sep>/java/game/tera/gameserver/model/skillengine/targethandler/AuraFractionTargetHandler.java package tera.gameserver.model.skillengine.targethandler; import rlib.util.array.Array; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.npc.Npc; /** * Модель для реализации рассчета целей в области от точки применения. * * @author Ronn */ public class AuraFractionTargetHandler extends AuraTargetHandler { @Override protected void addAllTargets(Array<Character> targets, Character caster, int radius) { World.getAround(Npc.class, targets, caster, radius).add(caster); } @Override protected boolean checkTarget(Character caster, Character target) { if(caster == target) return true; // если кто-то из них не нпс, цель не возможна if(!caster.isNpc() || !target.isNpc()) return false; // получаем нпс кастующего Npc casterNpc = caster.getNpc(); // получаем нпс цель Npc targetNpc = target.getNpc(); // являются ли они одной фракции return casterNpc.getFraction().equals(targetNpc.getFraction()); } } <file_sep>/java/game/tera/gameserver/model/skillengine/SkillName.java package tera.gameserver.model.skillengine; /** * Перечисление название скилов для серий и шанс скилов. * * @author Ronn */ public enum SkillName { COMBO_ATTACK_1, COMBO_ATTACK_2, COMBO_ATTACK_3, COMBO_ATTACK_4, WHIRLWIND, LEAPING_STRIKE, STUNNING_BACKHAND, STARTLING_KICK, HEART_THRUST, KNOCKDOWN_STRIKE, SHIELD_BASH, SHIELD_BARRAGE, COMBATIVE_STRIKE, POUNCE, TRAVERSE_CUT, VORTEX_SLASH, CHARGING_SLASH, RISING_FURY_1, RISING_FURY_2, SHOCKING_IMPLOSION, TRIPLE_NEMESIS, LEASH, UNKNOWN; } <file_sep>/java/game/tera/gameserver/network/serverpackets/StartSlowShot.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет для отображения выстрела. * * @author Ronn */ public class StartSlowShot extends ServerPacket { private static final ServerPacket instance = new StartSlowShot(); public static StartSlowShot getInstance(Character caster, Skill skill, int objectId, int subId, float targetX, float targetY, float targetZ) { StartSlowShot packet = (StartSlowShot) instance.newInstance(); packet.caster = caster; packet.skill = skill; packet.objectId = objectId; packet.subId = subId; packet.targetX = targetX; packet.targetY = targetY; packet.targetZ = targetZ; return packet; } /** кастер */ private Character caster; /** скил, откуда вылетел */ private Skill skill; /** ид выстрела */ private int objectId; /** тип выстрела */ private int subId; /** цель выстрела */ private float targetX; private float targetY; private float targetZ; @Override public void finalyze() { caster = null; skill = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.SKILL_SLOW_SHOT; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, caster.getObjectId()); // кастер обжект айди writeInt(buffer, caster.getSubId()); // кастер сабайди writeInt(buffer, caster.getModelId()); writeInt(buffer, 0); writeInt(buffer, objectId); // обжект айди шарика writeInt(buffer, subId); // саб айди шарика writeInt(buffer, skill.getDamageId()); // код скила damageId из xml writeFloat(buffer, caster.getX()); // шарик откуда летит X writeFloat(buffer, caster.getY()); // шарик откуда летит Y writeFloat(buffer, caster.getZ() + caster.getGeom().getHeight() - 5F); // шарик откуда летит Z writeFloat(buffer, targetX); // шарик куда летит X writeFloat(buffer, targetY); // шарик куда летит X writeFloat(buffer, targetZ); // шарик куда летит X writeShort(buffer, 0x8000); writeShort(buffer, 17048 + skill.getSpeed() + skill.getSpeedOffset()); } }<file_sep>/java/game/tera/gameserver/manager/PlayerManager.java package tera.gameserver.manager; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Strings; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.Config; import tera.gameserver.IdFactory; import tera.gameserver.model.Account; import tera.gameserver.model.Guild; import tera.gameserver.model.World; import tera.gameserver.model.base.Experience; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.base.Race; import tera.gameserver.model.base.Sex; import tera.gameserver.model.equipment.Equipment; import tera.gameserver.model.equipment.PlayerEquipment; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.inventory.PlayerInventory; import tera.gameserver.model.playable.Player; import tera.gameserver.model.playable.PlayerAppearance; import tera.gameserver.model.playable.PlayerDetails2; import tera.gameserver.model.quests.QuestList; import tera.gameserver.network.model.UserClient; import tera.gameserver.network.serverpackets.*; import tera.gameserver.tables.PlayerTable; import tera.gameserver.taskmanager.RegenTaskManager; import tera.gameserver.templates.PlayerTemplate; import tera.util.Location; import java.sql.DatabaseMetaData; /** * Менеджер игроков. * * @author Ronn */ public final class PlayerManager { private static final Logger log = Loggers.getLogger(PlayerManager.class); private static final Location BASE_POSITION = new Location(93545, -88207, -4524, 0, 0); private static final int BASE_WORLD_ID = 13; /** * @return стартовая позиция игрока. */ public static Location getBasePosition() { return BASE_POSITION; } private static PlayerManager instance; public static PlayerManager getInstance() { if(instance == null) instance = new PlayerManager(); return instance; } /** массив имен игроков */ private final Array<String> playerNames; private PlayerManager() { this.playerNames = Arrays.toArray(String.class); log.info("initialized."); } /** * Создание нового игрока. * * @param client клиент, который создает. * @param appearance внешность игрока. * @param name название игрока. * @param playerClass класс игрока. * @param race раса игрока. * @param sex пол игрока. */ public synchronized void createPlayer(UserClient client, PlayerAppearance appearance, PlayerDetails2 details2, String name, PlayerClass playerClass, Race race, Sex sex) { // получаем аккаунт клиента Account account = client.getAccount(); // если аккаунта нету if(account == null) { log.warning("not found account."); // отправляем результат client.sendPacket(CreatePlayerResult.getInstance(), true); // выходим return; } // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); if(!dbManager.isFreeName(name)) return; // получаем фабрику ид IdFactory idFactory = IdFactory.getInstance(); // получаем новый уникальный ид для игрока int objectId = idFactory.getNextPlayerId(); // проверяем на занятость, и если занят, генерируем новый for(int i = 0; i < 10 && !dbManager.isFreePlayerId(objectId); i++) objectId = idFactory.getNextPlayerId(); // если нормального ИД так и не нашли if(!dbManager.isFreePlayerId(objectId)) { log.warning("incorrect player id."); // отправляем результат client.sendPacket(CreatePlayerResult.getInstance(), true); // выходим return; } // вносим уникальный ид во внешность appearance.setObjectId(objectId); details2.setObjectId(objectId); // получаем таблицу игроков PlayerTable playerTable = PlayerTable.getInstance(); // получаем нужный нам шаблон PlayerTemplate template = playerTable.getTemplate(playerClass, race, sex); // если шаблон не нашли if(template == null) { log.warning("not found template."); // отправляем результат client.sendPacket(CreatePlayerResult.getInstance(), true); // выходим return; } // создаем экземпляр игрока Player player = new Player(objectId, template); // вносим стартовый разворот player.setHeading(31912); // вносим время онлайна player.setOnlineTime(0); // вносим дату создания player.setCreateTime(System.currentTimeMillis()); // вносим титул player.setTitle(Strings.EMPTY); // вносим гильдию player.setGuildId(0); // вносим уровень прав player.setAccessLevel(0); // вносим уровень персонажа if(player.getPlayerClass() == PlayerClass.REAPER){ player.setLevel(40); player.setExp(Experience.LEVEL[player.getLevel() + 1]); } else{ player.setLevel(1); player.setExp(0); } // вносим текущее состояние хп player.setCurrentHp(player.getMaxHp()); // вносим текущее состояние мп player.setCurrentMp(player.getMaxMp()); // указываем координаты player.setX(93545); // указываем координаты player.setY(-88207); // указываем координаты player.setZ(-4524); // указываем состояние усталости player.setStamina(120); // указываем имя player.setName(name); // указываем навыки сбора player.setPlantLevel(1); player.setEnergyLevel(1); player.setMiningLevel(1); // указываем ид зоны стартовой player.setZoneId(13); // устанавливаем внешнсоть player.setAppearance(appearance, false); player.setdetails2(details2, false); // если не удалось создать запись о игроке if(!dbManager.createPlayer(player, account.getName())) { log.warning("not ctreated player."); // отправляем результат client.sendPacket(CreatePlayerResult.getInstance(), true); // выходим return; } // создаем в БД запись внешности dbManager.insertPlayerAppearance(appearance); dbManager.insertPlayerPresets2(details2); // создаем инвентарь Inventory inventory = PlayerInventory.newInstance(player, 1); // создаем экиперовку Equipment equipment = PlayerEquipment.newInstance(player); // вносим инвентарь игроку player.setInventory(inventory); // вносим экиперовку игроку player.setEquipment(equipment); // выдаем итемы в инвентарь template.giveItems(inventory); // получаем ячейки инвенторя Cell[] cells = inventory.getCells(); // перебираем их for(Cell cell : cells) // если ячейка не пуста if(!cell.isEmpty()) // пробуем одеть итем equipment.dressItem(inventory, cell); // выдаем базовые скилы template.giveSkills(player); // отправляем результат client.sendPacket(CreatePlayerResult.getInstance(), true); // обновляем зону игрока dbManager.updatePlayerZoneId(player); // удаляем игрока player.deleteMe(); } /** * Обработка входа в мир игроком. * * @param client клиент вошедшего игрока. */ public void enterInWorld(UserClient client) { // если клиента нету if(client == null) { log.warning("not found client."); return; } // получаем вошедшего игрока Player player = client.getOwner(); // если игрока нету if(player == null) { log.warning("not found player."); return; } //player.sendPacket(Test29.getInstance(), false); //player.sendPacket(Test24.getInstance(), false); //player.sendPacket(Test25.getInstance(), false); //if(player.hasSettings()) // player.sendPacket(S_Load_Client_User_Setting.getInstance(player), true); //if(player.hasHotKey()) // player.sendPacket(HotKey.getInstance(player), true); //player.sendPacket(Test30.getInstance(), false); //player.sendPacket(Test27.getInstance(), false); if(player.hasGuild()) { player.updateGuild(); player.sendPacket(S_Guild_Name.getInstance(player), true); player.sendPacket(S_Total_Guild_War_Data.getInstance(),true); player.sendPacket(S_Union_State_Info.getInstance(), true); } player.sendPacket(S_Spawn_Me.getInstance(player), true); player.spawnMe(); //player.sendPacket(Test35.getInstance(player), true); player.sendPacket(S_Player_Stat_Update.getInstance(player), true); player.sendReuseSkills(); player.sendReuseItems(); player.sendEffects(); if(player.isDead()) { player.broadcastPacket(S_Creature_Life.getInstance(player, true)); player.sendPacket(S_Show_Dead_UI.getInstance(World.getRegion(player).getZoneId(player)), true); player.sendPacket(S_Hide_HP.getInstance(player), true); } //if(player.isPK()) // player.sendPacket(S_Change_Relation.getInstance(S_Change_Relation.COLOR_ORANGE, player), true); //else if(player.isPvPMode()) player.sendPacket(S_Change_Relation.getInstance(S_Change_Relation.COLOR_RED, player), true); } /** * Удаление персонажа с аккаунта. * * @param client клиент, который удаляет. * @param objectId уникальный ид игрока. */ public synchronized void removePlayer(UserClient client, int objectId) { if(client == null) { log.warning(this, "not found client."); return; } // получаем аккаунт игрока Account account = client.getAccount(); if(account == null) { log.warning(this, "not found account."); return; } // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // пробуем удалить персонажа int result = dbManager.deletePlayer(objectId, account.getName()); // отправляем результат client.sendPacket(S_Delete_User.getInstance(result), true); } /** * Обработка выбора игрока для входа в мир. * * @param client клиент, который выбрал игрока. * @param objectId уникальный ид игрока. */ public void selectPlayer(UserClient client, int objectId) { // если на сервере уже лимит онлайна, то выходим if(World.online() > Config.WORLD_MAXIMUM_ONLINE) return; // если клиента нету, выходим if(client == null) { log.warning("not found client."); return; } // получаем аккаунт Account account = client.getAccount(); // если его нет, выходим if(account == null) { log.warning(new Exception("not found account.")); return; } // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // пробуем загрузить игрока Player player = dbManager.fullRestore(objectId, account); // если не загрузился, выходим if(player == null) { log.warning("incorrect restore player " + objectId); return; } // если нет прав на вход в мир, выходим if(player.getAccessLevel() < Config.WORLD_MIN_ACCESS_LEVEL) return; // пробуем получить игрока с таким же ником в мире Player old = World.getPlayer(player.getName()); // если такой есть if(old != null) { // получаем его клиент UserClient con = old.getClient(); // если клиент есть if(con != null) // закрываем его con.close(); } // запоминаем за клиентом нового игрока client.setOwner(player); // запоминаем за игроком клиент player.setClient(client); // получаем менеджера регена RegenTaskManager regenManager = RegenTaskManager.getInstance(); // добавляем вреген менеджер regenManager.addCharacter(player); DataBaseManager.getInstance().getPlayerDungeons(player); // добавляем в мир World.addNewPlayer(player); // пробуем получить гильдию Guild guild = player.getGuild(); // если она есть if(guild != null) // добавляем его в онлаин guild.enterInGame(player); player.sendPacket(S_Select_User.getInstance(), true); player.sendPacket(S_Current_Election_State.getInstance(), false); player.sendPacket(S_Login.getInstance(player), true); if(player.isGM()){ player.sendPacket(S_Qa_Set_Admin_Level.getInstance(),false); } player.sendPacket(S_Inven.getInstance(player, false, false), true); player.sendPacket(S_Skill_List.getInstance(player), true); player.sendPacket(S_Crest_Info.getInstance(player), true); player.sendPacket(S_Available_Social_List.getInstance(), false); player.sendPacket(S_Clear_Quest_Info.getInstance(), false); // получаем список квестов QuestList questList = player.getQuestList(); // если квесты есть if(questList != null) questList.updateQuestList(); player.sendPacket(S_Daily_Quest_Complete_Count.getInstance(),false); player.sendPacket(S_Artisan_Skill_List.getInstance(), false); player.sendPacket(S_Artisan_Recipe_List.getInstance(), false); player.sendPacket(S_Npcguild_List.getInstance(), false); player.sendPacket(S_Pet_Incubator_Info_Change.getInstance(), false); player.sendPacket(S_Pet_Info_Clear.getInstance(), false); player.sendPacket(S_Virtual_Latency.getInstance(), false); player.sendPacket(S_Move_Distance_Delta.getInstance(), false); player.sendPacket(S_My_Description.getInstance(player), false); player.sendPacket(S_Masstige_Status.getInstance(), false); player.sendPacket(S_Festival_List.getInstance(), false); int zoneId = player.getZoneId(); if(zoneId < 1) player.setZoneId(player.getContinentId() + 1); player.sendPacket(S_Load_Topo.getInstance(player), true); player.sendPacket(S_Load_Hint.getInstance(), false); player.sendPacket(S_Account_Benefit_List.getInstance(), false); player.sendPacket(S_Fatigability_Point.getInstance(player.getAccount().getFatigability()), false); player.sendPacket(S_Update_Friend_Info.getInstance(player), true); if(player.hasSettings()) player.sendPacket(S_Load_Client_User_Setting.getInstance(player), true); if(player.hasHotKey()) player.sendPacket(HotKey.getInstance(player), true); player.sendPacket(S_Union_State_Info.getInstance(), true); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // уведомляем его eventManager.notifyPlayerSelect(player); } /** * Восстановление персонажей на аккаунте. * * @param player восстанавливающий игрок. */ public synchronized void restoreCharacters(Player player) { // получаем аккаунт игрока Account account = player.getAccount(); // если аккаунта нет, выходим if(account == null) return; // получаем контейнер имен Array<String> playerNames = getPlayerNames(); // очищаем playerNames.clear(); // получаем менеджер БД DataBaseManager dbManager = DataBaseManager.getInstance(); // загружаем список имен dbManager.restorePlayerNames(playerNames, account.getName()); // получаем имя этого игрока String playerName = player.getName(); // получаем массив имен String[] array = playerNames.array(); // перебираем имена for(int i = 0, length = playerNames.size(); i < length; i++) { // получаем имя игрока String name = array[i]; // пропускаем этого же игрока if(name.equals(playerName)) continue; // обновляем положение игрока в БД dbManager.updatePlayerLocation(BASE_POSITION, name, BASE_WORLD_ID); // сообщаем об этом player.sendMessage("Персонаж \"" + name + "\" был перемещен на стартовую позицию."); } } /** * @return список имен игроков. */ public Array<String> getPlayerNames() { return playerNames; } } <file_sep>/java/game/tera/gameserver/model/npc/RegionWarShop.java package tera.gameserver.model.npc; import tera.gameserver.events.global.regionwars.Region; import tera.gameserver.events.global.regionwars.RegionWarNpc; import tera.gameserver.model.Guild; import tera.gameserver.model.inventory.Bank; import tera.gameserver.templates.NpcTemplate; /** * Модель НПС, который работает с захватиываемым регионом. * * @author Ronn */ public class RegionWarShop extends FriendNpc implements TaxationNpc, RegionWarNpc { /** владелющий регион */ private Region region; public RegionWarShop(int objectId, NpcTemplate template) { super(objectId, template); } @Override public int getTax() { Region region = getRegion(); if(region == null) { log.warning("not found region for NPC " + getTemplateId() + " - " + getTemplateType()); return 0; } Guild owner = region.getOwner(); return owner == null ? 0 : region.getTax(); } @Override public Bank getTaxBank() { Region region = getRegion(); if(region == null) { log.warning("not found region for NPC " + getTemplateId() + " - " + getTemplateType()); return null; } Guild owner = region.getOwner(); return owner == null ? null : owner.getBank(); } @Override public void setRegion(Region region) { this.region = region; } @Override public Region getRegion() { return region; } @Override public void setGuildOwner(Guild guild) { } @Override public Guild getGuildOwner() { return null; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Return_To_Lobby.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Окно выхода на выбор перса. * * @author Ronn */ public class S_Return_To_Lobby extends ServerPacket { private static final ServerPacket instance = new S_Return_To_Lobby(); public static S_Return_To_Lobby getInstance(int seconds) { S_Return_To_Lobby packet = (S_Return_To_Lobby) instance.newInstance(); packet.seconds = seconds; return packet; } /** кол-во ожидания секунд */ private int seconds; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_RETURN_TO_LOBBY; } @Override protected final void writeImpl() { switch(seconds) { case 1: { writeOpcode(); writeInt(10); // 10 seconds before logout } default : { writeOpcode(); } } } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionStateQuest.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestState; import tera.gameserver.network.serverpackets.S_Quest_Info; /** * Акшен отображения стадии. * * @author Ronn */ public class ActionStateQuest extends AbstractQuestAction { /** ид след. нпс */ private int npcId; /** ид след. нпс */ private int npcType; /** координаты точки назначения */ private float x; private float y; private float z; public ActionStateQuest(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); try { VarTable vars = VarTable.newInstance(node); this.npcId = vars.getInteger("npcId"); this.npcType = vars.getInteger("npcType"); this.x = vars.getFloat("x"); this.y = vars.getFloat("y"); this.z = vars.getFloat("z"); } catch(Exception e) { log.warning(this, e); } } @Override public void apply(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // получаем квест Quest quest = event.getQuest(); // если чего-то нет, выходим if(player == null || quest == null) { log.warning(this, "not found player or quest"); return; } // получаем квестовый лист QuestList questList = player.getQuestList(); // если квест листа нет, выходим if(questList == null) { log.warning(this, "not found quest list"); return; } // получаем состояние квеста QuestState state = questList.getQuestState(quest); // если состояние есть if(state != null) // отправляем пакет player.sendPacket(S_Quest_Info.getInstance(state, npcType, npcId, x, y, z), true); } @Override public String toString() { return "ActionStateQuest npcId = " + npcId + ", npcType = " + npcType + ", x = " + x + ", y = " + y + ", z = " + z; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/Test31.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class Test31 extends ServerPacket { private static final ServerPacket instance = new Test31(); public static Test31 getInstance() { return (Test31) instance.newInstance(); } private Test31() { super(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.TEST_24; } @Override protected final void writeImpl() { writeOpcode(); writeInt(0x00000000); writeInt(0x00000000); } } <file_sep>/java/game/tera/gameserver/network/crypt/CryptKey.java package tera.gameserver.network.crypt; /** * Модель ключа криптора. */ public final class CryptKey { /** размер ключа */ protected int size; /** первая позиция */ protected int firstPos; /** вторая позиция */ protected int secondPos; /** максимальнаяпозиция */ protected int maxPos; /** ключ */ protected int key; /** буффер */ protected byte[] buffer; /** сумма */ protected long sum; protected CryptKey(int pos, int size) { this.secondPos = pos; this.maxPos = pos; this.size = size; this.buffer = new byte[size * 4]; } /** * @return буффер. */ public byte[] getBuffer() { return buffer; } /** * @return первая позиция. */ public int getFirstPos() { return firstPos; } /** * @return ключ. */ public int getKey() { return key; } /** * @return вторая позиция. */ public int getSecondPos() { return secondPos; } /** * @return размер. */ public int getSize() { return size; } /** * @return сумма. */ public long getSum() { return sum; } /** * @param buffer буффер. */ public void setBuffer(byte[] buffer) { this.buffer = buffer; } /** * @param firstPos первая позиция. */ public void setFirstPos(int firstPos) { this.firstPos = firstPos; } /** * @param key ключ. */ public void setKey(int key) { this.key = key; } /** * @param secondPos вторая позиция. */ public void setSecondPos(int secondPos) { this.secondPos = secondPos; } /** * @param sum сумма. */ public void setSum(long sum) { this.sum = sum; } } <file_sep>/java/game/tera/gameserver/model/MinionData.java package tera.gameserver.model; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.npc.Minion; import tera.gameserver.model.npc.MinionLeader; import tera.gameserver.model.npc.spawn.MinionSpawn; import tera.gameserver.model.npc.spawn.Spawn; /** * Модель данных о минионах. * * @author Ronn * @created 14.03.2012 */ public final class MinionData { /** набор спавнов минионов */ public MinionSpawn[] minions; /** ид лидера нпс */ private int leaderId; /** тип нпс */ private int type; /** время респавна всех минионов */ private int respawnDelay; /** итоговое кол-во минионов */ private int total; /** * @param spawns спавны минионов. * @param leaderId ид лидера. * @param type тип нпс. * @param respawnDelay время респавна мининонв. */ public MinionData(MinionSpawn[] minions, int leaderId, int type, int respawnDelay) { this.minions = minions; this.leaderId = leaderId; this.type = type; this.respawnDelay = respawnDelay; for(MinionSpawn info : minions) this.total += info.getCount(); } /** * Принадлежит к этой дате минион. * * @param spawn спавн миниона. * @param list список минионов. * @return принадлежит ли. */ public boolean containsMinion(Spawn spawn, Array<Minion> list) { return Arrays.contains(minions, spawn) && list.size() < total; } /** * @return ид лидера. */ public final int getLeaderId() { return leaderId; } /** * @return список спавнов минионов. */ public MinionSpawn[] getMinions() { return minions; } /** * @return время респавна минионов. */ public final int getRespawnDelay() { return respawnDelay; } /** * @return тип нпс. */ public int getType() { return type; } /** * @param respawnDelay время респавна минионов. */ public final void setRespawnDelay(int respawnDelay) { this.respawnDelay = respawnDelay; } /** * @return всего кол-во минионов. */ public final int size() { int counter = 0; // получаем массив спавнов минионов MinionSpawn[] minions = getMinions(); for(int i = 0, length = minions.length; i < length; i++) counter += minions[i].getCount(); return counter; } /** * Стартовый спавн минионов. * * @param leader лидер минионов. * @return список отспавненых минионов. */ public Array<Minion> spawnMinions(MinionLeader leader) { Array<Minion> array = Arrays.toConcurrentArray(Minion.class, size()); return spawnMinions(leader, array); } /** * Спавн минионов. * * @param leader лидер минионов. * @param array список минионов. * @return список отспавненых минионов. */ public Array<Minion> spawnMinions(MinionLeader leader, Array<Minion> array) { // получаем массив спавнов минионов MinionSpawn[] minions = getMinions(); for(int i = 0, length = minions.length; i < length; i++) minions[i].start(leader, array); return array; } @Override public String toString() { return "MinionData leaderId = " + leaderId + ", respawnDelay = " + respawnDelay; } } <file_sep>/java/game/tera/remotecontrol/handlers/StartGCHandler.java package tera.remotecontrol.handlers; import rlib.logging.Loggers; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Обработчик запуска сборщика мусора. * * @author Ronn */ public class StartGCHandler implements PacketHandler { public static final StartGCHandler instance = new StartGCHandler(); @Override public Packet processing(Packet packet) { Loggers.info(this, "start garbare collector..."); System.gc(); Loggers.info(this, "garbare collector finished."); return new Packet(PacketType.RESPONSE); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Unequip_Item.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; public class S_Unequip_Item extends ServerPacket { private static final ServerPacket instance = new S_Unequip_Item(); public static S_Unequip_Item getInstance(Player player, int itemId) { S_Unequip_Item packet = (S_Unequip_Item) instance.newInstance(); packet.player = player; packet.itemId = itemId; return packet; } private Player player; private int itemId; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_UNEQUIP_ITEM; } @Override protected final void writeImpl() { writeOpcode(); writeInt(player.getObjectId()); writeInt(player.getSubId()); writeInt(itemId); writeInt(0); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/GuildInputName.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Запрос названия клана. * * @author Ronn */ public class GuildInputName extends ServerPacket { private static final ServerPacket instance = new GuildInputName(); public static GuildInputName getInstance() { return (GuildInputName) instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.GUILD_INPUT_NAME; } @Override protected void writeImpl() { writeOpcode(); writeInt(5); //05 00 00 00 } } <file_sep>/java/game/tera/gameserver/model/ai/npc/taskfactory/AbstractTaskFactory.java package tera.gameserver.model.ai.npc.taskfactory; import org.w3c.dom.Node; import rlib.logging.Logger; import rlib.logging.Loggers; /** * Базовая модель фабрики заданий. * * @author Ronn */ public abstract class AbstractTaskFactory implements TaskFactory { protected static final Logger log = Loggers.getLogger(TaskFactory.class); public AbstractTaskFactory(Node node){} } <file_sep>/java/game/tera/gameserver/model/npc/AggroInfo.java package tera.gameserver.model.npc; import rlib.util.pools.Foldable; import tera.gameserver.model.Character; /** * Контейнер информации об колчестве аггра на персонажа. * * @author Ronn */ public final class AggroInfo implements Foldable, Comparable<AggroInfo> { /** атакующий персонаж */ private Character aggressor; /** уровень агрессии */ private long aggro; /** нанесенный урон */ private long damage; /** * @param aggro кол-во добавляемых аггр поинтов. */ public void addAggro(long aggro) { this.aggro += aggro; } /** * @param damage кол-во добавляемого урона. */ public void addDamage(long damage) { this.damage += damage; } @Override public int compareTo(AggroInfo info) { return (int) (aggro - info.aggro); } @Override public boolean equals(Object object) { if(object == null) return false; if(object == this) return true; if(object == aggressor) return true; return false; } @Override public void finalyze() { aggressor = null; aggro = 0L; damage = 0L; } /** * @return агрессор. */ public Character getAggressor() { return aggressor; } /** * @return кол-во агр поинтов. */ public long getAggro() { return aggro; } /** * @return нанесенный урон. */ public final long getDamage() { return damage; } /** * @return есть ли агрессор. */ public boolean hasAggressor() { return aggressor != null; } @Override public void reinit(){} /** * @param aggressor агрессор. */ public void setAggressor(Character aggressor) { this.aggressor = aggressor; } /** * @param aggro кол-во агр поинтов. */ public void setAggro(long aggro) { this.aggro = aggro; } /** * @param damage нанесенный урон. */ public final void setDamage(long damage) { this.damage = damage; } /** * @param aggro кол-во отнимаемых агр поинтов. */ public void subAggro(long aggro) { this.aggro -= aggro; } /** * @param damage кол-во отнимаемого урона. */ public void subDamage(long damage) { this.damage -= damage; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Use_Item.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.ItemExecutorManager; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; /** * Класс, присылающий инфу об итеме, который хотим юзнуть. * * @author Ronn */ public class C_Use_Item extends ClientPacket { /** игрок */ private Player player; /** ид итема, который юзаем */ private int itemId; /** обджект ид итема */ private int objectId; /** направление разворота */ private int heading; @Override public void finalyze() { player = null; objectId = 0; heading = -1; } @Override public void readImpl() { player = owner.getOwner(); readInt(); readInt(); itemId = readInt(); //ид итема который юзаем objectId = readInt(); // обджект ид итема readLong(); readLong(); readInt();//00 00 00 00 readInt(); readFloat();//08 51 aa 47 x где юзаем readFloat();//18 3d a5 c7 y где юзаем readFloat();//b1 eb 8f c5 z где юзаем heading = readShort();//2a c5 heading где юзаем } @Override public void runImpl() { if(player == null || player.isAllBlocking() || player.isOnMount()) return; // получаем инвентарь игрока Inventory inventory = player.getInventory(); // если инвенторя нет, выходим if(inventory == null) return; // создаем ссылку на итем ItemInstance item = null; inventory.lock(); try { // если указан уникальный и итема, ищем по нему if(objectId != 0) item = inventory.getItemForObjectId(objectId); else // иначе ищем по итем иду item = inventory.getItemForItemId(itemId); } finally { inventory.unlock(); } // если итем не нашли либо он забольшой для игрока, выходим if(item == null || item.getItemLevel() > player.getLevel()) return; // если неверных разворот, берем разворот игрока if(heading == -1) heading = player.getHeading(); // получаем исполнителя ItemExecutorManager executor = ItemExecutorManager.getInstance(); // если нету отдельного обработчика if(!executor.execute(item, player)) // передамем юз на АИ player.getAI().startUseItem(item, heading, false); } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_View_Inter_Party_Match_Dungoen_List.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.dungeons.DungeonList; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; import java.util.List; public class S_View_Inter_Party_Match_Dungoen_List extends ServerPacket { private static final ServerPacket instance = new S_View_Inter_Party_Match_Dungoen_List(); public static S_View_Inter_Party_Match_Dungoen_List getInstance(Player player) { S_View_Inter_Party_Match_Dungoen_List packet = (S_View_Inter_Party_Match_Dungoen_List) instance.newInstance(); packet.player = player; return packet; } /** кол-во ожидания секунд */ private Player player; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_VIEW_INTER_PARTY_MATCH_DUNGOEN_LIST; } @Override protected final void writeImpl() { int n = 11; List<DungeonList> dungeons = DungeonList.getDungeonAvailableTroughtLevel(player.getLevel()); writeOpcode(); writeShort(dungeons.size()); writeShort(n); writeShort(1); writeByte(1); for(int i = dungeons.size() - 1; i >= 0; i--) { writeShort(n); writeShort((i == 0) ? 0 : (n += 19)); writeInt(0); writeInt(dungeons.get(i).getDungeonId()); writeByte(0); writeInt(-1);// -1 OK / 0 item level too low writeByte(0); writeByte(0);//entries ? } } } <file_sep>/java/game/tera/gameserver/model/worldobject/BonfireObject.java package tera.gameserver.model.worldobject; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import rlib.util.SafeTask; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.pools.Foldable; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.IdFactory; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Bonfire; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.model.skillengine.funcs.StatFunc; import tera.util.LocalObjects; /** * Модель переносного костра. * * @author Ronn */ public class BonfireObject extends WorldObject implements Foldable, Bonfire { /** пул костров */ private static final FoldablePool<BonfireObject> bonfirePool = Pools.newConcurrentFoldablePool(BonfireObject.class); /** * Запуск нового костра. * * @param regenPower сила регена хп. * @param lifeTime время жизни. * @param x координата старта. * @param y координата старта. * @param z координата старта. */ public static void startBonfire(float regenPower, int lifeTime, int continentId, float x, float y, float z) { BonfireObject bonfire = bonfirePool.take(); if(bonfire != null) bonfire.reinit(regenPower, lifeTime); else { // получаем фабрику ИД IdFactory idFactory = IdFactory.getInstance(); bonfire = new BonfireObject(idFactory.getNextObjectId(), regenPower, lifeTime); } // устанавливаем ид континента bonfire.setContinentId(continentId); // спавним в нуждной точке bonfire.spawnMe(x, y, z, 0); } /** функция регена костра */ private final StatFunc func; /** таск жизни окстра */ private Runnable lifeTask; /** таск регена костра */ private Runnable regenTask; /** ссылка на таск жизни окстра */ private ScheduledFuture<Runnable> lifeSchedule; /** ссылка на таск регена костра */ private ScheduledFuture<Runnable> regenSchedule; /** список игроков в зоне действия костра */ private final Array<Player> players; /** мощность регена костра */ private float regenPower; /** время жизни костра */ private int lifeTime; /** * @param objectId уникальный ид костра. * @param regenPower мощность регена костра. * @param lifeTime время жизни костра. */ public BonfireObject(int objectId, float regenPower, int lifeTime) { super(objectId); this.regenPower = regenPower; this.lifeTime = lifeTime; this.players = Arrays.toArray(Player.class); // описываем бонус крегену хп у игроков this.func = new StatFunc() { @Override public void addFuncTo(Character owner) { owner.addStatFunc(this); } @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { return val *= getRegenPower(); } @Override public int compareTo(StatFunc func) { return 0x30 - func.getOrder(); } @Override public int getOrder() { return 0x30; } @Override public StatType getStat() { return StatType.REGEN_HP; } @Override public void removeFuncTo(Character owner) { owner.removeStatFunc(this); } }; // описываем таск жизни костра this.lifeTask = new SafeTask() { @Override protected void runImpl() { if(isDeleted()) return; deleteMe(); } }; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // создаем таск жизни костра this.lifeSchedule = executor.scheduleGeneral(lifeTask, lifeTime); // описываем таск регена игроков this.regenTask = new SafeTask() { @Override protected void runImpl() { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем текущий набор игроков Array<Player> players = getPlayers(); // получаем окружающих игроков Array<Player> around = World.getAround(Player.class, local.getNextPlayerList(), BonfireObject.this, 200F); // получаем функцию бонуса регена хп StatFunc func = getFunc(); // получаем костер BonfireObject bonfire = getBonfire(); // если окружющие есть if(!around.isEmpty()) { // получаем их массив Player[] array = around.array(); // перебираем for(int i = 0, length = around.size(); i < length; i++) { // получаем игрока Player player = array[i]; // если его нет в уже обрабатываемых и он не обрабатывается каким-то костром if(!players.contains(player) && player.addBonfire(bonfire)) { // добавляем бонус регена хп func.addFuncTo(player); // добавляем в обрабатывааемые players.add(player); } } } // если есть обрабатываемые игроки if(!players.isEmpty()) { // получаем их массив Player[] array = players.array(); // перебираем for(int i = 0, length = players.size(); i < length; i++) { // получаем игрока Player player = array[i]; // если его нет, пропускаем if(player == null) continue; // если игрок вышел из зоны костра if(!player.isInRangeZ(bonfire, 200) || player.isDead()) { // удаляемся из обрабатывающихся player.removeBonfire(bonfire); // удаляем у него бонус к хп func.removeFuncTo(player); // удаляем его из списка players.fastRemove(i--); // уменьшаем длинну массива length--; // идем дальше continue; } // увеличиваем значение стамины player.addStamina(); } } } }; this.regenSchedule = executor.scheduleGeneralAtFixedRate(regenTask, 3000, 3000); } @Override public void deleteMe() { try { // удаляем из мира super.deleteMe(); // отрубаем таск жизни if(lifeSchedule != null) { lifeSchedule.cancel(false); lifeSchedule = null; } // отрубаем таск регена if(regenSchedule != null) { regenSchedule.cancel(false); regenSchedule = null; } bonfirePool.put(this); } catch(Exception e) { log.warning(this, e); } } @Override public void finalyze() { // получаем список обрабатываемых игроков Array<Player> players = getPlayers(); // если он не пуст if(!players.isEmpty()) { // получаем масив Player[] array = players.array(); // перебираем for(int i = 0, length = players.size(); i < length; i++) { // получаем игрока Player player = array[i]; // если он есть if(player != null) { // удаляем у него бонус func.removeFuncTo(player); // удаляемся у него player.removeBonfire(this); } } } // очищаем список players.clear(); } /** * @return сам себя. */ protected BonfireObject getBonfire() { return this; } /** * @return функция бонуса регена хп. */ protected final StatFunc getFunc() { return func; } /** * @return кол-во оставшихся секунд. */ public long getLifeTime() { // если шедул есть, возвращаем его время if(lifeSchedule != null) return lifeSchedule.getDelay(TimeUnit.SECONDS); return 0; } /** * @return игроки на обработке костра. */ protected final Array<Player> getPlayers() { return players; } /** * @return сила регена. */ protected final float getRegenPower() { return regenPower; } @Override public void reinit(){} /** * Реинициализация костра. * * @param regenPower сила регена хп. * @param lifeTime время жизни. */ public synchronized void reinit(float regenPower, int lifeTime) { // запоминаем новые характеристики this.regenPower = regenPower; this.lifeTime = lifeTime; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // пересоздаем таски this.lifeSchedule = executor.scheduleGeneral(lifeTask, lifeTime); this.regenSchedule = executor.scheduleGeneralAtFixedRate(regenTask, 3000, 3000); } /** * Перезапуск костра. */ public synchronized void restart() { if(lifeSchedule == null) return; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); lifeSchedule.cancel(false); lifeSchedule = executor.scheduleGeneral(lifeTask, this.lifeTime); } @Override public String toString() { return "BonfireObject [" + getLifeTime() + "]"; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/EnchantResult.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Результат заточки предмета. * * @author Ronn */ public class EnchantResult extends ServerConstPacket { private static final EnchantResult SUCCESSFUL = new EnchantResult(1); private static final EnchantResult FAIL = new EnchantResult(0); public static final EnchantResult getSuccessful() { return SUCCESSFUL; } public static final EnchantResult getFail() { return FAIL; } @Override public ServerPacketType getPacketType() { return ServerPacketType.ENCHANT_RESULT; } /** результат */ private final int result; public EnchantResult(int result) { this.result = result; } public EnchantResult() { this.result = 0; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, result); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/ManaSingleShot.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.templates.SkillTemplate; /** * Модель быстро стреляющего скила. * * @author Ronn */ public class ManaSingleShot extends SingleShot { /** * @param template темплейт скила. */ public ManaSingleShot(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { AttackInfo info = super.applySkill(attacker, target); if(!info.isBlocked()) { int currentMp = attacker.getCurrentMp(); if(currentMp < attacker.getMaxMp()) { int mp = (int) attacker.calcStat(StatType.GAIN_MP, 0, target, this); if(mp > 0) { attacker.setCurrentMp(currentMp + mp); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); eventManager.notifyMpChanged(attacker); } } } return info; } } <file_sep>/java/game/tera/gameserver/tables/SkillTable.java package tera.gameserver.tables; import java.io.File; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Files; import rlib.util.Strings; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.Config; import tera.gameserver.document.DocumentSkill; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.templates.SkillTemplate; /** * Таблица шаблонов скилов. * * @author Ronn */ public final class SkillTable { private static final Logger log = Loggers.getLogger(SkillTable.class); private static SkillTable instance; /** * Создание массива скилов из массива темплейтов. * * @param templates массив темплейтов скилов. * @return массив скилов. */ public static Skill[] create(SkillTemplate[] templates) { // создаем массив экземпляров Skill[] skills = new Skill[templates.length]; // вносим экземпляры шаблонов for(int i = 0, length = templates.length; i < length; i++) skills[i] = templates[i].newInstance(); return skills; } public static SkillTable getInstance() { if(instance == null) instance = new SkillTable(); return instance; } /** * Парсит строку в виде "classId-skillId;classId-skillId;classId-skillId". * * @param text строка с описанием набора склиов. * @return массив скилов. */ public static Array<SkillTemplate> parseSkills(String text) { // если строки нет if(text == null || text.isEmpty()) // возвращаем пустой массив return Arrays.toArray(SkillTemplate.class, 0); // разбиваем строку String[] strings = text.split(";"); // если скилов нет if(strings.length < 1) // возвращаем путой массив return Arrays.toArray(SkillTemplate.class, 0); // созадем новый список Array<SkillTemplate> array = Arrays.toArray(SkillTemplate.class, strings.length); // получаем таблицу скилов SkillTable table = getInstance(); // перебираем for(String string : strings) { String[] vals = null; // отрицательный ли класс ид boolean negative = false; // если класс ид отрицательный if(string.startsWith("-")) { // заменяем знак отрицания string = string.replaceFirst("-", ":"); // ставим флаг наличия отрицательного ид класса negative = true; } // разбиваем строку vals = string.split("-"); // если недостаточно параметров, пропускаем if(vals.length < 2) continue; try { // парсими ид класса скилов int classId = Integer.parseInt(negative? vals[0].replaceFirst(":", "-") : vals[0]); // парсим ид шаблона скила int templateId = Integer.parseInt(vals[1]); // получаем шаблон скила SkillTemplate skill = table.getSkill(classId, templateId); // вносим в список if(skill != null) array.add(skill); } catch(NumberFormatException | ArrayIndexOutOfBoundsException e) { log.warning(e); } } return array; } /** * Парсит строку в ввиде "skillId;skillId;skillId". * * @param text строка с описанием набора склиов. * @return массив скилов. */ public static Array<SkillTemplate> parseSkills(String text, int classId) { // если строка пустая if(text == null || text == Strings.EMPTY || text.isEmpty()) // возвращаем пустой массивы return Arrays.toArray(SkillTemplate.class, 0); // разбиваем строку String[] strings = text.split(";"); // если в ней скилов нет if(strings.length < 1) // возвращаем пустой массив return Arrays.toArray(SkillTemplate.class, 0); // создаем новый массив скилов Array<SkillTemplate> array = Arrays.toArray(SkillTemplate.class, strings.length); // получаем таблицу скилов SkillTable table = getInstance(); // перебираем строки for(String string : strings) { // если пуста, пропускаем if(string.isEmpty()) continue; try { // парсим ид шаблона int templateId = Integer.parseInt(string); // получаем шаблон скила SkillTemplate skill = table.getSkill(classId, templateId); // если такой есть if(skill != null) // вносим в массив array.add(skill); } catch(NumberFormatException | ArrayIndexOutOfBoundsException e) { log.warning(e); } } array.trimToSize(); return array; } /** таблица скилов по класс ид и скилл ид */ private Table<IntKey, Table<IntKey, SkillTemplate>> skills; /** таблица комбо скилов по класс ид и скилл ид */ private Table<IntKey, Table<IntKey, SkillTemplate[]>> allskills; private SkillTable() { // создаем таблицы skills = Tables.newIntegerTable(); allskills =Tables.newIntegerTable(); int counter = 0; // получаем файлы File[] files = Files.getFiles(new File(Config.SERVER_DIR + "/data/skills")); // перебираем for(File file : files) { if(file == null) continue; if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file.getAbsolutePath()); continue; } // получаем отпарсенные шаблоны Array<SkillTemplate[]> parsed = new DocumentSkill(file).parse(); // перебираем массиы шаблонов for(SkillTemplate[] temps : parsed) { // пустые пропускаем if(temps.length == 0) continue; // получаем первый в массиве SkillTemplate first = temps[0]; // вносим данные в первую таблицу { // получаем таблицу с шаблоного этого же класса Table<IntKey, SkillTemplate> subTable = skills.get(first.getClassId()); // если нету if(subTable == null) { // создаем новую subTable = Tables.newIntegerTable(); // вносим skills.put(first.getClassId(), subTable); } // перебираем шаблоны for(SkillTemplate temp : temps) { // увеличиваем счетчик counter++; // получаем старый шаблон SkillTemplate old = subTable.put(temp.getId(), temp); // если такой есть, сообщаем if(old != null) log.warning("found duplicate skill " + temp.getId() + ", old " + old.getId() + " in file " + file); } } // вносим данные во вторую таблицу { Table<IntKey, SkillTemplate[]> subTable = allskills.get(first.getClassId()); // если тбалицы нет if(subTable == null) { // созадем новую subTable = Tables.newIntegerTable(); // вносим allskills.put(first.getClassId(), subTable); } if(subTable.put(first.getId(), temps) != null) log.warning("found duplicate skill " + Arrays.toString(temps)); } } } log.info("SkillTable", "loaded " + counter + " skills for " + skills.size() + " classes."); } /** * Получение соотвествтующего скила по класс и скил ид. * * @param classId класс шаблона. * @param templateId ид шаблона. * @return соответствующий шаблон. */ public SkillTemplate getSkill(int classId, int templateId) { Table<IntKey, SkillTemplate> table = skills.get(classId); if(table == null) return null; return table.get(templateId); } /** * Получение соотвествтующего комбо скила по класс и скил ид. * * @param classId класс шаблона. * @param templateId ид шаблона. * @return соответствующий массив шаблонов. */ public SkillTemplate[] getSkills(int classId, int templateId) { Table<IntKey, SkillTemplate[]> table = allskills.get(classId); if(table == null) return null; return table.get(templateId); } /** * Перезагрузка шаблонов скилов. */ public synchronized void reload() { // получаем файлы File[] files = Files.getFiles(new File(Config.SERVER_DIR + "/data/skills")); // перебираем for(File file : files) { if(file == null) continue; if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file.getAbsolutePath()); continue; } // получаем отпарсенные шаблоны Array<SkillTemplate[]> parsed = new DocumentSkill(file).parse(); // перебираем массиы шаблонов for(SkillTemplate[] temps : parsed) { // пустые пропускаем if(temps.length == 0) continue; // получаем первый в массиве SkillTemplate first = temps[0]; // получаем таблицу шаблонов Table<IntKey, SkillTemplate[]> table = allskills.get(first.getClassId()); // если ее нет, пропускаем if(table == null) continue; // получаем массив старых шаблонов SkillTemplate[] old = table.get(first.getId()); // если их нету if(old == null) // вносим новые table.put(first.getId(), temps); else { // перебираем старые шаблоны for(int i = 0; i < old.length; i++) { try { SkillTemplate oldSkill = old[i]; SkillTemplate newSkill = temps[i]; oldSkill.reload(newSkill); } catch(Exception e) { log.warning(e); } } } } } log.info("skills reloaded."); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Creature_Rotate.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакт обновляющий развотрот персонажа для клиентов. * * @author Ronn */ public class S_Creature_Rotate extends ServerPacket { private static final ServerPacket instance = new S_Creature_Rotate(); public static S_Creature_Rotate getInstance(Character character, int newHeading, int time) { S_Creature_Rotate packet = (S_Creature_Rotate) instance.newInstance(); if(character == null) log.warning(packet, new Exception("not found character")); packet.objectId = character.getObjectId(); packet.subId = character.getSubId(); packet.time = time; packet.newHeading = newHeading; return packet; } /** уникальный ид персонажа */ private int objectId; /** под ид персонажа */ private int subId; /** время, за которое он разворачивается */ private int time; /** новый разворот */ private int newHeading; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_CREATURE_ROTATE; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, objectId);//ожект ид writeInt(buffer, subId);//саб ид writeShort(buffer, newHeading);//хэдэр writeShort(buffer, time);//время writeShort(buffer, 0); } } <file_sep>/java/game/tera/gameserver/model/base/Experience.java package tera.gameserver.model.base; import tera.Config; /** * Таблица левел - экспа * * @author Ronn */ public abstract class Experience { // вбито для теры всё точно кто изменит данные убью public final static int LEVEL[] = { -1, // level 0 (не используется) 0, 840, 1846, 3048, 4470, 6145, 8113, 10410, 13088, 16197, 17795, 18952, 20270, 22820, 25748, 28633, 31859, 43702, 52077, 66490, 94955, 106448, 129397, 153355, 164682, 176358, 251223, 283342, 350584, 450475, 592831, 700643, 840159, 900823, 1056869, 1210194, 1420956, 1750218, 2250220, 2742201, 3104154, 3560755, 4524245, 6424027, 8942319, 10815896, 14351495, 16135907, 18594712, 22440436, 25893136, 27707107, 30765345, 34158159, 37921882, 42096768, 46727412, 51863218, 151558828, 264049598, 449513049, }; public static int getMaxLevel() { return Config.WORLD_PLAYER_MAX_LEVEL; } public static int getNextExperience(int currentLevel) { return LEVEL[currentLevel + 1]; } }<file_sep>/java/game/tera/gameserver/model/npc/interaction/links/ControlLink.java package tera.gameserver.model.npc.interaction.links; import tera.gameserver.model.Guild; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.IconType; import tera.gameserver.model.npc.interaction.LinkType; import tera.gameserver.model.npc.interaction.replyes.Reply; import tera.gameserver.model.npc.spawn.RegionWarSpawn; import tera.gameserver.model.playable.Player; /** * Модель линка телепорта к захваченной точке. * * @author Ronn */ public class ControlLink extends AbstractLink { /** спавн целевого контрола */ private RegionWarSpawn spawn; public ControlLink(String name, RegionWarSpawn spawn, Reply reply) { super(name, LinkType.DIALOG, IconType.DIALOG, reply, null); this.spawn = spawn; } @Override public boolean test(Npc npc, Player player) { // получаем владельца точки Guild owner = spawn.getOwner(); // есмли его нет, значит нельзя туда ТП if(owner == null) return false; // является ли глидьия игрока владеющей return owner == player.getGuild(); } /** * @return спавн ссылки. */ public RegionWarSpawn getSpawn() { return spawn; } @Override public String toString() { return "ControlLink name = " + name + ", type = " + type + ", icon = " + icon; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Empty_Guild_Window.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Empty_Guild_Window extends ServerPacket { private static final ServerPacket instance = new S_Empty_Guild_Window(); public static S_Empty_Guild_Window getInstance() { return (S_Empty_Guild_Window) instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_EMPTY_GUILD_WINDOW; } @Override protected final void writeImpl() { writeOpcode(); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestUpdateQuestPanel.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestPanelState; import tera.gameserver.model.quests.QuestState; /** * Клиентский пакет обновление квеста на панели. * * @author Ronn */ public class RequestUpdateQuestPanel extends ClientPacket { /** игрок */ private Player player; /** новое состояние квеста на панели */ private QuestPanelState panelState; /** уник ид квеста */ private int objectId; @Override public void finalyze() { player = null; } @Override public void readImpl() { player = owner.getOwner(); objectId = readInt(); readByte(); panelState = QuestPanelState.valueOf(readShort()); } @Override public void runImpl() { // если игрока нет, выходим if(player == null) return; // получаем его список квестов QuestList questList = player.getQuestList(); // если списка нет, выходим if(questList == null) return; // получаем нужный квест QuestState quest = questList.getQuestState(objectId); // если его нету, выходим if(quest == null) return; // если состояние не изменилось, выходим if(quest.getPanelState() == panelState) return; // обновляем квест на панели player.updateQuestInPanel(quest, panelState); } }<file_sep>/java/game/tera/gameserver/model/listeners/DieListener.java package tera.gameserver.model.listeners; import tera.gameserver.model.Character; /** * Прослушиватель смерти. * * @author Ronn */ public interface DieListener { /** * Прослушка убийства. * * @param killer убийца. * @param killed убитый. */ public void onDie(Character killer, Character killed); } <file_sep>/java/game/tera/gameserver/model/npc/Guard.java package tera.gameserver.model.npc; import tera.gameserver.model.Character; import tera.gameserver.templates.NpcTemplate; /** * Модель гварда. * * @author Ronn */ public class Guard extends FriendNpc { public Guard(int objectId, NpcTemplate template) { super(objectId, template); } @Override public boolean checkTarget(Character target) { if(!target.isNpc()) return false; Npc npc = target.getNpc(); return !npc.isGuard() && !npc.isFriendNpc(); } @Override public boolean isGuard() { return true; } } <file_sep>/java/game/tera/remotecontrol/PacketType.java package tera.remotecontrol; /** * Тип обмениваемого пакета дистанционного управления * * @author Ronn * @created 26.03.2012 */ public enum PacketType { /** запрос на авторизацию */ AUTH, /** ответ на авторизацию */ REQUEST_AUTH, /** запрос информации о статусе сервера */ STATUS_SERVER, /** ответ на запрос о статусе сервера */ REQUEST_STATUS_SERVER, /** запрос на загрузку анонсов */ LOAD_ANNOUNCES, /** список анонсов */ REQUEST_LOAD_ANNOUBCES, /** приминение нового списка анонсов */ APPLY_ANNOUNCES, /** отправка отдельного анонса */ SEND_ANNOUNCE, /** запрос загрузки чата игроков */ LOAD_PLAYER_CHAT, /** пакет с чатом игроков */ REQUEST_PLAYER_CHAT, /** отправить сообещние игроку */ SEND_PLAYER_MESSAGE, /** запрос на загрузку игроков */ LOAD_PLAYERS, /** пакет с информацией об игроках */ REQUEST_LOAD_PLAYERS, /** запрос обновление инфы об игроке */ UPDATE_PLAYER_INFO, /** пакет с обновленой информацией */ REQUEST_UPDATE_PLAYER_INFO, /** пакет запроса статичной информации о сервере */ GET_STATIC_INFO, /** пакет запроса динамичной информации о сервере*/ GET_DYNAMIC_INFO, /** пакет запроса игровой информации о сервере */ GET_GAME_INFO, /** пакет с стаичной инфой о сервере */ REQUEST_STATIC_INFO, /** пакет с диномичесой инфой о сервере */ REQUEST_DYNAMIC_INFO, /** пакет с игровой инфой о сервере */ REQUEST_GAME_INFO, /** рестарт сервер */ SERVER_RESTART, /** запрос на данные с серверной консоли */ REQUEST_SERVER_CONSOLE, /** запрос на сохранение игроков */ REQUEST_PLAYERS_SAVE, /** запрос на запуск гс */ REQUEST_START_GC, /** запрос на запуск рестарта */ REQUEST_START_RESTART, /** запрос на запуск выключения */ REQUEST_START_SHUTDOWN, /** запрос на отмену выключения/рестарта */ REQUEST_CANCEL_SHUTDOWN, /** запрос на чат игроков */ REQUEST_PLAYERS_CHAT, /** запрос списка онлаин игроков */ REQUEST_PLAYER_LIST, /** запрос основной ингфы об игроке */ REQUEST_PLAYER_MAIN_INFO, /** запрос характеристик игрока */ REQUEST_PLAYER_STAT_INFO, /** запрос списка итемов в инвенторе */ REQUEST_PLAYER_INVENTORY, /** запрос списка одетых итемов */ REQUEST_PLAYER_EQUIPMENT, /** запрос обновленной инфы об итеме */ REQUEST_ITEM_INFO, /** запрос на приминение изминений итема */ REQUEST_APPLY_ITEM_CHANGED, /** апрос на удаление итема */ REQUEST_REMOVE_ITEM, /** запрос на выдачу итема */ REQUEST_ADD_ITEM, /** запрос на получение данных об аккаунте */ REQUEST_GET_ACCOUNT, /** запрос на обновление данных аккаунта */ REQUEST_SET_ACCOUNT, /** запрос на приминение изменени й аккаунта */ REQUEST_UPDATE_ACCOUNT, /** пустой ответ */ RESPONSE; } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Union_Change_Notice.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.AllianceManager; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.model.Alliance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Union_Change_Notice; public class C_Union_Change_Notice extends ClientPacket { private String message; @Override protected void readImpl() { readShort(); message = readString(); } @Override protected void runImpl() { Player player = owner.getOwner(); //is exarch if(player.getAllianceClass() == Alliance.EXARCH_RANK_ID) { player.sendPacket(S_Union_Change_Notice.getInstance(message), true); AllianceManager.getInstance().getAlliance(player.getGuild().getAllianceId()).setMessage(message); DataBaseManager.getInstance().saveUnionMessage(player.getGuild().getAllianceId(),message); } } } <file_sep>/java/game/tera/gameserver/model/inventory/AbstractInventory.java package tera.gameserver.model.inventory; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.Config; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.Character; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.items.ItemLocation; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Inven_Changedslot; import tera.gameserver.network.serverpackets.S_Unequip_Item; import tera.gameserver.tables.ItemTable; import tera.gameserver.templates.ItemTemplate; import tera.util.LocalObjects; /** * Базовая модель реализации инвенторя. * * @author Ronn */ public abstract class AbstractInventory implements Inventory { protected static final Logger log = Loggers.getLogger(Inventory.class); /** блокировщик */ protected final Lock lock; /** владелец сумки */ protected Character owner; /** набор ячеяк */ protected Cell[] cells; /** ячейка, в которой хранятся деньги */ protected Cell gold; /** левел сумки */ protected int level; /** * @param level уровень сумки. */ public AbstractInventory(int level) { // сохраняем уровень this.level = level; // создаем блокировщика lock = Locks.newLock(); // создаем массив ячеяк cells = new Cell[getAllMaxCells()]; // заполняем массив for(int i = 0; i < cells.length; i++) cells[i] = new Cell(i, ItemLocation.INVENTORY); // слот для голда gold = new Cell(-1, ItemLocation.INVENTORY); } @Override public boolean addItem(int itemId, long count, String autor) { return addItem(itemId, count, autor, getMaxCells()); } /** * * @param itemId темплейт ид итема. * @param count кол-во создаваемых итемов. * @param autor <NAME>. * @param max максимальное кол-во обрабатываемых ячеяк. * @return был ли создан и добавлен итем. */ private boolean addItem(int itemId, long count, String autor, int max) { if(count < 1) return false; // проверяем отношение итема к донату if(!"wait_items".equals(autor) && Arrays.contains(Config.WORLD_DONATE_ITEMS, itemId)) { log.warning(this, new Exception("not create donate item for id " + itemId)); return false; } // получаем владельца инвенторя Character owner = getOwner(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); lock(); try { // если это деньги if(itemId == Inventory.MONEY_ITEM_ID) { // добавляем деньги addMoney(count); return true; } // получаем ячейки Cell[] cells = getCells(); // пустая ячейка Cell empty = null; // однотипный итем ItemInstance sametype = null; // перебираем ячейки for(int i = 0; i < max; i++) { Cell cell = cells[i]; // если ячейка пустая if(cell.isEmpty()) { // запоминаем ее как свободную if(empty == null) empty = cell; continue; } // лежачий итем в текущей ячейки ItemInstance old = cell.getItem(); // если итем стакуем и с тем же темплейт ид, то запоминаем if(old.isStackable() && old.getItemId() == itemId) { sametype = old; break; } } // если есть однотипный стакуемый итем, добавляем к нему if(sametype != null) { // ставим автора sametype.setAutor(autor); // добавляем итемов в стопку sametype.addItemCount(count); // уведомляем об добалвении итема eventManager.notifyInventoryAddItem(owner, sametype); // обновляем в базе итем dbManager.updateDataItem(sametype); return true; } // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); // получаем темплейт итема ItemTemplate template = itemTable.getItem(itemId); // если вариантов нет, выходим if(template == null || empty == null) return false; // создаем новый итем ItemInstance item = template.newInstance(); // если создать не получилось, выходим if(item == null) return false; // если стакуем if(template.isStackable()) // ставим нужное кол-во item.setItemCount(count); // добавляем владельца item.setOwnerId(owner.getObjectId()); // обновляем автора item.setAutor(autor); // устанавливаем итем в ячейку empty.setItem(item); // уведомляем об добалвении итема eventManager.notifyInventoryAddItem(owner, item); // обновляем в базе итем dbManager.updateItem(item); return true; } finally { unlock(); } } @Override public synchronized void addLevel() { level++; } @Override public void addMoney(long count) { // если денег новых нет, выходим if(count < 1) return; // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); // получаем владельца инвенторя Character owner = getOwner(); lock(); try { // текущий итем ItemInstance old = gold.getItem(); // если текущий есть if(old != null) // добавляем в стопку голда old.addItemCount(count); else { // создаем экземпляр голда ItemInstance item = itemTable.getItem(MONEY_ITEM_ID).newInstance(); // если не удалось создать итем, выходим if(item == null) { log.warning(this, new Exception("not created money item")); return; } // устанавливаем нужное кол-во item.setItemCount(count); // обноавляем владельца итема item.setOwnerId(owner.getObjectId()); // вставляем в ячейку gold.setItem(item); } // получаем итем денег ItemInstance item = gold.getItem(); // уведомляем об добалвении итема eventManager.notifyInventoryAddItem(owner, item); // обновляем в базе итем dbManager.updateItem(item); } finally { unlock(); } } @Override public boolean containsItems(int itemId, int itemCount) { lock(); try { // если ид денег if(itemId == Inventory.MONEY_ITEM_ID) { // получаем деньги ItemInstance item = gold.getItem(); // если нет их, выходим if(item == null) return false; // сравниваем с кол-вом денег return item.getItemCount() >= itemCount; } // создаем счетчик int counter = 0; // получаем все ячейки Cell[] cells = getCells(); // перебираем доступные ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем итем в ячейке ItemInstance item = cells[i].getItem(); // если итема нет, пропускаем if(item == null) continue; // если итем с нужным ид if(item.getItemId() == itemId) // увеличиваем счетчик на кол-во итемов counter += item.getItemCount(); // если нашли нужное кол-во if(counter >= itemCount) return true; } // нажли ли нужное кол-во return counter >= itemCount; } finally { unlock(); } } @Override public boolean forceAddItem(int itemId, long count, String autor) { return addItem(itemId, count, autor, getAllMaxCells()); } @Override public Cell getCell(int index) { // проверка индекса if(index < 0 || index >= getMaxCells()) return null; // извлекаем ячейку return cells[index]; } @Override public Cell getCellForObjectId(int objectId) { lock(); try { // получаем все ячейки Cell[] cells = getCells(); // перебор ячеяк for(int i = 0, length = getMaxCells(); i < length; i++) { // получаем ячейку Cell cell = cells[i]; // пустые пропускаем if(cell.isEmpty()) continue; // получаем итем в ячейке ItemInstance item = cell.getItem(); // если это искомый if(item.getObjectId() == objectId) return cell; } // получем деньги ItemInstance item = gold.getItem(); // если деньги есть и они нам нужны if(item != null && item.getObjectId() == objectId) return gold; return null; } finally { unlock(); } } @Override public Cell[] getCells() { return cells; } @Override public int getEngagedCells() { lock(); try { int counter = 0; // получаем достувпные ячейки Cell[] cells = getCells(); // перебераем ячейки for(int i = 0, length = getMaxCells(); i < length; i++) // считаем все занятые if(!cells[i].isEmpty()) counter++; return counter; } finally { unlock(); } } @Override public int getFreeCells() { lock(); try { // создаем счетчик int counter = 0; // получаем доступные ячейки Cell[] cells = getCells(); // перебераем for(int i = 0, length = getMaxCells(); i < length; i++) // считаем все свободные if(cells[i].isEmpty()) counter++; return counter; } finally { unlock(); } } @Override public Cell getGold() { return gold; } @Override public int getItemCount(int itemId) { lock(); try { // создаем счетчик int counter = 0; // получаем доступные ячейки Cell[] cells = getCells(); // перебираем итемы for(int i = 0, length = cells.length; i < length; i++) { // получаем итем ItemInstance item = cells[i].getItem(); // если итема нет либо не искомый, пропускаем if(item == null || item.getItemId() != itemId) continue; // плюсуем к счетчику counter += item.getItemCount(); } return counter; } finally { unlock(); } } @Override public ItemInstance getItemForItemId(int itemId) { lock(); try { // получаем массив ячеяк Cell[] cells = getCells(); // перебираем итемы for(int i = 0, length = getMaxCells(); i < length; i++) { // получаем итем в ячейке ItemInstance item = cells[i].getItem(); // если итема нет либо он не подходящий, пропускаем if(item == null || item.getItemId() != itemId) continue; // возвращаем искомый return item; } return null; } finally { unlock(); } } @Override public ItemInstance getItemForObjectId(int objectId) { lock(); try { // получаепм ячейку с итемом Cell cell = getCellForObjectId(objectId); // если ячейка есть, возвращаем ее итем return cell == null? null : cell.getItem(); } finally { unlock(); } } @Override public int getLastIndex() { lock(); try { // определяем последний индекс int last = getMaxCells() - 1; // получаем доступные ячейки Cell[] cells = getCells(); // перебираем с конца ячейки for(int i = last; i >= 0; i--) { // если ячейка занята, выходим if(!cells[i].isEmpty()) break; last--; } return last; } finally { unlock(); } } @Override public int getLevel() { return level; } @Override public long getMoney() { return gold.getItemCount(); } @Override public Character getOwner() { return owner; } @Override public void lock() { lock.lock(); } @Override public boolean moveItem(ItemInstance item, Inventory source) { if(item == null) return false; // получаем владельца инвенторя Character owner = getOwner(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем доступные ячейки Cell[] cells = getCells(); // кол-во доступных ячеяк int max = getMaxCells(); // если нужна будет свободная ячейка Cell empty = null; // если итем стопкуем if(item.isStackable()) { // перебираем ячейки for(int i = 0; i < max; i++) { // получаем ячейку Cell cell = cells[i]; // свободную ячейку запоминаем if(cell.isEmpty()) { // если еще не апоминали if(empty == null) // запоминаем empty = cell; continue; } // итем, лежачий в текущей ячейки ItemInstance old = cell.getItem(); // если темплейт ид одинаковый if(old.getItemId() == item.getItemId()) { // удаляем из старого инвенторя итем. source.removeItem(item); // удаляем владельца итема item.setOwnerId(0); // обновляем его положение в базе dbManager.updateLocationItem(item); // добавляем в стопку новых итемов old.addItemCount(item.getItemCount()); // обновляем в базе итем dbManager.updateDataItem(old); // удаляем итем item.deleteMe(); return true; } } } else // иначе ищем свободную ячейку { // перебираем ячейки for(int i = 0; i < max; i++) { // получаем ячейку Cell cell = cells[i]; // если она пустая if(cell.isEmpty() && empty == null) { // запоминаем и выходим empty = cell; break; } } } // если есть пустая ячеяка if(empty != null) { // удаляем из старого инвенторя итем. source.removeItem(item); // указываем владельца итема. item.setOwnerId(owner.getObjectId()); // вставляем в ячейку empty.setItem(item); // обновляем в базе итем dbManager.updateLocationItem(item); return true; } return false; } @Override public boolean putItem(ItemInstance item) { if(item == null) return false; // получаем владельца инвенторя Character owner = getOwner(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); lock(); try { // если итем является деньгами if(item.getItemId() == MONEY_ITEM_ID) { // получаем текущий итем денег ItemInstance old = gold.getItem(); // если денег в инвенторе небыло if(old == null) { // добавляем владельца item.setOwnerId(owner.getObjectId()); // устанавливаем итем в инвентарь gold.setItem(item); // обновляем в базе итем dbManager.updateLocationItem(item); } else { // добавляем денег old.addItemCount(item.getItemCount()); // обновляем в базе итем dbManager.updateDataItem(old); } // уведомляем об добалвении итема eventManager.notifyInventoryAddItem(owner, item); return true; } // получаем доступные ячейки Cell[] cells = getCells(); // кол-во доступных итемов int max = getMaxCells(); //если нужна будет свободная ячейка Cell empty = null; // если итем стопкуем if(item.isStackable()) { // перебираем ячейки for(int i = 0; i < max; i++) { // получаем ячейку Cell cell = cells[i]; // свободную ячейку запоминаем if(cell.isEmpty()) { // если еще не запоминали if(empty == null) // запоминаем empty = cell; continue; } // итем, лежачий в текущей ячейки ItemInstance old = cell.getItem(); // если темплейт ид одинаковый if(old.getItemId() == item.getItemId()) { // добавляем в стопку новых итемов old.addItemCount(item.getItemCount()); // уведомляем об добалвении итема eventManager.notifyInventoryAddItem(owner, item); // обновляем в базе итем dbManager.updateDataItem(old); return true; } } } else // иначе ищем свободную ячейку { // перебираем ячейки for(int i = 0; i < max; i++) { // получаем ячейку Cell cell = cells[i]; // есди ячейка пустая if(cell.isEmpty() && empty == null) { // запоминаем и выходим empty = cell; break; } } } // если нашли пустую ячейку if(empty != null) { // указываем владельца итема. item.setOwnerId(owner.getObjectId()); // вставляем в ячейку empty.setItem(item); // уведомляем об добалвении итема eventManager.notifyInventoryAddItem(owner, item); // обновляем в базе итем dbManager.updateLocationItem(item); owner.sendPacket(S_Unequip_Item.getInstance((Player) owner, item.getItemId()),true); owner.sendPacket(S_Inven_Changedslot.getInstance(1, empty.getIndex(), 0),true); return true; } return false; } finally { unlock(); } } @Override public boolean removeItem(int itemId) { // получаем владельца инвенторя Character owner = getOwner(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); lock(); try { // счетчик удаленных итемов int counter = 0; // получаем список ячеяк Cell[] cells = getCells(); // перебираем ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // итем, лежащий в ячейке ItemInstance item = cell.getItem(); // если не подходит, пропускаем if(item == null || item.getItemId() != itemId) continue; // обнуляем в чейке cell.setItem(null); // обнуляем владельца item.setOwnerId(0); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); // обновляем в БД dbManager.updateLocationItem(item); // удаляем с мира item.deleteMe(); counter++; } return counter > 0; } finally { unlock(); } } @Override public boolean removeItem(int itemId, long count) { // получаем владельца инвенторя Character owner = getOwner(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); lock(); try { // получаем список ячеяк Cell[] cells = getCells(); // перебираем ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // получаем итем из ячейки ItemInstance item = cell.getItem(); // если не подходит, пропускаем if(item == null || item.getItemId() != itemId) continue; // если кол-во итема в стопке больше нужного if(item.getItemCount() > count) { // уменьшаем стопку на нужное item.subItemCount(count); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); // обновляем в БД dbManager.updateDataItem(item); return true; } // есди в стопке ровно столько итемов, сколько надо удалить else if(item.getItemCount() == count) { // удаляем итем с ячейки cell.setItem(null); //зануляем владельца item.setOwnerId(0); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); // обновляем в БД dbManager.updateLocationItem(item); // удаляем с мира item.deleteMe(); return true; } // если меньше в стопке, чем надо else { // удаляем итем с ячейки cell.setItem(null); //зануляем владельца item.setOwnerId(0); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); // обновляем в БД dbManager.updateLocationItem(item); // удаляем с мира item.deleteMe(); // уменьшаем необходимое кол-во удаленных итемов на кол-во итемов в дулаенной стопке count -= item.getItemCount(); } } // выполнен ли план удаления полностью return count < 1; } finally { unlock(); } } @Override public boolean removeItem(ItemInstance item) { // получаем владельца инвенторя Character owner = getOwner(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); lock(); try { // получаем список доступных ячеяк Cell[] cells = getCells(); // перебираем ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // пропускаем пустые if(cell.isEmpty()) continue; // итем, лежащий в ячейке ItemInstance old = cell.getItem(); // если это искомый итем if(old == item) { // зануляем ячейку cell.setItem(null); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); return true; } } // получаем итем с деньгами ItemInstance old = gold.getItem(); // если это искомый итем if(!gold.isEmpty() && old == item) { // зануляем ячейку gold.setItem(null); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); return true; } return false; } finally { unlock(); } } @Override public boolean removeItemFromIndex(long count, int index) { if(index < 0 || index >= cells.length) return false; // получаем владельца инвенторя Character owner = getOwner(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); lock(); try { // искомая ячейка Cell cell = cells[index]; // итем лежащий в ячейке ItemInstance item = cell.getItem(); // если итема нет, выходим if(item == null) return false; // если кол-во итема в стопке больше нужного if(item.getItemCount() > count) { // уменьшаем стопку на нужное item.subItemCount(count); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); // обновляем в БД dbManager.updateDataItem(item); return true; } // есди в стопке ровно или меньше итемов, сколько надо удалить else { // удаляем итем с ячейки cell.setItem(null); //зануляем владельца item.setOwnerId(0); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); // обновляем в БД dbManager.updateLocationItem(item); // удаляем с мира item.deleteMe(); return true; } } finally { unlock(); } } @Override public void setCells(Cell[] cells) { this.cells = cells; } @Override public void setGold(Cell gold) { this.gold = gold; } @Override public boolean setItem(ItemInstance item, int index) { // если итема нет, выходим if(item == null) return false; lock(); try { // если это деньги if(index == -1) { // устанавливаем итем в ячейку денег gold.setItem(item); return true; } // проверка входимости в инвентарь if(index < 0 || index >= cells.length) return false; // устанавливаем итем в ячейку cells[index].setItem(item); return true; } finally { unlock(); } } @Override public void setOwner(Character owner) { this.owner = owner; } @Override public boolean sort() { lock(); try { // получаем индекс последней занятой ячейки int last = getLastIndex(); // если инвентарь пуст, выходим if(last < 1) return false; // получаем список всех ячеяк Cell[] cells = getCells(); // определяем флаг отсортированности boolean sorted = true; // перебираем ячейки с конца for(int i = last - 1; i >= 0; i--) // если между занятыми ячейками обнаруживается пустая if(cells[i].isEmpty()) { // ставим флаг не отсортированности выходим из цикла sorted = false; break; } // если инвентарь отсортирован, выходим if(sorted) return false; // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем список итемов Array<ItemInstance> items = local.getNextItemList(); // перебираем все ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // пустую пропускаем if(cell.isEmpty()) continue; // вносим итем из ячейки items.add(cell.getItem()); // опустошаем ячейку cell.setItem(null); } // получаем массив всех итемов инвенторя ItemInstance[] array = items.array(); // перебираем итемы for(int i = 0, g = 0, length = items.size(); i < length; i++) { // получаем итем ItemInstance item = array[i]; // упорядочено заполняем ячейки cells[g++].setItem(item); // обновляем положение итема в БД dbManager.updateLocationItem(item); } return true; } finally { unlock(); } } @Override public void subLevel() { level--; } @Override public void subMoney(long count) { if(count < 1) return; // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); lock(); try { // итем с деньгами ItemInstance item = gold.getItem(); // если тиема нет, выходим if(item == null) return; // уменьшаем кол-во итемов item.subItemCount(Math.min(count, item.getItemCount())); // уведомляем об удалении итема eventManager.notifyInventoryRemoveItem(owner, item); // обновляем в БД dbManager.updateDataItem(gold.getItem()); } finally { unlock(); } } @Override public String toString() { return "owner = " + owner.getName() + ", cells = " + Arrays.toString(cells) + ", gold = " + gold + ", level = " + level; } @Override public void unlock() { lock.unlock(); } } <file_sep>/java/game/tera/gameserver/model/base/Race.java package tera.gameserver.model.base; import java.io.File; import rlib.data.DocumentXML; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.array.Array; import tera.Config; import tera.gameserver.document.DocumentRaceAppearance; import tera.gameserver.document.DocumentRaceStats; import tera.gameserver.model.playable.PlayerAppearance; import tera.gameserver.model.skillengine.funcs.Func; /** * Перечисление рас игроков. * * @author Ronn */ @SuppressWarnings("unused") public enum Race { /** люди */ HUMAN(0), /** эльфы */ ELF(1), /** АМАНЫ */ AMAN(2), /** кастаники */ CASTANIC(3), /** попори */ POPORI(4), /** барака */ BARAKA(5), /** элин */ ELIN(4); private static final Logger log = Loggers.getLogger(Race.class); /** список всех рас */ public static final Race[] VALUES = values(); /** кол-во всех рас */ public static final int SIZE = VALUES.length; public static void init() { DocumentXML<Void> document = new DocumentRaceAppearance(new File(Config.SERVER_DIR + "/data/player_race_appearance.xml")); document.parse(); document = new DocumentRaceStats(new File(Config.SERVER_DIR + "/data/player_race_stats.xml")); document.parse(); log.info("race appearances initializable."); } public static Race valueOf(int id, Sex sex) { if(id == ELIN.id && sex == Sex.FEMALE) return ELIN; return values()[id]; } /** стандартная мухская внешность */ private PlayerAppearance male; /** стандартная женская внешность */ private PlayerAppearance female; /** набор функций расы */ private Array<Func> funcs; /** модификатор регена хп */ private float regHp; /** модификатор регена мп */ private float regMp; /** модификатор фактора атаки */ private float powerFactor; /** модификатор фактора защиты */ private float defenseFactor; /** модификатор фактора силы */ private float impactFactor; /** модификатор фактора баланса */ private float balanceFactor; /** модификатор скорости атаки */ private float atkSpd; /** модификатор скорости бега */ private float runSpd; /** модификатор шанса крита */ private float critRate; /** модификатор защиты от крита */ private float critRcpt; /** ид расы */ private int id; private Race(int id) { this.id = id; } /** * @param male мужская внешность. */ public void setMale(PlayerAppearance male) { this.male = male; } /** * @param female женская внешность. */ public void setFemale(PlayerAppearance female) { this.female = female; } /** * Получить базовую внешность расы указанного пола. * * @param sex пол расы. * @return базовая внешность. */ public PlayerAppearance getAppearance(Sex sex) { return sex == Sex.MALE? male : female; } /** * @param funcs набор функций расы. */ public void setFuncs(Array<Func> funcs) { this.funcs = funcs; } /** * @return модификатор регена мп. */ public float getRegMp() { return regMp; } /** * @return функции расы. */ public Array<Func> getFuncs() { return funcs; } /** * @return ид расы. */ public int getId() { return id; } } <file_sep>/java/game/tera/remotecontrol/handlers/DynamicInfoHandler.java package tera.remotecontrol.handlers; import rlib.Monitoring; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Сборщик диномичной инфы о сервере * * @author Ronn * @created 25.04.2012 */ public class DynamicInfoHandler implements PacketHandler { @Override public Packet processing(Packet packet) { return new Packet(PacketType.REQUEST_DYNAMIC_INFO, (Monitoring.getUpTime() / 1000 / 60), Monitoring.getThreadCount(), Monitoring.getDeamonThreadCount(), Monitoring.getUsedMemory(), Monitoring.getSystemLoadAverage()); } } <file_sep>/java/game/tera/gameserver/model/territory/AbstractTerritory.java package tera.gameserver.model.territory; import java.awt.Polygon; import org.w3c.dom.Node; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.TObject; import tera.gameserver.model.WorldRegion; import tera.gameserver.model.listeners.TerritoryListener; /** * Базовая модель територии. * * @author Ronn */ public abstract class AbstractTerritory implements Territory { protected static final Logger log = Loggers.getLogger(Territory.class); /** ид территории */ protected final int id; /** ид континента */ protected final int continentId; /** ширина территории по х */ protected int minimumX; protected int maximumX; /** ширина территории по у */ protected int minimumY; protected int maximumY; /** высота территории по z */ protected int minimumZ; protected int maximumZ; /** название территории */ protected final String name; /** полигон территории, описывающий ее границы */ protected final Polygon territory; /** тип территории */ protected final TerritoryType type; /** список слушателей */ protected final Array<TerritoryListener> listeners; /** список объектов на территории */ protected final Array<TObject> objects; /** список связанных регионов */ protected WorldRegion[] regions; public AbstractTerritory(Node node, TerritoryType type) { try { // созаем твблизу атрибутов VarTable vars = VarTable.newInstance(node); this.id = vars.getInteger("id"); this.continentId = vars.getInteger("continentId", 0); this.maximumZ = vars.getInteger("maxZ"); this.minimumZ = vars.getInteger("minZ"); this.name = vars.getString("name"); this.type = type; this.minimumX = Integer.MAX_VALUE; this.maximumX = Integer.MIN_VALUE; this.minimumY = Integer.MAX_VALUE; this.maximumY = Integer.MIN_VALUE; this.territory = new Polygon(); this.listeners = Arrays.toConcurrentArray(TerritoryListener.class); this.objects = Arrays.toConcurrentArray(TObject.class); // парсим точки территории for(Node point = node.getFirstChild(); point != null; point = point.getNextSibling()) if("point".equals(point.getNodeName())) { // парсим атрибуты точки vars.parse(point); // добавляем точку addPoint((int) vars.getFloat("x"), (int) vars.getFloat("y")); } } catch(Exception e) { log.warning(e); throw e; } } @Override public final void addListener(TerritoryListener listener) { listeners.add(listener); } @Override public final void addPoint(int x, int y) { // обновляем мин/макс х minimumX = Math.min(minimumX, x); maximumX = Math.max(maximumX, x); // обновляем мин/макс у minimumY = Math.min(minimumY, y); maximumY = Math.max(maximumY, y); // добавляем новую точку territory.addPoint(x, y); } @Override public final boolean contains(float x, float y) { return territory.contains(x, y); } @Override public final boolean contains(float x, float y, float z) { if(z > maximumZ || z < minimumZ) return false; return contains(x, y); } @Override public int getContinentId() { return continentId; } @Override public final int getId() { return id; } @Override public final int getMaximumX() { return maximumX; } @Override public final int getMaximumY() { return maximumY; } @Override public final int getMaximumZ() { return maximumZ; } @Override public final int getMinimumX() { return minimumX; } @Override public final int getMinimumY() { return minimumY; } @Override public final int getMinimumZ() { return minimumZ; } @Override public final String getName() { return name; } @Override public Array<TObject> getObjects() { return objects; } @Override public WorldRegion[] getRegions() { return regions; } @Override public final TerritoryType getType() { return type; } @Override public final int hashCode() { return id; } @Override public void onEnter(TObject object) { // добавляем в список объектов objects.add(object); // если слушателей нет, выходим if(listeners.isEmpty()) return; listeners.readLock(); try { TerritoryListener[] array = listeners.array(); // перебираем слушателей for(int i = 0, length = listeners.size(); i < length; i++) array[i].onEnter(this, object); } finally { listeners.readUnlock(); } } @Override public void onExit(TObject object) { // удаление объекта из списка объектов на территории objects.fastRemove(object); // если слушателей нет, выходим if(listeners.isEmpty()) return; listeners.readLock(); try { TerritoryListener[] array = listeners.array(); // перебираем слушателей for(int i = 0, length = listeners.size(); i < length; i++) array[i].onExit(this, object); } finally { listeners.readUnlock(); } } @Override public final void removeListener(TerritoryListener listener) { listeners.fastRemove(listener); } @Override public void setRegions(WorldRegion[] regions) { this.regions = regions; } @Override public String toString() { return "Territory id = " + id + ", " + "type = " + type; } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/SpawnTrap.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.traps.Trap; import tera.gameserver.tables.SkillTable; import tera.gameserver.templates.SkillTemplate; /** * @author Ronn */ public class SpawnTrap extends AbstractSkill { /** скил для ловушки */ protected Skill trapSkill; public SpawnTrap(SkillTemplate template) { super(template); SkillTable skillTable = SkillTable.getInstance(); SkillTemplate temp = skillTable.getSkill(template.getClassId(), template.getId() + template.getOffsetId()); if(temp != null) setTrapSkill(temp.newInstance()); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { Skill trapSkill = getTrapSkill(); if(trapSkill == null) return; int range = Math.max(getRange(), 20); Trap.newInstance(character, trapSkill, range, template.getLifeTime(), getRadius()); } private void setTrapSkill(Skill trapSkill) { this.trapSkill = trapSkill; } private Skill getTrapSkill() { return trapSkill; } } <file_sep>/java/game/tera/gameserver/model/equipment/PlayerEquipment.java package tera.gameserver.model.equipment; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.model.Character; import tera.gameserver.model.items.ItemInstance; /** * Модель экиперовки игроков. * * @author Ronn */ public final class PlayerEquipment extends AbstractEquipment { /** пул экиперовок */ private static FoldablePool<Equipment> pool = Pools.newConcurrentFoldablePool(Equipment.class); /** структура экиперовки игрока */ private static final SlotType[] STRUCTURE = { SlotType.SLOT_WEAPON, SlotType.NONE, SlotType.SLOT_ARMOR, SlotType.SLOT_GLOVES, SlotType.SLOT_BOOTS, SlotType.SLOT_EARRING, SlotType.SLOT_EARRING, SlotType.SLOT_RING, SlotType.SLOT_RING, SlotType.SLOT_NECKLACE, SlotType.SLOT_SHIRT, SlotType.SLOT_HAT,//head SlotType.SLOT_MASK,//face SlotType.SLOT_COSTUME_HEAD, SlotType.SLOT_COSTUME_FACE, SlotType.SLOT_COSTUME_WEAPON, SlotType.SLOT_COSTUME_BODY, SlotType.SLOT_COSTUME_BACK, SlotType.SLOT_BELT, SlotType.SLOT_BROOCH, }; /** * @param owner владелец экиперовки. * @return новая экиперовка игрока. */ public static final Equipment newInstance(Character owner) { Equipment equipment = pool.take(); if(equipment == null) equipment = new PlayerEquipment(owner); equipment.setOwner(owner); return equipment; } public PlayerEquipment(Character owner) { super(owner); } @Override public boolean equiped(ItemInstance item) { if(item == null || owner == null) return false; if(owner.isBattleStanced()) { owner.sendMessage("Нельзя одевать вещь в боевой стойке."); return false; } return item.equipmentd(owner, true); } @Override public void fold() { pool.put(this); } @Override public void prepare() { recreateSlots(STRUCTURE); } @Override public PlayerEquipment setOwner(Character owner) { super.setOwner(owner); return this; } @Override public boolean unequiped(ItemInstance item) { if(item == null || owner == null) return false; if(owner.isBattleStanced()) { owner.sendMessage("Нельзя снимать вещь в боевой стойке."); return false; } return true; } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/dialogs/LoadGuildIcon.java package tera.gameserver.model.npc.interaction.dialogs; import tera.gameserver.model.Guild; import tera.gameserver.model.GuildIcon; import tera.gameserver.model.GuildRank; import tera.gameserver.model.MessageType; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.GuildLoadIcon; /** * Модель окна загрузки иконки для гильдии. * * @author Ronn */ public final class LoadGuildIcon extends AbstractDialog { /** * Создание нового диалога. * * @param npc нпс, с которым говорим. * @param player игрок, который говорит. * @return новый диалог. */ public static LoadGuildIcon newInstance(Npc npc, Player player) { LoadGuildIcon dialog = (LoadGuildIcon) DialogType.GUILD_LOAD_ICON.newInstance(); dialog.player = player; dialog.npc = npc; return dialog; } /** картинка гильдии */ private byte[] icon; @Override public synchronized boolean apply() { // игрок Player player = getPlayer(); // если игрока нету, выходим if(player == null) { log.warning(this, new Exception("not found player")); return false; } // получаем гильдию игрока Guild guild = player.getGuild(); // если ее нет, выходим if(guild == null) { log.warning(this, new Exception("not found guild")); return false; } // получаем контейнер иконки гильдии GuildIcon iconInfo = guild.getIcon(); // вставляем туда иконку iconInfo.setIcon(guild, icon); // обновляем иконку всем мемберам guild.updateIcon(); // отправляем сообщение player.sendMessage("Вы загрузили эмблему гильдии, сделайте релог."); return true; } @Override public void finalyze() { icon = null; super.finalyze(); } @Override public DialogType getType() { return DialogType.GUILD_LOAD_ICON; } @Override public synchronized boolean init() { if(!super.init()) return false; //получаем игрока Player player = getPlayer(); // если его нету, выходим if(player == null) { log.warning(this, new Exception("not found player")); return false; } // получаем гильдию игрока Guild guild = player.getGuild(); // если гильдии нету if(guild == null) { // сообщаем и выходим player.sendMessage(MessageType.YOU_NOT_IN_GUILD); return false; } // получаем ранг игрока в гильдии GuildRank rank = player.getGuildRank(); // если это не лидер if(!rank.isGuildMaster()) { // сообщаем и выходим player.sendMessage(MessageType.YOU_ARE_NOT_THE_GUILD_MASTER); return false; } // отправляем пакет диалога загрузки иконки player.sendPacket(GuildLoadIcon.getInstance(), true); return true; } /** * @param icon иконка гильдии. */ public void setIcon(byte[] icon) { this.icon = icon; } } <file_sep>/java/game/tera/gameserver/model/inventory/PlayerInventory.java package tera.gameserver.model.inventory; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.model.Character; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.items.ItemLocation; /** * Модель инвенторя игрока. * * @author Ronn */ public final class PlayerInventory extends AbstractInventory { /** пул инвенторей */ private static final FoldablePool<Inventory> inventoryPool = Pools.newConcurrentFoldablePool(Inventory.class); /** пул массивов ячеяк инвенторей */ private static final Array<Cell[]>[] cellPool = Arrays.create(Array.class, 200); // инициализация пула ячеяк static { for(int i = 0; i < cellPool.length; i++) { Array<Cell[]> cells = Arrays.toConcurrentArray(Cell[].class); cellPool[i] = cells; } } /** * @return новый инвентарь. */ public static Inventory newInstance(Character owner) { Inventory inventory = newInstance(owner, 1); // получаем менеджер БД DataBaseManager dbManager = DataBaseManager.getInstance(); // создаем запись о инвенторе в БД dbManager.createInventory(owner, inventory); return inventory; } /** * Создание нового инвенторя. * * @param level уровень инвенторя. * @return новый инвентарь. */ public static final Inventory newInstance(Character owner, int level) { // получаем старый инвентарь из пула AbstractInventory inventory = (AbstractInventory) inventoryPool.take(); // если его нету if(inventory == null) // создаем новый inventory = new PlayerInventory(owner, level); // иначе переинициализируем старый else { // применяем уровень inventory.level = level; // применяем владельца inventory.owner = owner; // получаем его размер int size = inventory.getAllMaxCells(); // получаем с пула масив ячеяк для инвенторя Cell[] cells = cellPool[size].pop(); // если больше нет в пуле их if(cells == null) { // создаем новые cells = new Cell[size]; for(int i = 0; i < size; i++) cells[i] = new Cell(i, ItemLocation.INVENTORY); } // применяем массив ячеяк к инвенторю inventory.cells = cells; } // готовый инвентарь для нового владельца return inventory; } /** * @param level уровень инвенторя. */ public PlayerInventory(Character owner, int level) { super(level); this.owner = owner; } @Override public void addLevel() { // получаем менеджер БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // старый набор ячеяк Cell[] old = cells; super.addLevel(); // создаем новый набор ячеяк cells = new Cell[getAllMaxCells()]; // заполняем новый массив ячейками for(int i = 0, length = cells.length; i < length; i++) cells[i] = new Cell(i, ItemLocation.INVENTORY); // переносим в новый набор итемы for(int i = 0, length = old.length; i < length; i++) cells[i].setItem(old[i].getItem()); // очищаем старый набор for(int i = 0, length = old.length; i < length; i++) old[i].setItem(null); // вносим в пул старый набор cellPool[old.length].add(old); dbManager.updateInventory(owner, this); } finally { unlock(); } } @Override public void finalyze() { // размер инвенторя int size = cells.length; //перебирем ячейки for(int i = 0; i < size; i++) { Cell cell = cells[i]; // получаем инвентарь с ячейки ItemInstance item = cell.getItem(); if(item == null) continue; // удаляем итем с мира item.deleteMe(); // очищаем ячейку cell.setItem(null); } // ложим с пул массив ячеяк cellPool[size].add(cells); // забываем ячейки этого инвенторя cells = null; // очищаем ячейку с деньгами if(!gold.isEmpty()) { ItemInstance item = gold.getItem(); // удаляем из мира item.deleteMe(); // зануляем ячейку gold.setItem(null); } owner = null; } @Override public void fold() { // ложим в пул инвентарь inventoryPool.put(this); } @Override public int getAllMaxCells() { // масимальное клл-во доступных ячеяк в массиве return getMaxCells() + 8; } @Override public int getBaseLevel() { return 1; } @Override public int getLevelBonus() { return 8; } @Override public int getMaxCells() { return 48 + level * getLevelBonus(); } @Override public void reinit(){} @Override public void subLevel() { // получаем менеджер БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // старый набор ячеяк Cell[] old = cells; super.subLevel(); // создаем новый набор ячеяк cells = new Cell[getAllMaxCells()]; // заполняем новый массив ячейками for(int i = 0, length = cells.length; i < length; i++) cells[i] = new Cell(i, ItemLocation.INVENTORY); // переносим в новый набор итемы for(int i = 0, length = cells.length; i < length; i++) cells[i].setItem(old[i].getItem()); // очищаем старый набор for(int i = 0, length = old.length; i < length; i++) { ItemInstance item = old[i].getItem(); if(item != null) item.deleteMe(); old[i].setItem(null); } // вносим в пул старый набор cellPool[old.length].add(old); dbManager.updateInventory(owner, this); } finally { unlock(); } } }<file_sep>/java/game/tera/gameserver/model/ai/npc/taskfactory/EventHealBattleTaskFactory.java package tera.gameserver.model.ai.npc.taskfactory; import org.w3c.dom.Node; import rlib.util.Strings; import rlib.util.array.Array; import tera.gameserver.model.World; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.SkillGroup; import tera.util.LocalObjects; /** * Модель фабрики заданий для хилера. * * @author Ronn */ public class EventHealBattleTaskFactory extends EventRangerBattleTaskFactory { public EventHealBattleTaskFactory(Node node) { super(node); } @Override public <A extends Npc> void addNewTask(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime) { // если срабатывает шанс на хил if(chance(SkillGroup.HEAL)) { // получаем скил для хила Skill skill = actor.getRandomSkill(SkillGroup.HEAL); // если скил готов к использованию if(skill != null && !actor.isSkillDisabled(skill)) { // если не фул хп у хилера, то хилим сами себя if(actor.getCurrentHpPercent() < 100) ai.addCastTask(skill, actor); // иначе если он состоит в фракции else if(actor.getFraction() != Strings.EMPTY) { // получаем список нпс Array<Npc> npcs = local.getNextNpcList(); // получаем список окружающих нпс World.getAround(Npc.class, npcs, actor, 450); // если такие нашлись if(!npcs.isEmpty()) { // получаем их массив Npc[] array = npcs.array(); // перебираем НПС for(int i = 0, length = npcs.size(); i < length; i++) { // получаем НПС Npc npc = array[i]; // если НПс с его фракции if(npc.getCurrentHpPercent() < 100 && npc.getFraction().equals(actor.getFraction())) { // хилим его ai.addCastTask(skill, npc); return; } } } } } } super.addNewTask(ai, actor, local, config, currentTime); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/StageStrike.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.network.serverpackets.S_Action_Stage; import tera.gameserver.templates.SkillTemplate; /** * Модель комплексного удара из 2х фаз. * * @author Ronn */ public class StageStrike extends Strike { /** * @param template темплейт скила. */ public StageStrike(SkillTemplate template) { super(template); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { int stage = getStage(); if(stage > 0) character.broadcastPacket(S_Action_Stage.getInstance(character, getIconId(), getCastId(), stage)); if(isApply()) super.useSkill(character, targetX, targetY, targetZ); else applyOrder++; } } <file_sep>/java/game/tera/gameserver/manager/OnlineManager.java package tera.gameserver.manager; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.concurrent.ScheduledFuture; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.SafeTask; import tera.Config; import tera.gameserver.model.World; /** * Менеджер онлайна сервера. * * @author Ronn */ public final class OnlineManager { private static final Logger log = Loggers.getLogger(OnlineManager.class); private static OnlineManager instance; public static OnlineManager getInstance() { if(instance == null) instance = new OnlineManager(); return instance; } /** файл для записи онлайна */ private File file; /** ссылка на таск обновления онлайна */ private ScheduledFuture<SafeTask> schedule; /** текущий онлаин сервера */ private volatile int currentOnline; private OnlineManager() { // если указан фаил экспорта онлайна if(!Config.SERVER_ONLINE_FILE.isEmpty()) // создаем файл для экспорта file = new File(Config.SERVER_ONLINE_FILE); // создаем таск периодичной записи SafeTask task = new SafeTask() { @Override protected void runImpl() { // обновляем значение онлайна currentOnline = (int) (World.online() * Config.SERVER_ONLINE_FAKE); // если есть записчик if(file != null && file.canWrite()) { try(PrintWriter writer = new PrintWriter(file)) { // записываем онлайн writer.print(currentOnline); } catch(FileNotFoundException e) { Loggers.warning(OnlineManager.class, e); } } } }; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // ставим на выполнение задание schedule = executor.scheduleGeneralAtFixedRate(task, 60000, 60000); log.info("initialized."); } /** * @return текущий онлаин. */ public int getCurrentOnline() { return currentOnline; } /** * Остановка онлайн менеджера. */ public synchronized void stop() { // если есть таск if(schedule != null) { // останавливаем schedule.cancel(false); schedule = null; } // если есть записчик if(file != null && file.canWrite()) { try(PrintWriter writer = new PrintWriter(file)) { // зануляем онлаин writer.print(0); } catch(FileNotFoundException e) { Loggers.warning(OnlineManager.class, e); } } } }<file_sep>/java/game/tera/gameserver/model/skillengine/conditions/ConditionUsingItem.java package tera.gameserver.model.skillengine.conditions; import tera.gameserver.model.Character; import tera.gameserver.model.equipment.Equipment; import tera.gameserver.model.equipment.Slot; import tera.gameserver.model.skillengine.Skill; /** * Класс для проверки корректности пушки * * @author Ronn */ public class ConditionUsingItem extends AbstractCondition { /** необходимый тип */ private Enum<?>[] types; /** * @param npcType */ public ConditionUsingItem(Enum<?>[] types) { this.types = types; } @Override public boolean test(Character attacker, Character attacked, Skill skill, float val) { if(!attacker.isPlayer()) return true; Equipment equipment = attacker.getEquipment(); if(equipment == null) return false; Slot[] slots = equipment.getSlots(); for(Enum<?> type : types) { for(Slot slot : slots) { if(slot.isEmpty()) continue; if(type == slot.getItem().getType()) return true; } } return false; } } <file_sep>/java/game/tera/gameserver/scripts/commands/SummonCommand.java package tera.gameserver.scripts.commands; import tera.gameserver.model.playable.Player; /** * @author Ronn */ public class SummonCommand extends AbstractCommand { public SummonCommand(int access, String[] commands) { super(access, commands); } /* @Override public void execution(String command, Player player, String values) { // получаем таблицу сумонов SummonTable summonTable = SummonTable.getInstance(); switch(command) { case "reload_summons": { summonTable.reload(); break; } case "summon_cast": { int skillId = Integer.parseInt(values); Array<NewSummon> summons = World.getAround(NewSummon.class, player, 300F); for(final NewSummon summon : summons) { if(!summon.isBattleStanced()) summon.startBattleStance(player); Skill skill = summon.getSkill(skillId); if(skill == null) continue; summon.setTarget(player); summon.setHeading(summon.calcHeading(player.getX(), player.getY())); summon.getAI().startCast(skill, summon.getHeading(), player.getX(), player.getY(), player.getZ()); } break; } case "around_summon_cast": { final int id = Integer.decode(values); Array<NewSummon> summons = World.getAround(NewSummon.class, player, 300F); for(final NewSummon summon : summons) { summon.broadcastPacket(S_Action_Stage.getInstance(summon, id, 1, 0)); Runnable run = new Runnable() { @Override public void run() { summon.broadcastPacket(S_Action_End.getInstance(summon, 1, id)); } }; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); executor.scheduleGeneral(run, 100); } break; } } }*/ @Override public void execution(String command, Player player, String values) { // TODO Auto-generated method stub } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionSubVar.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import rlib.util.wraps.Wrap; import rlib.util.wraps.Wraps; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestState; /** * Акшен отнимания числа к квестовой переменной. * * @author Ronn */ public class ActionSubVar extends AbstractQuestAction { /** название переменной */ private String name; /** прибавляемое значение */ private int value; public ActionSubVar(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); try { VarTable vars = VarTable.newInstance(node); this.name = vars.getString("var"); this.value = vars.getInteger("value"); } catch(Exception e) { log.warning(this, e); } } @Override public void apply(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // если его нет, выходим if(player == null) { log.warning(this, "not found player"); return; } // получаем квестовый лист QuestList questList = player.getQuestList(); // если его нет, выходим if(questList == null) { log.warning(this, "not found questList"); return; } // получаем состояние квеста QuestState state = questList.getQuestState(quest); // если его нет, выходим if(state == null) { log.warning(this, "not found quest state"); return; } // получаем значение переменной Wrap wrap = state.getVar(name); // если оно есть if(wrap != null) // увеличиваем wrap.setInt(wrap.getInt() - value); else // иначе вставляем созданное state.setVar(name, Wraps.newIntegerWrap(-value, true)); } @Override public String toString() { return "SubVar name = " + name + ", value = " + value; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Guild_Name.java package tera.gameserver.network.serverpackets; import rlib.util.Strings; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; public class S_Guild_Name extends ServerPacket { private static final ServerPacket instance = new S_Guild_Name(); public static S_Guild_Name getInstance(Player player) { S_Guild_Name packet = (S_Guild_Name) instance.newInstance(); packet.player = player; return packet; } private Player player; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_GUILD_NAME; } @Override protected final void writeImpl() { writeOpcode(); int n = 20; writeShort(n);//offset guild name writeShort(n += Strings.length(player.getGuildName()));//offset rank writeShort(n += Strings.length(player.getGuildRank().getName()));//offset unk, (title ?) writeShort(n + Strings.length(player.getGuildTitle()));//offset guildemblem writeInt(player.getObjectId()); writeInt(player.getSubId()); writeString(player.getGuildName()); writeString(player.getGuildRank().getName()); writeString(player.getGuildTitle()); //writeShort(0); writeShort(0); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Collection_Progress.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с прогрессом сбора ресурсов. * * @author Ronn */ public class S_Collection_Progress extends ServerPacket { private static final ServerPacket instance = new S_Collection_Progress(); public static S_Collection_Progress getInstance(int progress) { S_Collection_Progress packet = (S_Collection_Progress) instance.newInstance(); packet.progress = progress; return packet; } /** сколько % уже выполнено */ private int progress; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_COLLECTION_PROGRESS; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, progress);//18 00 00 00 ПРогресс сбора в процентах writeLong(buffer,0); } } <file_sep>/java/game/tera/gameserver/model/inventory/AbstractBank.java package tera.gameserver.model.inventory; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Nameable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.Config; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.items.ItemLocation; import tera.gameserver.tables.ItemTable; import tera.gameserver.templates.ItemTemplate; import tera.util.Identified; import tera.util.LocalObjects; /** * Базовая модель реализации банка. * * @author Ronn */ @SuppressWarnings("unchecked") public abstract class AbstractBank<T extends Nameable & Identified> implements Bank { protected static final Logger log = Loggers.getLogger(Bank.class); /** блокировщик */ protected final Lock lock; /** владелец банка */ protected T owner; /** массив ячеяк банка */ protected Cell[] cells; /** ячейка для денег */ protected Cell gold; public AbstractBank() { this.lock = Locks.newLock(); this.cells = new Cell[getMaxSize()]; ItemLocation location = getLocation(); for(int i = 0, length = cells.length; i < length; i++) cells[i] = new Cell(i, location); this.gold = new Cell(-1, location); } @Override public boolean addItem(int id, int count) { if(count < 1) return false; // проверяем отношение итема к донату if(Arrays.contains(Config.WORLD_DONATE_ITEMS, id)) { log.warning(this, new Exception("not create donate item for id " + id)); return false; } // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // если это деньги if(id == Inventory.MONEY_ITEM_ID) { // добавляем деньги и выходим addMoney(count); return true; } // получаем ячейки Cell[] cells = getCells(); // пустая ячейка Cell empty = null; // однотипный итем ItemInstance sametype = null; // перебираем доступные ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // если ячейка пустая if(cell.isEmpty()) { // запоминаем ее как свободную if(empty == null) empty = cell; continue; } // лежачий итем в текущей ячейки ItemInstance old = cell.getItem(); // если итем стакуем и с тем же темплейт ид, то запоминаем if(old.isStackable() && old.getItemId() == id) { sametype = old; break; } } // если есть однотипный стакуемый итем, добавляем к нему if(sametype != null) { // ставим автора sametype.setAutor(owner.getName()); // добавляем итемов в стопку sametype.addItemCount(count); // обновляем в базе итем dbManager.updateDataItem(sametype); return true; } // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); // получаем темплейт итема ItemTemplate template = itemTable.getItem(id); // если вариантов нет, выходим if(template == null || empty == null) return false; // создаем новый итем ItemInstance item = template.newInstance(); // если создать не вышло, выходим if(item == null) return false; // если стакауемый if(template.isStackable()) // указываем нужное кол-во item.setItemCount(count); // добавляем владельца item.setOwnerId(getOwnerId()); // обновляем автора item.setAutor(owner.getName()); // устанавливаем итем в ячейку empty.setItem(item); // обновляем в базе итем dbManager.updateItem(item); return true; } finally { unlock(); } } @Override public void addMoney(long count) { if(count < 1) return; // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // получаем текущие деньги ItemInstance old = gold.getItem(); // если деньги есть if(old != null) // просто увеличиваем их кол-во old.addItemCount(count); else { // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); // создаем экземпляр денег old = itemTable.getItem(Inventory.MONEY_ITEM_ID).newInstance(); // если не удалось создать итем, выходим if(old == null) { log.warning(this, new Exception("not created money item.")); return; } // устанавливаем нужное кол-во old.setItemCount(count); // обновляем владельца итема old.setOwnerId(getOwnerId()); // вставляем в ячейку gold.setItem(old); } // обновляем в базе итем dbManager.updateItem(old); } finally { unlock(); } } @Override public void finalyze() { // олучаем ячейки банка Cell[] cells = getCells(); // перебираем ячейки банка for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // получаем итем с ячейки ItemInstance item = cell.getItem(); // если итем есть if(item != null) // удаляем итем item.deleteMe(); // обнуляем ячейку cell.setItem(null); } // получаем деньги ItemInstance item = gold.getItem(); // если деньги есть if(item != null) // удаляем их item.deleteMe(); // обнуляем ячейку gold.setItem(null); // обнуляем владельца setOwner(null); } @Override public Cell getCell(int index) { if(index < 0 || index >= cells.length) return null; return cells[index]; } @Override public Cell[] getCells() { return cells; } @Override public ItemInstance getItemForObjectId(int objectId) { lock(); try { // получаем набор ячеяк банка Cell[] cells = getCells(); // перебираем их for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // есди она пустая, пропускаем if(cell.isEmpty()) continue; // получаем итем в ячейке ItemInstance item = cell.getItem(); // если это искомый итем if(item.getObjectId() == objectId) return item; } return null; } finally { unlock(); } } @Override public int getLastIndex() { lock(); try { // получаем ячейки банка Cell[] cells = getCells(); // получаем индекс последней ячейки int last = cells.length - 1; // перебираем с конца ячейки for(int i = last; i >= 0; i--) { // если ячейка занята, выходим if(!cells[i].isEmpty()) break; last--; } return last; } finally { unlock(); } } @Override public long getMoney() { return gold.getItemCount(); } @Override public T getOwner() { return owner; } /** * @return ид владельца итемов в этом банке. */ protected int getOwnerId() { return 0; } @Override public int getTabSize() { return 72; } @Override public int getUsedCount() { lock(); try { // создаем счетчик int counter = 0; // получаем ячейки банка Cell[] cells = getCells(); // мчитаем занятые ячейки for(int i = 0, length = cells.length; i < length; i++) if(!cells[i].isEmpty()) counter++; return counter; } finally { unlock(); } } @Override public void lock() { lock.lock(); } @Override public boolean putItem(ItemInstance item) { if(item == null) return false; // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // получаем доступные ячейки Cell[] cells = getCells(); //если нужна будет свободная ячейка Cell empty = null; // если итем стопкуем if(item.isStackable()) { // перебираем ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // если ячейка свободная if(cell.isEmpty()) { // и свободной у нас еще нет if(empty == null) // запоминаем ее empty = cell; continue; } // получаем иттем в ячейке ItemInstance old = cell.getItem(); // если нужный ид у итема if(old.getItemId() == item.getItemId()) { // добавляем в стопку новых итемов old.addItemCount(item.getItemCount()); // обновляем в базе итем dbManager.updateDataItem(old); return true; } } } else // иначе ищем свободную ячейку { // перебираем ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // если нашли пустую if(cell.isEmpty() && empty == null) { // запоминаем empty = cell; break; } } } // если есть пустая ячейка if(empty != null) { // указываем владельца итема. item.setOwnerId(getOwnerId()); // вставляем в ячейку empty.setItem(item); // обновляем в базе итем dbManager.updateLocationItem(item); return true; } return false; } finally { unlock(); } } @Override public void reinit(){} @Override public boolean removeItem(int itemId, int itemCount) { if(itemCount < 1) return false; // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // получаем доступные ячейки Cell[] cells = getCells(); // перебираем ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // если пустая, пррпускаем if(cell.isEmpty()) continue; // достаем итем из ячейки ItemInstance item = cell.getItem(); // если это искомый if(item.getItemId() == itemId) { // и есть нужное кол-во для удаления if(item.getItemCount() > itemCount) { // отнимаем item.subItemCount(itemCount); // обновляем в БД dbManager.updateDataItem(item); return true; } // есди в стопке ровно столько итемов, сколько надо удалить else if(item.getItemCount() == itemCount) { // удаляем итем с ячейки cell.setItem(null); // зануляем владельца item.setOwnerId(0); // зануляем счетчик item.setItemCount(0); // обновляем в БД dbManager.updateItem(item); // удаляем с мира item.deleteMe(); return true; } return false; } } return false; } finally { unlock(); } } @Override public boolean removeItem(ItemInstance item) { if(item == null) return false; lock(); try { // получаем доступные ячейки Cell[] cells = getCells(); // перебираекм все ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // если ячейка пустаяЮ пррпускаем if(cell.isEmpty()) continue; // вынимаем итем из ячейки ItemInstance old = cell.getItem(); // если это искомый итем if(old == item) { // итем удаляем и выходим cell.setItem(null); return true; } } return false; } finally { unlock(); } } @Override public boolean setItem(int index, ItemInstance item) { // если индекс некорректен, выходим if(index < -1 || index >= cells.length) return false; lock(); try { Cell cell = null; // получаем ячейку, куда хотим вставить if(index == -1) cell = gold; else cell = cells[index]; // если она заняты, выходим if(!cell.isEmpty()) return false; // применяем итем в ячейку cell.setItem(item); return true; } finally { unlock(); } } @Override public void setOwner(Object owner) { this.owner = (T) owner; } @Override public boolean sort() { // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // получаем ячейки банка Cell[] cells = getCells(); // получаем индекс последней занятой ячейки int last = getLastIndex(); // если банк пуст ,выходим if(last < 1) return false; // флаг отсортированности boolean sorted = true; // проверяем, есть ли пустые ячейки между итемами for(int i = last - 1; i >= 0; i--) if(cells[i].isEmpty()) { sorted = false; break; } // если нету, выходим if(sorted) return false; // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем буферный список итемов Array<ItemInstance> items = local.getNextItemList(); // перебираем ячейки for(int i = 0, length = cells.length; i < length; i++) { // получаем ячейку Cell cell = cells[i]; // если она пуста, пропускаем if(cell.isEmpty()) continue; // ложим итем с ячейки в список items.add(cell.getItem()); // опусташаем ячейку cell.setItem(null); } // получаем массив итемов ItemInstance[] array = items.array(); // перебираем итемы for(int i = 0, g = 0, length = items.size(); i < length; i++) { // получаем итем ItemInstance item = array[i]; // ложим его в ячейку cells[g++].setItem(item); // обновляем место итема в БД dbManager.updateLocationItem(item); } return true; } finally { unlock(); } } @Override public void subMoney(long count) { if(count < 1) return; // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); lock(); try { // получаем итем с деньгами ItemInstance item = gold.getItem(); // если его нет, выходим if(item == null) return; // уменьшаем кол-во итемов item.subItemCount(Math.min(count, item.getItemCount())); // обновляем в БД dbManager.updateDataItem(gold.getItem()); } finally { unlock(); } } @Override public void unlock() { lock.unlock(); } } <file_sep>/java/game/tera/gameserver/model/traps/BuffTrap.java package tera.gameserver.model.traps; import rlib.geom.Coords; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.IdFactory; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Character; import tera.gameserver.model.Party; import tera.gameserver.model.TObject; import tera.gameserver.model.World; import tera.gameserver.model.skillengine.Skill; import tera.util.LocalObjects; /** * Модель баф ауры. * * @author Ronn */ public class BuffTrap extends Trap { private static final FoldablePool<BuffTrap> pool = Pools.newConcurrentFoldablePool(BuffTrap.class); /** * Создание новой ловукши. * * @param owner создатель и владелец. * @param spawnSkill скил, который спавнит ауру. * @param skill скил, который создает. * @param lifeTime время жизни. * @param radius ражиус активации. * @return новая ловука. */ public static Trap newInstance(Character owner, Skill spawnSkill, Skill skill, int lifeTime, int radius) { // извлекаем баф ловушку BuffTrap trap = pool.take(); // если такой нет if(trap == null) { // получаем фабрику ид IdFactory idFactory = IdFactory.getInstance(); // создаем новую trap = new BuffTrap(idFactory.getNextTrapId()); } // устанавливаем ид континента trap.setContinentId(owner.getContinentId()); // спавним trap.spawnMe(spawnSkill, owner, skill, lifeTime, radius); return trap; } /** список персов, на которых применился */ private final Array<Character> appled; public BuffTrap(int objectId) { super(objectId); this.appled = Arrays.toArray(Character.class); } @Override public boolean activate(TObject object) { // если объект не персонаж, выходим if(!object.isCharacter()) return false; // владелец ауры Character owner = getOwner(); // вошедший персонаж Character target = (Character) object; // если что-тоиз этого нулевое ,выходим if(owner == null || target == null) return false; // определяем дистанцию цели до цента float dist = target.getGeomDistance(x, y); // если он не входит в зону либо уже был пробафан, выходим if(dist > radius || appled.contains(target)) return false; // флаг, нужно ли его бафать boolean active = owner == target; // если еще не нужно, то смотрим является ли он соппартийцем if(!active) { // пати владельца Party party = owner.getParty(); // если он в пати вместе сцелью if(party != null && target.getParty() == party) // активируем баф active = true; } // если всетаки не активируем, выходим if(!active) return false; // применяем баф skill.applySkill(owner, target); // добавляем цель в уже пробафанные персы appled.add(target); return false; } @Override public void finalyze() { super.finalyze(); // очищаем список пробафанных appled.clear(); } @Override public void fold() { pool.put(this); } /** * <NAME>. */ public void spawnMe(Skill spawnSkill, Character owner, Skill skill, int lifeTime, int radius) { this.owner = owner; this.skill = skill; this.radius = radius; // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); this.lifeTask = executor.scheduleGeneral(this, lifeTime * 1000); // расчитываем новую точку на нужном удалении float newX = Coords.calcX(owner.getX(), spawnSkill.getRange(), owner.getHeading()); float newY = Coords.calcY(owner.getY(), spawnSkill.getRange(), owner.getHeading()); // спавним на этом удалении spawnMe(newX, newY, owner.getZ(), 0); LocalObjects local = LocalObjects.get(); // получаем набор персонажей в радиусе ловушки Array<Character> chars = World.getAround(Character.class, local.getNextCharList(), owner); // если такие есть if(!chars.isEmpty()) { // получаем массив персонажей Character[] array = chars.array(); // перебираем for(int i = 0, length = chars.size(); i < length; i++) // пробуем активировать activate(array[i]); } } } <file_sep>/java/game/tera/gameserver/model/skillengine/Condition.java package tera.gameserver.model.skillengine; import org.w3c.dom.Node; import tera.gameserver.model.Character; /** * Класс для описания условий * * @author Ronn */ public interface Condition { public static final Condition[] EMPTY_CONDITIONS = new Condition[0]; /** * @return сообщение при невыполнении кондишена. */ public String getMsg(); /** * @param msg сообщение при невыполнении кондишена. */ public Condition setMsg(Node msg); /** * Проверка выполнения условий. * * @param attacker атакующий. * @param attacked атакуемый. * @param skill используемый скил. * @param val значение. * @return выполнены ли все условия. */ public boolean test(Character attacker, Character attacked, Skill skill, float val); } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestUseRushSkill.java package tera.gameserver.network.clientpackets; import tera.Config; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; /** * Клиентский пакет старта скила. * * @author Ronn */ public class RequestUseRushSkill extends ClientPacket { /** игрок */ private Player player; /** скил ид */ private int skillId; /** нужный разворот */ private int heading; /** ид цели */ private int targetId; /** саб ид цели */ private int targetSubId; /** целевые координаты */ private float targetX; private float targetY; private float targetZ; /** точка каста скила */ private float startX; private float startY; private float startZ; @Override public void finalyze() { player = null; targetId = 0; targetSubId = 0; } /** * @return игрок. */ public final Player getPlayer() { return player; } @Override protected void readImpl() { player = owner.getOwner(); readInt(); skillId = readInt(); startX = readFloat(); startY = readFloat(); startZ = readFloat(); heading = readShort(); targetX = readFloat(); targetY = readFloat(); targetZ = readFloat(); readInt(); targetId = readInt();// обжект ид targetSubId = readInt();// саб ид } @Override protected void runImpl() { // получаем игрока Player player = getPlayer(); // если его нет, выходим if(player == null) return; // пробуем получить скил игрока Skill skill = player.getSkill(skillId); // если его у него нету if(skill == null) { // сообщаем и выходим player.sendMessage("You don't have this skill (maybe update ?)"); return; } // ссылка на возможную цель Character target = null; if(player.getSquareDistance(startX, startY) > Config.WORLD_MAX_SKILL_DESYNC) { startX = player.getX(); startY = player.getY(); } // если игрок был нацелен на кого-то if(targetId > 0 && targetSubId == Config.SERVER_PLAYER_SUB_ID) // ищем его target = World.getAroundById(Character.class, player, targetId, targetSubId); // запоминаем цель player.setTarget(target); // отправляем на обработку запрос каста player.getAI().startCast(startX, startY, startZ, skill, 0, heading, targetX, targetY, targetZ); } @Override public String toString() { return "UseRunningSkill skillId = " + skillId + ", heading = " + heading + ", targetX = " + targetX + ", targetY = " + targetY + ", targetZ = " + targetZ + ", startX = " + startX + ", startY = " + startY + ", startZ = " + startZ; } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionFinishQuest.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestState; import tera.gameserver.network.serverpackets.S_Daily_Quest_Complete_Count; import tera.gameserver.network.serverpackets.S_Delete_Quest; /** * Акшен удаления квеста с боковой панели. * * @author Ronn */ public class ActionFinishQuest extends AbstractQuestAction { public ActionFinishQuest(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); } @Override public void apply(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // получаем квест Quest quest = event.getQuest(); // если игрока нет, выходим if(player == null) { log.warning(this, "not found player"); return; } // если квеста нет, выходим if(quest == null) { log.warning(this, "not found quest"); return; } // получаем список квеста QuestList questList = player.getQuestList(); // если списка нету, выходим if(questList == null) { log.warning(this, "not found quest list"); return; } // получаем состояние квеста QuestState state = questList.getQuestState(quest); // если состояния нет, выходим if(state == null) { log.warning(this, "not found quest state"); return; } // отправляем пакет player.sendPacket(S_Delete_Quest.getInstance(state, false), true); player.sendPacket(S_Daily_Quest_Complete_Count.getInstance(),false); } @Override public String toString() { return "ActionRemoveToPanel "; } } <file_sep>/java/game/tera/remotecontrol/handlers/SetAccountHandler.java package tera.remotecontrol.handlers; import tera.gameserver.manager.AccountManager; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.model.Account; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Сборщик диномичной инфы о сервере * * @author Ronn * @created 25.04.2012 */ public class SetAccountHandler implements PacketHandler { public static final SetAccountHandler instance = new SetAccountHandler(); @Override public Packet processing(Packet packet) { String login = packet.nextString(); AccountManager accountManager = AccountManager.getInstance(); Account account = accountManager.getAccount(login.toLowerCase()); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); boolean inDB = false; if(account == null) { account = dbManager.restoreAccount(login); inDB = true; } if(account == null) return new Packet(PacketType.RESPONSE, false); account.setEmail(packet.nextString()); account.setLastIP(packet.nextString()); account.setAllowIPs(packet.nextString()); account.setComments(packet.nextString()); account.setEndBlock(packet.nextLong()); account.setEndPay(packet.nextLong()); account.setAccessLevel(packet.nextInt()); dbManager.updateFullAccount(account); if(inDB) accountManager.removeAccount(account); return new Packet(PacketType.RESPONSE, true); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Creature_Life.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, сообщающий о смерти персонажа. * * @author Ronn */ public class S_Creature_Life extends ServerPacket { private static final ServerPacket instance = new S_Creature_Life(); /** * @return новый экземпляр пакета. */ public static S_Creature_Life getInstance(Character character, boolean dead) { S_Creature_Life packet = (S_Creature_Life) instance.newInstance(); packet.objectId = character.getObjectId(); packet.subId = character.getSubId(); packet.state = dead? 0 : 1; packet.x = character.getX(); packet.y = character.getY(); packet.z = character.getZ(); return packet; } /** уникальный ид перса */ private int objectId; /** под ид перса */ private int subId; /** состояние персонажа */ private int state; /** координаты перса */ private float x; private float y; private float z; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_CREATURE_LIFE; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, objectId); writeInt(buffer, subId); writeFloat(buffer, x); writeFloat(buffer, y); writeFloat(buffer, z); writeByte(buffer, state); writeByte(buffer,0); writeByte(buffer, 0); } }<file_sep>/java/game/tera/gameserver/network/clientpackets/C_Player_Location.java package tera.gameserver.network.clientpackets; import rlib.logging.Loggers; import tera.gameserver.manager.GeoManager; import tera.gameserver.model.MoveType; import tera.gameserver.model.playable.Player; /** * Клиентский пакет для указания типа и точку перемещения игрока. * * @author Ronn */ public class C_Player_Location extends ClientPacket { /** игрок */ private Player player; /** тип перемещения */ private MoveType type; /** направление */ private int heading; /** целевая точка */ private float targetX; private float targetY; private float targetZ; /** стартовая точка */ private float startX; private float startY; private float startZ; @Override public void finalyze() { player = null; } @Override public void readImpl() { player = owner.getOwner(); if(player == null || buffer.remaining() < 27) { player = null; Loggers.warning(this, "incorrect packet"); return; } startX = readFloat(); startY = readFloat(); startZ = readFloat(); heading = readShort(); //целевая точка targetX = readFloat(); targetY = readFloat(); targetZ = readFloat(); //тип перемещения type = MoveType.valueOf(readByte()); int speed = readInt(); } @Override public void runImpl() { if(player == null) return; if(type == MoveType.RUN) { GeoManager.write(player.getContinentId(), startX, startY, startZ); GeoManager.write(player.getContinentId(), targetX, targetY, targetZ); } /*if(player.getDistance(startX, startY) > 64) { player.sendMessage("Рассинхронизация!!!"); player.stopMove(); player.sendPacket(player.getMovePacket(MoveType.STOP, player.getX(), player.getY(), player.getZ()), true); return; }*/ player.getAI().startMove(startX, startY, startZ, heading, type, targetX, targetY, targetZ, true, false); } }<file_sep>/java/game/tera/gameserver/network/clientpackets/RequestUseDefenseSkill.java package tera.gameserver.network.clientpackets; import tera.Config; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; /** * Запрос на юз деф скила. * * @author Ronn */ public class RequestUseDefenseSkill extends ClientPacket { /** включить деф */ public static final int DEFENSE_START = 1; /** выключить деф */ public static final int DEFENSE_END = 0; /** игрок */ private Player player; /** скил ид игрока */ private int skillId; /** режим */ private int state; /** направление */ private int heading; /** точка каста скила */ private float startX; private float startY; private float startZ; @Override public void finalyze() { player = null; } /** * @return игрок. */ public final Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } @Override public void readImpl() { if(buffer.remaining() < 19) return; setPlayer(getOwner().getOwner()); setSkillId(readInt()); setState(readByte()); setStartX(readFloat()); setStartY(readFloat()); setStartZ(readFloat()); setHeading(readShort()); } @Override public void runImpl() { // получаем игрока Player player = getPlayer(); // если его нет, выходим if(player == null) return; // пробуем получить скил игрока Skill skill = player.getSkill(getSkillId()); // если его у него нету if(skill == null) { // сообщаем и выходим player.sendMessage("You don't have this skill (maybe update ?)"); return; } float startX = getStartX(); float startY = getStartY(); float startZ = getStartZ(); if(player.getSquareDistance(startX, startY) > Config.WORLD_MAX_SKILL_DESYNC) { startX = player.getX(); startY = player.getY(); } player.getAI().startCast(startX, startY, startZ, skill, getState(), getHeading(), player.getX(), player.getY(), player.getZ()); } @Override public String toString() { return "RequestUseDefenseSkill state = " + state; } public int getSkillId() { return skillId; } public int getHeading() { return heading; } public float getStartX() { return startX; } public float getStartY() { return startY; } public float getStartZ() { return startZ; } public int getState() { return state; } public void setHeading(int heading) { this.heading = heading; } public void setSkillId(int skillId) { this.skillId = skillId; } public void setStartX(float startX) { this.startX = startX; } public void setStartY(float startY) { this.startY = startY; } public void setStartZ(float startZ) { this.startZ = startZ; } public void setState(int state) { this.state = state; } }<file_sep>/java/game/tera/gameserver/network/clientpackets/C_Return_To_Lobby.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Return_To_Lobby; /** * Клиентский пакет, запрашивающий выход из игры * * @author Ronn */ public class C_Return_To_Lobby extends ClientPacket { /** игрок */ private Player player; @Override public void finalyze() { player = null; } @Override public void readImpl() { player = owner.getOwner(); } @Override public void runImpl() { if(player == null || player.isBattleStanced()) return; owner.sendPacket(S_Return_To_Lobby.getInstance(0), true);//как настроите таймер поставить 1 player.deleteMe(); player.setClient(null); player.setConnected(false); } }<file_sep>/java/game/tera/gameserver/network/serverpackets/Test6.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; public class Test6 extends ServerConstPacket { private static final Test6 instance = new Test6(); public static Test6 getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.TEST_6; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 0x43480000); } }<file_sep>/java/game/tera/gameserver/model/territory/Territory.java package tera.gameserver.model.territory; import rlib.util.array.Array; import tera.gameserver.model.TObject; import tera.gameserver.model.WorldRegion; import tera.gameserver.model.listeners.TerritoryListener; /** * Интерфейс для реализации территорий. * * @author Ronn * @created 13.04.2012 */ public interface Territory { /** * @param listener добавляемый слушатель. */ public void addListener(TerritoryListener listener); /** * Добавляет точку в полигон. * * @param x координата грани территории. * @param y координата грани территории. */ public void addPoint(int x, int y); /** * @param x координата объекта. * @param y координата объекта. * @return находится ли в территории. */ public boolean contains(float x, float y); /** * @param x координата объекта. * @param y координата объекта. * @param z координата объекта. * @return находится ли в территории. */ public boolean contains(float x, float y, float z); /** * @return ид континента. */ public int getContinentId(); /** * @return ид территории. */ public int getId(); /** * @return максимальная х координата. */ public int getMaximumX(); /** * @return максимальная у координата. */ public int getMaximumY(); /** * @return максимальная z координата. */ public int getMaximumZ(); /** * @return минимальная x координата. */ public int getMinimumX(); /** * @return минимальная y координата. */ public int getMinimumY(); /** * @return минимальная z координата. */ public int getMinimumZ(); /** * @return название территории. */ public String getName(); /** * @return список объектов на территории. */ public Array<TObject> getObjects(); /** * @return список связаных регионов. */ public WorldRegion[] getRegions(); /** * @return тип территории. */ public TerritoryType getType(); /** * Обработка входа объекта в зону. * * @param object входимый объект. */ public void onEnter(TObject object); /** * Обработка выхода объекта из зоны. * * @param object выходимый объект. */ public void onExit(TObject object); /** * @param listener удаляемый слушатель. */ public void removeListener(TerritoryListener listener); /** * @param regions список связаных регионов. */ public void setRegions(WorldRegion[] regions); } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionSystemMessage.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.network.serverpackets.S_Sytem_Message; /** * Акшен для отображения квестового события. * * @author Ronn */ public class ActionSystemMessage extends AbstractQuestAction { /** системное сообщение */ private String message; public ActionSystemMessage(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); try { VarTable vars = VarTable.newInstance(node); String id = "@" + vars.getString("id"); message = vars.getString("message", "").replace('%', (char) 0x0B); message = message.isEmpty()? id : id + ((char) 0x0B) + message; } catch(Exception e) { log.warning(this, e); } } @Override public void apply(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); //если его нет, выходим if(player == null) { log.warning(this, "not found player"); return; } // отправляем ему пакет player.sendPacket(S_Sytem_Message.getInstance(message), true); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Despawn_Npc.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет для удаления объекта. * * @author Ronn */ public class S_Despawn_Npc extends ServerPacket { /** гибель */ public static final int DEAD = 5; /** исчезает с пылью под ногами */ public static final int DISAPPEARS_DUST = 4; /** просто исчезает */ public static final int DISAPPEARS = 1; private static final ServerPacket instance = new S_Despawn_Npc(); public static S_Despawn_Npc getInstance(Character character, int type) { S_Despawn_Npc packet = (S_Despawn_Npc) instance.newInstance(); packet.type = type; packet.objectId = character.getObjectId(); packet.subId = character.getSubId(); packet.x = character.getX(); packet.y = character.getY(); packet.z = character.getZ(); return packet; } /** тип удаления */ private int type; /** обджект ид */ private int objectId; /** саб ид */ private int subId; /** координаты персонажа */ private float x; private float y; private float z; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_DESPAWN_NPC; } @Override protected final void writeImpl() { writeOpcode(); writeInt(objectId); writeInt(subId); writeFloat(x); writeFloat(y); writeFloat(z); writeByte(type); writeInt(0); writeShort(0); writeByte(0); } }<file_sep>/java/game/tera/gameserver/events/auto/AbstractAutoEvent.java package tera.gameserver.events.auto; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import rlib.util.SafeTask; import rlib.util.Synchronized; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.gameserver.Messages.CustomMessage; import tera.gameserver.events.Event; import tera.gameserver.events.EventPlayer; import tera.gameserver.events.EventState; import tera.gameserver.events.NpcInteractEvent; import tera.gameserver.events.Registered; import tera.gameserver.manager.EventManager; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.Character; import tera.gameserver.model.TObject; import tera.gameserver.model.World; import tera.gameserver.model.listeners.DeleteListener; import tera.gameserver.model.listeners.DieListener; import tera.gameserver.model.listeners.TerritoryListener; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.model.skillengine.funcs.Func; import tera.gameserver.model.skillengine.funcs.stat.MathFunc; import tera.gameserver.model.territory.Territory; import tera.gameserver.tables.TerritoryTable; import tera.gameserver.tables.WorldZoneTable; /** * Базовая модель авто ивента. * * @author Ronn */ public abstract class AbstractAutoEvent extends SafeTask implements Event, Synchronized, NpcInteractEvent, Registered, TerritoryListener, DieListener, DeleteListener { /** блокировщик движения игроков */ private static final Func RUN_LOCKER = new MathFunc(StatType.RUN_SPEED, 0x50, null, null) { @Override public float calc(Character attacker, Character attacked, Skill skill, float val) { return 0; } }; /** синхронизатор */ private final Lock lock; /** таблица участников */ private final Table<IntKey, EventPlayer> players; /** ожидающие участия игроки */ private final Array<Player> prepare; /** активные участники */ private final Array<Player> activePlayers; /** территория ивента */ private final Territory eventTerritory; /** ссылка на таск ивента */ protected ScheduledFuture<? extends AbstractAutoEvent> schedule; /** статус ивента */ protected EventState state; /** счетчик времени */ protected int time; /** запущен ли ивент */ protected boolean started; protected AbstractAutoEvent() { this.lock = Locks.newLock(); this.prepare = Arrays.toArray(Player.class); this.activePlayers = Arrays.toArray(Player.class); // получаем таблицу территорий TerritoryTable territoryTable = TerritoryTable.getInstance(); this.eventTerritory = territoryTable.getTerritory(getTerritoryId()); this.players = Tables.newIntegerTable(); } /** * добавление игрока в активные. */ public final void addActivePlayer(Player player) { activePlayers.add(player); } @Override public void addLinks(Array<Link> links, Npc npc, Player player) { } /** * Очистить территорию от левых игроков. */ protected final void clearTerritory() { if(eventTerritory == null) { return; } WorldZoneTable worldZoneTable = WorldZoneTable.getInstance(); Array<TObject> objects = eventTerritory.getObjects(); TObject[] objs = objects.array(); objects.writeLock(); try { for(int i = 0, length = objects.size(); i < length; i++) { TObject object = objs[i]; if(!object.isPlayer()) { continue; } Player player = object.getPlayer(); if(!players.containsKey(player.getObjectId())) { player.teleToLocation(worldZoneTable.getRespawn(player)); i--; length--; } } } finally { objects.writeUnlock(); } } protected void finishedState() { } protected void finishingState() { } /** * @return список аткивных игроков. */ public Array<Player> getActivePlayers() { return activePlayers; } /** * @return территория ивента. */ public final Territory getEventTerritory() { return eventTerritory; } /** * @return максимальный уровень для участия. */ protected int getMaxLevel() { return 0; } /** * @return минимальный уровень для участия. */ protected int getMinLevel() { return 0; } /** * @return таблица участников. */ public final Table<IntKey, EventPlayer> getPlayers() { return players; } /** * @return список зарегестрированных. */ public final Array<Player> getPrepare() { return prepare; } /** * @return время на регистрацию игроков. */ protected int getRegisterTime() { return 0; } /** * @return стадия ивента. */ protected final EventState getState() { return state; } /** * @return ид ивент территории. */ protected int getTerritoryId() { return 0; } @Override public boolean isAuto() { return true; } /** * @return нужно ли при текущей стадии смотреть на убийства. */ protected boolean isCheckDieState() { return false; } /** * @return нужно ли при текущей стадии ивента проверять зону. */ protected boolean isCheckTerritoryState() { return false; } /** * @return запущен ли ивент. */ public final boolean isStarted() { return started; } @Override public final void lock() { lock.lock(); } /** * Блокер движения. */ protected void lockMove(Player player) { RUN_LOCKER.addFuncTo(player); } /** * обработка удаление из мира указанного игрока. * * @param player удаляемый игрок. */ protected void onDelete(Player player) { } @Override public void onDelete(TObject object) { if(!object.isPlayer()) { return; } Player player = object.getPlayer(); if(!player.isEvent()) { return; } onDelete(player); } @Override public void onDie(Character killer, Character killed) { if(!isCheckDieState() || !killed.isPlayer()) { return; } Player player = killed.getPlayer(); if(!player.isEvent() || !players.containsKey(killed.getObjectId())) { return; } onDie(player, killer); } /** * Обработка убийства игрока. * * @param killed убитый игрок. * @param killer убийка игрока. */ protected void onDie(Player killed, Character killer) { } /** * Обработка входа левого игрока в ивент зону. * * @param player вошедший игрок. */ protected void onEnter(Player player) { } @Override public void onEnter(Territory territory, TObject object) { if(territory != eventTerritory || !isCheckTerritoryState() || !object.isPlayer() || players.containsKey(object.getObjectId())) { return; } onEnter(object.getPlayer()); } /** * Обработка выхода левого игрока из ивент зоны. * * @param player вышедший игрок. */ protected void onExit(Player player) { } @Override public void onExit(Territory territory, TObject object) { if(territory != eventTerritory || !isCheckTerritoryState() || !object.isPlayer() || !players.containsKey(object.getObjectId())) { return; } onExit(object.getPlayer()); } @Override public boolean onLoad() { return true; } @Override public boolean onReload() { return true; } @Override public boolean onSave() { return true; } protected void prepareBattleState() { } protected void prepareEndState() { } protected void prepareStartState() { } @Override public boolean registerPlayer(Player player) { lock(); try { if(!isStarted()) { player.sendMessage(CustomMessage.EVENT_NO_RUNNING); return false; } if(getState() != EventState.REGISTER) { player.sendMessage(CustomMessage.EVENT_REGISTRATION_LEFT); return false; } if(player.getLevel() > getMaxLevel() || player.getLevel() < getMinLevel()) { player.sendMessage(CustomMessage.EVENT_NO_LVL_REQUIRED); return false; } Array<Player> prepare = getPrepare(); if(prepare.contains(player)) { player.sendMessage(CustomMessage.EVENT_ALREADY_REGISTERED); return false; } if(player.isDead()) { player.sendMessage(CustomMessage.EVENT_PLAYER_DEAD); return false; } if(player.hasDuel()) { player.sendMessage(CustomMessage.EVENT_PLAYER_IN_DUEL); return false; } prepare.add(player); player.setEvent(true); player.sendMessage(CustomMessage.EVENT_REGISTRATION_OK); return true; } finally { unlock(); } } protected boolean isNeedShowPlayerCount() { return true; } /** * Отправка анонса о регистрации. */ protected void registerState() { World.sendAnnounce(CustomMessage.EVENT_TIME_BEFORE_EVENT + time + CustomMessage.MINUTES); World.sendAnnounce("Prior to the start of Event left " + time + " Minute(s)"); if(isNeedShowPlayerCount()) { World.sendAnnounce("They are " + prepare.size() + CustomMessage.REGISTERED_PARTICIPANTS); } World.sendAnnounce(CustomMessage.EVENT_HOW_TO_REGISTER + getName()); time--; if(time == 0) { setState(EventState.PREPARE_START); } } /** * Удаление игрока из активных. */ public final void removeActivePlayer(Object player) { activePlayers.fastRemove(player); } /** * удаление из таблицы участников игрока. * * @param objectId ид игрока. * @return удаляемый игрок. */ public final EventPlayer removeEventPlayer(int objectId) { return players.remove(objectId); } @Override protected void runImpl() { lock(); try { switch(getState()) { case REGISTER: { registerState(); break; } case PREPARE_START: { prepareStartState(); break; } case PREPARE_BATLE: { prepareBattleState(); break; } case RUNNING: { runningState(); break; } case PREPARE_END: { prepareEndState(); break; } case FINISHING: { finishingState(); break; } case FINISHED: { finishedState(); } } } finally { unlock(); } } protected void runningState() { } /** * @param запущен ли ивент. */ public final void setStarted(boolean started) { this.started = started; } /** * @param state стадия ивента. */ protected final void setState(EventState state) { this.state = state; } @Override public boolean start() { lock(); try { if(isStarted()) { return false; } if(eventTerritory != null) { eventTerritory.addListener(this); } ObjectEventManager objectEventManager = ObjectEventManager.getInstance(); objectEventManager.addDeleteListener(this); objectEventManager.addDieListener(this); time = getRegisterTime(); EventManager eventManager = EventManager.getInstance(); eventManager.start(this); World.sendAnnounce(CustomMessage.EVENT_START_MESSAGE + "\"" + getName() + "\""); setStarted(true); setState(EventState.REGISTER); ExecutorManager executor = ExecutorManager.getInstance(); schedule = executor.scheduleGeneralAtFixedRate(this, 60000, 60000); return true; } finally { unlock(); } } @Override public boolean stop() { lock(); try { if(!isStarted()) { return false; } players.clear(); activePlayers.clear(); if(eventTerritory != null) { eventTerritory.removeListener(this); } ObjectEventManager objectEventManager = ObjectEventManager.getInstance(); objectEventManager.removeDeleteListener(this); objectEventManager.removeDieListener(this); World.sendAnnounce(CustomMessage.EVENT_END_MESSAGE + "\"" + getName() + "\""); setStarted(false); setState(EventState.FINISHED); return true; } finally { unlock(); } } @Override public final void unlock() { lock.unlock(); } /** * Разблокер движения. */ protected void unlockMove(Player player) { RUN_LOCKER.removeFuncTo(player); } @Override public boolean unregisterPlayer(Player player) { lock(); try { if(!isStarted()) { player.sendMessage(CustomMessage.EVENT_NO_RUNNING); return false; } if(getState() != EventState.REGISTER) { player.sendMessage(CustomMessage.EVENT_CAN_REGISTER); return false; } Array<Player> prepare = getPrepare(); if(!prepare.contains(player)) { player.sendMessage(CustomMessage.EVENT_NO_REGISTER); return false; } prepare.fastRemove(player); player.setEvent(false); player.sendMessage(CustomMessage.EVENT_USER_REGISTERED); return false; } finally { unlock(); } } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Begin_Through_Arbiter_Contract.java package tera.gameserver.network.serverpackets; import rlib.util.Strings; import tera.gameserver.network.ServerPacketType; /** * Приглашение в акшен игроку * * @author Ronn * @created 26.04.2012 */ public class S_Begin_Through_Arbiter_Contract extends ServerPacket { private static final ServerPacket instance = new S_Begin_Through_Arbiter_Contract(); /** * @param actorName имя инициатора. * @param enemyName имя опонента. * @param id ид акшена. * @param objectId уникальный ид акшена. * @return новый пакет. */ public static S_Begin_Through_Arbiter_Contract getInstance(String actorName, String enemyName, int id, int objectId) { S_Begin_Through_Arbiter_Contract packet = (S_Begin_Through_Arbiter_Contract) instance.newInstance(); packet.actorName = actorName; packet.enemyName = enemyName; packet.id = id; packet.objectId = objectId; return packet; } /** имя инициатора */ private String actorName; /** имя опонента */ private String enemyName; /** ид акшена */ private int id; /** уникальный ид акшена */ private int objectId; @Override public void finalyze() { actorName = null; enemyName = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_BEGIN_THROUGH_ARBITER_CONTRACT; } @Override protected void writeImpl() { writeOpcode(); writeShort(22);//senderName writeShort(22 + Strings.length(actorName));//targetName writeShort(Strings.length(actorName)); //длинна первого ника +2 writeInt(id); writeInt(objectId); writeInt(13583); writeString(actorName); writeString(enemyName); writeShort(0); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Artisan_Skill_List.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; public class S_Artisan_Skill_List extends ServerConstPacket { private static final S_Artisan_Skill_List instance = new S_Artisan_Skill_List(); public static S_Artisan_Skill_List getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_ARTISAN_SKILL_LIST; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeShort(buffer, 5); writeShort(buffer, 25); writeInt(buffer, 0); writeInt(buffer, 0); writeInt(buffer, 0x48000000); writeInt(buffer, 0x00000E44); writeByte(buffer, 0); writeShort(buffer, 25); writeShort(buffer, 57); writeInt(buffer, 6); writeInt(buffer, 6); writeInt(buffer, 0x3F800000); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 1); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 0); writeShort(buffer, 57); writeShort(buffer, 89); writeInt(buffer, 7); writeInt(buffer, 7); writeInt(buffer, 0x3F800000); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 1); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 0); writeShort(buffer, 89); writeShort(buffer, 121); writeInt(buffer, 21); writeInt(buffer, 21); writeInt(buffer, 0x3F800000); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 1); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 0); writeShort(buffer, 121); writeShort(buffer, 153); writeInt(buffer, 22); writeInt(buffer, 22); writeInt(buffer, 0x3F800000); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 1); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 0); writeShort(buffer, 153); writeShort(buffer, 0); writeInt(buffer, 23); writeInt(buffer, 23); writeInt(buffer, 0x3F800000); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 1); writeInt(buffer, 0xFFFFFFFF); writeInt(buffer, 0); } }<file_sep>/java/game/tera/gameserver/network/clientpackets/RequestActionInvite.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.actions.ActionType; import tera.gameserver.model.playable.Player; import tera.gameserver.network.model.UserClient; import tera.gameserver.network.serverpackets.S_Reply_Request_Contract; /** * Приглашение на участие в акшене. * * @author Ronn * @created 26.04.2012 */ public class RequestActionInvite extends ClientPacket { /** имя приглашаемого */ private String name; /** тип акшена */ private ActionType actionType; @Override public void finalyze() { name = null; } @Override protected void readImpl() { readInt();// 1A 00 24 00 readShort();// 00 00 actionType = ActionType.valueOf(readByte()); readLong();// 00 00 00 00 00 00 00 00 readInt();// 00 00 00 00 readShort();// 00 readByte(); switch (actionType) { case CREATE_GUILD: { readShort(); name = readString(); break; } case BIND_ITEM: { readShort(); name = String.valueOf(readInt()); break; } default: name = readString(); } } @Override protected void runImpl() { UserClient client = getOwner(); if (client == null) return; Player actor = client.getOwner(); if (actor == null || actor.getName().equals(name)) return; ActionType actionType = getActionType(); actor.sendPacket(S_Reply_Request_Contract.getInstance(actionType), true); if (!actionType.isImplemented() || actor.hasLastAction()) return; actor.getAI().startAction(actionType.newInstance(actor, name)); } private ActionType getActionType() { return actionType; } } <file_sep>/java/game/tera/gameserver/document/DocumentTown.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.TownInfo; /** * Парсер городов с xml. * * @author Ronn */ public final class DocumentTown extends AbstractDocument<Array<TownInfo>> { /** * @param file отпрасиваемый фаил. */ public DocumentTown(File file) { super(file); } @Override protected Array<TownInfo> create() { return Arrays.toArray(TownInfo.class); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node town = list.getFirstChild(); town != null; town = town.getNextSibling()) if("town".equals(town.getNodeName())) result.add(new TownInfo(town)); } }<file_sep>/java/game/tera/gameserver/templates/CharTemplate.java package tera.gameserver.templates; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Objects; import rlib.util.Reloadable; import rlib.util.VarTable; import tera.gameserver.model.skillengine.funcs.Func; /** * Базовая модель шаблона персонажей. * * @author Ronn */ public abstract class CharTemplate implements Reloadable<CharTemplate> { protected static final Logger log = Loggers.getLogger(CharTemplate.class); /** контейнер всех переменных */ protected final VarTable vars; /** набор функций */ protected Func[] funcs; /** базовое макс хп */ protected int maxHp; /** базовое макс мп */ protected int maxMp; /** базовый реген хп */ protected int regHp; /** базовый реген мп */ protected int regMp; /** базовая атака */ protected int powerFactor; /** базовая защита */ protected int defenseFactor; /** базавая мощность опрокидывания */ protected int impactFactor; /** базавая защита от опрокидывания */ protected int balanceFactor; /** базавая скорость атаки */ protected int atkSpd; /** базавая скорость бега */ protected int runSpd; /** базовый шанс крита */ protected int critRate; /** базовая защита от крита */ protected int critRcpt; /** скорость разворота */ protected int turnSpeed; public CharTemplate(VarTable vars, Func[] funcs) { this.maxHp = vars.getInteger("maxHp"); this.maxMp = vars.getInteger("maxMp"); this.regHp = vars.getInteger("regHp", 9); this.regMp = vars.getInteger("regMp", 9); this.powerFactor = vars.getInteger("powerFactor", 0); this.defenseFactor = vars.getInteger("defenseFactor", 0); this.impactFactor = vars.getInteger("impactFactor", 50); this.balanceFactor = vars.getInteger("balanceFactor", 50); this.atkSpd = vars.getInteger("atkSpd"); this.runSpd = vars.getInteger("runSpd"); this.critRate = vars.getInteger("critRate", 50); this.critRcpt = vars.getInteger("critRcpt", 50); this.turnSpeed = vars.getInteger("turnSpeed", 6000); this.funcs = funcs; this.vars = VarTable.newInstance().set(vars); } /** * @return базовая скорость атаки. */ public final int getAtkSpd() { return atkSpd; } /** * @return базовая защита от опракидывания. */ public final int getBalanceFactor() { return balanceFactor; } /** * @return базовый шанс крита. */ public final int getCritRate() { return critRate; } /** * @return базовая защита от крита. */ public final int getCritRcpt() { return critRcpt; } /** * @return базовая защита. */ public final int getDefenseFactor() { return defenseFactor; } /** * @return набор функций. */ public final Func[] getFuncs() { return funcs; } /** * @return базовая сила опракидывания. */ public final int getImpactFactor() { return impactFactor; } /** * @return базовый макс хп персонажа. */ public final int getMaxHp() { return maxHp; } /** * @return базовый макс мп персонажа. */ public final int getMaxMp() { return maxMp; } /** * @return ид модели персонажа. */ public int getModelId() { return 0; } /** * @return базовая сила. */ public final int getPowerFactor() { return powerFactor; } /** * @return базовый реген хп. */ public final int getRegHp() { return regHp; } /** * @return базовый реген мп. */ public final int getRegMp() { return regMp; } /** * @return базовая скорость бега. */ public final int getRunSpd() { return runSpd; } /** * @return ид шаблона. */ public int getTemplateId() { return 0; } /** * @return тип шаблона. */ public int getTemplateType() { return 0; } /** * @return скорость разворота персонажа. */ public int getTurnSpeed() { return turnSpeed; } /** * @return таблица всех переменных. */ public VarTable getVars() { return vars; } @Override public void reload(CharTemplate update) { if(getClass() != update.getClass()) return; Objects.reload(this, update); } @Override public String toString() { return getClass().getSimpleName() + " maxHp = " + maxHp + ", maxMp = " + maxMp + ", regHp = " + regHp + ", regMp = " + regMp + ", powerFactor = " + powerFactor + ", defenseFactor = " + defenseFactor + ", impactFactor = " + impactFactor + ", balanceFactor = " + balanceFactor + ", atkSpd = " + atkSpd + ", runSpd = " + runSpd + ", critRate = " + critRate + ", critRcpt = " + critRcpt; } }<file_sep>/java/game/tera/util/LocalObjects.java package tera.util; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.ServerThread; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.TObject; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.npc.AggroInfo; import tera.gameserver.model.npc.Minion; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.QuestEvent; /** * Модель локальных объектов для серверного потока. * * @author Ronn */ public final class LocalObjects { private static final int DEFAULT_BUFFER_SIZE = 20; public static LocalObjects get() { return ServerThread.currentThread().getLocal(); } /** буффер списков игроков */ private Array<Player>[] playerLists; /** буффер списков минионов */ private Array<Minion>[] minionLists; /** буффер списков итемов */ private Array<ItemInstance>[] itemLists; /** буффер списков нпс */ private Array<Npc>[] npcLists; /** буффер списков персонажей */ private Array<Character>[] charLists; /** буффер списков объектов */ private Array<TObject>[] objectLists; /** буфер списков ссылок */ private Array<Link>[] linkLists; /** буфер агро инфы */ private Array<AggroInfo>[] aggroInfoLists; /** буффер квестовых ивентов */ private QuestEvent[] questEvents; /** буффер атак инф */ private AttackInfo[] attackInfos; /** индекс след. свободного списка игроков */ private int playerListIndex; /** индекс след. свободного списка минионов */ private int minionListIndex; /** индекс след. свободного списка итемов */ private int itemListIndex; /** индекс след. свободного списка нпс */ private int npcListIndex; /** индекс след. свободного списка персонадей */ private int charListIndex; /** индекс след. свободного списко объектов */ private int objectListIndex; /** индекс след. свободного списка ссылок */ private int linkListIndex; /** индекс след. свободного списка аггро инфы */ private int aggroInfoListIndex; /** индекс след. свободного квестового ивента */ private int questEventIndex; /** индекс след. свободного атак инфо */ private int attackInfotIndex; @SuppressWarnings("unchecked") public LocalObjects() { this.playerLists = new Array[DEFAULT_BUFFER_SIZE]; this.minionLists = new Array[DEFAULT_BUFFER_SIZE]; this.itemLists = new Array[DEFAULT_BUFFER_SIZE]; this.npcLists = new Array[DEFAULT_BUFFER_SIZE]; this.charLists = new Array[DEFAULT_BUFFER_SIZE]; this.objectLists = new Array[DEFAULT_BUFFER_SIZE]; this.linkLists = new Array[DEFAULT_BUFFER_SIZE]; this.aggroInfoLists = new Array[DEFAULT_BUFFER_SIZE]; this.questEvents = new QuestEvent[DEFAULT_BUFFER_SIZE]; this.attackInfos = new AttackInfo[DEFAULT_BUFFER_SIZE]; for(int i = 0, length = DEFAULT_BUFFER_SIZE; i < length; i++) { playerLists[i] = Arrays.toArray(Player.class); minionLists[i] = Arrays.toArray(Minion.class); itemLists[i] = Arrays.toArray(ItemInstance.class); npcLists[i] = Arrays.toArray(Npc.class); charLists[i] = Arrays.toArray(Character.class); objectLists[i] = Arrays.toArray(TObject.class); linkLists[i] = Arrays.toArray(Link.class); aggroInfoLists[i] = Arrays.toArray(AggroInfo.class); questEvents[i] = new QuestEvent(); attackInfos[i] = new AttackInfo(); } } /** * @return свободный список ссылок. */ public Array<AggroInfo> getNextAggroInfoList() { if(aggroInfoListIndex == DEFAULT_BUFFER_SIZE) aggroInfoListIndex = 0; return aggroInfoLists[aggroInfoListIndex++].clear(); } /** * @return свободный атак инфо. */ public AttackInfo getNextAttackInfo() { if(attackInfotIndex == DEFAULT_BUFFER_SIZE) attackInfotIndex = 0; return attackInfos[attackInfotIndex++].clear(); } /** * @return свободный список игроков. */ public Array<Character> getNextCharList() { if(charListIndex == DEFAULT_BUFFER_SIZE) charListIndex = 0; return charLists[charListIndex++].clear(); } /** * @return свободный список итемлв. */ public Array<ItemInstance> getNextItemList() { if(itemListIndex == DEFAULT_BUFFER_SIZE) itemListIndex = 0; return itemLists[itemListIndex++].clear(); } /** * @return свободный список ссылок. */ public Array<Link> getNextLinkList() { if(linkListIndex == DEFAULT_BUFFER_SIZE) linkListIndex = 0; return linkLists[linkListIndex++].clear(); } /** * @return свободный список минионов. */ public Array<Minion> getNextMinionList() { if(minionListIndex == DEFAULT_BUFFER_SIZE) minionListIndex = 0; return minionLists[minionListIndex++].clear(); } /** * @return свободный список игроков. */ public Array<Npc> getNextNpcList() { if(npcListIndex == DEFAULT_BUFFER_SIZE) npcListIndex = 0; return npcLists[npcListIndex++].clear(); } /** * @return свободный список объектов. */ public Array<TObject> getNextObjectList() { if(objectListIndex == DEFAULT_BUFFER_SIZE) objectListIndex = 0; return objectLists[objectListIndex++].clear(); } /** * @return свободный список игроков. */ public Array<Player> getNextPlayerList() { if(playerListIndex == DEFAULT_BUFFER_SIZE) playerListIndex = 0; return playerLists[playerListIndex++].clear(); } /** * @return свободный квестовый ивент. */ public QuestEvent getNextQuestEvent() { if(questEventIndex == DEFAULT_BUFFER_SIZE) questEventIndex = 0; return questEvents[questEventIndex++].clear(); } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionRemoveItem.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; /** * Акшен удаления итема из инвенторя. * * @author Ronn */ public class ActionRemoveItem extends AbstractQuestAction { /** ид итема */ private int id; /** кол-во итемов */ private long count; public ActionRemoveItem(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); try { VarTable vars = VarTable.newInstance(node); this.id = vars.getInteger("id"); this.count = vars.getInteger("count"); } catch(Exception e) { log.warning(this, e); } } @Override public void apply(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // если его нет, выходим if(player == null) { log.warning(this, "not found player"); return; } // получаем инвентарь Inventory inventory = player.getInventory(); // если его нет, выходим if(inventory == null) { log.warning(this, "not found inventory"); return; } if(count == -1) { if(inventory.removeItem(id)) { // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // если удалили успешно, обновляем инвентарь eventManager.notifyInventoryChanged(player); } } else if(inventory.removeItem(id, count)) { // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // если удалили успешно, обновляем инвентарь eventManager.notifyInventoryChanged(player); } } @Override public String toString() { return "ActionRemoveItem id = " + id + ", count = " + count; } } <file_sep>/java/game/tera/gameserver/manager/CommandManager.java package tera.gameserver.manager; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.gameserver.model.playable.Player; import tera.gameserver.scripts.commands.Command; import tera.gameserver.scripts.commands.CommandType; /** * Менеджер обработки команд из чата. * * @author Ronn */ public final class CommandManager { private static final Logger log = Loggers.getLogger(CommandManager.class); private static CommandManager instance; public static CommandManager getInstance() { if(instance == null) instance = new CommandManager(); return instance; } /** таюлица обработчиков команд */ private Table<String, Command> commands; private CommandManager() { // создаем таблицу команд и обработчиков commands = Tables.newObjectTable(); // регистрируем доступные команды for(CommandType cmds : CommandType.values()) registerCommands(cmds.newInstance()); log.info("loaded " + commands.size() + " commands."); } /** * Обработка команды. * * @param player игрок, который ввел команду. * @param command название команды. * @param values параметры команды. * @return обработана ли команда. */ public final boolean execute(Player player, String cmd, String values) { // если команды нет, выходим if(cmd == null) return false; // получаем обработчика команды Command command = commands.get(cmd); // если обработчика нет, выходим if(command == null) return false; // если игрок не имеет доступа к обработчику, выходим if(player.getAccessLevel() < command.getAccess()) return false; try { // обрабатываем command.execution(cmd, player, values); } catch(Exception e) { log.warning(e); } return true; } /** * Регистрация обработчика команды. * * @param command обработчик команды. */ public final void registerCommands(Command command) { String[] cmmds = command.getCommands(); for(String cmd : cmmds) if(commands.containsKey(cmd)) log.warning("found a duplicate command " + cmd + "."); else commands.put(cmd, command); } /** * @return кол-во обрабатываемых команд. */ public final int size() { return commands.size(); } }<file_sep>/java/game/tera/gameserver/network/clientpackets/C_Load_Topo_Fin.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.PlayerManager; /** * Клиентский пакет для входа в мир. * * @author Ronn */ public class C_Load_Topo_Fin extends ClientPacket { @Override public boolean isSynchronized() { return false; } @Override public void readImpl(){} @Override public void runImpl() { // получаем менеджера по игрокам PlayerManager playerManager = PlayerManager.getInstance(); // обрабатываем вход в мир playerManager.enterInWorld(getOwner()); } }<file_sep>/java/game/tera/gameserver/document/DocumentDialog.java package tera.gameserver.document; import java.io.File; import java.lang.reflect.InvocationTargetException; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.gameserver.model.npc.interaction.DialogData; import tera.gameserver.model.npc.interaction.IconType; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.npc.interaction.LinkType; import tera.gameserver.model.npc.interaction.links.NpcLink; import tera.gameserver.model.npc.interaction.replyes.Reply; /** * Парсер ссылок нпс диалогов. * * @author Ronn */ public final class DocumentDialog extends AbstractDocument<Table<IntKey, Table<IntKey, DialogData>>> { /** * Парс ссылки в диалоге. * * @param node данные с хмл. * @return новая ссылка. */ public static Link parseLink(Node node) { // получаем аттрибуты ссылки VarTable vars = VarTable.newInstance(node); // получаем название ссылки String name = vars.getString("name"); // получаем иконку IconType icon = vars.getEnum("icon", IconType.class, IconType.NONE); Reply reply = null; //парсим ответ на ссылку for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { //находим ответ if("reply".equals(child.getNodeName())) { //получаем название ответа String replyName = child.getAttributes().getNamedItem("name").getNodeValue(); if(replyName == null) continue; //создаем экземпляр ответа try { reply = (Reply) Class.forName("tera.gameserver.model.npc.interaction.replyes." + replyName).getConstructor(Node.class).newInstance(child); } catch(ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { log.warning(DocumentDialog.class, e); } } } //Возвращаем готовую ссылку с ответом return new NpcLink(name, LinkType.DIALOG, icon, reply); } /** * @param file отпрасиваемый фаил. */ public DocumentDialog(File file) { super(file); } @Override protected Table<IntKey, Table<IntKey, DialogData>> create() { return Tables.newIntegerTable(); } @Override protected void parse(Document doc) { for(Node lst = doc.getFirstChild(); lst != null; lst = lst.getNextSibling()) if("list".equals(lst.getNodeName())) for(Node npc = lst.getFirstChild(); npc != null; npc = npc.getNextSibling()) if("npc".equals(npc.getNodeName())) { DialogData dialog = parseNpc(npc); Table<IntKey, DialogData> table = result.get(dialog.getNpcId()); if(table == null) { table = Tables.newIntegerTable(); result.put(dialog.getNpcId(), table); } table.put(dialog.getType(), dialog); } } /** * Парсим диалог нпс с хмл. * * @param node данные с схмл. * @return новый диалог. */ private DialogData parseNpc(Node node) { // поучаем атрибуты диалога VarTable vars = VarTable.newInstance(node); // получаем ид нпс, к которому принадлежит диалог int id = vars.getInteger("id"); // получаем ид нпс, к которому принадлежит диалог int type = vars.getInteger("type"); // создаем массив ссылок Array<Link> links = Arrays.toArray(Link.class, 2); // Находим ссылки и парсим их for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) if("link".equals(child.getNodeName())) links.add(parseLink(child)); // сужаем массив links.trimToSize(); // создаем и возвращаем диалог с указанныым массивом ссылок return new DialogData(links.array(), id, type); } } <file_sep>/java/game/tera/gameserver/model/skillengine/conditions/ConditionTargetAggroMe.java package tera.gameserver.model.skillengine.conditions; import tera.gameserver.model.Character; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.skillengine.Skill; /** * Условие для выполнение проверки на тип атакуемго нпс. * * @author Ronn */ public class ConditionTargetAggroMe extends AbstractCondition { /**флаг ярости */ private boolean value; /** * @param value должен ли находится нпс в ярости. */ public ConditionTargetAggroMe(boolean value) { this.value = value; } @Override public boolean test(Character attacker, Character attacked, Skill skill, float val) { if(attacked == null || !attacked.isNpc()) return false; Npc npc = attacked.getNpc(); Character top = npc.getMostHated(); if(value) return top == attacker; else return top != attacker; } } <file_sep>/java/game/tera/gameserver/model/skillengine/funcs/StatFunc.java package tera.gameserver.model.skillengine.funcs; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.model.skillengine.StatType; /** * Интерфейс для реализации функции статов. * * @author Ronn */ public interface StatFunc extends Func, Comparable<StatFunc> { /** * Рассчет значения параметра. * * @param attacker владелец функции. * @param attacked целевой персонаж. * @param skill кастуемый скил. * @param val исходное значение. * @return итоговое значение. */ public float calc(Character attacker, Character attacked, Skill skill, float val); /** * @return позиция в массиве функций. */ public int getOrder(); /** * @return стат, который модифицирует функция. */ public StatType getStat(); } <file_sep>/java/game/tera/gameserver/model/ai/npc/thinkaction/DefaultBattleAction.java package tera.gameserver.model.ai.npc.thinkaction; import org.w3c.dom.Node; import rlib.util.Rnd; import rlib.util.VarTable; import rlib.util.array.Array; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.Character; import tera.gameserver.model.NpcAIState; import tera.gameserver.model.World; import tera.gameserver.model.WorldRegion; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.MessagePackage; import tera.gameserver.model.ai.npc.NpcAI; import tera.gameserver.model.npc.Npc; import tera.gameserver.network.serverpackets.S_User_Status.NotifyType; import tera.gameserver.tables.MessagePackageTable; import tera.util.LocalObjects; /** * Базовая модель генератора действий в бою. * * @author Ronn */ public class DefaultBattleAction extends AbstractThinkAction { /** пакет сообщений при смене цели боя */ protected final MessagePackage switchTargetMessages; /** радиус ведения боя */ protected final int battleMaxRange; /** радиус реакции НПС на врагов */ protected final int reactionMaxRange; /** уровень критического хп */ protected final int criticalHp; /** шанс перехода в ярость */ protected final int rearRate; /** шанс перехода в убегание */ protected final int runAwayRate; /** максимум для скольких нпс цель может быть топ агром */ protected final int maxMostHated; public DefaultBattleAction(Node node) { super(node); try { // парсим параметры VarTable vars = VarTable.newInstance(node, "set", "name", "val"); this.battleMaxRange = vars.getInteger("battleMaxRange", ConfigAI.DEFAULT_BATTLE_MAX_RANGE); this.reactionMaxRange = vars.getInteger("reactionMaxRange", ConfigAI.DEFAULT_REACTION_MAX_RANGE); this.criticalHp = vars.getInteger("criticalHp", ConfigAI.DEFAULT_CRITICAL_HP); this.rearRate = vars.getInteger("rearRate", ConfigAI.DEFAULT_REAR_RATE); this.runAwayRate = vars.getInteger("runAwayRate", ConfigAI.DEFAULT_RUN_AWAY_RATE); this.maxMostHated = vars.getInteger("maxMostHated", ConfigAI.DEFAULT_MAX_MOST_HATED); // получаем таблицу сообщений MessagePackageTable messageTable = MessagePackageTable.getInstance(); this.switchTargetMessages = messageTable.getPackage(vars.getString("switchTargetMessages", ConfigAI.DEFAULT_SWITCH_TARGET_MESSAGES)); } catch(Exception e) { log.warning(this, e); throw new IllegalArgumentException(e); } } /** * @return радиус ведения боя. */ protected final int getBattleMaxRange() { return battleMaxRange; } /** * @return % хп, который является критическим. */ protected final int getCriticalHp() { return criticalHp; } /** * @return максимальное число топ агров для цели. */ protected final int getMaxMostHated() { return maxMostHated; } /** * @return радиус реакции НПС на врагов. */ protected final int getReactionMaxRange() { return reactionMaxRange; } /** * @return шанс входа в состояние ярости. */ protected final int getRearRate() { return rearRate; } /** * @return шанс входа в состояние убегания. */ protected final int getRunAwayRate() { return runAwayRate; } @Override public <A extends Npc> void think(NpcAI<A> ai, A actor, LocalObjects local, ConfigAI config, long currentTime) { if(actor.isDead()) { ai.clearTaskList(); actor.clearAggroList(); ai.setNewState(NpcAIState.WAIT); return; } if(actor.isTurner() || actor.isCastingNow()) { return; } if(actor.isStuned() || actor.isOwerturned()) { if(ai.isWaitingTask()) { ai.clearTaskList(); } return; } if(!actor.isInRangeZ(actor.getSpawnLoc(), getReactionMaxRange())) { ai.clearTaskList(); actor.clearAggroList(); ai.setNewState(NpcAIState.RETURN_TO_HOME); PacketManager.showNotifyIcon(actor, NotifyType.NOTICE_THINK); ai.setLastNotifyIcon(currentTime); return; } Character mostHated = actor.getMostHated(); if(mostHated == null && actor.isAggressive()) { WorldRegion region = actor.getCurrentRegion(); if(region != null) { Array<Character> charList = local.getNextCharList(); World.getAround(Character.class, charList, actor, actor.getAggroRange()); Character[] array = charList.array(); for(int i = 0, length = charList.size(); i < length; i++) { Character target = array[i]; if(ai.checkAggression(target)) { actor.addAggro(target, 1, false); } } } } mostHated = actor.getMostHated(); if(mostHated == null) { ai.clearTaskList(); actor.clearAggroList(); ai.setNewState(NpcAIState.RETURN_TO_HOME); PacketManager.showNotifyIcon(actor, NotifyType.NOTICE_THINK); ai.setLastNotifyIcon(currentTime); return; } Character target = ai.getTarget(); if(mostHated.isDead() || !mostHated.isInRange(actor.getSpawnLoc(), getBattleMaxRange())) { actor.removeAggro(mostHated); ai.clearTaskList(); return; } if(actor.getCurrentHpPercent() < getCriticalHp()) { int rate = Rnd.nextInt(0, 100000); if(rate < getRearRate()) { ai.clearTaskList(); ai.setNewState(NpcAIState.IN_RAGE); PacketManager.showNotifyIcon(actor, NotifyType.READ_REAR); ai.setLastNotifyIcon(currentTime); return; } // if(rate < getRunAwayRate()) { // ai.clearTaskList(); // ai.setNewState(NpcAIState.IN_RUN_AWAY); // return; // } } if(mostHated != target) { ai.setTarget(mostHated); } if(ai.isWaitingTask()) { if(ai.doTask(actor, currentTime, local)) { return; } } if(actor.isTurner() || actor.isCastingNow() || actor.isStuned() || actor.isOwerturned() || actor.isMoving()) { return; } if(currentTime - ai.getLastNotifyIcon() > 15000) { PacketManager.showNotifyIcon(actor, NotifyType.YELLOW_QUESTION); ai.setLastNotifyIcon(currentTime); } ai.getCurrentFactory().addNewTask(ai, actor, local, config, currentTime); if(ai.isWaitingTask()) { ai.doTask(actor, currentTime, local); } } } <file_sep>/java/game/tera/gameserver/document/DocumentNpcConfigAI.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.ai.npc.ConfigAI; /** * Парсер конфига АИ нпс с хмл. * * @author Ronn */ public class DocumentNpcConfigAI extends AbstractDocument<Array<ConfigAI>> { public DocumentNpcConfigAI(File file) { super(file); } @Override protected Array<ConfigAI> create() { return Arrays.toArray(ConfigAI.class); } @Override protected void parse(Document doc) { for(Node lst = doc.getFirstChild(); lst != null; lst = lst.getNextSibling()) if("list".equals(lst.getNodeName())) for(Node config = lst.getFirstChild(); config != null; config = config.getNextSibling()) if("config".equals(config.getNodeName())) result.add(new ConfigAI(config)); } } <file_sep>/java/game/tera/gameserver/model/skillengine/funcs/stat/AbstractStatFunc.java package tera.gameserver.model.skillengine.funcs.stat; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Condition; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.model.skillengine.funcs.StatFunc; import tera.gameserver.model.skillengine.lambdas.Lambda; /** * Фундаментальная модель функции. * * @author Ronn */ public abstract class AbstractStatFunc implements StatFunc { public static final StatFunc[] EMPTY_FUNC = new StatFunc[0]; /** тип стата */ protected StatType stat; /** порядок применения */ protected int order; /** условие для применения */ protected Condition condition; /** значение для вычисления */ protected Lambda lambda; /** * @param stat тип параметра, на который влияет функция. * @param order порядок в списке функции. * @param condition условия для применения функции. * @param lambda модификатор функции. */ public AbstractStatFunc(StatType stat, int order, Condition condition, Lambda lambda) { this.stat = stat; this.order = order; this.condition = condition; this.lambda = lambda; } @Override public void addFuncTo(Character owner) { if(owner == null) return; owner.addStatFunc(this); } @Override public int compareTo(StatFunc func) { if(func == null) return -1; return order - func.getOrder(); } @Override public int getOrder() { return order; } @Override public StatType getStat() { return stat; } @Override public void removeFuncTo(Character owner) { if(owner == null) return; owner.removeStatFunc(this); } @Override public String toString() { return getClass().getSimpleName() + " stat = " + stat + ", order = " + order + ", condition = " + condition + ", lambda = " + lambda; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Each_Skill_Result.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с отображением результата атаки. * * @author Ronn */ public class S_Each_Skill_Result extends ServerPacket { /** отображения заблокированного уронеа */ public static final int BLOCK = 0; /** отображение обычного урона */ public static final int DAMAGE = 1; /** отображение хила */ public static final int HEAL = 2; /** отображение хила мп */ public static final int MANAHEAL = 3; /** отображение наложения эффекта */ public static final int EFFECT = 4; private static final ServerPacket instance = new S_Each_Skill_Result(); public static S_Each_Skill_Result getInstance(Character attacker, Character attacked, AttackInfo info, Skill skill, int type) { S_Each_Skill_Result packet = (S_Each_Skill_Result) instance.newInstance(); if(attacker == null || attacked == null) log.warning(packet, new Exception("not found attacker or attacked")); packet.attacker = attacker; packet.attacked = attacked; packet.damage = info.getDamage(); packet.crit = info.isCrit(); packet.owerturned = info.isOwerturn(); packet.type = type; packet.damageId = skill.getDamageId(); return packet; } public static S_Each_Skill_Result getInstance(Character attacker, Character attacked, int damageId, int damage, boolean crit, boolean owerturned, int type) { S_Each_Skill_Result packet = (S_Each_Skill_Result) instance.newInstance(); if(attacker == null || attacked == null) log.warning(packet, new Exception("not found attacker or attacked")); packet.attacker = attacker; packet.attacked = attacked; packet.damageId = damageId; packet.damage = damage; packet.crit = crit; packet.owerturned = owerturned; packet.type = type; return packet; } /** атакер */ private Character attacker; /** атакуемый */ private Character attacked; /** ид урона */ private int damageId; /** кол-во урона */ private int damage; /** тип атаки */ private int type; /** блы лиудар критом */ private boolean crit; /** опрокинул ли удар цель */ private boolean owerturned; @Override public void finalyze() { attacker = null; attacked = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_EACH_SKILL_RESULT; } @Override protected final void writeImpl() { writeOpcode(); writeInt(owerturned ? 0x00540003 : 0); writeInt(attacker.getObjectId()); writeInt(attacker.getSubId()); writeInt(attacked.getObjectId()); writeInt(attacked.getSubId()); writeInt(attacker.getModelId()); writeInt(damageId); writeInt(0); writeInt(0); writeInt(0); // думаю 2е 2 байта хп цели 0x058E3E50 writeInt(0); // было ноль writeInt(damage); // Сколько надамажил writeShort(type);// ИД если 2 то будет лечить +80 и т.д. writeByte(crit? 1 : 0); // 01 Крит writeByte(0); //електровсплеск writeByte(owerturned? 1 : 0); //01 опрокинул writeByte(owerturned? 1 : 0); if(owerturned) { writeFloat(attacked.getX()); writeFloat(attacked.getY()); writeFloat(attacked.getZ()); writeShort(attacked.getHeading());//8 heading writeInt(attacked.getOwerturnId()); writeInt(0); writeInt(0); } else { writeInt(0); writeInt(0); writeInt(0); writeInt(0); writeInt(0); writeInt(0); writeShort(0); } } }<file_sep>/java/game/tera/gameserver/network/serverpackets/SkillLockTarget.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, показывающий игроку, что он взял в цель объект. * * @author Ronn */ public class SkillLockTarget extends ServerPacket { private static final ServerPacket instance = new SkillLockTarget(); public static SkillLockTarget getInstance(Character target, Skill skill, boolean locked) { SkillLockTarget packet = (SkillLockTarget) instance.newInstance(); packet.id = target.getObjectId(); packet.subId = target.getSubId(); packet.skillId = skill.getIconId(); packet.locked = locked? 1 : 0; return packet; } /** ид цели */ private int id; /** саб ид цели */ private int subId; /** ид скила */ private int skillId; /** захвачен ли */ private int locked; @Override public ServerPacketType getPacketType() { return ServerPacketType.SKILL_LOCK_TARGET; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, id); writeInt(buffer, subId); writeInt(buffer, skillId); writeByte(buffer, locked);//1 захват удался,0 захват не удался } } <file_sep>/java/game/tera/gameserver/model/quests/events/CanceledQuestListener.java package tera.gameserver.model.quests.events; import org.w3c.dom.Node; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestAction; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestEventType; /** * Слушатель отмены квестов. * * @author Ronn */ public class CanceledQuestListener extends AbstractQuestEventListener { public CanceledQuestListener(QuestEventType type, QuestAction[] actions, Quest quest, Node node) { super(type, actions, quest, node); } @Override public void notifyQuest(QuestEvent event) { if(event.getQuest() == quest) super.notifyQuest(event); } } <file_sep>/java/game/tera/gameserver/model/skillengine/targethandler/SelfTargetHandler.java package tera.gameserver.model.skillengine.targethandler; import rlib.util.array.Array; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Модель цели на себя. * * @author Ronn */ public final class SelfTargetHandler extends AbstractTargetHandler { @Override public void addTargetsTo(Array<Character> targets, Character caster, Skill skill, float targetX, float targetY, float targetZ) { targets.add(caster); } } <file_sep>/java/game/tera/gameserver/model/npc/playable/NpcAppearance.java package tera.gameserver.model.npc.playable; import tera.gameserver.model.playable.PlayerAppearance; /** * Модель внешности НПС на базе внешности игрока. * * @author Ronn */ public class NpcAppearance extends PlayerAppearance { /** ид шляпы */ private int hatId; /** ид маски */ private int maskId; /** ид перчаток */ private int glovesId; /** ид ботинок */ private int bootsId; /** ид брони */ private int armorId; /** ид пушки */ private int weaponId; /** * @return ид брони. */ public int getArmorId() { return armorId; } /** * @return ид ботинок. */ public int getBootsId() { return bootsId; } /** * @return ид перчаток. */ public int getGlovesId() { return glovesId; } /** * @return ид кепки. */ public int getHatId() { return hatId; } /** * @return */ public int getMaskId() { return maskId; } /** * @return ид пушки. */ public int getWeaponId() { return weaponId; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Start_Combo_Instant_Skill.java package tera.gameserver.network.clientpackets; import rlib.geom.Angles; import tera.Config; import tera.gameserver.model.Character; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.model.skillengine.Skill; /** * Клиентский пакет старта мили скила. * * @author Ronn */ public class C_Start_Combo_Instant_Skill extends ClientPacket { /** игрок */ private Player player; /** скил ид */ private int skillId; /** нужный разворот */ private int heading; /** ид возможной цели */ private int targetId; /** саб ид возможной цели */ private int targeSubId; /** целевые координаты */ private float targetX; private float targetY; private float targetZ; /** точка каста скила */ private float startX; private float startY; private float startZ; @Override public void finalyze() { setPlayer(null); setTargetId(0); } /** * @return направление каста. */ public int getHeading() { return heading; } /** * @return игрок. */ public final Player getPlayer() { return player; } /** * @return ид кастуемого скила. */ public int getSkillId() { return skillId; } /** * @return стартовая координата. */ public float getStartX() { return startX; } /** * @return стартовая координата. */ public float getStartY() { return startY; } /** * @return стартовая координата. */ public float getStartZ() { return startZ; } /** * @return под ид цели. */ public int getTargeSubId() { return targeSubId; } /** * @return ид цели. */ public int getTargetId() { return targetId; } /** * @return целевая координата. */ public float getTargetX() { return targetX; } /** * @return целевая координата. */ public float getTargetY() { return targetY; } /** * @return целевая координата. */ public float getTargetZ() { return targetZ; } @Override public void readImpl() { setPlayer(getOwner().getOwner()); boolean isHit = readInt() != 0; //4 readShort(); //6 readShort(); //8 setSkillId(readInt()); //12 setStartX(readFloat()); setStartY(readFloat()); setStartZ(readFloat()); setHeading(readShort()); readInt(); //27 if(isHit) { readInt(); setTargetId(readInt()); setTargeSubId(readInt()); readInt(); setTargetX(readFloat()); setTargetY(readFloat()); setTargetZ(readFloat()); } else { setTargetX(readFloat()); setTargetY(readFloat()); setTargetZ(readFloat()); } } @Override public void runImpl() { // получаем игрока Player player = getPlayer(); // если его нет, выходим if(player == null) return; // пробуем получить скил игрока Skill skill = player.getSkill(getSkillId()); // если его у него нету if(skill == null) { // сообщаем и выходим player.sendMessage("Этого скила у вас нету."); return; } float startX = getStartX(); float startY = getStartY(); float startZ = getStartZ(); // ссылка на возможную цель Character target = null; // если десинхрон превышает допустимый if(player.getSquareDistance(startX, startY) > Config.WORLD_MAX_SKILL_DESYNC) { startX = player.getX(); startY = player.getY(); } int targetId = getTargetId(); int targetSubId = getTargeSubId(); // если есть конкретная цель if(targetId > 0 && targetSubId == Config.SERVER_PLAYER_SUB_ID) // ищем ее target = World.getAroundById(Character.class, player, targetId, targetSubId); // запоминаем цель player.setTarget(target); float targetX = getTargetX(); float targetY = getTargetY(); float targetZ = getTargetZ(); int heading = getHeading(); // если цель есть if(target != null && skill.isCorrectableTarget()) { // правим координаты выстрела targetX = target.getX(); targetY = target.getY(); targetZ = target.getZ() + target.getGeomHeight() * 0.5F; // правим направление heading = Angles.calcHeading(startX, startY, targetX, targetY); } // отправляем на обработку запрос каста player.getAI().startCast(startX, startY, startZ, skill, 0, heading, targetX, targetY, targetZ); } /** * @param heading направление каста. */ public void setHeading(int heading) { this.heading = heading; } /** * @param player игрок. */ public void setPlayer(Player player) { this.player = player; } /** * @param skillId ид кастуемого скила. */ public void setSkillId(int skillId) { this.skillId = skillId; } /** * @param startX стартовая координата. */ public void setStartX(float startX) { this.startX = startX; } /** * @param startY стартовая координата. */ public void setStartY(float startY) { this.startY = startY; } /** * @param startZ стартовая координата. */ public void setStartZ(float startZ) { this.startZ = startZ; } /** * @param targeSubId под ид цели. */ public void setTargeSubId(int targeSubId) { this.targeSubId = targeSubId; } /** * @param targetId ид цели. */ public void setTargetId(int targetId) { this.targetId = targetId; } /** * @param targetX целевая координата. */ public void setTargetX(float targetX) { this.targetX = targetX; } /** * @param targetY целевая координата. */ public void setTargetY(float targetY) { this.targetY = targetY; } /** * @param targetZ целевая координата. */ public void setTargetZ(float targetZ) { this.targetZ = targetZ; } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_Start_Cooltime_Skill.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, отображающий откат скилов. * * @author Ronn */ public class S_Start_Cooltime_Skill extends ServerPacket { private static final ServerPacket instance = new S_Start_Cooltime_Skill(); public static S_Start_Cooltime_Skill getInstance(int skillId, int reuseDelay) { S_Start_Cooltime_Skill packet = (S_Start_Cooltime_Skill) instance.newInstance(); packet.skillId = skillId; packet.reuseDelay = reuseDelay; return packet; } /** ид скила */ private int skillId; /** время отката */ private int reuseDelay; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_START_COOLTIME_SKILL; } @Override protected final void writeImpl() { writeOpcode(); writeInt(skillId); writeInt(reuseDelay); } }<file_sep>/java/game/tera/gameserver/model/actions/classes/DuelStartAction.java package tera.gameserver.model.actions.classes; import tera.Config; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Duel; import tera.gameserver.model.MessageType; import tera.gameserver.model.World; import tera.gameserver.model.actions.ActionType; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Cancel_Contract; import tera.gameserver.network.serverpackets.S_Request_Contract; import tera.gameserver.network.serverpackets.DuelStart; import tera.gameserver.network.serverpackets.S_Sytem_Message; /** * Модель запуска акшена дуэли. * * @author Ronn */ public class DuelStartAction extends PlayerAction { @Override public synchronized void assent(Player player) { // цель акшена Player target = getTarget(); // инициатор акшена Player actor = getActor(); super.assent(player); // если условия не выполнены, отменяем if(!test(actor, target)) { cancel(null); return; } // получаем тип акшена ActionType type = getType(); // отправляем необходимые пакеты actor.sendPacket(S_Cancel_Contract.getInstance(actor.getObjectId(), actor.getSubId(), target.getObjectId(), target.getSubId(), type.ordinal(), objectId), true); target.sendPacket(S_Cancel_Contract.getInstance(actor.getObjectId(), actor.getSubId(), target.getObjectId(), target.getSubId(), type.ordinal(), objectId), true); // создаем сообщение о том, что игрок согласился на дуэль S_Sytem_Message packet = S_Sytem_Message.getInstance(MessageType.TARGET_ACCEPTED_THE_DUEL); // добавляем имя игрока packet.addTarget(target.getName()); // отправляем пакет actor.sendPacket(packet, true); actor.sendPacket(DuelStart.getInstance(), true); target.sendPacket(DuelStart.getInstance(), true); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // создаем таск начала дуэли executor.scheduleGeneral(Duel.newInstance(actor, target), 5500); } @Override public synchronized void cancel(Player player) { // получаем инициатора Player actor = getActor(); // получаем опонента инициатора Player target = getTarget(); // если все есть if(actor != null && target != null) { ActionType type = getType(); S_Sytem_Message packet; // если отменивший опонент if(player == target) { // создаем пакет с сообщением packet = S_Sytem_Message.getInstance(MessageType.TARGET_REJERECT_THE_DUEL); // добавляем имя отменившего packet.addTarget(target.getName()); // отправляем пакет actor.sendPacket(packet, true); } // отправляем соответствующие пакеты actor.sendPacket(S_Cancel_Contract.getInstance(actor.getObjectId(), actor.getSubId(), target.getObjectId(), target.getSubId(), type.ordinal(), objectId), true); target.sendPacket(S_Cancel_Contract.getInstance(actor.getObjectId(), actor.getSubId(), target.getObjectId(), target.getSubId(), type.ordinal(), objectId), true); } super.cancel(player); } @Override public ActionType getType() { return ActionType.DUEL; } @Override public void init(Player actor, String name) { this.actor = actor; this.target = World.getAroundByName(Player.class, actor, name); } @Override public synchronized void invite() { // получаем инициатора Player actor = getActor(); // получаем цель инициатора Player target = getTarget(); // если кого-то из них нет, выходим if(actor == null || target == null) { log.warning(this, new Exception("not found actor or target")); return; } // запоминаем приглашение actor.setLastAction(this); target.setLastAction(this); // получаем тип приглашения ActionType type = getType(); // лтправляем необходимые пакеты actor.sendPacket(S_Request_Contract.newInstance(actor, target, type.ordinal(), objectId), true); target.sendPacket(S_Request_Contract.newInstance(actor, target, type.ordinal(), objectId), true); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // создаем новый отложенный таск setSchedule(executor.scheduleGeneral(this, 30000)); } @Override public boolean test(Player actor, Player target) { // если кого-то их них нет, выходим if(actor == null) return false; // если игрок уже в дуэли if(actor.getDuel() != null) { actor.sendMessage(MessageType.YOU_ARE_IN_A_DUEL_NOW); return false; } // если игрок не онлаин if(target == null) { actor.sendMessage(MessageType.THAT_CHARACTER_ISNT_ONLINE); return false; } // если цель слишком далеко if(!actor.isInRange(target, Config.WORLD_DUEL_MAX_RANGE)) { actor.sendMessage(MessageType.TOO_FAR_AWAY); return false; } // если цель уже занята другим предложением if(target.getLastAction() != null) { actor.sendMessage(MessageType.TARGET_IS_BUSY); return false; } // если игрок в пвп режиме if(actor.isPvPMode() || actor.isBattleStanced()) { actor.sendMessage(MessageType.YOU_CANT_DUEL_WITH_SOMEONE_IN_PVP); return false; } // еси кто-то из них на ивенте, выходим if(actor.isEvent() || target.isEvent()) { actor.sendMessage("Нельзя начинать дуэль на ивенте."); return false; } if(target.isBattleStanced() || target.isPvPMode()) { actor.sendMessage(MessageType.TARGET_IS_IN_COMBAT); return false; } // если кто-то из них уже в дуэли, выходим if(target.hasDuel()) { actor.sendMessage("Игрок уже в дуэли."); return false; } // если целевой игрок мертв if(target.isDead()) { actor.sendPacket(S_Sytem_Message.getInstance(MessageType.USER_NAME_IS_DEAD).addUserName(target.getName()), true); return false; } return true; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/PegasReplyPacket.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет для открытия карты, в которой нужно выбирать пункт назначения для полета * * @author Ronn * @created 25.02.2012 */ public class PegasReplyPacket extends ServerPacket { private static final ServerPacket instance = new PegasReplyPacket(); public static PegasReplyPacket getInstance(Player player) { PegasReplyPacket packet = (PegasReplyPacket) instance.newInstance(); packet.player = player; return packet; } /** игрок */ private Player player; @Override public void finalyze() { player = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_REQUEST_CONTRACT; } @Override protected void writeImpl() { writeOpcode(); writeShort(44); writeShort(58); writeInt(60); writeInt(player.getObjectId()); writeInt(player.getSubId()); writeLong(0);//00 00 00 00 00 00 00 00 writeInt(15); writeInt(0x989b0300); writeLong(0);//00 00 00 00 00 00 00 00 writeS(player.getName()); writeShort(0); } } <file_sep>/java/game/tera/remotecontrol/handlers/AnnounceApplyHandler.java package tera.remotecontrol.handlers; import java.util.ArrayList; import java.util.List; import rlib.util.array.Array; import tera.gameserver.manager.AnnounceManager; import tera.gameserver.tasks.AnnounceTask; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; /** * Принятие новых настроек * * @author Ronn * @created 08.04.2012 */ public class AnnounceApplyHandler implements PacketHandler { @Override @SuppressWarnings("unchecked") public Packet processing(Packet packet) { // получаем менеджер аннонсов AnnounceManager announceManager = AnnounceManager.getInstance(); { List<String> startingAnnounces = packet.next(ArrayList.class); Array<String> current = announceManager.getStartAnnouncs(); current.clear(); for(String announce : startingAnnounces) current.add(announce); current.trimToSize(); } { List<Object[]> runningAnnounces = packet.next(ArrayList.class); Array<AnnounceTask> current = announceManager.getRuningAnnouncs(); for(AnnounceTask task : current) task.cancel(); current.clear(); for(Object[] announce : runningAnnounces) current.add(new AnnounceTask(announce[0].toString(), (int) announce[1])); } announceManager.save(); return null; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Update_Friend_Info.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import rlib.util.Strings; import tera.gameserver.model.FriendInfo; import tera.gameserver.model.FriendList; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с информацией о списке друзей. * * @author Ronn */ public class S_Update_Friend_Info extends ServerPacket { private static final ServerPacket instance = new S_Update_Friend_Info(); public static S_Update_Friend_Info getInstance(Player player) { S_Update_Friend_Info packet = (S_Update_Friend_Info) instance.newInstance(); ByteBuffer buffer = packet.getPrepare(); try { // получаем список друзей игрока FriendList friendList = player.getFriendList(); packet.writeShort(buffer, 8);// 08 00 кол-во перосов(друзей) или статик packet.writeShort(buffer, 8);// 08 00 кол-во перосов(друзей) или статик int n = 8; synchronized(friendList) { // получаем список друзей FriendInfo[] friends = friendList.getFriends(); // перебираем друзей for(int i = 0, length = friendList.size(); i < length; i++) { // получаем информацию о друге FriendInfo friend = friends[i]; // получаем его имя String name = friend.getName(); // получаем длинну имени int nameLength = Strings.length(name); packet.writeShort(buffer, n);// 08 00 байт начала описания друга if(i == length) packet.writeShort(buffer, 0); else packet.writeShort(buffer, n + 42 + nameLength);// 44 00 байта конца описания друга , если друг в списке последний то 0 packet.writeShort(buffer, n + 40);// 30 00 байт начала ника packet.writeShort(buffer, n + 40 + nameLength);// 42 00 байт конец ника packet.writeInt(buffer, friend.getObjectId());// 79 12 00 00 обж ид вроде packet.writeInt(buffer, friend.getLevel());// 3C 00 00 00 уровень packet.writeInt(buffer, friend.getRaceId());// 03 00 00 00 расса packet.writeInt(buffer, friend.getClassId());// 04 00 00 00 класс packet.writeInt(buffer, 0);// 01 00 00 00 хз потесть вроде онлайн packet.writeInt(buffer, 0);// 01 00 00 00 локация packet.writeInt(buffer, 0);// 0F 00 00 00 локация packet.writeInt(buffer, 0);// B0 00 00 00 локация packet.writeString(buffer, name); // 46 00 61 00 72 00 76 00 61 00 74 00 65 00 72 00 00 00 F.a.r.v.a.t.e.r. packet.writeShort(buffer, 0); n = n + 42 + nameLength; } } return packet; } finally { buffer.flip(); } } /** подготовленный буффер для отправки данных */ private ByteBuffer prepare; public S_Update_Friend_Info() { this.prepare = ByteBuffer.allocate(1024).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_UPDATE_FRIEND_INFO; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); // получаем промежуточный буффер ByteBuffer prepare = getPrepare(); // переносим данные buffer.put(prepare.array(), 0, prepare.limit()); } /** * @return подготовленный буфер. */ public ByteBuffer getPrepare() { return prepare; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Select_User.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет подтверждающий выбор персонажа для входа. * * @author Ronn * @created 31.03.2012 */ public class S_Select_User extends ServerConstPacket { private static final S_Select_User instance = new S_Select_User(); public static S_Select_User getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SELECT_USER; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeByte(buffer, 1); writeInt(buffer, 0); writeInt(buffer, 0); } }<file_sep>/java/game/tera/gameserver/model/inventory/Cell.java package tera.gameserver.model.inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.items.ItemLocation; /** * Модель ячейки инвенторя. * * @author Ronn */ public final class Cell implements Comparable<Cell> { /** итем ячейки */ private ItemInstance item; /** местоположение ячейки */ private ItemLocation location; /** номер ячейки */ private int index; /** * @param index номер ячейки. * @param location местоположение ячейки. */ public Cell(int index, ItemLocation location) { this.index = index; this.location = location; } @Override public int compareTo(Cell cell) { return (item == null? 1 : 0) - (cell.getItem() == null? 1 : 0); } /** * @return номер ячейки. */ public int getIndex() { return index; } /** * @return итем в ячейке. */ public ItemInstance getItem() { return item; } /** * @return кол-во итемов в ячейке. */ public long getItemCount() { return item == null? 0 : item.getItemCount(); } /** * @return ид темплейта итема. */ public int getItemId() { return item == null? 0 : item.getItemId(); } /** * @return пустая ли ячейка. */ public boolean isEmpty() { return item == null; } /** * @param index номер ячейки. */ public void setIndex(int index) { this.index = index; } /** * @param item итем. */ public void setItem(ItemInstance item) { this.item = item; if(item != null) { item.setLocation(location); item.setIndex(index); } } @Override public String toString() { return "index = " + index + ", item = " + item; } } <file_sep>/java/game/tera/gameserver/tables/BonfireTable.java package tera.gameserver.tables; import rlib.util.array.Arrays; import tera.gameserver.model.TObject; import tera.gameserver.model.WorldRegion; import tera.gameserver.model.territory.BonfireTerritory; import tera.gameserver.model.territory.Territory; import tera.gameserver.model.territory.TerritoryType; /** * Таблица костров. * * @author Ronn */ public abstract class BonfireTable { /** массив всех костров */ private static BonfireTerritory[] array; /** * Добавить костер в список. * * @param bonfire костер. */ public static void addBonfire(BonfireTerritory bonfire) { array = Arrays.addToArray(array, bonfire, BonfireTerritory.class); } /** * Получение ближайшего костра к объекту. * * @param object объект. * @return ближайший костер. */ public static BonfireTerritory getNearBonfire(TObject object) { // получаем текущий регион объекта WorldRegion region = object.getCurrentRegion(); // ближайший костер BonfireTerritory near = null; // дистанция до костра float dist = 0; // если регион есть if(region != null && region.hasTerritories()) { // получаем список территорий региона Territory[] terrs = region.getTerritories(); // перебираем территории for(int i = 0, length = terrs.length; i < length; i++) { Territory terr = terrs[i]; // если территория не костер, пропускаем if(terr.getType() != TerritoryType.CAMP_TERRITORY) continue; // кастим в территорию костра BonfireTerritory bonfire = (BonfireTerritory) terr; // определяем расстояние до костра float newDist = object.getDistance(bonfire.getCenterX(), bonfire.getCenterY(), bonfire.getCenterZ()); // если ближайшего нету либо расстояние у него меньше, чем у текущего ближайшего if(near == null || newDist < dist) { // запоминаем территорию near = bonfire; // запоминаем расстояние dist = newDist; } } // если нашли ближайший костер, возвращаем if(near != null) return near; } // если в регионе не нашли костер, перебираем среди всех for(int i = 0, length = array.length; i < length; i++) { BonfireTerritory terr = array[i]; // считаем расстояние до костра float newDist = object.getDistance(terr.getCenterX(), terr.getCenterY(), terr.getCenterZ()); // если ближайшего нету либо расстояние у него меньше, чем у текущего ближайшего if(near == null || newDist < dist) { near = terr; dist = newDist; } } return near; } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/SlowShot.java package tera.gameserver.model.skillengine.shots; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.IdFactory; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; import tera.gameserver.network.serverpackets.DeleteShot; import tera.gameserver.network.serverpackets.StartSlowShot; /** * Модель медленных выстрелов. * * @author Ronn */ public class SlowShot extends AbstractShot { /** пул выстрелов */ private static FoldablePool<SlowShot> shotPool = Pools.newConcurrentFoldablePool(SlowShot.class); /** * @param caster стреляющий персонаж. * @param skill стреляющий скил. * @param targetX координата точки полета. * @param targetY координата точки полета. * @param targetZ координата точки полета. */ public static void startShot(Character caster, Skill skill, float targetX, float targetY, float targetZ) { // получаем объект из пула SlowShot shot = shotPool.take(); // если его нет if(shot == null) // создаем новый shot = new SlowShot(); // подготавливаем shot.prepare(caster, skill, targetX, targetY, targetZ); // запускаем shot.start(); } /** уникальный ид выстрела */ protected int objectId; public SlowShot() { setType(ShotType.SLOW_SHOT); } @Override public int getObjectId() { return objectId; } @Override public void start() { super.start(); // получаем фабрику ИД IdFactory idFactory = IdFactory.getInstance(); // получаем новый ид objectId = idFactory.getNextShotId(); // отправляем пакет caster.broadcastPacket(StartSlowShot.getInstance(caster, skill, objectId, getSubId(), targetX, targetY, targetZ)); } @Override public void stop() { super.stop(); // отправляем пакет caster.broadcastPacket(DeleteShot.getInstance(objectId, getSubId())); // ложим в пул shotPool.put(this); } } <file_sep>/java/game/tera/gameserver/model/Alliance.java package tera.gameserver.model; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; public class Alliance { private static final Logger log = Loggers.getLogger(Alliance.class); public static final int EXARCH_RANK_ID = 400; public static final int DEFENSE_COMMANDER_ID = 303; public static final int ASSAULT_COMMANDER_ID = 302; public static final int ADJUNCT_COMMANDER_ID = 301; public static final int ECHELON_ID = 301; private int allianceId; private int leaderId; private String leaderName; private String leaderGuildName; private int taxRate; private int strength; private int bonus; private String message; private final Table<IntKey, Guild> guilds; public Alliance(int allianceId, int leaderId, String leaderName, String leaderGuildName, int taxRate, int strength, int bonus, String message) { this.allianceId = allianceId; this.leaderId = leaderId; this.leaderName = (leaderName == null) ? "" : leaderName; this.leaderGuildName = leaderGuildName; this.taxRate = taxRate; this.strength = strength; this.bonus = bonus; this.message = message; this.guilds = Tables.newIntegerTable(); } public int getAllianceId() { return allianceId; } public int getLeaderId() { return leaderId; } public String getLeaderName() { return leaderName; } public String getLeaderGuildName() { return leaderGuildName; } public int getTaxRate() { return taxRate; } public int getStrength() { return strength; } public int getBonus() { return bonus; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void setTaxRate(int taxRate) { this.taxRate = taxRate; } public Table<IntKey, Guild> getGuilds() { return guilds; } public void addGuild(Guild guild) { Table<IntKey, Guild> guilds = getGuilds(); if(guilds.containsKey(guild.getObjectId())){ log.warning("found duplicate " + guild + " for alliance " + getAllianceId()); return; } guilds.put(guild.getObjectId(), guild); } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/conditions/ConditionQuestAgoComplete.java package tera.gameserver.model.npc.interaction.conditions; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestDate; import tera.gameserver.model.quests.QuestList; /** * Условие проверки на время, после выполения квеста. * * @author Ronn */ public class ConditionQuestAgoComplete extends AbstractCondition { /** сколько времени назад был выполнен квест */ private long time; public ConditionQuestAgoComplete(Quest quest, long time) { super(quest); this.time = time * 60 * 1000; } @Override public boolean test(Npc npc, Player player) { // если игрока нет, возвращаем плохо if(player == null) { log.warning(this, "not found player"); return false; } // получаем список квестов игрока QuestList questList = player.getQuestList(); // если его нет, возвращаем плохо if(questList == null) { log.warning(this, "not found quest list"); return false; } // получаем временной штамп квеста QuestDate date = questList.getQuestDate(quest.getId()); if(date == null) return false; // проверяем, прошло ли нужное кол-во времени return System.currentTimeMillis() - date.getTime() > time; } @Override public String toString() { return "ConditionQuestAgoComplete time = " + time; } } <file_sep>/java/game/tera/gameserver/model/drop/AbstractDrop.java package tera.gameserver.model.drop; import java.util.Arrays; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.array.Array; import tera.Config; import tera.gameserver.model.Character; import tera.gameserver.model.TObject; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; /** * Базовая модель дропа. * * @author Ronn */ public abstract class AbstractDrop implements Drop { protected static final Logger log = Loggers.getLogger(Drop.class); /** группы дропа */ protected DropGroup[] groups; /** ид темплейта, к которому принадлежит дроп */ protected int templateId; public AbstractDrop(int templateId, DropGroup[] groups) { this.templateId = templateId; this.groups = groups; } @Override public void addDrop(Array<ItemInstance> container, TObject creator, Character owner) { // если владельца нет, выходим if(owner == null) { log.warning(this, new Exception("not found owner")); return; } // если генератора нет, выходим if(creator == null) { log.warning(this, new Exception("not found creator")); return; } // если условия не выполняются, выходим if(!checkCondition(creator, owner)) return; // пробуем получить игрока Player player = owner.getPlayer(); // начало рассчета рейтов дропа float dropRate = Config.SERVER_RATE_DROP_ITEM; // начало рассчета рейтов денег float moneyRate = Config.SERVER_RATE_MONEY; // определяем, есть ли премиум у игрока boolean payed = player.hasPremium(); // если активирован бонус премиума на деньги, и игрок с премиумом if(Config.ACCOUNT_PREMIUM_MONEY && payed) // увеличиваем соответсвенно рейты на деньги moneyRate *= Config.ACCOUNT_PREMIUM_MONEY_RATE; // если активирован бонус премиума на дроп, и игрок с премиумом if(Config.ACCOUNT_PREMIUM_DROP && payed) // увеличиваем соответсвенно рейты на дроп dropRate *= Config.ACCOUNT_PREMIUM_DROP_RATE; // получаем группы с дропом DropGroup[] groups = getGroups(); // перебираем группы for(int i = 0, length = groups.length; i < length; i++) { // получаем группу DropGroup group = groups[i]; // получаем кол-во проходов по группе float maxCount = group.getCount(); // если это не деньги if(!group.isMoney()) // то увеличиваем на рейты maxCount *= dropRate; // получаем итоговое кол-во проходов int count = Math.max((int) maxCount, 1); // начинаем проходы for(int g = 0; g < count; g++) { // пробуем получить итем из группы ItemInstance item = group.getItem(); // если его нет, проход пропускаем if(item == null) continue; // если это деньги if(item.getItemId() == Inventory.MONEY_ITEM_ID) { // увеличиваем кол-во на рейт денег long newCount = (long) (item.getItemCount() * moneyRate); // если кол-во меньше 1 о_О if(newCount < 1) { // удаляем итем item.deleteMe(); // идем дальше continue; } // устанавливаем новое кол-во item.setItemCount(newCount); } // добавляем в контейнер container.add(item); } } } /** * @return нужно ли вообще рассчитывать для владельца дроп. */ protected abstract boolean checkCondition(TObject creator, Character owner); /** * @return группы с дропом. */ protected final DropGroup[] getGroups() { return groups; } @Override public int getTemplateId() { return templateId; } @Override public String toString() { return "AbstractDrop groups = " + Arrays.toString(groups) + ", templateId = " + templateId; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Visit_New_Section.java package tera.gameserver.network.clientpackets; public class C_Visit_New_Section extends ClientPacket { private int worldMapWorldId; private int worldMapGuardId; private int areaId; @Override protected void readImpl() { worldMapWorldId = readInt(); worldMapGuardId = readInt(); areaId = readInt(); } @Override protected void runImpl() { /** * todo: Send S_VISIT_NEW_SECTION packet */ } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Auth_Failed.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * @author Ronn */ public class S_Auth_Failed extends ServerPacket { private static final ServerPacket instance = new S_Auth_Failed(); public static S_Auth_Failed getInstance() { return (S_Auth_Failed) instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_AUTH_FAILED; } @Override protected void writeImpl() { writeOpcode(); writeInt(0x01010000); writeInt(0x00008000); writeShort(0); writeByte(0); } }<file_sep>/java/game/tera/gameserver/model/quests/classes/AbstractQuest.java package tera.gameserver.model.quests.classes; import org.w3c.dom.Node; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Objects; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.document.DocumentQuestCondition; import tera.gameserver.manager.GameLogManager; import tera.gameserver.model.MessageType; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.npc.interaction.IconType; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.npc.interaction.links.QuestLink; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestAction; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestEventListener; import tera.gameserver.model.quests.QuestEventType; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestPanelState; import tera.gameserver.model.quests.QuestState; import tera.gameserver.model.quests.QuestType; import tera.gameserver.model.quests.Reward; import tera.gameserver.network.serverpackets.S_Clear_World_Quest_Villager_Info; import tera.gameserver.network.serverpackets.S_Daily_Quest_Complete_Count; import tera.gameserver.network.serverpackets.S_Delete_Quest; import tera.gameserver.network.serverpackets.S_Sytem_Message; import tera.gameserver.tables.NpcTable; import tera.gameserver.templates.NpcTemplate; import tera.util.LocalObjects; /** * Базовая модель для реализации квеста. * * @author Ronn */ public abstract class AbstractQuest implements Quest { protected static final Logger log = Loggers.getLogger(Quest.class); protected static final DocumentQuestCondition conditionParser = DocumentQuestCondition.getInstance(); /** название квеста */ protected String name; /** тип квеста */ protected QuestType type; /** награда за квест */ protected Reward reward; /** список обрабатываемых событий */ protected QuestEventListener[] events; /** список ссылок квестовых */ protected Link[] links; /** ид квеста */ protected int id; /** можно ли отменить квест */ protected boolean cancelable; public AbstractQuest(QuestType type, Node node) { try { // парсим атрибуты квеста VarTable vars = VarTable.newInstance(node); this.type = type; this.name = vars.getString("name"); this.id = vars.getInteger("id"); if(name.isEmpty()) System.out.println("found empty name for quest " + id); this.cancelable = vars.getBoolean("cancelable", type.isCancelable()); this.reward = new Reward(); // создаем список ссылок Array<Link> links = Arrays.toArray(Link.class); // создаем список ивентов Array<QuestEventListener> events = Arrays.toArray(QuestEventListener.class); // получаем таблицу НПС NpcTable npcTable = NpcTable.getInstance(); // пребираем внутринние элементы квеста for(Node nd = node.getFirstChild(); nd != null; nd = nd.getNextSibling()) { switch(nd.getNodeName()) { // если это набор нпс, учавствующих в квесте case "npcs": { // перебираем нпс for(Node npc = nd.getFirstChild(); npc != null; npc = npc.getNextSibling()) { if(!"npc".equals(npc.getNodeName())) continue; // парсим атрибуты нпс vars.parse(npc); // получаем темплейт нпс NpcTemplate template = npcTable.getTemplate(vars.getInteger("id"), vars.getInteger("type")); // если такой темплейт есть if(template != null) // добавляем ему этот квест template.addQuest(this); } break; } // если это набор награды case "rewards": { // перебираем акшены с наградами for(Node act = nd.getFirstChild(); act != null; act = act.getNextSibling()) if("action".equals(act.getNodeName())) // добавляем акшен reward.addReward(parseAction(act)); break; } // если это набор ссылок case "links": { // перебираем ссылки for(Node link = nd.getFirstChild(); link != null; link = link.getNextSibling()) if("link".equals(link.getNodeName())) links.add(parseLink(link)); break; } // если это набор ивентов квеста case "events": { // перебираем ивенты for(Node evt = nd.getFirstChild(); evt != null; evt = evt.getNextSibling()) if("event".equals(evt.getNodeName())) events.add(parseEvent(evt)); break; } } } links.trimToSize(); events.trimToSize(); this.links = links.array(); this.events = events.array(); } catch(Exception e) { log.warning(e); } } @Override public final void addLinks(Array<Link> container, Npc npc, Player player) { // получаем ссылки квеста Link[] links = getLinks(); // перебираем ссылки квеста for(int i = 0, length = links.length; i < length; i++) { // получаем ссылку Link link = links[i]; // если условия для отображения ссылки не выполнены, пропускаем if(!link.test(npc, player)) continue; // добавляем в контейнер ссылку container.add(link); } } @Override public void cancel(QuestEvent event, boolean force) { // получаем игрока Player player = event.getPlayer(); // получаем нпс Npc npc = event.getNpc(); // если игрока нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // если квест нельзя отменить if(!force && !cancelable) { // отправляем сообщени об этом player.sendPacket(S_Sytem_Message.getInstance(MessageType.QUEST_NAME_CANT_BE_ABANDONED).addQuestName(name), true); return; } // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем дополнительный квестовый ивент QuestEvent newEvent = local.getNextQuestEvent(); // ставим тип финиша newEvent.setType(QuestEventType.CANCELED_QUEST); // запоминаем игрока newEvent.setPlayer(player); // запоминаем нпс newEvent.setNpc(npc); // запоминаем квест newEvent.setQuest(this); // отправляем новый ивент notifyQuest(newEvent); // получаем квест лист игрока QuestList questList = player.getQuestList(); // получаем текущее состояние квеста QuestState questState = questList.getQuestState(this); // удаляем квест из панели и книги player.sendPacket(S_Delete_Quest.getInstance(questState, true), true); // удаляем с панели player.updateQuestInPanel(questState, QuestPanelState.REMOVED); // финишируем его questList.finishQuest(this, questState, true); // если нпс есть if(npc != null){ //player.sendPacket(S_Clear_World_Quest_Villager_Info.getInstance(), true); npc.updateQuestInteresting(player, true); } // отправляем сообщени об этом player.sendPacket(S_Sytem_Message.getInstance(MessageType.ABANDONED_QUEST_NAME).addQuestName(name), true); player.sendPacket(S_Daily_Quest_Complete_Count.getInstance(),false); // получаем логера игровых событий GameLogManager gameLogger = GameLogManager.getInstance(); // записываем событие отмены квеста игроком gameLogger.writeQuestLog(player.getName() + " cancel quest [id = " + getId() + ", name = " + getName() + "]"); } @Override public final void finish(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // получаем нпс Npc npc = event.getNpc(); // если игрока нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем дополнительный квестовый ивент QuestEvent newEvent = local.getNextQuestEvent(); // ставим тип финиша newEvent.setType(QuestEventType.FINISHED_QUEST); // запоминаем игрока newEvent.setPlayer(player); // запоминаем нпс newEvent.setNpc(npc); // запоминаем квест newEvent.setQuest(this); // отправляем новый ивент notifyQuest(newEvent); // получаем квест лист игрока QuestList questList = player.getQuestList(); // получаем текущее состояние квеста QuestState questState = questList.getQuestState(this); // удаляем с панели player.updateQuestInPanel(questState, QuestPanelState.REMOVED); // устанавливаем этот квест как выполненный questList.complete(this); // финишируем его questList.finishQuest(this, questList.getQuestState(this), false); // обрабатываем награду reward.giveReward(event); // если нпс есть if(npc != null) // обновляем его значек над головой npc.updateQuestInteresting(player, true); // отправляем сообщени об этом player.sendPacket(S_Sytem_Message.getInstance(MessageType.CONGRATULATIONS_QUEST_NAME_COMPLETED).addQuestName(id), true); // получаем логера игровых событий GameLogManager gameLogger = GameLogManager.getInstance(); // записываем событие завершения квеста игроком gameLogger.writeQuestLog(player.getName() + " finish quest [id = " + getId() + ", name = " + getName() + "]"); } /** * @return список ивентов квеста. */ protected final QuestEventListener[] getEvents() { return events; } /** * @return ид квеста. */ public final int getId() { return id; } /** * @return список ссылок квеста. */ protected final Link[] getLinks() { return links; } /** * @return название квеста. */ public final String getName() { return name; } @Override public final Reward getReward() { return reward; } /** * @return тип квеста. */ public final QuestType getType() { return type; } @Override public final boolean isAvailable(Npc npc, Player player) { // получаем ссылки квеста Link[] links = getLinks(); // перебираем ссылки квеста для поиска начальной for(int i = 0, length = links.length; i < length; i++) { // получам ссылку Link link = links[i]; // если это начальная if(link.getId() == 1) // возращаем результат кондишена ссылки return link.test(npc, player); } return false; } @Override public final void notifyQuest(QuestEvent event) { notifyQuest(event.getType(), event); } @Override public final void notifyQuest(QuestEventType type, QuestEvent event) { // получаем ивенты квеста QuestEventListener[] events = getEvents(); for(int i = 0, length = events.length; i < length; i++) { // получаем ивент QuestEventListener listener = events[i]; // если ивент соотвествующего типа if(listener.getType() == type) // уведомляем его listener.notifyQuest(event); } } /** * @return отпаршенный акшен. */ private QuestAction parseAction(Node node) { // парсим атрибуты акшена VarTable vars = VarTable.newInstance(node); // получаем тип акшена QuestActionType actionType; try { actionType = vars.getEnum("name", QuestActionType.class); } catch(Exception e) { return null; } // парсим кондишен для акшена Condition condition = conditionParser.parseCondition(node, this); // создаем акшен QuestAction action = actionType.newInstance(this, condition, node); return action; } /** * @return отпаршенный ивент. */ private QuestEventListener parseEvent(Node node) { // парсим атрибуты ивента VarTable vars = VarTable.newInstance(node); // создаем список акшенов внутри ивента Array<QuestAction> actions = Arrays.toArray(QuestAction.class); // перебираем акшены for(Node act = node.getFirstChild(); act != null; act = act.getNextSibling()) if("action".equals(act.getNodeName())) // парсим и добавляем акшен actions.add(parseAction(act)); // сжимаем список акшенов actions.trimToSize(); // получаем тип ивента QuestEventType eventType = vars.getEnum("name", QuestEventType.class); return eventType.newInstance(this, actions.array(), node); } /** * @return отпаршенная ссылка. */ private Link parseLink(Node node) { // парсим атрибуты ссылки VarTable vars = VarTable.newInstance(node); // получаем имя ссылки String name = vars.getString("name"); // получаем ид ссылки int id = vars.getInteger("id"); // получаем иконку ссылки IconType icon = vars.getEnum("icon", IconType.class); // получаем кондишен ссылки Condition condition = conditionParser.parseCondition(node, this); // создаем и возвращаем новую ссылку return new QuestLink(name, icon, id, this, condition); } @Override public final void reload(Quest update) { Objects.reload((Quest) this, update); } @Override public final void reply(Npc npc, Player player, Link link) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем событие квеста QuestEvent event = local.getNextQuestEvent(); // получаем последнюю ссылку игрока Link lastLink = player.getLastLink(); // если последняя ссылка есть, то это нажатие на ссылку if(lastLink != null) { // ставим тип события " нажатие на ссылку " event.setType(QuestEventType.SELECT_LINK); // запоминаем нажатую ссылку event.setLink(link); // запоминаем нпс event.setNpc(npc); // запоминаем игрока event.setPlayer(player); // запоминаем квест event.setQuest(this); } // иначе это было нажатие на кнопку в квест диалоге else { // ставим флаг нажатия на кнопку event.setType(QuestEventType.SELECT_BUTTON); // запоминаем нажатую ссылку event.setLink(link); // запоминаем нпс event.setNpc(npc); // запоминаем игрока event.setPlayer(player); // запоминаем квест event.setQuest(this); } // запускаемсобытие на обработку notifyQuest(event); } @Override public final void start(QuestEvent event) { // получаем игрока Player player = event.getPlayer(); // получаем нпс Npc npc = event.getNpc(); // если игрока нет, выходим if(player == null) return; // получаем квест лист QuestList questList = player.getQuestList(); // запускаем квест у игрока QuestState quest = questList.startQuest(this); // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем дополнительный квестовый ивент QuestEvent newEvent = local.getNextQuestEvent(); // ставим тип ивента взятие квеста newEvent.setType(QuestEventType.ACCEPTED_QUEST); // запоминаем игрока newEvent.setPlayer(player); // запоминаем нпс newEvent.setNpc(npc); // запоминаем квест newEvent.setQuest(this); // если нпс есть if(npc != null) // обновляем значек над ним npc.updateQuestInteresting(player, true); // запускаем новый ивент notifyQuest(newEvent); // обновляем на панели player.updateQuestInPanel(quest, QuestPanelState.ACCEPTED); // получаем логера игровых событий GameLogManager gameLogger = GameLogManager.getInstance(); // записываем событие взятие квеста игроком gameLogger.writeQuestLog(player.getName() + " accepted quest [id = " + getId() + ", name = " + getName() + "]"); } @Override public String toString() { return "AbstractQuest name = " + name + ", type = " + type + ", reward = " + reward + ", events = " + Arrays.toString(events) + ", links = " + Arrays.toString(links) + ", id = " + id; } } <file_sep>/java/game/tera/gameserver/model/npc/SocialMonster.java package tera.gameserver.model.npc; import tera.gameserver.templates.NpcTemplate; /** * Модель социального монстра. * * @author Ronn */ public class SocialMonster extends Monster { public SocialMonster(int objectId, NpcTemplate template) { super(objectId, template); } @Override public int getKarmaMod() { return 0; } } <file_sep>/java/game/tera/remotecontrol/handlers/SendAnnounceHandler.java package tera.remotecontrol.handlers; import tera.gameserver.model.World; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; /** * Отправка анонса * * @author Ronn * @created 08.04.2012 */ public class SendAnnounceHandler implements PacketHandler { @Override public Packet processing(Packet packet) { String announce = packet.nextString(); if(announce.isEmpty()) return null; World.sendAnnounce(announce); return null; } } <file_sep>/java/game/tera/gameserver/model/npc/summons/Summon.java package tera.gameserver.model.npc.summons; import rlib.idfactory.IdGenerator; import rlib.idfactory.IdGenerators; import tera.gameserver.IdFactory; import tera.gameserver.model.Character; import tera.gameserver.model.MessageType; import tera.gameserver.model.npc.Npc; import tera.gameserver.network.serverpackets.S_Sytem_Message; import tera.gameserver.network.serverpackets.S_Show_Hp; import tera.gameserver.templates.NpcTemplate; /** * Базовая модель суммона. * * @author Ronn */ public class Summon extends Npc { private static final IdGenerator ID_FACTORY = IdGenerators.newSimpleIdGenerator(1300001, 1600000); /** владелец сумона */ protected Character owner; public Summon(int objectId, NpcTemplate template) { super(objectId, template); } @Override public void addAggro(Character aggressor, long aggro, boolean damage) { } @Override public void subAggro(Character aggressor, long aggro) { } @Override public Character getMostDamager() { return null; } @Override public void clearAggroList() { } @Override public long getAggro(Character aggressor) { return 0; } @Override public boolean checkTarget(Character target) { Character owner = getOwner(); if(owner != null) return owner.checkTarget(target); return false; } @Override protected void addCounter(Character attacker) { } @Override public void doDie(Character attacker) { Character owner = getOwner(); if(owner != null && owner.isPlayer()) { if(owner == attacker) owner.sendMessage(MessageType.YOUR_PET_HAS_BEEN_DESTRUYED); else owner.sendPacket(S_Sytem_Message.getInstance(MessageType.ATTACKER_DESTROYED_YOUR_PET).addAttacker(attacker.getName()), true); } if(owner != null) owner.setSummon(null); super.doDie(attacker); getAI().stopAITask(); } @Override protected void calculateRewards(Character killer) { } @Override public Character getMostHated() { return null; } @Override public void removeAggro(Character agressor) { } @Override public int getOwerturnTime() { return 3500; } @Override public final boolean isSummon() { return true; } @Override public void reinit() { IdFactory idFactory = IdFactory.getInstance(); setObjectId(idFactory.getNextNpcId()); getAI().startAITask(); } /** * Удаление сумона. */ public void remove() { if(!isDead()) { setCurrentHp(0); doDie(owner); } } @Override public void setOwner(Character owner) { this.owner = owner; } @Override public Character getOwner() { return owner; } @Override public void updateHp() { Character owner = getOwner(); if(owner != null && owner.isPlayer()) owner.sendPacket(S_Show_Hp.getInstance(this, S_Show_Hp.BLUE), true); } @Override public int nextCastId() { return ID_FACTORY.getNextId(); } @Override public void effectHealHp(int heal, Character healer) { super.effectHealHp(heal, healer); updateHp(); } @Override public void doRegen() { int currentHp = getCurrentHp(); super.doRegen(); if(currentHp != getCurrentHp()) updateHp(); } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/Shot.java package tera.gameserver.model.skillengine.shots; import rlib.util.pools.Foldable; import tera.gameserver.model.Character; /** * Интерфейс для реализации выстрелов. * * @author Ronn */ public interface Shot extends Foldable, Runnable { /** * @return уникальный ид выстрела. */ public int getObjectId(); /** * @return саб ид выстрела. */ public int getSubId(); /** * @return цель выстрела. */ public Character getTarget(); /** * @return целевая координата. */ public float getTargetX(); /** * @return целевая координата. */ public float getTargetY(); /** * @return целевая координата. */ public float getTargetZ(); /** * @return тип выстрела. */ public ShotType getType(); /** * @return является ли автонаводкой. */ public boolean isAuto(); /** * Запуск выстрела. */ public void start(); /** * Остановка выстрела. */ public void stop(); } <file_sep>/java/game/tera/gameserver/document/DocumentTerritory.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.territory.Territory; import tera.gameserver.model.territory.TerritoryType; /** * Парсер территорий с xml. * * @author Ronn * @created 09.03.2012 */ public final class DocumentTerritory extends AbstractDocument<Array<Territory>> { /** * @param file отпрасиваемый фаил. */ public DocumentTerritory(File file) { super(file); } @Override protected Array<Territory> create() { return Arrays.toArray(Territory.class); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node node = list.getFirstChild(); node != null; node = node.getNextSibling()) if("territory".equals(node.getNodeName())) { // получаем атрибуты территории VarTable vars = VarTable.newInstance(node); // создаем и добавляем территорию result.add(vars.getEnum("type", TerritoryType.class).newInstance(node)); } } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_Login_Account_Info.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * @author <NAME> */ public class S_Login_Account_Info extends ServerPacket { private static final ServerPacket instance = new S_Login_Account_Info(); public static ServerPacket getInstance() { return instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_LOGIN_ACCOUNT_INFO; } @Override protected void writeImpl() { writeOpcode(); writeShort(0x0E00); writeShort(3672); writeShort(29449); writeInt(0); writeString("GameDB"); } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_Party_Member_Interval_Pos_Update.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.config.MissingConfig; import tera.gameserver.model.playable.Playable; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с координатами члена пати. * * @author Ronn */ public class S_Party_Member_Interval_Pos_Update extends ServerPacket { private static final ServerPacket instance = new S_Party_Member_Interval_Pos_Update(); public static S_Party_Member_Interval_Pos_Update getInstance(Playable member) { S_Party_Member_Interval_Pos_Update packet = (S_Party_Member_Interval_Pos_Update) instance.newInstance(); packet.objectId = member.getObjectId(); packet.zoneId = member.getZoneId(); packet.x = member.getX(); packet.y = member.getY(); packet.z = member.getZ(); return packet; } /** ид члена пати */ private int objectId; /** ид зоны, в которойо н */ private int zoneId; /** его координаты */ private float x; private float y; private float z; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_PARTY_MEMBER_INTERVAL_POS_UPDATE; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, MissingConfig.SERVER_ID);// SERVER ID writeInt(buffer, objectId);// 5F 78 00 00 writeFloat(buffer, x);// 66 3D B0 47 writeFloat(buffer, y);// 86 8B AD C7 writeFloat(buffer, z);// 00 30 92 C5 writeInt(buffer, zoneId);// 0D 00 00 00 помойму тоже writeInt(buffer, 6);// 04 00 00 00 } } <file_sep>/java/game/tera/gameserver/network/serverpackets/FFStructure.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; public class FFStructure extends ServerConstPacket { private static final FFStructure instance = new FFStructure(); public static FFStructure getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.FF_STRUCTURE; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeShort(buffer, 5); writeShort(buffer, 22); writeInt(buffer, 1); writeInt(buffer, 0); writeInt(buffer, 60); writeShort(buffer, 0); writeShort(buffer, 22); writeShort(buffer, 34); writeInt(buffer, 0); writeInt(buffer, 0); writeShort(buffer, 34); writeShort(buffer, 46);//2E00 writeInt(buffer, -1); writeInt(buffer, 0); writeShort(buffer, 46); writeShort(buffer, 58); writeInt(buffer, -1); writeInt(buffer, 0); writeShort(buffer, 58); //3A00 writeShort(buffer, 70); writeInt(buffer, -1); writeInt(buffer, 0); writeShort(buffer, 70); //46000000 writeShort(buffer, 0); //46000000 writeInt(buffer, -1); writeInt(buffer, 0); } }<file_sep>/java/game/tera/gameserver/scripts/items/ItemExecutorType.java package tera.gameserver.scripts.items; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import rlib.logging.Loggers; /** * Виды используемых итемов. * * @author Ronn * @created 04.03.2012 */ public enum ItemExecutorType { /** награда за ивент */ EVENT_REWARD_BOX(EventRewardBox.class, 0, 408, 409, 410, 411), SKILL_LEARN_ITEM(SkillLearnItem.class, 0, 20, 21, 41, 166, 167, 168, 169, 170, 306, 307, 336, 350, 351, 384, 385, 412, 413, 414, 415, 416, 417, 425), BARBECUE_ITEMS(BarbecueItem.class, 0, 5027); /** конструктор обработчика */ private Constructor<? extends ItemExecutor> constructor; /** уровень доступа для игрока */ private int access; /** массив идов итемов */ private int[] itemIds; /** * @param type тип обработчика. * @param access минимальный уровень доступа. * @param itemIds массив итем ид. */ private ItemExecutorType(Class<? extends ItemExecutor> type, int access, int... itemIds) { this.access = access; this.itemIds = itemIds; try { constructor = type.getConstructor(int[].class, int.class); } catch(NoSuchMethodException | SecurityException e) { Loggers.warning(this, e); } } /** * @return кол-во итем идов. */ public int getCount() { return itemIds.length; } /** * @return новый экземпляр обработчика. */ public ItemExecutor newInstance() { try { return constructor.newInstance(itemIds, access); } catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { Loggers.warning(this, e); } return null; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/Test29.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; public class Test29 extends ServerConstPacket { private static final Test29 instance = new Test29(); public static Test29 getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.TEST_29; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 0); } }<file_sep>/java/game/tera/gameserver/model/ReactionType.java /** * */ package tera.gameserver.model; /** * @author Ronn * */ public enum ReactionType { } <file_sep>/java/game/tera/gameserver/network/clientpackets/RequestState.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.StateAllowed; /** * Клиентский пакет старта мили скила. * * @author Ronn */ public class RequestState extends ClientPacket { /** игрок */ private Player player; /** уник ид игрока */ private int objectId; /** саб ид игрока */ private int subId; /** ид состояния */ private int stateId; @Override public void finalyze() { player = null; } @Override public void readImpl() { player = owner.getOwner(); objectId = readInt();//обжект ид B4 4D 0D 00 subId = readInt();//саб ид 00 80 00 00 stateId = readInt();//1E 00 00 00 } @Override public void runImpl() { if(player == null || player.getObjectId() != objectId || player.getSubId() != subId) return; player.sendPacket(StateAllowed.getInstance(player, stateId), true); } }<file_sep>/java/game/tera/gameserver/model/npc/interaction/links/AbstractLink.java package tera.gameserver.model.npc.interaction.links; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.npc.interaction.IconType; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.npc.interaction.LinkType; import tera.gameserver.model.npc.interaction.replyes.Reply; import tera.gameserver.model.playable.Player; /** * Модель ссылки в диалоге. * * @author Ronn */ public abstract class AbstractLink implements Link { /** название ссылки */ protected String name; /** тип ссылки */ protected LinkType type; /** иконка ссылки */ protected IconType icon; /** ответ */ protected Reply reply; /** кондишен на отображение ссылки */ protected Condition condition; /** * @param name название ссылки. * @param type тип ссылки. * @param icon тип иконки. * @param reply ответ на ссылку. * @param condition условие на отображение ссылки. */ public AbstractLink(String name, LinkType type, IconType icon, Reply reply, Condition condition) { this.name = name; this.type = type; this.reply = reply; this.icon = icon; } /** * @return ид иконки. */ public int getIconId() { return icon.ordinal(); } @Override public int getId() { return 0; } /** * @return название ссылки. */ public String getName() { return name; } /** * @return ответ на ссылку. */ public Reply getReply() { return reply; } /** * @return тип ссылки. */ public LinkType getType() { return type; } /** * Обработка ответа на ссылку. * * @param npc нпс, у которого была нажата ссылка. * @param player игрок, который нажал на ссылку. */ public void reply(Npc npc, Player player) { reply.reply(npc, player, this); } @Override public boolean test(Npc npc, Player player) { return false; } } <file_sep>/java/game/tera/remotecontrol/Packet.java package tera.remotecontrol; import java.io.Serializable; import java.util.Arrays; /** * Пакет * * @author Ronn * @created 26.03.2012 */ public final class Packet implements Serializable { /** long Packet.java */ private static final long serialVersionUID = -5515767380967971929L; /** тип пакета */ private PacketType type; /** передоваемая информация */ private Serializable[] values; /** позиция в масиве значений */ private int ordinal; /** * @param type * @param values */ public Packet(PacketType type, Serializable...values) { this.type = type; this.values = values; } /** * @return тип пакета */ public PacketType getType() { return type; } /** * @return values */ public Serializable[] getValues() { return values; } /** * @return есть ли еще элементы */ public boolean hasNext() { return ordinal < values.length; } /** * @return next object */ public Object next() { return values[ordinal++]; } /** * @param type * @return next T object */ public <T> T next(Class<T> type) { return type.cast(values[ordinal++]); } /** * @return next boolean */ public boolean nextBoolean() { return (Boolean) values[ordinal++]; } /** * @return next double */ public double nextDouble() { return (Double) values[ordinal++]; } /** * @return next float */ public float nextFloat() { return (Float) values[ordinal++]; } /** * @return next int */ public int nextInt() { return (Integer) values[ordinal++]; } /** * @return next long */ public long nextLong() { return (Long) values[ordinal++]; } /** * @return next string */ public String nextString() { return values[ordinal++].toString(); } /** * @param values */ public void setValues(Serializable... values) { this.values = values; } @Override public String toString() { return "Packet " + (type != null ? "type = " + type + ", " : "") + (values != null ? "values = " + Arrays.toString(values) + ", " : "") + "ordinal = " + ordinal; } } <file_sep>/java/game/tera/gameserver/scripts/items/SkillLearnItem.java package tera.gameserver.scripts.items; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.MessageType; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Sytem_Message; import tera.gameserver.tables.SkillTable; import tera.gameserver.templates.SkillTemplate; /** * Модель итемов, изучающие скилы. * * @author Ronn */ public class SkillLearnItem extends AbstractItemExecutor { /** таблица изучаемых скилов */ private final Table<IntKey, SkillTemplate[]> skillTable; public SkillLearnItem(int[] itemIds, int access) { super(itemIds, access); this.skillTable = Tables.newIntegerTable(); try { skillTableInit(); } catch(Exception e) { log.warning(this, e); } } @Override public void execution(ItemInstance item, Player player) { // получаем темплейт изучаемого скила SkillTemplate[] template = skillTable.get(item.getItemId()); // если темплейтов нет, ыходим if(template == null || template.length < 1) return; // получаем первый темплейт в массиве SkillTemplate first = template[0]; // если скил такой уже есть, выходим if(player.getSkill(first.getId()) != null) return; // получаем инвентарь игрока Inventory inventory = player.getInventory(); // если такой итем удалился из него if(inventory != null && inventory.removeItem(item.getItemId(), 1L)) { // изучаем скил player.addSkills(template, true); // отпровляем сообщение об изучении player.sendPacket(S_Sytem_Message.getInstance(MessageType.YOUVE_LEARNED_SKILL_NAME).addSkillName(template[0].getName()), true); // отправляем пакет о использовании рецепта player.sendPacket(S_Sytem_Message.getInstance(MessageType.ITEM_USE).addItem(item.getItemId(), 1), true); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // обновляем инвентарь eventManager.notifyInventoryChanged(player); } } /** * Инициализация таблицы скилов. */ private void skillTableInit() { // Get a table skill SkillTable table = SkillTable.getInstance(); //book for the study of the first mount skillTable.put(20, table.getSkills(-15, 67219975)); //book for the study of the another mounts/book for the study of the another mounts skillTable.put(21, table.getSkills(-15, 67219976)); skillTable.put(41, table.getSkills(-15, 67219978)); skillTable.put(166, table.getSkills(-15, 67219991)); skillTable.put(167, table.getSkills(-15, 67219980)); skillTable.put(168, table.getSkills(-15, 67219981)); skillTable.put(169, table.getSkills(-15, 67219982)); skillTable.put(170, table.getSkills(-15, 67219983)); skillTable.put(306, table.getSkills(-15, 67219985)); skillTable.put(307, table.getSkills(-15, 67219986)); skillTable.put(336, table.getSkills(-15, 67220054)); skillTable.put(350, table.getSkills(-15, 67219988)); skillTable.put(351, table.getSkills(-15, 67219989)); skillTable.put(384, table.getSkills(-15, 67220061)); skillTable.put(385, table.getSkills(-15, 67220062)); skillTable.put(412, table.getSkills(-15, 67219990)); skillTable.put(413, table.getSkills(-15, 67219991)); skillTable.put(414, table.getSkills(-15, 67219992)); skillTable.put(415, table.getSkills(-15, 67219981)); skillTable.put(416, table.getSkills(-15, 67219982)); skillTable.put(417, table.getSkills(-15, 67219996)); skillTable.put(425, table.getSkills(-15, 67220056)); } } <file_sep>/java/game/tera/gameserver/model/skillengine/funcs/task/AbstractTaskFunc.java package tera.gameserver.model.skillengine.funcs.task; import java.util.concurrent.ScheduledFuture; import rlib.logging.Loggers; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.model.Character; import tera.gameserver.model.playable.Player; /** * Базовая модель периодической функции. * * @author Ronn */ public abstract class AbstractTaskFunc implements TaskFunc { /** список обрабатываемых персонажей */ protected final Array<Character> characters; /** ссылка на задачу */ protected volatile ScheduledFuture<AbstractTaskFunc> schedule; /** кол-во оставшихся выполнений */ protected volatile int currentCount; public AbstractTaskFunc(VarTable vars) { this.characters = Arrays.toConcurrentArray(Player.class); } @Override public final void addFuncTo(Character owner) { // получаем персонажи Array<Character> characters = getCharacters(); characters.writeLock(); try { // вносим нового characters.add(owner); // устанавливаем новый лимит currentCount = getLimit(); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); if(schedule == null) schedule = executor.scheduleAiAtFixedRate(this, getInterval(), getInterval()); } finally { characters.writeUnlock(); } } /** * Приминение функции на персонажа. */ public abstract void applyFunc(); /** * @return обрабатываемые персонажи. */ public final Array<Character> getCharacters() { return characters; } @Override public final void removeFuncTo(Character owner) { // получаем персонажи Array<Character> characters = getCharacters(); characters.writeLock(); try { characters.fastRemove(owner); if(characters.isEmpty() && schedule != null) { schedule.cancel(true); schedule = null; } } finally { characters.writeUnlock(); } } @Override public final void run() { if(currentCount > -2) { if(currentCount < 1) return; currentCount--; } try { applyFunc(); } catch(Exception e) { Loggers.warning(this, e); } } } <file_sep>/java/game/tera/remotecontrol/handlers/ServerConsoleHandler.java package tera.remotecontrol.handlers; import java.util.ArrayList; import rlib.logging.LoggerListener; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Обработчик запроса на данные из консоли сервера. * * @author Ronn */ public class ServerConsoleHandler implements PacketHandler, LoggerListener { public static final ServerConsoleHandler instance = new ServerConsoleHandler(); /** хранилище сообщений */ private final ArrayList<String> messages; private ServerConsoleHandler() { messages = new ArrayList<String>(); } @Override public void println(String text) { if(messages.size() > 1000) messages.clear(); messages.add(text); } @Override public Packet processing(Packet packet) { ArrayList<String> buffer = new ArrayList<String>(); buffer.addAll(messages); messages.clear(); return new Packet(PacketType.RESPONSE, buffer); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Show_Dead_UI.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет, запускающий окно смерти. * * @author Ronn */ public class S_Show_Dead_UI extends ServerConstPacket { private static final S_Show_Dead_UI instance = new S_Show_Dead_UI(); private int zone; public static S_Show_Dead_UI getInstance(int zone) { S_Show_Dead_UI packet = (S_Show_Dead_UI) instance.newInstance(); packet.zone = zone; return packet; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_SHOW_DEAD_UI; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 30); writeInt(buffer,zone);//zone writeInt(buffer, 0); writeShort(buffer, 0); writeByte(buffer, 0); } }<file_sep>/java/game/tera/gameserver/model/skillengine/conditions/ConditionAttackerPvP.java package tera.gameserver.model.skillengine.conditions; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Кондишен, является ли атакующий playable * * @author Ronn */ public class ConditionAttackerPvP extends AbstractCondition { private boolean value; /** * @param value */ public ConditionAttackerPvP(boolean value) { this.value = value; } @Override public boolean test(Character attacker, Character attacked, Skill skill, float val) { return attacker.isPlayer() == value; } } <file_sep>/java/game/tera/gameserver/document/DocumentResourse.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.templates.ResourseTemplate; /** * Парсер темплейтов ресурсов с xml. * * @author Ronn * @created 16.03.2012 */ public final class DocumentResourse extends AbstractDocument<Array<ResourseTemplate>> { /** * @param file отпрасиваемый фаил. */ public DocumentResourse(File file) { super(file); } @Override protected Array<ResourseTemplate> create() { return Arrays.toArray(ResourseTemplate.class); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node temp = list.getFirstChild(); temp != null; temp = temp.getNextSibling()) if(temp.getNodeType() == Node.ELEMENT_NODE && "template".equals(temp.getNodeName())) result.add(new ResourseTemplate(VarTable.newInstance(temp))); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Apply_Guild.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.GuildManager; import tera.gameserver.model.Guild; import tera.gameserver.model.GuildApply; import tera.gameserver.model.MessageType; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Sytem_Message; public class C_Apply_Guild extends ClientPacket { private String guildName; private String message; @Override protected void readImpl() { readShort(); readShort(); guildName = readString(); message = readString(); } @Override protected void runImpl() { Player player = owner.getOwner(); Guild guild = GuildManager.getInstance().getGuildByName(guildName); GuildApply apply = GuildApply.newInstance(player.getObjectId(), player.getClassId(), player.getLevel(), player.getName(), message); guild.addApply(apply, true); S_Sytem_Message packet = S_Sytem_Message.getInstance(MessageType.YOU_APPLIED_TO_GUILD); packet.add("GuildName", guildName); getOwner().sendPacket(packet); } } <file_sep>/java/game/tera/gameserver/scripts/commands/HealCommand.java package tera.gameserver.scripts.commands; import rlib.logging.Loggers; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Creature_Change_Hp; import tera.gameserver.network.serverpackets.S_Player_Change_Mp; /** * Список команд для лечения. * * @author Ronn */ public class HealCommand extends AbstractCommand { public HealCommand(int access, String[] commands) { super(access, commands); } @Override public void execution(String command, Player player, String values) { try { switch(command) { case "set_hp" : { Player target = null; String[] vals = values.split(" "); if(vals.length == 1) target = player; else target = World.getAroundByName(Player.class, player, vals[1]); if(target == null) return; target.setCurrentHp(Integer.parseInt(vals[0])); target.sendPacket(S_Creature_Change_Hp.getInstance(target, null, 0, S_Creature_Change_Hp.INCREASE), true); break; } case "set_mp": { Player target = null; String[] vals = values.split(" "); if(vals.length == 1) target = player; else target = World.getAroundByName(Player.class, player, vals[1]); if(target == null) return; target.setCurrentMp(Integer.parseInt(vals[0])); target.sendPacket(S_Player_Change_Mp.getInstance(target, null, 0, S_Player_Change_Mp.INCREASE), true); break; } case "heal": { Player target = null; if(values == null || values.isEmpty()) target = player; else target = World.getAroundByName(Player.class, player, values); if(target == null) return; target.setCurrentHp(target.getMaxHp()); target.setCurrentMp(target.getMaxMp()); target.sendPacket(S_Creature_Change_Hp.getInstance(target, null, 0, S_Creature_Change_Hp.INCREASE), true); target.sendPacket(S_Player_Change_Mp.getInstance(player, null, 0, S_Player_Change_Mp.INCREASE), true); } } } catch(NumberFormatException e) { Loggers.warning(getClass(), "parsing error of " + values); } } } <file_sep>/java/game/tera/gameserver/model/equipment/AbstractEquipment.java package tera.gameserver.model.equipment; import java.util.Arrays; import java.util.concurrent.locks.Lock; import rlib.concurrent.Locks; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.Character; import tera.gameserver.model.MessageType; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.CrystalInstance; import tera.gameserver.model.items.CrystalList; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.items.ItemLocation; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Equip_Item; import tera.gameserver.network.serverpackets.S_Inven_Changedslot; /** * Фундаментальная модель экиперовки. * * @author Ronn */ public abstract class AbstractEquipment implements Equipment { /** пустой массив слотов */ protected static final Slot[] EMPTY_SLOTS = new Slot[0]; /** блокировщик */ protected final Lock lock; /** массив слотов */ private Slot[] slots; /** владелец экиперовки */ protected Character owner; /** * @param owner владелец экиперовки. */ public AbstractEquipment(Character owner) { this.lock = Locks.newLock(); this.owner = owner; prepare(); } @Override public boolean dressItem(Inventory inventory, Cell cell) { if(cell == null) return false; // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем менеджер БД DataBaseManager dbManager = DataBaseManager.getInstance(); // получаем все слоты Slot[] slots = getSlots(); // получаем владельца экиперовки Character owner = getOwner(); inventory.lock(); try { lock(); try { // если ячейка пуста, выходим if(cell.isEmpty()) return false; // получаем итем из ячейки ItemInstance item = cell.getItem(); // если итем кристал if(item.isCrystal()) { CrystalInstance crystal = item.getCrystal(); // подготавливаем целевой итем ItemInstance target = null; // список кристалов итема CrystalList list = null; // перебираем слоты for(int i = 0, length = slots.length; i < length; i++) { // получаем слот Slot slot = slots[i]; // пустой пропускаем if(slot.isEmpty()) continue; // получаем итем из слота item = slot.getItem(); // получаем его список кристалов list = item.getCrystals(); // пропускаем итемы, без списка кристалов if(list == null) continue; // если уже такого тип кристала вставлен if(crystal.isNoStack() && list.containsCrystal(crystal.getStackType())) return false; // запоминаем подходящий итем if(target == null && item.checkCrystal(crystal)) target = item; } // если не нашли подходящий итем if(target == null) owner.sendMessage(MessageType.ALL_CRYSTAL_SLOTS_ARE_FULL); else { // получаем его список критсалов list = target.getCrystals(); // вставляем туда кристал list.put(crystal, cell, owner); // обновляем инвентарь eventManager.notifyInventoryChanged(owner); // обновляем статы eventManager.notifyStatChanged(owner); return true; } return false; } // если итем нельзя экиперовать, выходим if(item.getSlotType() == SlotType.NONE) return false; // если нельзя сейчас его экиперовать, тоже выходим if(!equiped(item)) return false; // заготавливаем пустой слот Slot empty = null; // заготавливаем занятый однотипный слот Slot emplayed = null; // перебираем все слоты for(int i = 0, length = slots.length; i < length; i++) { // получаем слот Slot slot = slots[i]; // если слот подходит по типу if(slot.getType() == item.getSlotType()) { // если он занят, запоминаем if(!slot.isEmpty()) emplayed = slot; else { // если свободен, выходим и запоминаем empty = slot; break; } } } // если есть свободный слот if(empty != null) { // добавляем туда итем empty.setItem(item); // опусташаем ячейку cell.setItem(null); // добавляем бонусы item.addFuncsTo(owner); // обновляем итем в БД dbManager.updateLocationItem(item); // обновляем экиперовку eventManager.notifyEquipmentChanged(owner); // обновляем статы eventManager.notifyStatChanged(owner); owner.sendPacket(S_Equip_Item.getInstance((Player )owner, item.getItemId()),true); owner.sendPacket(S_Inven_Changedslot.getInstance(1, empty.getIndex(), 0),true); return true; } // если найден занятый однотипный else if(emplayed != null) { // получаем уже экиперованный итем ItemInstance old = emplayed.getItem(); // удаляем его бонусы old.removeFuncsTo(owner); // ложим его в ячейку cell.setItem(old); // экиперуем новый итем emplayed.setItem(item); // добавляем его бонусы item.addFuncsTo(owner); // обновляем снятый итем в БД dbManager.updateLocationItem(old); // обновляем одетый итем в БД dbManager.updateLocationItem(item); // обновляем экиперовку eventManager.notifyEquipmentChanged(owner); // обновляем статы eventManager.notifyStatChanged(owner); return true; } return false; } finally { unlock(); } } finally { inventory.unlock(); } } @Override public void finalyze() { // получаем все слоты Slot[] slots = getSlots(); // получаем владельца экиперови Character owner = getOwner(); // перебираем слоты for(int i = 0, length = slots.length; i < length; i++) { // получаем слот Slot slot = slots[i]; // пустой пропускаем if(slot.isEmpty()) continue; // получаем итем в слоте ItemInstance item = slot.getItem(); // удаляем функции итема item.removeFuncsTo(owner); // зануляем уникальный ид item.setObjectId(-1); // удаляем итем item.deleteMe(); // зануляем слот slot.setItem(null); } // зануляем владельца setOwner(null); } @Override public int getCount(SlotType type) { // объявляем счетчик int counter = 0; // получаем слоты Slot[] slots = getSlots(); lock(); try { // перебираем слоты for(int i = 0, length = slots.length; i < length; i++) { // получаем слот Slot slot = slots[i]; //если слот с указанны индексом, увеличиваем счетчик if(!slot.isEmpty() && slot.getType() == type) counter++; } return counter; } finally { unlock(); } } @Override public int getEngagedSlots() { // объявляем счетчик int counter = 0; // получаем слоты Slot[] slots = getSlots(); lock(); try { // подсчет занятых слотов for(int i = 0, length = slots.length; i < length; i++) if(!slots[i].isEmpty()) counter++; return counter; } finally { unlock(); } } @Override public ItemInstance getItem(int index) { // получаем слоты Slot[] slots = getSlots(); // если индекс не корректный, выходим if(index < 0 || index >= slots.length) return null; // получаем нужный слот Slot slot = slots[index]; // возвращаем его итем return slot == null? null : slot.getItem(); } @Override public ItemInstance getItem(SlotType type) { // получаем слоты Slot[] slots = getSlots(); lock(); try { // перебираем слоты for(int i = 0, length = slots.length; i < length; i++) { // получаем слот Slot slot = slots[i]; // если это искомый слот if(slot.getType() == type && !slot.isEmpty()) // возвращаем его итем return slot.getItem(); } return null; } finally { unlock(); } } @Override public int getItemId(SlotType type) { // получаем итем с нужным слотом ItemInstance item = getItem(type); // возврааем его ид return item == null? 0 : item.getItemId(); } @Override public Character getOwner() { return owner; } @Override public Slot getSlotForObjectId(int objectId) { // получаем слоты Slot[] slots = getSlots(); lock(); try { // перебираем слоты for(int i = 0, length = slots.length; i < length; i++) { // получаем слот Slot slot = slots[i]; // пустой пропускаем if(slot.isEmpty()) continue; // получаем итем в слоте ItemInstance item = slot.getItem(); // если это искомый итем, возвращаем слот if(item.getObjectId() == objectId) return slot; } return null; } finally { unlock(); } } @Override public Slot[] getSlots() { return slots; } @Override public void lock() { lock.lock(); } /** * Создание набора слотов. */ protected abstract void prepare(); @Override public void recreateSlots(SlotType... slotTypes) { lock(); try { slots = new Slot[slotTypes.length]; for(int i = 0; i < slots.length; i++) slots[i] = new Slot(slotTypes[i], i); } finally { unlock(); } } @Override public void reinit(){} @Override public boolean setItem(ItemInstance item, int index) { if(item == null) return false; // устанавливаем итем в слот slots[index].setItem(item); // выдаем функции итема владельцу item.addFuncsTo(owner); return true; } @Override public Equipment setOwner(Character owner) { this.owner = owner; return this; } @Override public void setSlots(Slot[] slots) { this.slots = slots; } @Override public boolean shootItem(Inventory inventory, int index, int itemId) { // получаем слоты Slot[] slots = getSlots(); // если индекс не корректен, выходим if(index < 0 || index >= slots.length) return false; // получаем владельца экиперовки Character owner = getOwner(); // получаем менеджер событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем менеджер БД DataBaseManager dbManager = DataBaseManager.getInstance(); inventory.lock(); try { lock(); try { // получаем целевой слот Slot slot = slots[index]; // получаем итем в слоте ItemInstance item = slot.getItem(); // если итема там нет, выходим if(item == null) return false; // если ид с итемом не совпадает, скорее всего это кристал if(item.getItemId() != itemId) { // получаем список кристалов итема CrystalList crystals = item.getCrystals(); // если кристалов у итема быть не может, выходим if(crystals == null) return false; // получаем кристал с нужным ид CrystalInstance target = crystals.getCrystal(itemId); // если такого нет или его сейчас нельзя снять, выходим if(target == null || !unequiped(target)) return false; // если положить итем в инвентарь не удалось if(!inventory.putItem(target)) // сообщаем об этом owner.sendMessage(MessageType.INVENTORY_IS_FULL); else { // удаляем кристал из списка кристалов crystals.remove(target); // удаляем функции кристала у владельца target.removeFuncsTo(owner); // если этот кристал просто приплюсовался в инвенторе, значит экземпляр нужно удалить if(target.getLocation() == ItemLocation.CRYSTAL) { // зануляем владельца target.setOwnerId(0); // обновляем в БД dbManager.updateLocationItem(target); // удаляем кристал из мира target.deleteMe(); } } // обновляем экиперовку eventManager.notifyEquipmentChanged(owner); // обновляем статы eventManager.notifyStatChanged(owner); } else { // если итем снять нельзя, выходим if(!unequiped(item)) return false; // если не получилось положить в инвентарь if(!inventory.putItem(item)) // сообщаем owner.sendMessage(MessageType.INVENTORY_IS_FULL); else { // опусташаем слот slot.setItem(null); // удаляем его бонусы item.removeFuncsTo(owner); // обновляем экиперовку eventManager.notifyEquipmentChanged(owner); // обновляем статы eventManager.notifyStatChanged(owner); return true; } } return false; } finally { unlock(); } } finally { inventory.unlock(); } } @Override public int size() { return slots.length; } @Override public String toString() { return "Equipment " + (slots != null ? "slots = " + Arrays.toString(slots) + ", " : ""); } @Override public void unlock() { lock.unlock(); } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/NpcFastShot.java package tera.gameserver.model.skillengine.shots; import rlib.util.pools.FoldablePool; import rlib.util.pools.Pools; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Модель быстрых выстрелов. * * @author Ronn */ public class NpcFastShot extends AbstractShot { /** пул выстрелов */ private static FoldablePool<NpcFastShot> shotPool = Pools.newConcurrentFoldablePool(NpcFastShot.class); /** * @param caster стреляющий персонаж. * @param skill стреляющий скил. * @param impactX координата точки полета. * @param impactY координата точки полета. * @param impactZ координата точки полета. */ public static void startShot(Character caster, Skill skill, Character target) { // вытаскиваем из пула NpcFastShot shot = shotPool.take(); // если нет if(shot == null) // созадем новый shot = new NpcFastShot(); // подготавливаем shot.prepare(caster, skill, target); // запускаем shot.start(); } /** цель выстрела */ private Character target; public NpcFastShot() { setType(ShotType.FAST_SHOT); } @Override public void finalyze() { target = null; super.finalyze(); } /** * @param caster * @param skill * @param target */ public void prepare(Character caster, Skill skill, Character target) { this.target = target; super.prepare(caster, skill, target.getX(), target.getY(), target.getZ()); } @Override public void run() { this.targetX = target.getX(); this.targetY = target.getY(); this.targetZ = target.getZ(); super.run(); } @Override public void stop() { super.stop(); // ложим в пул shotPool.put(this); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Npcguild_List.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Created by Luciole on 25/06/2016. */ public class S_Npcguild_List extends ServerPacket { private static final ServerPacket instance = new S_Npcguild_List(); public static ServerPacket getInstance() { return instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_NPC_GUILD_LIST; } @Override protected void writeImpl() { writeOpcode(); writeInt(0); writeInt(0x0FAC2722); writeInt(0x00008000); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/StateAllowed.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет для продолжения полета после вылета из портала * * @author Ronn */ public class StateAllowed extends ServerPacket { private static final ServerPacket instance = new StateAllowed(); public static StateAllowed getInstance(Character actor, int stateId) { StateAllowed packet = (StateAllowed) instance.newInstance(); packet.actor = actor; packet.stateId = stateId; return packet; } /** персонаж */ private Character actor; /** ид состояния */ private int stateId; @Override public void finalyze() { actor = null; } @Override public ServerPacketType getPacketType() { return ServerPacketType.STATE_ALLOWED; } @Override protected void writeImpl() { writeOpcode(); writeInt(actor.getObjectId());//обжект айди наш writeInt(actor.getSubId()); //саб айди нашь writeInt(stateId); } } <file_sep>/java/game/tera/gameserver/model/skillengine/shots/ShotType.java package tera.gameserver.model.skillengine.shots; /** * Перечисление типов выстрелов. * * @author Ronn */ public enum ShotType { FAST_SHOT, SLOW_SHOT, } <file_sep>/java/game/tera/gameserver/model/skillengine/OperateType.java package tera.gameserver.model.skillengine; /** * Перечисление тип работ скилов * * @author Ronn */ public enum OperateType { /** пассивный */ PASSIVE, /** активный */ ACTIVE, /** заряжающийся */ CHARGE, /** активиремые скилы */ ACTIVATE, /** кастовый для итема */ CAST_ITEM, /** без каста для итема */ NO_CAST_ITEM, /** лок он скил */ LOCK_ON; } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Remove_Guild_Group.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Remove_Guild_Group extends ServerPacket { private static final ServerPacket instance = new S_Remove_Guild_Group(); public static S_Remove_Guild_Group getInstance(int id) { S_Remove_Guild_Group packet = (S_Remove_Guild_Group) instance.newInstance(); packet.id = id; return packet; } /** кол-во ожидания секунд */ private int id; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_REMOVE_GUILD_GROUP; } @Override protected final void writeImpl() { writeOpcode(); writeInt(id); } } <file_sep>/java/game/tera/remotecontrol/ClientPackets.java package tera.remotecontrol; public class ClientPackets { } <file_sep>/java/game/tera/gameserver/model/WorldZone.java package tera.gameserver.model; import java.awt.Polygon; import rlib.util.array.Arrays; import tera.gameserver.tables.WorldZoneTable; import tera.util.Location; /** * Класс, описывающий зону с содержанем кода зоны для пакета * * @author Ronn * @created 08.03.2012 */ public final class WorldZone { /** долгота зоны */ private int maximumX; private int minimumX; /** ширина зоны */ private int maximumY; private int minimumY; /** высота зоны */ private int maximumZ; private int minimumZ; /** ид зоны */ private int zoneId; /** ид континента */ private int continentId; /** описание территории */ private Polygon zone; /** точки респавна */ private Location[] respawnPoints; /** * @param maxZ максимальная высота зоны. * @param minZ минимальная высота зоны. * @param zoneId ид зоны. * @param continentId ид континента. */ public WorldZone(int maxZ, int minZ, int zoneId, int continentId) { this.maximumZ = maxZ; this.minimumZ = minZ; this.zoneId = zoneId; this.continentId = continentId; maximumX = Integer.MIN_VALUE; minimumX = Integer.MAX_VALUE; maximumY = Integer.MIN_VALUE; minimumY = Integer.MAX_VALUE; zone = new Polygon(); respawnPoints = new Location[0]; } /** * Добавляем точку в полигон. * * @param x координата. * @param y координата. */ public final void addPoint(int x, int y) { maximumX = Math.max(maximumX, x); minimumX = Math.min(minimumX, x); maximumY = Math.max(maximumY, y); minimumY = Math.min(minimumY, y); zone.addPoint(x, y); } /** * @param point новая точка респавна. */ public final void addRespawnPoint(Location point) { respawnPoints = Arrays.addToArray(respawnPoints, point, Location.class); } /** * Находятся ли эти координаты в зоне. * * @param x координата. * @param y координата. * @param z координата. * @return находятся ли в зоне. */ public final boolean contains(int x, int y, int z) { if(z > maximumZ || z < minimumZ) return false; return zone.contains(x, y); } /** * @return ид континента. */ public int getContinentId() { return continentId; } /** * @return максимальный х. */ public final int getMaximumX() { return maximumX; } /** * @return максимальный у. */ public final int getMaximumY() { return maximumY; } /** * @return максимальный z. */ public final int getMaximumZ() { return maximumZ; } /** * @return минимальный х. */ public final int getMinimumX() { return minimumX; } /** * @return минимальный y. */ public final int getMinimumY() { return minimumY; } /** * @return минимальный z. */ public final int getMinimumZ() { return minimumZ; } /** * Получить ближайшую респавн точку. * * @param object умерший объект. * @return point точка респавна. */ public final Location getRespawn(TObject object) { Location target = null; float min = Float.MAX_VALUE; for(int i = 0, length = respawnPoints.length; i < length; i++) { Location point = respawnPoints[i]; float dist = object.getDistance(point.getX(), point.getY(), point.getZ()); if(dist < min) { min = dist; target = point; } } if(target == null) return WorldZoneTable.DEFAULT_RESPAWN_POINT; return target; } /** * @return точки респавна. */ public final Location[] getRespawnPoints() { return respawnPoints; } /** * @return полигон зоны. */ public final Polygon getZone() { return zone; } /** * @return ид зоны. */ public final int getZoneId() { return zoneId; } @Override public String toString() { return "S_Load_Topo maxX = " + maximumX + ", minX = " + minimumX + ", maxY = " + maximumY + ", minY = " + minimumY + ", maxZ = " + maximumZ + ", minZ = " + minimumZ + ", zoneId = " + zoneId + ", zone = " + zone + ", respawnPoints = " + Arrays.toString(respawnPoints); } } <file_sep>/java/game/tera/gameserver/model/resourse/ResourseInstance.java package tera.gameserver.model.resourse; import rlib.geom.Coords; import rlib.util.Rnd; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.Config; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.Character; import tera.gameserver.model.MessageType; import tera.gameserver.model.Party; import tera.gameserver.model.TObject; import tera.gameserver.model.drop.ResourseDrop; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Despawn_Collection; import tera.gameserver.network.serverpackets.S_Sytem_Message_Loot_Item; import tera.gameserver.network.serverpackets.S_Spawn_Collection; import tera.gameserver.templates.ResourseTemplate; import tera.util.LocalObjects; /** * Базовая модель ресурсов. * * @author Ronn */ public abstract class ResourseInstance extends TObject { /** список сборщиков ресурса */ protected final Array<Character> collectors; /** темплейт инстанса */ protected final ResourseTemplate template; /** спавн ресурса */ protected ResourseSpawn spawn; /** группа, которая начала собирать */ protected volatile Party party; /** заблокирован ли сбор */ protected volatile boolean lock; public ResourseInstance(int objectId, ResourseTemplate template) { super(objectId); this.collectors = Arrays.toArray(Character.class); this.template = template; } @Override public void addMe(Player player) { player.sendPacket(S_Spawn_Collection.getInstance(this), true); } /** * @return подходит ли игрок для сбора. */ public boolean checkCondition(Player collector) { return true; } /** * Собрать ресурс указанным персонажем. * * @param actor соберающий персонаж. */ public void collectMe(Character actor) { // если это не игрок, выходим if(!actor.isPlayer()) return; // получаем игрока Player collector = actor.getPlayer(); // если условия не выполнены, выходим if(!checkCondition(collector)) { collector.sendMessage(MessageType.YOU_CANT_DO_THAT_RIGHT_NOW_TRY_AGAINT_IN_A_MOMENT); return; } synchronized(this) { if(isLock()) return; // получаем активную группу Party party = getParty(); // если активной пати нет, но есть уже соберающий, выходим if(party == null && !collectors.isEmpty()) { actor.sendMessage(MessageType.ANOTHER_PLAYER_IS_ALREADY_GATHERING_THAT); return; } // если есть активная пати, и персонаж не из нее, то выходим if(party != null && actor.getParty() != party) { actor.sendMessage(MessageType.ANOTHER_PLAYER_IS_ALREADY_GATHERING_THAT); return; } // если персонаж уже есть в списке соберающих, выходим if(collectors.contains(actor)) { actor.sendMessage(MessageType.YOU_CANT_DO_THAT_RIGHT_NOW_TRY_AGAINT_IN_A_MOMENT); return; } // если активной пати нет if(party == null) // заносим пати персонажа setParty(actor.getParty()); } // добавляем в список соберальщиков collectors.add(actor); // запускаем сбор actor.doCollect(this); } @Override public void deleteMe() { // очищаем список сборщиков collectors.clear(); // удаляем из мира super.deleteMe(); // отдаем спавну spawn.onCollected(this); } /** * Расчет шанса сбора для указанного игрока. * * @param player собирающий игрок. * @return шанс сбора. */ public int getChanceFor(Player player) { return 80; } /** * @return список собирающих персонажей. */ public final Array<Character> getCollectors() { return collectors; } /** * @return собирающая группа. */ public final Party getParty() { return party; } @Override public ResourseInstance getResourse() { return this; } /** * @return спавн ресурса. */ public final ResourseSpawn getSpawn() { return spawn; } @Override public int getSubId() { return Config.SERVER_RESOURSE_SUB_ID; } /** * @return темплейт ресурса. */ public ResourseTemplate getTemplate() { return template; } @Override public int getTemplateId() { return template.getId(); } /** * Увеличение навыка сбора ресурса. * * @param player игрок ,которому надо увеличить навык. */ public void increaseReq(Player player) { log.warning(this, new Exception("unsupported method")); } /** * @return заблокирован ли сбор. */ public boolean isLock() { return lock; } @Override public boolean isResourse() { return true; } /** * Завершение сбора ресурса. * * @param collector тот кто завершает сбор. * @param cancel отмена ли это. */ public void onCollected(Player collector, boolean cancel) { if(isDeleted()) return; // блокируем след. попытки сбора setLock(true); // нужно ли удалять boolean finish = false; synchronized(this) { // если уже пустой список ,выходим if(collectors.isEmpty()) { log.warning(this, new Exception("found incorrect finish collect.")); return; } // удаляем из соберающих collectors.fastRemove(collector); // определяем, закончился ли сбор finish = collectors.isEmpty(); } // если сбор успешен if(!cancel) { collector.addExp(template.getExp(), null, getName()); // получаем темплейт ресурса ResourseTemplate template = getTemplate(); // получаем дроп ресурса ResourseDrop drop = template.getDrop(); // если дроп есть if(drop != null) { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем список итемов Array<ItemInstance> items = local.getNextItemList(); // рассчитываем полученный дроп drop.addDrop(items, this, collector); // если он есть if(!items.isEmpty()) { // получаем инвентарь игрока Inventory inventory = collector.getInventory(); // если инвенторя нет, уведомляем if(inventory == null) log.warning(this, new Exception("not found inventiry")); else { // получаем массив итемов ItemInstance[] array = items.array(); // перебираем итемы for(int i = 0, length = items.size(); i < length; i++) { // получаем итем ItemInstance item = array[i]; // если не удалось положить в инвентакрь if(!inventory.putItem(item)) { // сообщаем об заполнености его collector.sendMessage(MessageType.INVENTORY_IS_FULL); // устанавливаем континент, на котором расположен итем item.setContinentId(collector.getContinentId()); // расчитываем направление дропа int heading = Rnd.nextInt(0, 32000) + collector.getHeading(); // рамчитываем дистанцию int dist = Rnd.nextInt(30, 60); // определяем новые координаты float x = Coords.calcX(collector.getX(), dist, heading); float y = Coords.calcY(collector.getY(), dist, heading); // запоминаем владельца item.setTempOwner(collector); // запоминаем того, кто выбрасывает item.setDropper(collector); // выбрасываем итем на землю item.spawnMe(x, y, collector.getZ(), 0); } else { // отправляем пакет о том, что итем положился collector.sendPacket(S_Sytem_Message_Loot_Item.getInstance(collector.getName(), item.getItemId(), (int) item.getItemCount()), true); // если итем без владельца if(!item.hasOwner()) // удаляем его item.deleteMe(); } } } } } // увеличиваем навык сбора increaseReq(collector); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // уведомляем о сборе eventManager.notifyCollect(this, collector); //TODO баф от ресурса } //TODO если это был последний активный сборщик и он не отменил сбор if(finish) // удаляем ресурс deleteMe(); } @Override public void removeMe(Player player, int type) { player.sendPacket(S_Despawn_Collection.getInstance(this, type), true); } /** * @param lock блокирован ли сбор. */ public void setLock(boolean lock) { this.lock = lock; } /** * @param party собирающая группа. */ public final void setParty(Party party) { this.party = party; } /** * @param spawn спавн ресурса. */ public final void setSpawn(ResourseSpawn spawn) { this.spawn = spawn; } @Override public void spawnMe() { // убираем блок сбора setLock(lock); // спавним super.spawnMe(); } @Override public String toString() { return "ResourseInstance [getTemplateId()=" + getTemplateId() + "]"; } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Create_User.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.PlayerManager; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.base.Race; import tera.gameserver.model.base.Sex; import tera.gameserver.model.playable.PlayerAppearance; import tera.gameserver.model.playable.PlayerDetails2; import tera.gameserver.network.serverpackets.CreatePlayerResult; import tera.gameserver.network.serverpackets.S_Create_User; /** * Клиентский пакет для создания персонажа * * @author Ronn */ public class C_Create_User extends ClientPacket { /** имя игрока */ private String name; /** внешность игрока */ private PlayerAppearance appearance; private PlayerDetails2 detailsappearance; /** пол игрока */ private Sex sex; /** раса игрока */ private Race race; /** класс игрока */ private PlayerClass playerClass; @Override public void finalyze() { name = null; appearance = null; } @Override public boolean isSynchronized() { return false; } @Override public void readImpl(){ int name_pos = readShort(); int detail_pos = readShort(); int detail_2_pos = readShort(); readInt(); this.sex = Sex.valueOf(readInt()); this.race = Race.valueOf(readInt(), sex); playerClass = PlayerClass.values()[readInt()]; appearance = PlayerAppearance.getInstance(0); detailsappearance = PlayerDetails2.getInstance(0); readByte(); appearance.setFaceColor(readByte()); appearance.setFaceSkin(readByte()); appearance.setAdormentsSkin(readByte()); appearance.setFeaturesSkin(readByte()); appearance.setFeaturesColor(readByte()); appearance.setVoice(readByte()); buffer.position(name_pos); name = readString(); appearance.setBoneStructureBrow(readByte()); appearance.setBoneStructureCheekbones(readByte()); appearance.setBoneStructureJaw(readByte()); appearance.setBoneStructureJawJut(readByte()); appearance.setEarsRotation(readByte()); appearance.setEarsExtension(readByte()); appearance.setEarsTrim(readByte()); appearance.setEarsSize(readByte()); appearance.setEyesWidth(readByte()); appearance.setEyesHeight(readByte()); appearance.setEyesSeparation(readByte()); readByte(); appearance.setEyesAngle(readByte()); appearance.setEyesInnerBrow(readByte()); appearance.setEyesOuterBrow(readByte()); readByte(); appearance.setNoseExtension(readByte()); appearance.setNoseSize(readByte()); appearance.setNoseBridge(readByte()); appearance.setNoseNostrilWidth(readByte()); appearance.setNoseTipWidth(readByte()); appearance.setNoseTip(readByte()); appearance.setNoseNostrilFlare(readByte()); appearance.setMouthPucker(readByte()); appearance.setMouthPosition(readByte()); appearance.setMouthWidth(readByte()); appearance.setMouthLipThickness(readByte()); appearance.setMouthCorners(readByte()); appearance.setEyesShape(readByte()); appearance.setNoseBend(readByte()); appearance.setBoneStructureJawWidth(readByte()); appearance.setMothGape(readByte()); int[] Details2 = new int[64]; for(int i = 0; i < 64;++i){ Details2[i] = readByte(); } detailsappearance.setDetails2(Details2); } @Override public void runImpl() { if(name == null) return; // получаем менеджера игроков PlayerManager playerManager = PlayerManager.getInstance(); // пробуем создать игрока playerManager.createPlayer(getOwner(), appearance, detailsappearance, name, playerClass, race, sex); //System.out.println("appearance " + appearance.toXML(appearance, "")); //owner.sendPacket(CreatePlayerResult.getInstance(), true); owner.sendPacket(S_Create_User.getInstance(S_Create_User.SUCCESS), true); } }<file_sep>/java/game/tera/gameserver/model/npc/interaction/conditions/ConditionPlayerMaxLevel.java package tera.gameserver.model.npc.interaction.conditions; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; /** * Проверка на максимальный уровень игрока. * * @author Ronn */ public class ConditionPlayerMaxLevel extends AbstractCondition { /** с какого уровня */ private int level; public ConditionPlayerMaxLevel(Quest quest, int level) { super(quest); this.level = level; } @Override public boolean test(Npc npc, Player player) { if(player == null) return false; return player.getLevel() <= level; } @Override public String toString() { return "ConditionPlayerMaxLevel level = " + level; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Cancel_Contract.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет с уведомление о принятии решения насчет акшена. * * @author Ronn * @created 07.03.2012 */ public class S_Cancel_Contract extends ServerPacket { private static final ServerPacket instance = new S_Cancel_Contract(); /** * @param actorId ид инициатора. * @param actorSubId под ид инициатора. * @param enemyId ид опонента. * @param enemySubId под ид опонента. * @param id ид акшена. * @param objectId уникальный ид акшена. * @return новый пакет. */ public static S_Cancel_Contract getInstance(int actorId, int actorSubId, int enemyId, int enemySubId, int id, int objectId) { S_Cancel_Contract packet = (S_Cancel_Contract) instance.newInstance(); packet.actorId = actorId; packet.actorSubId = actorSubId; packet.enemyId = enemyId; packet.enemySubId = enemySubId; packet.id = id; packet.objectId = objectId; return packet; } /** ид создателя акшена */ private int actorId; private int actorSubId; /** ид приглашаемого в акшен */ private int enemyId; private int enemySubId; /** ид акшена */ private int id; /** уникальный ид акшена */ private int objectId; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_CANCEL_CONTRACT; } @Override protected void writeImpl() { writeOpcode(); writeInt(actorId); writeInt(actorSubId); writeInt(enemyId); writeInt(enemySubId); writeInt(id); writeInt(objectId); } } <file_sep>/java/game/tera/gameserver/model/actions/dialogs/TradeDialog.java package tera.gameserver.model.actions.dialogs; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.IdFactory; import tera.gameserver.manager.GameLogManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.MessageType; import tera.gameserver.model.TradeItem; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.ServerPacket; import tera.gameserver.network.serverpackets.ShowTrade; import tera.gameserver.network.serverpackets.S_Sytem_Message; /** * Модель диалога трейда. * * @author Ronn */ public class TradeDialog extends AbstractActionDialog { /** максимальное кол-во итемов для передачи */ public static final int MAX_ITEMS = 18; /** * Создание нового диалога. * * @param actor инициатор диалога. * @param enemy опонент диалога. * @return новый диалог. */ public static final TradeDialog newInstance(Player actor, Player enemy) { TradeDialog dialog = (TradeDialog) ActionDialogType.TRADE_DIALOG.newInstance(); // получаем фабрику ИД IdFactory idFactory = IdFactory.getInstance(); dialog.actor = actor; dialog.enemy = enemy; dialog.objectId = idFactory.getNextActionId(); return dialog; } /** передаваемые инициатором итемы */ private Array<TradeItem> actorItems; /** передываемые апонентом итемы */ private Array<TradeItem> enemyItems; /** передаваемые инициатором деньги */ private long actorMoney; /** передаваемые деньги опонентом */ private long enemyMoney; /** заблокирование изминения инициатором */ private boolean actorLock; /** заблокирование изминения опонентом */ private boolean enemyLock; /** завершен ли трейд */ private boolean done; public TradeDialog() { this.actorItems = Arrays.toArray(TradeItem.class, MAX_ITEMS); this.enemyItems = Arrays.toArray(TradeItem.class, MAX_ITEMS); } /** * Добавление итема на передачу. * * @param player игрок, который добавляет. * @param count кол-во итемов. * @param index индекс ячейки инвенторя. */ public synchronized void addItem(Player player, int count, int index) { // если уже кто-то заблокировал, выходим if(isActorLock() || isEnemyLock()) return; // список предложенных итемов Array<TradeItem> items; // инвентарь игрока Inventory inventory = player.getInventory(); // если инициатор if(player == getActor()) items = getActorItems(); else items = getEnemyItems(); inventory.lock(); try { // получаем ячейку инвенторя Cell cell = inventory.getCell(index); // если ее нет или она пуста, выходим if(cell == null || cell.isEmpty()) return; // получаем итем ItemInstance item = cell.getItem(); // если он не передается if(!item.isTradable()) { // создаем сообщение S_Sytem_Message packet = S_Sytem_Message.getInstance(MessageType.YOU_CANT_TRADE); // добавляем указание о итеме packet.addItemName(item.getItemId()); // отправляем пакет player.sendPacket(packet, true); return; } // если итема больше чем есть, выходим if(count > item.getItemCount()) return; // получаем позицию итема в текущем списке int order = items.indexOf(item); // если он уже добавлен в список, значит это стакуемый if(order > -1) { // получаем его аналог в положенных TradeItem tradeItem = items.get(order); // если по кол-ву не сходится, выходим if(tradeItem.getCount() + count > item.getItemCount()) return; // увеличиваем кол-вд tradeItem.addCount(count); // обновляем диалог updateDialog(); } // если еще не переполнен else if(items.size() < MAX_ITEMS) { // добалвяем новый итем items.add(TradeItem.newInstance(item, count)); // обновляем диалог updateDialog(); } } finally { inventory.unlock(); } } /** * Добавление денег на передачу. * * @param player игрок, который добавляет. * @param money кол-во добавляемых денег. */ public synchronized void addMoney(Player player, long money) { // если уже кто-то заблокировал, выходим if(isActorLock() || isEnemyLock()) return; // получаем инвентарь игрока Inventory inventory = player.getInventory(); // определяем кто это boolean isActor = player == getActor(); // если у инициатора есть столько денег if(isActor && money + actorMoney <= inventory.getMoney()) { // добавляем actorMoney += money; // обновляем окно updateDialog(); } // если у опонента есть столько денег else if(money + enemyMoney <= inventory.getMoney()) { // добавляем enemyMoney += money; // обновляем окно updateDialog(); } } @Override public synchronized boolean apply() { // если уже был выполнен, выходим if(isDone()) return false; // ставим флаг выполнения setDone(true); // инициатор трейда Player actor = getActor(); // опонент Player enemy = getEnemy(); // если кого-то из них нету, выходим if(actor == null || enemy == null) { log.warning(this, new Exception("not found actor or enemy,")); return false; } // получаем инвентори обоих участников Inventory actorInventory = actor.getInventory(); Inventory enemyInventory = enemy.getInventory(); // если чьего-то инвенторя нету, выходим if(actorInventory == null || enemyInventory == null) return false; actorInventory.lock(); try { enemyInventory.lock(); try { // если инициатор пробует передать больше, чем у него есть, зануляем if(actorMoney > actorInventory.getMoney()) actorMoney = 0; // получаем список передаваемых инициатором итемов TradeItem[] array = actorItems.array(); // перебираем их for(int i = 0, length = actorItems.size(); i < length; i++) { // получаем передаваемый итем TradeItem tradeItem = array[i]; // смотрим, есть ли он у него ItemInstance item = actorInventory.getItemForObjectId(tradeItem.getObjectId()); // если его нет или недостаточное кол-во if(item == null || item.getItemCount() < tradeItem.getCount()) { // удаляем из списка actorItems.fastRemove(i--); length--; } } // если опонент пробует передать больше, чем у него есть, зануляем if(enemyMoney > enemyInventory.getMoney()) enemyMoney = 0; // получаем список передаваемых итемов опонентом array = enemyItems.array(); // перебираем их for(int i = 0, length = enemyItems.size(); i < length; i++) { // получаем передаваемый итем TradeItem tradeItem = array[i]; // смотрим, есть ли он у него ItemInstance item = enemyInventory.getItemForObjectId(tradeItem.getObjectId()); // если его нет или недостаточное кол-во if(item == null || item.getItemCount() < tradeItem.getCount()) { // удаляем из списка enemyItems.fastRemove(i--); length--; } } // передаем деньги actorInventory.addMoney(enemyMoney); actorInventory.subMoney(actorMoney); enemyInventory.addMoney(actorMoney); enemyInventory.subMoney(enemyMoney); // получаем логера игровых событий GameLogManager gameLogger = GameLogManager.getInstance(); // записываем событие о передаче денег gameLogger.writeItemLog(actor.getName() + " add " + actorMoney + " money to " + enemy.getName()); // записываем событие о передаче денег gameLogger.writeItemLog(enemy.getName() + " add " + enemyMoney + " money to " + actor.getName()); // получаем список передаваемых итемов инициатором array = actorItems.array(); // перебираем их for(int i = 0, length = actorItems.size(); i < length; i++) { // получаем передаваемый итем TradeItem trade = array[i]; // получаем кол-во передаваемых итемов long count = trade.getCount(); // получаем сам итем ItemInstance item = trade.getItem(); // если итем не стакуемый if(!trade.isStackable()) // то переносим его enemyInventory.moveItem(item, actorInventory); else // иначе { // добавляем опоненту нужное кол-во нового итема if(enemyInventory.addItem(trade.getItemId(), trade.getCount(), actor.getName())) // и удаляем это кол-во у инициатора actorInventory.removeItem(trade.getItemId(), trade.getCount()); } // записываем событие передачи итема gameLogger.writeItemLog(actor.getName() + " trade item [id = " + item.getItemId() + ", count = " + count + ", name = " + item.getName() + "] to " + enemy.getName()); } // получаем список передаваемых итемов опонентом array = enemyItems.array(); // перебираем их for(int i = 0, length = enemyItems.size(); i < length; i++) { // получаем передаваемый итем TradeItem trade = array[i]; // получаем кол-во передаваемых итемов long count = trade.getCount(); // получаем сам итем ItemInstance item = trade.getItem(); // если итем не стакуемый if(!trade.isStackable()) // то переносим его actorInventory.moveItem(trade.getItem(), enemyInventory); else // иначе { // добавляем инициатору нужное кол-во нового итема if(actorInventory.addItem(trade.getItemId(), trade.getCount(), actor.getName())) // и удаляем это кол-во у опонента enemyInventory.removeItem(trade.getItemId(), trade.getCount()); } // записываем событие передачи итема gameLogger.writeItemLog(enemy.getName() + " trade item [id = " + item.getItemId() + ", count = " + count + ", name = " + item.getName() + "] to " + actor.getName()); } // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // обновляемся eventManager.notifyInventoryChanged(actor); eventManager.notifyInventoryChanged(enemy); } finally { enemyInventory.unlock(); } } finally { actorInventory.unlock(); } actor.sendMessage(MessageType.TRADE_COMPLETED); enemy.sendMessage(MessageType.TRADE_COMPLETED); return true; } @Override public synchronized void cancel(Player player) { // если кто-то закрыл, значит была отмена if(player != null) { // получаем инициатора Player actor = getActor(); // получаем цель его Player enemy = getEnemy(); if(player == actor) { actor.sendMessage(MessageType.TRADE_CANCELED); enemy.sendPacket(S_Sytem_Message.getInstance(MessageType.OPPONENT_CANCELED_THE_TRADE).addOpponent(actor.getName()), true); } else if(player == enemy) { enemy.sendMessage(MessageType.TRADE_CANCELED); actor.sendPacket(S_Sytem_Message.getInstance(MessageType.OPPONENT_CANCELED_THE_TRADE).addOpponent(enemy.getName()), true); } } super.cancel(player); } @Override public void finalyze() { TradeItem[] array = actorItems.array(); for(int i = 0, length = actorItems.size(); i < length; i++) array[i].fold(); actorItems.clear(); array = enemyItems.array(); for(int i = 0, length = enemyItems.size(); i < length; i++) array[i].fold(); enemyItems.clear(); actorMoney = 0; enemyMoney = 0; actorLock = false; enemyLock = false; done = false; super.finalyze(); } /** * @return список передоваемых итемов инициатором. */ protected final Array<TradeItem> getActorItems() { return actorItems; } /** * @return кол-во передоваемых денег инициатором. */ protected final long getActorMoney() { return actorMoney; } /** * @return список передоваемых итемов опонентом. */ protected Array<TradeItem> getEnemyItems() { return enemyItems; } /** * @return кол-во передаваемых денег опонентом. */ protected final long getEnemyMoney() { return enemyMoney; } /** * Кол-во выставленных итемов у указанного игрока. * * @param player игрок. * @return сколько видов итемов выставил указанный итем. */ public int getItemCount(Player player) { if(player == actor) return actorItems.size(); else if(player == enemy) return enemyItems.size(); return 0; } /** * Получаем список положенных итемов. * * @param player игрок. * @return список положенных итемов. */ public Array<TradeItem> getItems(Player player) { if(player == actor) return actorItems; else if(player == enemy) return enemyItems; return null; } /** * Кол-во выставленных на передачу денег у указанного игрока. * * @param player игрок. * @return сколько денег указанный игрок выставил на передачу. */ public long getMoney(Player player) { if(player == actor) return getActorMoney(); else if(player == enemy) return getEnemyMoney(); return 0; } @Override public ActionDialogType getType() { return ActionDialogType.TRADE_DIALOG; } @Override public synchronized boolean init() { if(super.init()) { Player actor = getActor(); Player enemy = getEnemy(); PacketManager.updateInventory(actor); PacketManager.updateInventory(enemy); updateDialog(); actor.sendMessage(MessageType.TRADE_HAS_BEGUN); enemy.sendMessage(MessageType.TRADE_HAS_BEGUN); return true; } return false; } /** * @return заблокировал ли трейд инициатор. */ protected final boolean isActorLock() { return actorLock; } /** * @return завершена ли передача. */ protected final boolean isDone() { return done; } /** * @return заблокировал ли трейд опонент. */ protected final boolean isEnemyLock() { return enemyLock; } /** * Заблокирован ли трейд у указанного игрока. * * @param player игрок. * @return заблокирован ли. */ public boolean isLock(Player player) { if(player == actor) return isActorLock(); else if(player == enemy) return isEnemyLock(); return false; } /** * Блокировка трейда. * * @param player игрок. */ public synchronized void lock(Player player) { // если это инициатор if(actor == player) // блочим у него setActorLock(true); // если это опонент else if(enemy == player) // блочим у опонента setEnemyLock(true); // нсли у обоих диалог заблокирован if(isActorLock() && isEnemyLock()) { // применяем apply(); // закрываем окно cancel(null); return; } // обновляем диалог updateDialog(); } protected final void setActorItems(Array<TradeItem> actorItems) { this.actorItems = actorItems; } protected final void setActorLock(boolean actorLock) { this.actorLock = actorLock; } protected final void setDone(boolean done) { this.done = done; } protected final void setEnemyLock(boolean enemyLock) { this.enemyLock = enemyLock; } /** * Обновление отображения диалога. */ protected void updateDialog() { Player actor = getActor(); Player enemy = getEnemy(); if(actor == null || enemy == null) return; // создаем новый пакет ServerPacket packet = ShowTrade.getInstance(actor, enemy, objectId, this); packet.increaseSends(); packet.increaseSends(); // отправляем actor.sendPacket(packet, false); enemy.sendPacket(packet, false); } } <file_sep>/java/game/tera/remotecontrol/handlers/UpdateAccountHandler.java package tera.remotecontrol.handlers; import tera.gameserver.manager.AccountManager; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.model.Account; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Сборщик диномичной инфы о сервере * * @author Ronn * @created 25.04.2012 */ public class UpdateAccountHandler implements PacketHandler { public static final UpdateAccountHandler instance = new UpdateAccountHandler(); @Override public Packet processing(Packet packet) { String login = packet.nextString(); AccountManager accountManager = AccountManager.getInstance(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); Account account = accountManager.getAccount(login.toLowerCase()); boolean inDB = false; if(account == null) { account = dbManager.restoreAccount(login); inDB = true; } if(account == null) return new Packet(PacketType.RESPONSE, false); Packet response = new Packet(PacketType.RESPONSE, true, account.getEmail(), account.getLastIP(), account.getAllowIPs(), account.getComments(), account.getEndBlock(), Math.max(System.currentTimeMillis(), account.getEndPay()), account.getAccessLevel()); if(inDB) accountManager.removeAccount(account); return response; } } <file_sep>/java/game/tera/remotecontrol/handlers/SavePlayersHandler.java package tera.remotecontrol.handlers; import rlib.logging.GameLoggers; import rlib.logging.Loggers; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Обработчик запроса на сохранение всех игроков. * * @author Ronn */ public class SavePlayersHandler implements PacketHandler { public static final SavePlayersHandler instance = new SavePlayersHandler(); @Override public Packet processing(Packet packet) { Loggers.info(this, "start save players..."); for(Player player : World.getPlayers()) { Loggers.info(this, "store " + player.getName()); player.store(false); } Loggers.info(this, "all players saved."); GameLoggers.finish(); Loggers.info(this, "all game loggers writed."); return new Packet(PacketType.RESPONSE); } } <file_sep>/java/game/tera/gameserver/model/npc/spawn/Spawn.java package tera.gameserver.model.npc.spawn; import tera.gameserver.model.npc.Npc; import tera.util.Location; /** * Интерфейс для реализации спавна нпс. * * @author Ronn */ public interface Spawn { /** * Обработка смерти нпс из этого спавна. * * @param npc умерший нпс. */ public void doDie(Npc npc); /** * @return позиция спавна. */ public Location getLocation(); /** * @return маршрут патрулирования. */ public Location[] getRoute(); /** * @return ид темплейта. */ public int getTemplateId(); /** * @return тип темплейта. */ public int getTemplateType(); /** * @param location позиция спавна. */ public void setLocation(Location location); /** * Запуск спавна. */ public void start(); /** * Остановка спавна. */ public void stop(); } <file_sep>/java/game/tera/gameserver/network/serverpackets/Test25.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; public class Test25 extends ServerConstPacket { private static final Test25 instance = new Test25(); public static Test25 getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.TEST_25; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, 0x00000000); } }<file_sep>/java/game/tera/gameserver/network/serverpackets/Test7.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; public class Test7 extends ServerConstPacket { private static final Test7 instance = new Test7(); public static Test7 getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.TEST_7; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeShort(buffer, 6);//06 00 5E 00 5F 00 5E 00 00 00 writeShort(buffer, 94);// writeShort(buffer, 95);// writeShort(buffer, 94);// writeShort(buffer, 0);// } }<file_sep>/java/game/tera/gameserver/network/serverpackets/S_Completed_Mission_Info.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import tera.gameserver.model.quests.QuestDate; import tera.gameserver.network.ServerPacketType; /** * Пакет со списком выполненных квестов. * * @author Ronn */ public class S_Completed_Mission_Info extends ServerPacket { private static final ServerPacket instance = new S_Completed_Mission_Info(); public static S_Completed_Mission_Info getInstance(Table<IntKey, QuestDate> completeTable) { S_Completed_Mission_Info packet = (S_Completed_Mission_Info) instance.newInstance(); ByteBuffer buffer = packet.getPrepare(); try { Array<QuestDate> completed = packet.getCompleted(); // вносим и сортируем штамы выполнения completeTable.values(completed); // получаем массив штампов QuestDate[] array = completed.array(); // получаем последний штамп QuestDate last = completed.last(); int bytes = 8; packet.writeShort(buffer, completeTable.size()); //1B 00 кол-во квестов в книге packet.writeShort(buffer, bytes); //08 00 for(int i = 0, length = completed.size(); i < length; i++) { QuestDate next = array[i]; packet.writeShort(buffer, bytes); if(next != last) bytes += 8; else bytes = 0; packet.writeShort(buffer, bytes); packet.writeInt(buffer, next.getQuestId()); } return packet; } finally { buffer.flip(); } } /** список выполненных квестов */ private Array<QuestDate> completed; /** промежуточный буффер */ private ByteBuffer prepare; public S_Completed_Mission_Info() { this.prepare = ByteBuffer.allocate(4096).order(ByteOrder.LITTLE_ENDIAN); this.completed = Arrays.toSortedArray(QuestDate.class); } @Override public void finalyze() { prepare.clear(); completed.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_COMPLETED_MISSION_INFO; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); // получаем промежуточный буффер ByteBuffer prepare = getPrepare(); // переносим данные buffer.put(prepare.array(), 0, prepare.limit()); } /** * @return подготовленный буфер. */ public ByteBuffer getPrepare() { return prepare; } /** * @return список выполннных квестов. */ public Array<QuestDate> getCompleted() { return completed; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_View_Battle_Field_Result.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.battlefields.BattlefieldList; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; import java.util.List; public class S_View_Battle_Field_Result extends ServerPacket { private static final ServerPacket instance = new S_View_Battle_Field_Result(); public static S_View_Battle_Field_Result getInstance(Player player) { S_View_Battle_Field_Result packet = (S_View_Battle_Field_Result) instance.newInstance(); packet.player = player; return packet; } /** кол-во ожидания секунд */ private Player player; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_VIEW_BATTLE_FIELD_RESULT; } @Override protected final void writeImpl() { int n = 16; List<BattlefieldList> battlefields = BattlefieldList.getBattleFieldList(); writeOpcode(); writeShort(battlefields.size()); writeShort(n); writeInt(player.getObjectId()); writeInt(28);//reset days for(int i = battlefields.size() - 1; i >= 0; i--) { writeShort(n); writeShort((i == 0) ? 0 : (n += 64)); writeInt(battlefields.get(i).getBattleFieldId()); writeInt(3); writeInt(0);//wins writeInt(0);//loses writeInt(0);//draws writeInt(0);//kills writeInt(0);//deaths writeInt(0);//assists writeInt(1000);//previous rating writeInt(0); writeInt(0); writeInt(0);//destroyed writeInt(1000);//rating writeInt(0);//icon -> 0/1/2 bronze/silver/gold writeInt(0);//captured } } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Request_User_Paperdoll_Info_With_Gameid.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.World; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_User_Paperdoll_info; public class C_Request_User_Paperdoll_Info_With_Gameid extends ClientPacket { private int objectId; @Override protected void readImpl() { objectId = readInt(); } @Override protected void runImpl() { Player player = World.getPlayer(objectId); if(player != null) owner.getOwner().sendPacket(S_User_Paperdoll_info.getInstance(player), true); } } <file_sep>/java/game/tera/gameserver/scripts/items/BarbecueItem.java package tera.gameserver.scripts.items; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.MessageType; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.S_Sytem_Message_Loot_Item; import tera.gameserver.network.serverpackets.S_Sytem_Message; /** * Обработчик жарки мяса у костра по квесту. * * @author Ronn */ public class BarbecueItem extends AbstractItemExecutor { public static final int RECEPT_ID = 5027; public static final int RESOURSE_ID = 5028; public static final int RESOURSE_2_ID = 5029; public static final int RESULT_ID = 5030; public BarbecueItem(int[] itemIds, int access) { super(itemIds, access); } @Override public void execution(ItemInstance item, Player player) { // если игроок не у огня, выходим if(!player.isInBonfireTerritory()) { player.sendMessage("You can only use a fixed fire."); return; } // получаем инвентарь игроа Inventory inventory = player.getInventory(); inventory.lock(); try { // если в инвенторе нет нужного кол-во иитемов, выходим if(!inventory.containsItems(RECEPT_ID, 1) || !inventory.containsItems(RESOURSE_ID, 1) || !inventory.containsItems(RESOURSE_2_ID, 1)) { player.sendMessage("You are not components."); return; } // удаляем 1 рецепт inventory.removeItem(RECEPT_ID, 1L); // удаляем 1 ресурс inventory.removeItem(RESOURSE_ID, 1L); // удаляем 1 ресурс inventory.removeItem(RESOURSE_2_ID, 1L); // выдаем 1 итоговый inventory.forceAddItem(RESULT_ID, 1, "Bonfire"); } finally { inventory.unlock(); } // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // уведомляем о использовании придмета eventManager.notifyUseItem(item, player); // уведомляем всех об этом eventManager.notifyInventoryChanged(player); // отправляем пакет о использовании рецепта player.sendPacket(S_Sytem_Message.getInstance(MessageType.ITEM_USE).addItem(RECEPT_ID, 1), true); // отпправляем пакет о выдачи player.sendPacket(S_Sytem_Message_Loot_Item.getInstance(player.getName(), RESULT_ID, 1), true); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Inventory_Auto_Sort.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.npc.interaction.dialogs.BankDialog; import tera.gameserver.model.npc.interaction.dialogs.Dialog; import tera.gameserver.model.playable.Player; /** * Пакет запроса на сортировку итемов в инвентаре. * * @author Ronn * @created 11.04.2012 */ public class C_Inventory_Auto_Sort extends ClientPacket { private static enum SortLocation { INVENTORY, BANK, } /** игрок, который хочет отсортировать инвентарь */ private Player player; /** что именно сортировать */ private SortLocation location; @Override public void finalyze() { player = null; } @Override public boolean isSynchronized() { return false; } @Override protected void readImpl() { player = owner.getOwner(); location = SortLocation.values()[readInt()]; } @Override protected void runImpl() { if(player == null) return; switch(location) { case INVENTORY: { // получаем инвентарь Inventory inventory = player.getInventory(); // если его нет, выходим if(inventory == null) { log.warning(this, new Exception("not found inventory")); return; } // сортируем inventory.sort(); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // обновляем eventManager.notifyInventoryChanged(player); break; } case BANK: { Dialog dialog = player.getLastDialog(); if(dialog == null || !(dialog instanceof BankDialog)) return; BankDialog bank = (BankDialog) dialog; bank.sort(); } } } } <file_sep>/java/game/tera/gameserver/model/ai/npc/Task.java package tera.gameserver.model.ai.npc; import rlib.util.pools.Foldable; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.Skill; /** * Модель задания АИ. * * @author Ronn * @created 12.04.2012 */ public final class Task implements Foldable { /** цели задания */ private Character target; /** скил для задания */ private Skill skill; /** тип задания */ private TaskType type; /** сообщение при выполнении */ private String message; /** целевые координаты задания */ private float x; private float y; private float z; /** разворот в заданиях */ private int heading; public Task() { super(); } /** * @param type тип задания. * @param target цель задания. */ public Task(TaskType type, Character target) { this.type = type; this.target = target; } /** * @param type тип задания. * @param target цель задания. * @param skill скил для задания. */ public Task(TaskType type, Character target, Skill skill) { this.type = type; this.target = target; this.skill = skill; } /** * @param type тип задания. * @param target цель задания. * @param skill скил для задания. * @param heading разворот. */ public Task(TaskType type, Character target, Skill skill, int heading) { this(type, target, skill); this.heading = heading; } /** * @param type тип задания. * @param x целевая координата. * @param y целевая координата. * @param z целевая координата. */ public Task(TaskType type, float x, float y, float z) { this.x = x; this.y = y; this.z = z; this.type = type; } /** * @param type тип задания. * @param x целевая координата. * @param y целевая координата. * @param z целевая координата. * @param skill скил для задания. * @param target цель задания. */ public Task(TaskType type, float x, float y, float z, Skill skill, Character target) { this(type, x, y, z); this.skill = skill; this.target = target; } @Override public void finalyze() { type = null; target = null; skill = null; } /** * @return разворот. */ public int getHeading() { return heading; } /** * @return сообщение при выполнении. */ public String getMessage() { return message; } /** * @return скилл задания. */ public Skill getSkill() { return skill; } /** * @return цель задания. */ public Character getTarget() { return target; } /** * @return тип задания. */ public TaskType getType() { return type; } /** * @return целевая координата. */ public float getX() { return x; } /** * @return целевая координата. */ public float getY() { return y; } /** * @return целевая координата. */ public float getZ() { return z; } @Override public void reinit(){} /** * @param heading разворот. */ public Task setHeading(int heading) { this.heading = heading; return this; } /** * @param message сообщение при выполнении. */ public Task setMessage(String message) { this.message = message; return this; } /** * @param skill скилл задания. */ public Task setSkill(Skill skill) { this.skill = skill; return this; } /** * @param target цель задания. */ public Task setTarget(Character target) { this.target = target; return this; } /** * @param type тип задания. */ public Task setType(TaskType type) { this.type = type; if(type == null) Thread.dumpStack(); return this; } /** * @param x целевая координата. */ public Task setX(float x) { this.x = x; return this; } /** * @param y целевая координата. */ public Task setY(float y) { this.y = y; return this; } /** * @param z целевая координата. */ public Task setZ(float z) { this.z = z; return this; } @Override public String toString() { return "Task [target=" + target + ", skill=" + skill + ", type=" + type + ", message=" + message + ", x=" + x + ", y=" + y + ", z=" + z + ", heading=" + heading + "]"; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Pet_Info_Clear.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; import tera.gameserver.network.serverpackets.ServerConstPacket; import java.nio.ByteBuffer; /** * Created by Luciole on 25/06/2016. */ public class S_Pet_Info_Clear extends ServerConstPacket { private static final S_Pet_Info_Clear instance = new S_Pet_Info_Clear(); public static S_Pet_Info_Clear getInstance() { return instance; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_PET_INFO_CLEAR; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/Trigger.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.templates.SkillTemplate; /** * Обработчик тригеров. * * @author Ronn */ public class Trigger extends Effect { /** * @param template темплейт скила. */ public Trigger(SkillTemplate template) { super(template); } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ){} @Override public void useSkill(Character character, float targetX, float targetY, float targetZ){} } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Cancel_Exit.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Cancel_Exit extends ServerPacket { private static final ServerPacket instance = new S_Cancel_Exit(); public static S_Cancel_Exit getInstance() { return (S_Cancel_Exit) instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_CANCEL_EXIT; } @Override protected void writeImpl() { writeOpcode(); writeByte(0x00); // 00 - Successful. } }<file_sep>/java/game/tera/gameserver/model/listeners/PlayerSelectListener.java package tera.gameserver.model.listeners; import tera.gameserver.model.playable.Player; /** * Интерфейс для реализации слушателя выбора игрока для входа. * * @author Ronn */ public interface PlayerSelectListener { /** * Обработка выбора игрока для входа в игру. * * @param player выбранный игрок для входа. */ public void onSelect(Player player); } <file_sep>/sql/tera_server.sql -- Adminer 4.6.3 MySQL dump SET NAMES utf8; SET time_zone = '+00:00'; SET foreign_key_checks = 0; SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'; DROP TABLE IF EXISTS `accounts`; CREATE TABLE `accounts` ( `AccountId` int(11) NOT NULL AUTO_INCREMENT, `login` varchar(32) NOT NULL DEFAULT '', `password` varchar(256) CHARACTER SET latin1 DEFAULT '', `email` varchar(45) CHARACTER SET latin1 DEFAULT 'null<PASSWORD>', `access_level` smallint(6) NOT NULL DEFAULT '0', `end_pay` bigint(15) NOT NULL DEFAULT '0', `end_block` bigint(15) NOT NULL DEFAULT '0', `last_ip` varchar(15) NOT NULL DEFAULT '', `allow_ips` varchar(255) NOT NULL DEFAULT '*', `comments` varchar(255) NOT NULL DEFAULT '', `LastOnlineUtc` bigint(64) NOT NULL DEFAULT '0', `EmailVerify` varchar(256) NOT NULL, `PasswordRecovery` varchar(128) NOT NULL, `Coins` int(11) NOT NULL DEFAULT '0', `Ip` varchar(64) NOT NULL, `Membership` int(1) NOT NULL DEFAULT '0', `isGM` int(1) NOT NULL DEFAULT '0', `fatigability` int(1) NOT NULL DEFAULT '2500', PRIMARY KEY (`AccountId`), KEY `access_level` (`access_level`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `account_bank`; CREATE TABLE `account_bank` ( `account_name` varchar(45) NOT NULL, `bank_id` int(10) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`bank_id`), UNIQUE KEY `account_name_UNIQUE` (`account_name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ð©ð┤ ð▒ð░ð¢ð║ð¥ð▓, ðÀð░ð║ÐÇðÁð┐ð╗ðÁð¢ð¢ÐïÐà ðÀð░ ð░ð║ð║ð░Ðâð¢Ðéð░ð╝ð©.'; DROP TABLE IF EXISTS `boss_spawn`; CREATE TABLE `boss_spawn` ( `npc_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ÐéðÁð╝ð┐ð╗ðÁð╣Ðéð░ ð¢ð┐Ðü.', `npc_type` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðóð©ð┐ ÐéðÁð╝ð┐ð╗ðÁð╣Ðéð░ ð¢ð┐Ðü.', `spawn` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÆÐÇðÁð╝ÐÅ ðÀð░ð▓ðÁÐÇÐêðÁð¢ð©ÐÅ Ðüð┐ð░ð▓ð¢ð░.', PRIMARY KEY (`npc_id`,`npc_type`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ÐÇðÁÐüð┐ð░ð▓ð¢ð¥ð▓ ðáðæ.'; DROP TABLE IF EXISTS `characters`; CREATE TABLE `characters` ( `account_name` varchar(45) NOT NULL DEFAULT '', `object_id` int(11) NOT NULL DEFAULT '0', `class_id` tinyint(3) NOT NULL DEFAULT '0', `race_id` tinyint(1) NOT NULL DEFAULT '0', `sex` tinyint(1) NOT NULL DEFAULT '0', `char_name` varchar(35) NOT NULL DEFAULT '', `heading` int(15) NOT NULL DEFAULT '0', `online_time` bigint(15) NOT NULL DEFAULT '0', `create_time` bigint(15) NOT NULL DEFAULT '0', `end_ban` bigint(15) NOT NULL DEFAULT '0', `end_chat_ban` bigint(15) NOT NULL DEFAULT '0', `title` varchar(16) NOT NULL DEFAULT '', `guild_id` int(15) NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ð║ð╗ð░ð¢ð░ ð©ð│ÐÇð¥ð║ð░.', `access_level` tinyint(4) NOT NULL DEFAULT '0', `union_level` int(11) NOT NULL DEFAULT '100', `level` tinyint(3) NOT NULL DEFAULT '0', `exp` bigint(15) NOT NULL DEFAULT '0', `hp` int(11) NOT NULL DEFAULT '0', `mp` int(11) NOT NULL DEFAULT '0', `x` double(11,2) DEFAULT '0.00', `y` double(11,2) DEFAULT '0.00', `z` double(11,2) DEFAULT '0.00', `heart` smallint(3) NOT NULL DEFAULT '0', `attack_counter` tinyint(3) NOT NULL DEFAULT '0', `pvp_count` int(11) NOT NULL DEFAULT '0', `pve_count` int(11) NOT NULL DEFAULT '0', `guild_rank` tinyint(3) NOT NULL DEFAULT '0', `zone_id` int(10) unsigned NOT NULL DEFAULT '0', `guild_note` varchar(35) NOT NULL DEFAULT '' COMMENT 'ðáÔÇöðá┬░ðáÐÿðá┬ÁðíÔÇÜðáÐöðá┬░ ðáÐò ðáÐæðáÐûðíðéðáÐòðáÐöðá┬Á ðáÊæðá┬╗ðíðÅ ðáÐûðáÐæðá┬╗ðáÊæ ðá┬╗ðáÐæðíðâðíÔÇÜðá┬░.', `karma` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÜð░ÐÇð╝ð░ ð©ð│ÐÇð¥ð║ð░.', `collect_mining` int(10) unsigned NOT NULL DEFAULT '1' COMMENT 'ðáУðá┬░ðáðåðíÔÇ╣ðáÐö ðíðâðá┬▒ðáÐòðíðéðá┬░ ðáÐöðá┬░ðáÐÿðáðàðá┬ÁðáÔäû.', `collect_plant` int(10) unsigned NOT NULL DEFAULT '1' COMMENT 'ðáУðá┬░ðáðåðíÔÇ╣ðáÐö ðíðâðá┬▒ðáÐòðíðéðá┬░ ðíðéðá┬░ðíðâðíÔÇÜðá┬ÁðáðàðáÐæðáÔäû.', `collect_energy` int(10) unsigned NOT NULL DEFAULT '1' COMMENT 'ðáУðá┬░ðáðåðíÔÇ╣ðíðâðáÐö ðíðâðá┬▒ðáÐòðíðéðá┬░ ðáÐöðíðéðáÐæðíðâðíÔÇÜðá┬░ðá┬╗ðáÐòðáðå.', `description` varchar(255) NOT NULL DEFAULT '', `last_online` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÆÐÇðÁð╝ÐÅ ð┐ð¥Ðüð╗ðÁð┤ð¢ðÁð│ð¥ ð¥ð¢ð╗ð░ð╣ð¢ð░ ð©ð│ÐÇð¥ð║ð░.', `continent_id` smallint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ð║ð¥ð¢Ðéð©ð¢ðÁð¢Ðéð░, ð¢ð░ ð║ð¥Ðéð¥ÐÇð¥ð╝ ð¢ð░Ðàð¥ð┤ð©ÐéÐüÐÅ ð©ð│ÐÇð¥ð║.', PRIMARY KEY (`object_id`), UNIQUE KEY `char_name` (`char_name`), KEY `account_name` (`account_name`), KEY `guild` (`guild_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `character_appearances`; CREATE TABLE `character_appearances` ( `object_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðáðêðáðàðáÐæðáÐöðá┬░ðá┬╗ðíðèðáðàðíÔÇ╣ðáÔäû ðáÐæðáÊæ ðáÐæðáÐûðíðéðáÐòðáÐöðá┬░.', `face_color` tinyint(3) unsigned NOT NULL DEFAULT '0', `face_skin` tinyint(3) unsigned NOT NULL DEFAULT '0', `adorments_skin` tinyint(3) unsigned NOT NULL DEFAULT '0', `features_skin` tinyint(3) unsigned NOT NULL DEFAULT '0', `features_color` tinyint(3) unsigned NOT NULL DEFAULT '0', `voice` tinyint(3) unsigned NOT NULL DEFAULT '0', `bone_structure_brow` tinyint(3) unsigned NOT NULL DEFAULT '0', `bone_structure_cheekbones` tinyint(3) unsigned NOT NULL DEFAULT '0', `bone_structure_jaw` tinyint(3) unsigned NOT NULL DEFAULT '0', `bone_structure_jaw_jut` tinyint(3) unsigned NOT NULL DEFAULT '0', `ears_rotation` tinyint(3) unsigned NOT NULL DEFAULT '0', `ears_extension` tinyint(3) unsigned NOT NULL DEFAULT '0', `ears_trim` tinyint(3) unsigned NOT NULL DEFAULT '0', `ears_size` tinyint(3) unsigned NOT NULL DEFAULT '0', `eyes_width` tinyint(3) unsigned NOT NULL DEFAULT '0', `eyes_height` tinyint(3) unsigned NOT NULL DEFAULT '0', `eyes_separation` tinyint(3) unsigned NOT NULL DEFAULT '0', `eyes_angle` tinyint(3) unsigned NOT NULL DEFAULT '0', `eyes_inner_brow` tinyint(3) unsigned NOT NULL DEFAULT '0', `eyes_outer_brow` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_extension` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_size` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_bridge` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_nostril_width` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_tip_width` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_tip` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_nostril_flare` tinyint(3) unsigned NOT NULL DEFAULT '0', `mouth_pucker` tinyint(3) unsigned NOT NULL DEFAULT '0', `mouth_position` tinyint(3) unsigned NOT NULL DEFAULT '0', `mouth_width` tinyint(3) unsigned NOT NULL DEFAULT '0', `mouth_lip_thickness` tinyint(3) unsigned NOT NULL DEFAULT '0', `mouse_corners` tinyint(3) unsigned NOT NULL DEFAULT '0', `eyes_shape` tinyint(3) unsigned NOT NULL DEFAULT '0', `nose_bend` tinyint(3) unsigned NOT NULL DEFAULT '0', `bone_structure_jaw_width` tinyint(3) unsigned NOT NULL DEFAULT '0', `mouth_gape` tinyint(3) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ð▓ð¢ðÁÐêð¢ð¥ÐüÐéð© ð©ð│ÐÇð¥ð║ð¥ð▓.'; DROP TABLE IF EXISTS `character_dungeons`; CREATE TABLE `character_dungeons` ( `id` int(11) NOT NULL AUTO_INCREMENT, `object_id` int(11) NOT NULL, `dungeon_id` int(11) NOT NULL, `clear_count` int(11) NOT NULL, `last_entry` int(11) NOT NULL, `daily_count` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin; DROP TABLE IF EXISTS `character_faces`; CREATE TABLE `character_faces` ( `objectId` int(11) NOT NULL DEFAULT '0', `faceColor` int(10) NOT NULL DEFAULT '0', `hairColor` int(10) NOT NULL DEFAULT '0', `eyebrowsFirstVal` int(10) NOT NULL DEFAULT '0', `eyebrowsSecondVal` int(10) NOT NULL DEFAULT '0', `eyebrowsThridVal` int(10) NOT NULL DEFAULT '0', `eyeFirstVal` int(10) NOT NULL DEFAULT '0', `eyeSecondVal` int(10) NOT NULL DEFAULT '0', `eyeThridVal` int(10) NOT NULL DEFAULT '0', `eyePosVertical` int(10) NOT NULL DEFAULT '0', `eyeWidth` int(10) NOT NULL DEFAULT '0', `eyeHeight` int(10) NOT NULL DEFAULT '0', `chin` int(10) NOT NULL DEFAULT '0', `cheekbonePos` int(10) NOT NULL DEFAULT '0', `earsFirstVal` int(10) NOT NULL DEFAULT '0', `earsSecondVal` int(10) NOT NULL DEFAULT '0', `earsThridVal` int(10) NOT NULL DEFAULT '0', `earsFourthVal` int(10) NOT NULL DEFAULT '0', `noseFirstVal` int(10) NOT NULL DEFAULT '0', `noseSecondVal` int(10) NOT NULL DEFAULT '0', `noseThridVal` int(10) NOT NULL DEFAULT '0', `noseFourthVal` int(10) NOT NULL DEFAULT '0', `noseFifthVal` int(10) NOT NULL DEFAULT '0', `lipsFirstVal` int(10) NOT NULL DEFAULT '0', `lipsSecondVal` int(10) NOT NULL DEFAULT '0', `lipsThridVal` int(10) NOT NULL DEFAULT '0', `lipsFourthVal` int(10) NOT NULL DEFAULT '0', `lipsFifthVal` int(10) NOT NULL DEFAULT '0', `lipsSixthVal` int(10) NOT NULL DEFAULT '0', `cheeks` int(10) NOT NULL DEFAULT '0', `bridgeFirstVal` int(10) NOT NULL DEFAULT '0', `bridgeSecondVal` int(10) NOT NULL DEFAULT '0', `bridgeThridVal` int(10) NOT NULL DEFAULT '0', `temp1` int(10) NOT NULL DEFAULT '0', `temp2` int(10) NOT NULL DEFAULT '0', `temp3` int(10) NOT NULL DEFAULT '0', `temp4` int(10) NOT NULL DEFAULT '0', `temp5` int(10) NOT NULL DEFAULT '0', `temp6` int(10) NOT NULL DEFAULT '0', `temp7` int(10) NOT NULL DEFAULT '0', `temp8` int(10) NOT NULL DEFAULT '0', `temp9` int(10) NOT NULL DEFAULT '0', `temp10` int(10) NOT NULL DEFAULT '0', `temp11` int(10) NOT NULL DEFAULT '0', `temp12` int(10) NOT NULL DEFAULT '0', `temp13` int(10) NOT NULL DEFAULT '0', `temp14` int(10) NOT NULL DEFAULT '0', `temp15` int(10) NOT NULL DEFAULT '0', `temp16` int(10) NOT NULL DEFAULT '0', `temp17` int(10) NOT NULL DEFAULT '0', `temp18` int(10) NOT NULL DEFAULT '0', `temp19` int(10) NOT NULL DEFAULT '0', PRIMARY KEY (`objectId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `character_friends`; CREATE TABLE `character_friends` ( `object_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðúð¢ð©ð║ð░ð╗Ðîð¢Ðïð╣ ð©ð┤ ð©ð│ÐÇð¥ð║ð░.', `friend_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðúð¢ð©ð║ð░ð╗Ðîð¢Ðïð╣ ð©ð┤ ð┤ÐÇÐâð│ð░.', `friend_note` varchar(45) NOT NULL COMMENT 'ðƒð¥ð╝ðÁÐéð║ð░ ð¥ð▒ ð┤ÐÇÐâð│ðÁ.', PRIMARY KEY (`object_id`,`friend_id`), KEY `select` (`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ð┤ÐÇÐâðÀðÁð╣ ð©ð│ÐÇð¥ð║ð¥ð▓.'; DROP TABLE IF EXISTS `character_hotkey`; CREATE TABLE `character_hotkey` ( `object_id` int(11) NOT NULL DEFAULT '0' COMMENT 'ðáðêðáðàðáÐæðáÐöðá┬░ðá┬╗ðíðèðáðàðíÔÇ╣ðáÔäû ðáÐæðáÊæ ðáÐæðáÐûðíðéðáÐòðáÐöðá┬░.', `data` blob COMMENT 'ðôð¥ÐÇÐÅÐçð©ðÁ ð║ð╗ð░ð▓ð©ÐêÐï', PRIMARY KEY (`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='ðáÐûðáÐòðíðéðíðÅðíÔÇíðáÐæðá┬Á ðáÐöðáðàðáÐòðáÐùðáÐöðáÐæ.'; DROP TABLE IF EXISTS `character_inventors`; CREATE TABLE `character_inventors` ( `owner_id` int(11) unsigned NOT NULL DEFAULT '0', `id` int(11) unsigned NOT NULL DEFAULT '0', `level` smallint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`owner_id`,`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `character_presets_2`; CREATE TABLE `character_presets_2` ( `objectId` int(10) unsigned NOT NULL DEFAULT '0', `temp1` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp2` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp3` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp4` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp5` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp6` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp7` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp8` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp9` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp10` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp11` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp12` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp13` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp14` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp15` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp16` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp17` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp18` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp19` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp20` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp21` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp22` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp23` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp24` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp25` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp26` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp27` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp28` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp29` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp30` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp31` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp32` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp33` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp34` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp35` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp36` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp37` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp38` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp39` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp40` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp41` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp42` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp43` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp44` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp45` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp46` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp47` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp48` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp49` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp50` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp51` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp52` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp53` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp54` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp55` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp56` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp57` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp58` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp59` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp60` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp61` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp62` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp63` tinyint(3) unsigned NOT NULL DEFAULT '0', `temp64` tinyint(3) unsigned NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; DROP TABLE IF EXISTS `character_quests`; CREATE TABLE `character_quests` ( `object_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ðáÐøðá┬▒ðáÊæðá┬Âðá┬ÁðáÐöðíÔÇÜ ðáÐæðáÊæ ðáÐæðáÐûðíðéðáÐòðáÐöðá┬░.', `quest_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðá┬ÿðáÊæ ðáÐöðáðåðá┬ÁðíðâðíÔÇÜðá┬░.', `state` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'ðáðÄðíÔÇÜðá┬░ðáÊæðáÐæðíðÅ ðáÐöðáðåðá┬ÁðíðâðíÔÇÜðá┬░.', `date` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'ðáÔÇØðá┬░ðíÔÇÜðá┬░ ðá┬Àðá┬░ðáðåðá┬ÁðíðéðíÔé¼ðá┬ÁðáðàðáÐæðíðÅ ðáÐöðáðåðá┬ÁðíðâðíÔÇÜðá┬░.', `panel_state` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'ð×Ðéð¥ð▒ÐÇð░ðÂð░ÐéÐî ð╗ð© ð¢ð░ ð┐ð░ð¢ðÁð╗ð©.', PRIMARY KEY (`object_id`,`quest_id`) USING BTREE ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðáÐ×ðá┬░ðá┬▒ðá┬╗ðáÐæðíÔÇáðá┬░ ðáÐöðáðåðá┬ÁðíðâðíÔÇÜðáÐòðáðå ðáÐæðáÐûðíðéðáÐòðáÐöðáÐòðáðå.'; DROP TABLE IF EXISTS `character_quest_vars`; CREATE TABLE `character_quest_vars` ( `object_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ðáÐøðá┬▒ðáÊæðá┬ÁðáÐöðíÔÇÜ ðáÐæðáÊæ ðáÐæðáÐûðíðéðáÐòðáÐöðá┬░.', `quest_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðá┬ÿðáÊæ ðáÐöðáðåðá┬ÁðíðâðíÔÇÜðá┬░.', `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '0' COMMENT 'ðáУðá┬░ðá┬Àðáðåðá┬░ðáðàðáÐæðá┬Á ðáÐùðá┬Áðíðéðá┬ÁðáÐÿðá┬ÁðáðàðáðàðáÐòðáÔäû.', `value` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðáÔÇöðáðàðá┬░ðíÔÇíðá┬ÁðáðàðáÐæðá┬Á ðáÐùðá┬Áðíðéðá┬ÁðáÐÿðá┬ÁðáðàðáðàðáÐòðáÔäû.', PRIMARY KEY (`object_id`,`quest_id`,`name`), KEY `key_id` (`quest_id`,`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðáÐ×ðá┬░ðá┬▒ðá┬╗ðáÐæðíÔÇáðá┬░ ðáÐùðá┬Áðíðéðá┬ÁðáÐÿðá┬ÁðáðàðáðàðíÔÇ╣ðíÔǪ ðáÐöðáðåðá┬ÁðíðâðíÔÇÜðáÐòðáðå.'; DROP TABLE IF EXISTS `character_save_effects`; CREATE TABLE `character_save_effects` ( `object_id` int(11) NOT NULL DEFAULT '0', `class_id` tinyint(3) NOT NULL DEFAULT '0', `skill_id` int(11) NOT NULL DEFAULT '0', `effect_order` tinyint(3) NOT NULL DEFAULT '0', `count` int(11) NOT NULL DEFAULT '0', `duration` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`object_id`,`class_id`,`skill_id`,`effect_order`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `character_settings`; CREATE TABLE `character_settings` ( `object_id` int(11) NOT NULL DEFAULT '0' COMMENT 'ðúð¢ð©ð║ð░ð╗Ðîð¢Ðïð╣ ð©ð┤ ð©ð│ÐÇð¥ð║ð░.', `data` blob COMMENT 'ðÿð¢Ðäð¥ÐÇð╝ð░Ðåð©ÐÅ ð¥ ð¢ð░ÐüÐéÐÇð¥ð╣ð║ð░Ðà.', PRIMARY KEY (`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='ðØð░ÐüÐéÐÇð¥ð╣ð║ð© ð║ð╗ð©ðÁð¢Ðéð░ ð©ð│ÐÇð¥ð║ð¥ð▓.'; DROP TABLE IF EXISTS `character_skills`; CREATE TABLE `character_skills` ( `object_id` int(11) NOT NULL DEFAULT '0', `class_id` tinyint(3) NOT NULL DEFAULT '0', `skill_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`object_id`,`class_id`,`skill_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `character_skill_reuses`; CREATE TABLE `character_skill_reuses` ( `object_id` int(11) NOT NULL DEFAULT '0', `skill_id` int(11) NOT NULL DEFAULT '0', `item_id` int(11) NOT NULL DEFAULT '0', `end_time` bigint(110) NOT NULL DEFAULT '0', PRIMARY KEY (`object_id`,`skill_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `character_territories`; CREATE TABLE `character_territories` ( `object_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðúð¢ð©ð║ð░ð╗Ðîð¢Ðïð╣ ð©ð┤ ð©ð│ÐÇð¥ð║ð░.', `territory_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ÐéðÁÐÇÐÇð©Ðéð¥ÐÇð©ð©, ð▓ ð║ð¥Ðéð¥ÐÇð¥ð╣ ð¥ð¢ ð┐ð¥ð▒Ðïð▓ð░ð╗', UNIQUE KEY `key_territory` (`territory_id`,`object_id`), KEY `key_player` (`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ÐéðÁÐÇÐÇð©Ðéð¥ÐÇð©ð╣, ð▓ ð║ð¥Ðéð¥ÐÇÐïÐà ð┐ð¥ð▒Ðïð▓ð░ð╗ ð©ð│ÐÇð¥ð║.'; DROP TABLE IF EXISTS `character_variables`; CREATE TABLE `character_variables` ( `object_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðúð¢ð©ð║ð░ð╗Ðîð¢Ðïð╣ ð©ð┤ ð©ð│ÐÇð¥ð║ð░.', `var_name` varchar(45) NOT NULL DEFAULT '' COMMENT 'ðØð░ðÀð▓ð░ð¢ð©ðÁ ð┐ðÁÐÇðÁð╝ðÁð¢ð¢ð¥ð╣.', `var_value` varchar(45) NOT NULL DEFAULT '' COMMENT 'ðùð¢ð░ÐçðÁð¢ð©ðÁ ð┐ðÁÐÇðÁð╝ðÁð¢ð¢ð¥ð╣.', PRIMARY KEY (`object_id`,`var_name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ð┐ðÁÐÇðÁð╝ðÁð¢ð¢ÐïÐà ð©ð│ÐÇð¥ð║ð¥ð▓.'; DROP TABLE IF EXISTS `guilds`; CREATE TABLE `guilds` ( `id` int(11) NOT NULL DEFAULT '0' COMMENT 'ðúð¢ð©ð║ð░ð╗Ðîð¢Ðïð╣ ð©ð┤ ð║ð╗ð░ð¢ð░.', `name` varchar(45) NOT NULL COMMENT 'ðØð░ðÀð▓ð░ð¢ð©ðÁ ð║ð╗ð░ð¢ð░.', `title` varchar(45) NOT NULL COMMENT 'ðóð©ÐéÐâð╗ ð│ð©ð╗Ðîð┤ð©ð©.', `level` smallint(6) NOT NULL DEFAULT '0' COMMENT 'ðúÐÇð¥ð▓ðÁð¢Ðî ð║ð╗ð░ð¢ð░.', `icon` blob COMMENT 'ðÿð║ð¥ð¢ð║ð░ ð║ð╗ð░ð¢ð░.', `icon_name` varchar(45) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT 'ðØð░ðÀð▓ð░ð¢ð©ðÁ ð©ð║ð¥ð¢ð║ð© ð│ð©ð╗Ðîð┤ð©ð©.', `message` varchar(255) NOT NULL DEFAULT '' COMMENT 'ðáÔÇóðá┬Âðá┬ÁðáÊæðáðàðáðåðáðàðáÐòðá┬Á ðíðâðáÐòðáÐòðá┬▒ðíÔÇ░ðá┬ÁðáðàðáÐæðá┬Á ðáÐûðáÐæðá┬╗ðíðèðáÊæðáÐæðáÐæ.', `praise` int(11) NOT NULL DEFAULT '0', `alliance` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) USING BTREE ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ð║ð╗ð░ð¢ð¥ð▓'; DROP TABLE IF EXISTS `guild_ranks`; CREATE TABLE `guild_ranks` ( `guild_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ðÿð┤ ð│ð©ð╗Ðîð┤ð©ð©.', `rank_name` varchar(45) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'ðØð░ðÀð▓ð░ð¢ð©ðÁ ÐÇð░ð¢ð│ð░.', `order` tinyint(3) unsigned NOT NULL COMMENT 'ðÿð¢ð┤ðÁð║Ðü ÐÇð░ð¢ð│ð░.', `law` tinyint(3) unsigned NOT NULL COMMENT 'ðØð░ð▒ð¥ÐÇ ð┐ÐÇð░ð▓.', KEY `guild_id` (`guild_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='ðóð░ð▒ð╗ÐéÐåð░ ÐÇð░ð¢ð│ð¥ð▓ ð│ð©ð╗Ðîð┤ð©ð╣.'; DROP TABLE IF EXISTS `items`; CREATE TABLE `items` ( `object_id` int(10) unsigned NOT NULL DEFAULT '0', `owner_id` int(10) unsigned NOT NULL DEFAULT '0', `owner_name` varchar(45) NOT NULL DEFAULT '', `item_id` int(10) unsigned NOT NULL DEFAULT '0', `item_count` bigint(20) unsigned NOT NULL DEFAULT '0', `masterworked` int(11) NOT NULL DEFAULT '0', `enigma` int(11) NOT NULL DEFAULT '0', `enchant_level` smallint(5) NOT NULL DEFAULT '0', `bonus_id` int(10) NOT NULL DEFAULT '0', `autor` varchar(255) NOT NULL DEFAULT '', `location` tinyint(3) unsigned NOT NULL DEFAULT '0', `index` smallint(6) NOT NULL DEFAULT '0', `has_crystal` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`object_id`) USING HASH, KEY `key_owner_id` (`owner_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=1; DROP TABLE IF EXISTS `region_status`; CREATE TABLE `region_status` ( `region_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ÐÇðÁð│ð©ð¥ð¢ð░.', `owner_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ð▓ð╗ð░ð┤ðÁÐÄÐëðÁð╣ ð│ð©ð╗Ðîð┤ð©ð©.', `state` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðíð¥ÐüÐéð¥ÐÅð¢ð©ðÁ ÐÇðÁð│ð©ð¥ð¢ð░.', PRIMARY KEY (`region_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ÐüÐéð░ÐéÐâÐüð¥ð▓ ÐÇðÁð│ð©ð¥ð¢ð¥ð▓.'; INSERT INTO `region_status` (`region_id`, `owner_id`, `state`) VALUES (400, 0, 0), (401, 0, 0), (402, 0, 0), (403, 0, 0); DROP TABLE IF EXISTS `region_war_register`; CREATE TABLE `region_war_register` ( `region_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ÐÇðÁð│ð©ð¥ð¢ð░.', `guild_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðÿð┤ ð│ð©ð╗Ðîð┤ð©ð©.', PRIMARY KEY (`region_id`,`guild_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ÐÇðÁð│ð©ÐüÐéÐÇð░Ðåð©ð© ð¢ð░ ð▒ð©Ðéð▓Ðï ðÀð░ ÐÇðÁð│ð©ð¥ð¢Ðï.'; DROP TABLE IF EXISTS `server_variables`; CREATE TABLE `server_variables` ( `var_name` varchar(45) NOT NULL DEFAULT '' COMMENT 'ðØð░ðÀð▓ð░ð¢ð©ðÁ ð┐ðÁÐÇðÁð╝ðÁð¢ð¢ð¥ð╣.', `var_value` varchar(45) NOT NULL DEFAULT '' COMMENT 'ðùð¢ð░ÐçðÁð¢ð©ðÁ ð┐ðÁÐÇðÁð╝ðÁð¢ð¢ð¥ð╣.', PRIMARY KEY (`var_name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ÐüðÁÐÇð▓ðÁÐÇð¢ÐïÐà ð┐ðÁÐÇðÁð╝ðÁð¢ð¢ÐïÐà.'; DROP TABLE IF EXISTS `skill_learns`; CREATE TABLE `skill_learns` ( `classId` tinyint(3) NOT NULL DEFAULT '0', `skillId` int(11) NOT NULL DEFAULT '0', `minLevel` smallint(6) NOT NULL DEFAULT '0', `price` int(11) NOT NULL DEFAULT '0', `replaceId` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`classId`,`skillId`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `union`; CREATE TABLE `union` ( `id` int(11) NOT NULL AUTO_INCREMENT, `union_id` int(11) DEFAULT NULL, `leader_id` int(11) NOT NULL, `tax_rate` int(11) NOT NULL DEFAULT '0', `strength` int(11) NOT NULL DEFAULT '0', `bonus` int(11) NOT NULL DEFAULT '0', `message` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `union` (`id`, `union_id`, `leader_id`, `tax_rate`, `strength`, `bonus`, `message`) VALUES (1, 1, 0, 7, 1, 0, ''), (2, 2, 0, 4, 2, 0, ''), (3, 3, 0, 4, 3, 0, ''); DROP TABLE IF EXISTS `wait_guild_apply`; CREATE TABLE `wait_guild_apply` ( `id` int(11) NOT NULL AUTO_INCREMENT, `guild_id` int(11) NOT NULL, `character_id` int(11) NOT NULL, `message` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin; DROP TABLE IF EXISTS `wait_items`; CREATE TABLE `wait_items` ( `order` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ðá┬áðíÐÜðá┬áðíÔÇóðá┬áðí┬ÿðá┬áðÆ┬ÁðáðÄðáÔÇÜ ðá┬áðáÔÇáðáðÄð▓ðéÔäûðá┬áðóÔÇÿðá┬áðÆ┬░ðáðÄð▓ðéðÄðá┬áðíÔÇÿ.', `emptor` varchar(45) CHARACTER SET utf8 NOT NULL COMMENT 'ðáÔÇ║ðáÐòðáÐûðáÐæðáðà ðáÐùðáÐòðáÐöðíÐôðáÐùðá┬░ðíÔÇÜðá┬Áðá┬╗ðíðÅ.', `char_name` varchar(45) COLLATE utf8_unicode_ci NOT NULL COMMENT 'ðá┬áðÆ┬ÿðá┬áðí┬ÿðáðÄðáðÅ ðá┬áðíÔÇÿðá┬áðíÔÇôðáðÄðáÔÇÜðá┬áðíÔÇóðá┬áðíÔÇØðá┬áðÆ┬░.', `item_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ðá┬áðÆ┬ÿðá┬áðóÔÇÿ ðá┬áðíÔÇÿðáðÄð▓ðéÐÖðá┬áðÆ┬Áðá┬áðí┬ÿðá┬áðÆ┬░.', `item_count` int(10) unsigned NOT NULL DEFAULT '1' COMMENT 'ðá┬áðíÔäóðá┬áðíÔÇóðá┬áðÆ┬╗-ðá┬áðáÔÇáðá┬áðíÔÇó ðá┬áðíÔÇÿðáðÄð▓ðéÐÖðá┬áðÆ┬Áðá┬áðí┬ÿðá┬áðíÔÇóðá┬áðáÔÇá.', `enchant_level` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`order`,`char_name`,`item_id`,`item_count`) USING BTREE, KEY `name_key` (`char_name`), KEY `order_key` (`order`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='ðá┬áðÆ┬ÿðáðÄð▓ðéÐÖðá┬áðÆ┬Áðá┬áðí┬ÿðáðÄð▓ðéÔäû ðá┬áðáÔÇáðá┬áðíÔÇóðá┬áðÆ┬Âðá┬áðíÔÇÿðá┬áðóÔÇÿðá┬áðÆ┬░ðáðÄðáÔÇ╣ðáðÄð▓ðé┬░ðá┬áðíÔÇÿ'; DROP TABLE IF EXISTS `wait_skills`; CREATE TABLE `wait_skills` ( `order` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ðÿð┤ ðÀð░ð┐ð©Ðüð©.', `char_name` varchar(45) NOT NULL COMMENT 'ðÿð╝ÐÅ ð┐ðÁÐÇÐüð¥ð¢ð░ðÂð░.', `skill_id` int(10) unsigned NOT NULL COMMENT 'ðÿð┤ Ðüð║ð©ð╗ð░.', `skill_class` int(10) NOT NULL COMMENT 'ðÜð╗ð░ÐüÐü Ðüð║ð©ð╗ð░.', PRIMARY KEY (`order`), KEY `name_key` (`char_name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='ðóð░ð▒ð╗ð©Ðåð░ ð¥ðÂð©ð┤ð░ÐÄÐëð©Ðà ð▓Ðïð┤ð░Ðçð© Ðüð║ð©ð╗ð¥ð▓.'; -- 2019-03-11 01:26:02 <file_sep>/java/game/tera/gameserver/model/quests/classes/LevelUpQuest.java package tera.gameserver.model.quests.classes; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.listeners.LevelUpListener; import tera.gameserver.model.listeners.PlayerSpawnListener; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.QuestEvent; import tera.gameserver.model.quests.QuestList; import tera.gameserver.model.quests.QuestType; import tera.util.LocalObjects; /** * Модель квеста, который автоматически выдается при достижении определенного уровня. * * @author Ronn */ public class LevelUpQuest extends AbstractQuest implements LevelUpListener, PlayerSpawnListener { /** стартовый уровень */ private int startLevel; /** предыдущий квест */ private int prev; public LevelUpQuest(QuestType type, Node node) { super(type, node); VarTable vars = VarTable.newInstance(node); // получаем стартовый уровень this.startLevel = vars.getInteger("startLevel", -1); this.prev = vars.getInteger("prev", 0); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // добавляемся на праслушку лвл апов eventManager.addLevelUpListener(this); // добавляемся на прослушку спавнов eventManager.addPlayerSpawnListener(this); } @Override public void onLevelUp(Player player) { // если игрока нет, выходим if(player == null || player.getLevel() < startLevel) return; // получаем квест лист игрока QuestList questList = player.getQuestList(); // если его нет илоб этот квест уже выполнен/активен, то выходим if(questList == null || questList.isCompleted(this) || questList.getQuestState(this) != null) return; // если требуется предыдущий квест, а он не выполнен, выходим if(prev != 0 && !questList.isCompleted(prev)) return; // получаем локальные объекты LocalObjects local = LocalObjects.get(); // вынимаем с него ивент QuestEvent event = local.getNextQuestEvent(); // запоминаем игрока event.setPlayer(player); // запоминаем квест event.setQuest(this); // запускаем квест start(event); } @Override public void onSpawn(Player player) { onLevelUp(player); } } <file_sep>/java/game/tera/gameserver/model/base/Sex.java package tera.gameserver.model.base; /** * Класс с типами полов * * @author Ronn */ public enum Sex { MALE, FEMALE; public static Sex valueOf(int index) { return values()[index]; } /** список всех полов */ public static final Sex[] VALUES = values(); /** кол-во всех полов */ public static final int SIZE = VALUES.length; } <file_sep>/java/game/tera/gameserver/document/DocumentPlayer.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.base.PlayerClass; import tera.gameserver.model.base.Race; import tera.gameserver.model.base.Sex; import tera.gameserver.model.skillengine.funcs.Func; import tera.gameserver.parser.FuncParser; import tera.gameserver.tables.ItemTable; import tera.gameserver.tables.SkillTable; import tera.gameserver.templates.ItemTemplate; import tera.gameserver.templates.PlayerTemplate; import tera.gameserver.templates.SkillTemplate; /** * Парсер темплейтов игроков с xml. * * @author Ronn * @created 16.03.2012 */ public final class DocumentPlayer extends AbstractDocument<Array<PlayerTemplate>> { /** * @param file отпрасиваемый фаил. */ public DocumentPlayer(File file) { super(file); } @Override protected Array<PlayerTemplate> create() { return Arrays.toArray(PlayerTemplate.class); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node template = list.getFirstChild(); template != null; template = template.getNextSibling()) if("template".equals(template.getNodeName())) parseTemplate(template); } /** * @param node данные с хмл. * @return набор функций. */ private final Func[] parseFuncs(Node node) { Array<Func> array = Arrays.toArray(Func.class); // получаем парсер функций FuncParser parser = FuncParser.getInstance(); // парсим функции parser.parse(node, array, file); // сжимаем список array.trimToSize(); return array.array(); } /** * @param node данные с хмл. * @return массив выдаваемых итемов. */ private final int[][] parseItems(Node node) { Array<int[]> items = Arrays.toArray(int[].class); // получаем таблицу итемов ItemTable itemTable = ItemTable.getInstance(); for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) if("item".equals(child.getNodeName())) { // получаем значения аргументов VarTable vars = VarTable.newInstance(child); int id = vars.getInteger("id"); int count = vars.getInteger("count"); // получаем if,kjy итема ItemTemplate template = itemTable.getItem(id); // если такого итема на сервере нет, пропускаем if(template == null) continue; // вносим итем items.add(Arrays.toIntegerArray(id, count)); } // сжимаем массив items.trimToSize(); // возвращаем return items.array(); } /** * @param node данные с хмл. * @return массив скилов. */ private final Array<SkillTemplate[]> parseSkills(Node node) { Array<SkillTemplate[]> skills = Arrays.toArray(SkillTemplate[].class, 2); // получаем таблицу скилов SkillTable skillTable = SkillTable.getInstance(); for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) if("skill".equals(child.getNodeName())) { // получаем значения аргументов VarTable vars = VarTable.newInstance(child); int id = vars.getInteger("id"); int classId = vars.getInteger("class"); // получаем темплейт скила SkillTemplate[] template = skillTable.getSkills(classId, id); // если такой есть if(template != null) // вносим skills.add(template); } return skills; } /** * @param node данные с хмл. * @param playerClass класс игрока. * @return массив скиллов. */ private final SkillTemplate[][] parseSkills(Node node, PlayerClass playerClass) { Array<SkillTemplate[]> skills = Arrays.toArray(SkillTemplate[].class, 2); // получаем таблицу скилов SkillTable skillTable = SkillTable.getInstance(); for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) if("skill".equals(child.getNodeName())) { // получаем значения аргументов VarTable vars = VarTable.newInstance(child); // получаем ид скила int id = vars.getInteger("id"); // получаем темплейт скила SkillTemplate[] template = skillTable.getSkills(playerClass.getId(), id); // если такой есть if(template != null) // вносим skills.add(template); } // сжимаем список skills.trimToSize(); // возвращаем массив return skills.array(); } /** * @param node данные с хмл. */ private final void parseTemplate(Node node) { VarTable vars = VarTable.newInstance(node); // получаем класс игрока PlayerClass pclass = vars.getEnum("class", PlayerClass.class); VarTable set = null; int[][] items = null; SkillTemplate[][] skills = null; Func[] funcs = new Func[0]; for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if(child.getNodeType() != Node.ELEMENT_NODE) continue; else if("stats".equals(child.getNodeName())) set = VarTable.newInstance(child, "stat", "name", "val"); else if("funcs".equals(child.getNodeName())) funcs = parseFuncs(child); else if("items".equals(child.getNodeName())) items = parseItems(child); else if("skills".equals(child.getNodeName())) skills = parseSkills(child, pclass); else if("races".equals(child.getNodeName())) parseTemplate(child, set, funcs, pclass, items, skills); } } /** * @param node данные с хмл. * @param stats таблица параметров. * @param funcs набор функций. * @param playerClass класс игрока. * @param items массив итемов. * @param skills массив скилов. */ private final void parseTemplate(Node node, VarTable stats, Func[] funcs, PlayerClass playerClass, int[][] items, SkillTemplate[][] skills) { for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) if("race".equals(child.getNodeName())) { // парсим атрибуты VarTable vars = VarTable.newInstance(child); // получаем расу Race race = vars.getEnum("type", Race.class); // контейнер скилов Array<SkillTemplate[]> skillList = null; // парсим рассовые скилы for(Node temp = child.getFirstChild(); temp != null; temp = temp.getNextSibling()) if("skills".equals(temp.getNodeName())) skillList = parseSkills(temp); // вносим классовые скилы for(SkillTemplate[] skill : skills) skillList.add(skill); // сжимаем массив skillList.trimToSize(); int modelId = vars.getInteger("male", -1); if(modelId != -1) result.add(new PlayerTemplate(stats, funcs, playerClass, race, Sex.MALE, modelId, items, skillList.array())); modelId = vars.getInteger("female", -1); if(modelId != -1) result.add(new PlayerTemplate(stats, funcs, playerClass, race, Sex.FEMALE, modelId, items, skillList.array())); } } } <file_sep>/java/game/tera/gameserver/tables/SpawnTable.java package tera.gameserver.tables; import java.io.File; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Files; import rlib.util.array.Array; import rlib.util.array.Arrays; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.Config; import tera.gameserver.document.DocumentNpcSpawn; import tera.gameserver.document.DocumentResourseSpawn; import tera.gameserver.model.npc.spawn.NpcSpawn; import tera.gameserver.model.npc.spawn.Spawn; import tera.gameserver.model.resourse.ResourseSpawn; import tera.util.Location; /** * Таблица спавнов НПС и ресурсов. * * @author Ronn */ public final class SpawnTable { private static final Logger log = Loggers.getLogger(SpawnTable.class); private static SpawnTable instance; public static SpawnTable getInstance() { if(instance == null) instance = new SpawnTable(); return instance; } /** таблица спавнов нпс */ private Table<IntKey, Table<IntKey, Array<Spawn>>> npcSpawnTable; /** таблица спавнов ресурсов */ private Table<IntKey, Array<ResourseSpawn>> resourseSpawnTable; private SpawnTable() { npcSpawnTable = Tables.newIntegerTable(); resourseSpawnTable = Tables.newIntegerTable(); int counterNpc = 0; int counterResourses = 0; // получаем все нужные нам хмлки File[] files = Files.getFiles(new File(Config.SERVER_DIR + "/data/spawns")); // перебираем for(File file : files) { if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file.getAbsolutePath()); continue; } if(file.getName().startsWith("example")) continue; // парсим спавны НПС Array<Spawn> spawnsNpc = new DocumentNpcSpawn(file).parse(); // плюсуем к счетчику counterNpc += spawnsNpc.size(); // перебираем спавны for(Spawn spawn : spawnsNpc) { // получаем под-таблицу спавнов нпс Table<IntKey, Array<Spawn>> table = npcSpawnTable.get(spawn.getTemplateId()); // если ее нет if(table == null) { // создаем новую table = Tables.newIntegerTable(); // вставялем npcSpawnTable.put(spawn.getTemplateId(), table); } // получаем список спавнов этого НПС Array<Spawn> array = table.get(spawn.getTemplateType()); // если списка нет if(array == null) { // создаем новый array = Arrays.toArray(Spawn.class); // вставляем table.put(spawn.getTemplateType(), array); } // добавляем спавн array.add(spawn); } // парсим спавны ресурсов Array<ResourseSpawn> spawnsResourses = new DocumentResourseSpawn(file).parse(); // плюсуем к счетчику counterResourses += spawnsResourses.size(); // перебираем спавны ресурсов for(ResourseSpawn spawn : spawnsResourses) { // получаем список спавнов этого ресурса Array<ResourseSpawn> spawns = resourseSpawnTable.get(spawn.getTemplateId()); // если списка нет if(spawns == null) { // создаем новый spawns = Arrays.toArray(ResourseSpawn.class); // вставляем в таблицу resourseSpawnTable.put(spawn.getTemplateId(), spawns); } // добавляем в список spawns.add(spawn); } } // сжимаем все списки спавнов нпс for(Table<IntKey, Array<Spawn>> table : npcSpawnTable) for(Array<Spawn> spawns : table) spawns.trimToSize(); for(Array<ResourseSpawn> spawns : resourseSpawnTable) spawns.trimToSize(); startSpawns(); log.info("loaded " + counterNpc + " spawns for " + npcSpawnTable.size() + " npcs and " + counterResourses + " spawns for " + resourseSpawnTable.size() + " resourses."); } /** * Получение точки спавна нужного НПС. * * @param templateId ид шаблона НПС. * @param templateType тип шаблона НПС. * @return точка спавна. */ public Location getNpcSpawnLoc(int templateId, int templateType) { // получаем подтаблицу спавнов Table<IntKey, Array<Spawn>> table = npcSpawnTable.get(templateId); // если ее нет, выходим if(table == null) return null; // получаем список спавнов нужных НПС Array<Spawn> spawns = table.get(templateType); // если таких нет, выходим if(spawns == null || spawns.isEmpty()) return null; // получаем первый спавн Spawn spawn = spawns.first(); // если это актуальный спавн if(spawn instanceof NpcSpawn) { // кастим его NpcSpawn npcSpawn = (NpcSpawn) spawn; // извлекаем точку спавна return npcSpawn.getLocation(); } return null; } /** * Перезагрузка таблицы спавнов. */ public synchronized void reload() { stopSpawns(); npcSpawnTable.clear(); resourseSpawnTable.clear(); // получаем все нужные нам хмлки File[] files = Files.getFiles(new File(Config.SERVER_DIR + "/data/spawns")); // перебираем for(File file : files) { if(!file.getName().endsWith(".xml")) { log.warning("detected once the file " + file.getAbsolutePath()); continue; } if(file.getName().startsWith("example")) continue; // парсим спавны НПС Array<Spawn> spawnsNpc = new DocumentNpcSpawn(file).parse(); // перебираем спавны for(Spawn spawn : spawnsNpc) { // получаем под-таблицу спавнов нпс Table<IntKey, Array<Spawn>> table = npcSpawnTable.get(spawn.getTemplateId()); // если ее нет if(table == null) { // создаем новую table = Tables.newIntegerTable(); // вставялем npcSpawnTable.put(spawn.getTemplateId(), table); } // получаем список спавнов этого НПС Array<Spawn> array = table.get(spawn.getTemplateType()); // если списка нет if(array == null) { // создаем новый array = Arrays.toArray(Spawn.class); // вставляем table.put(spawn.getTemplateType(), array); } // добавляем спавн array.add(spawn); } // парсим спавны ресурсов Array<ResourseSpawn> spawnsResourses = new DocumentResourseSpawn(file).parse(); // перебираем спавны ресурсов for(ResourseSpawn spawn : spawnsResourses) { // получаем список спавнов этого ресурса Array<ResourseSpawn> spawns = resourseSpawnTable.get(spawn.getTemplateId()); // если списка нет if(spawns == null) { // создаем новый spawns = Arrays.toArray(ResourseSpawn.class); // вставляем в таблицу resourseSpawnTable.put(spawn.getTemplateId(), spawns); } // добавляем в список spawns.add(spawn); } } // сжимаем все списки спавнов нпс for(Table<IntKey, Array<Spawn>> table : npcSpawnTable) for(Array<Spawn> spawns : table) spawns.trimToSize(); for(Array<ResourseSpawn> spawns : resourseSpawnTable) spawns.trimToSize(); startSpawns(); log.info("reloaded."); } /** * Запуск спавна всех нпс. */ public void startSpawns() { for(Table<IntKey, Array<Spawn>> table : npcSpawnTable) for(Array<Spawn> spawns : table) for(Spawn spawn : spawns) spawn.start(); for(Array<ResourseSpawn> spawns : resourseSpawnTable) for(ResourseSpawn spawn : spawns) spawn.start(); } /** * Остановка и деспавн всех нпс. */ public void stopSpawns() { for(Table<IntKey, Array<Spawn>> table : npcSpawnTable) for(Array<Spawn> spawns : table) for(Spawn spawn : spawns) spawn.stop(); for(Array<ResourseSpawn> spawns : resourseSpawnTable) for(ResourseSpawn spawn : spawns) spawn.stop(); } }<file_sep>/java/game/tera/gameserver/model/dungeons/DungeonList.java package tera.gameserver.model.dungeons; import rlib.data.DocumentXML; import rlib.logging.Logger; import rlib.logging.Loggers; import tera.Config; import tera.gameserver.config.MissingConfig; import tera.gameserver.document.DocumentDungeon; import java.io.File; import java.util.ArrayList; import java.util.List; public class DungeonList implements Dungeon { private static final Logger log = Loggers.getLogger(DungeonList.class); private static List<DungeonList> list = new ArrayList<>(); private int dungeonId; private int dungeonMaxLevel; private int dungeonMinLevel; private int minItemLevel; private String name; public DungeonList() { list.add(this); } public static void init() { DocumentXML<Void> document = new DocumentDungeon(new File(Config.SERVER_DIR + "/data/dungeons.xml")); document.parse(); log.info("Dungeon list initialized."); } public void setDungeonId(int dungeonId) { this.dungeonId = dungeonId; } public void setDungeonMaxLevel(int dungeonMaxLevel) { this.dungeonMaxLevel = dungeonMaxLevel; } public void setDungeonMinLevel(int dungeonMinLevel) { this.dungeonMinLevel = dungeonMinLevel; } public void setMinItemLevel(int minItemLevel) { this.minItemLevel = minItemLevel; } public void setName(String name) { this.name = name; } public int getDungeonId() { return dungeonId; } public int getDungeonMaxLevel() { return dungeonMaxLevel; } public int getDungeonMinLevel() { return dungeonMinLevel; } public int getMinItemLevel() { return minItemLevel; } public String getName() { return name; } public static List<DungeonList> getDungeonAvailableTroughtLevel(int level) { List<DungeonList> dungeons = new ArrayList<>(); for(DungeonList dungeon : list) { if(level + MissingConfig.LEVEL_RANGE_DUNGEON >= dungeon.getDungeonMinLevel() && level < dungeon.getDungeonMaxLevel()) dungeons.add(dungeon); } return dungeons; } public static DungeonList getDungeon(int dungeonId) { DungeonList dungeon = null; for(int i = 0; i < list.size(); i++){ if(list.get(i).getDungeonId() == dungeonId) { dungeon = list.get(i); break; } } return dungeon; } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/dialogs/Dialog.java package tera.gameserver.model.npc.interaction.dialogs; import rlib.util.pools.Foldable; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; /** * Интерфейс для реализации диалога с НПС. * * @author Ronn * @created 12.04.2012 */ public interface Dialog extends Foldable { /** * Применить изминения в окне. * * @return произошли ли изминения. */ public boolean apply(); /** * Закрыть окно. * * @return произошли ли изминения. */ public boolean close(); /** * @return нпс у которого было начат диалог. */ public Npc getNpc(); /** * @return игрок, который говорит с нпс. */ public Player getPlayer(); /** * @return тип диалогового окна */ public DialogType getType(); /** * Инициализация окна. * * @return успешно ли инициализировалось. */ public boolean init(); } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Collection_Pickend.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.model.Character; import tera.gameserver.model.playable.Player; import tera.gameserver.model.resourse.ResourseInstance; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет со стартом сбора ресурсов. * * @author Ronn */ public class S_Collection_Pickend extends ServerPacket { private static final ServerPacket instance = new S_Collection_Pickend(); /** сбор был успешен */ public static final int SUCCESSFUL = 3; /** сбор был просран */ public static final int FAILED = 2; /** сбор был прерван */ public static final int INTERRUPTED = 0; public static S_Collection_Pickend getInstance(Character collector, ResourseInstance resourse, int result) { S_Collection_Pickend packet = (S_Collection_Pickend) instance.newInstance(); packet.collectorId = collector.getObjectId(); packet.collectorSubId = collector.getSubId(); packet.resourseId = resourse.getObjectId(); packet.resourseSubId = resourse.getSubId(); packet.result = result; packet.fatigability = ((Player) collector).getAccount().getFatigability(); return packet; } /** обджект ид сборщика */ private int collectorId; /** саб ид сборщика */ private int collectorSubId; /** обджект ид ресурса */ private int resourseId; /** саб ид ресурса */ private int resourseSubId; /** результат */ private int result; private int fatigability; @Override public ServerPacketType getPacketType() { return ServerPacketType.S_COLLECTION_PICKEND; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, collectorId);//AA 6C 0D 00 //обжект ид кто собирает writeInt(buffer, collectorSubId);//00 80 00 01 //саб ид того кто собирает writeInt(buffer, resourseId);//3B 95 07 00 //обжект ид растения writeInt(buffer, resourseSubId);//00 80 04 00 //саб ид растение writeInt(buffer, result);//03 00 00 00 writeInt(buffer, fatigability); } } <file_sep>/java/game/tera/gameserver/model/npc/summons/PlayerSummon.java package tera.gameserver.model.npc.summons; import tera.gameserver.network.serverpackets.S_Change_Relation; import tera.gameserver.templates.NpcTemplate; /** * Модель сумона игрока на основе игрокоподобных суммонов. * * @author Ronn */ public class PlayerSummon extends PlayableSummon { public PlayerSummon(int objectId, NpcTemplate template) { super(objectId, template); } @Override public int getNameColor() { return S_Change_Relation.COLOR_LIGHT_BLUE; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Instant_Move.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.playable.Player; import tera.gameserver.network.ServerPacketType; /** * @author <NAME> */ public class S_Instant_Move extends ServerPacket { private static final ServerPacket instance = new S_Instant_Move(); private static Player player; private static float targetX; private static float targetY; private static float targetZ; private static int heading; public static ServerPacket getInstance(Player p,float x,float y,float z,int h) { player = p; targetX = x; targetY = y; targetZ = z; heading = h; return instance.newInstance(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_INSTANT_MOVE; } @Override protected void writeImpl() { writeOpcode(); writeInt(player.getObjectId()); writeInt(player.getSubId()); writeFloat(targetX); //A5A88E47 writeFloat(targetY); //51818EC7 writeFloat(targetZ); //80039AC4 writeShort(heading); //0020 } }<file_sep>/java/game/tera/gameserver/network/serverpackets/SkillLeash.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import tera.gameserver.network.ServerPacketType; /** * Пакет с результатом использования удочки танка. * * @author Ronn */ public class SkillLeash extends ServerPacket { private static final ServerPacket instance = new SkillLeash(); public static SkillLeash getInstance(int casterId, int casterSubId, int targetId, int targetSubId, boolean resut) { SkillLeash packet = (SkillLeash) instance.newInstance(); packet.casterId = casterId; packet.casterSubId = casterSubId; packet.targetId = targetId; packet.targetSubId = targetSubId; packet.resut = resut; return packet; } /** тот кто кинул */ private int casterId; private int casterSubId; /** на кого кинул */ private int targetId; private int targetSubId; /** удачно ли */ private boolean resut; @Override public ServerPacketType getPacketType() { return ServerPacketType.SKILL_LEASH; } @Override public boolean isSynchronized() { return false; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); writeInt(buffer, casterId);//7C 65 0D 00 writeInt(buffer, casterSubId);//00 80 00 01 writeInt(buffer, targetId);///38 96 0C 00 writeInt(buffer, targetSubId);//00 80 0B 00 writeShort(buffer, resut? 1 : 0);//01 00 } } <file_sep>/java/game/tera/gameserver/document/DocumentNpcSpawn.java package tera.gameserver.document; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Node; import rlib.data.AbstractDocument; import rlib.util.VarTable; import rlib.util.array.Array; import rlib.util.array.Arrays; import tera.gameserver.model.ai.npc.ConfigAI; import tera.gameserver.model.ai.npc.NpcAIClass; import tera.gameserver.model.npc.NpcType; import tera.gameserver.model.npc.spawn.Spawn; import tera.gameserver.tables.ConfigAITable; import tera.gameserver.tables.NpcTable; import tera.gameserver.templates.NpcTemplate; import tera.util.Location; /** * Парсер спавнов нпс с xml. * * @author Ronn * @created 16.03.2012 */ public final class DocumentNpcSpawn extends AbstractDocument<Array<Spawn>> { /** * @param file отпрасиваемый фаил. */ public DocumentNpcSpawn(File file) { super(file); } @Override protected Array<Spawn> create() { return result = Arrays.toArray(Spawn.class); } @Override protected void parse(Document doc) { for(Node list = doc.getFirstChild(); list != null; list = list.getNextSibling()) if("list".equals(list.getNodeName())) for(Node node = list.getFirstChild(); node != null; node = node.getNextSibling()) if("npc".equals(node.getNodeName())) parseSpawns(node); } /** * @param node данные с хмл. * @param template темплейт нпс. * @param continentId ид континента. */ private final void parseAiSpawns(Node node, NpcTemplate template, int continentId) { // получаем атрибуты спавна VarTable vars = VarTable.newInstance(node); // получаем таблицу конфигов АИ ConfigAITable configTable = ConfigAITable.getInstance(); // получаем класс АИ NpcAIClass aiClass = vars.getEnum("class", NpcAIClass.class); // получаем конфиг АИ ConfigAI config = configTable.getConfig(vars.getString("config")); if(config == null) { log.warning(this, "not found config AI " + vars.getString("config") + " in file " + file); return; } // парсим сами спавны for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if(child.getNodeType() != Node.ELEMENT_NODE) continue; if("time".equals(child.getNodeName())) parseTimeSpawns(child, template, aiClass, config, continentId); } } /** * @param node узел данных с хмл. */ private final void parseSpawns(Node node) { // получаем атрибуты спавна VarTable vars = VarTable.newInstance(node); // получаем нпс ид спавна int npcId = vars.getInteger("id"); int type = vars.getInteger("type"); int continentId = vars.getInteger("continentId", 0); // получаем таблицу НПС NpcTable npcTable = NpcTable.getInstance(); // получаем темплейт нпс NpcTemplate template = npcTable.getTemplate(npcId, type); // если его нет, выходим if(template == null) { log.warning(this, new Exception("not found npc template for id " + npcId + ", type " + type)); return; } // перебираем внутренние элементы в поисках АИ for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) if(child.getNodeType() == Node.ELEMENT_NODE && "ai".equals(child.getNodeName())) parseAiSpawns(child, template, continentId); } /** * @param node данные с хмл. * @param template темплейт нпс. * @param aiClass тип аи. * @param continentId ид континента. * @param config конфиг аи. * @param respawn время респавна. * @param randomRespawn рандоминайзер респавна. */ private final void parseSpawns(Node node, NpcTemplate template, NpcAIClass aiClass, ConfigAI config, int continentId, int respawn, int randomRespawn) { // получаем атрибуты спавна VarTable vars = VarTable.newInstance(node); // получаем координаты спавна float x = vars.getFloat("x"); float y = vars.getFloat("y"); float z = vars.getFloat("z"); // получаем разворот нпс int heading = vars.getInteger("heading", -1); // получаем минимальный радиус спавна от тояки int min = vars.getInteger("min", 0); // получаем максимальный радиус спавна от точки int max = vars.getInteger("max", 0); // получаем тип НПС NpcType type = template.getNpcType(); // добавляем в массив спавнов новый спавн result.add(type.newSpawn(node, vars, template, new Location(x, y, z, heading, continentId), respawn, randomRespawn, min, max, config, aiClass)); } /** * @param node параметры с хмл. * @param template темплейт нпс. * @param aiClass класс аи. * @param config конфиг АИ. * @param continentId ид континента. */ private final void parseTimeSpawns(Node node, NpcTemplate template, NpcAIClass aiClass, ConfigAI config, int continentId) { // получаем таблицу атрибутов VarTable vars = VarTable.newInstance(node); // получаем время респа int respawn = vars.getInteger("respawn", -1); // рандомная прибавка к респу int random = vars.getInteger("random", -1); for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if(child.getNodeType() != Node.ELEMENT_NODE) continue; if("point".equals(child.getNodeName())) parseSpawns(child, template, aiClass, config, continentId, respawn, random); } } } <file_sep>/java/game/tera/remotecontrol/HandlerManager.java package tera.remotecontrol; import tera.remotecontrol.handlers.AddPlayerItemHandler; import tera.remotecontrol.handlers.AnnounceApplyHandler; import tera.remotecontrol.handlers.AnnounceLoadHandler; import tera.remotecontrol.handlers.AuthHandler; import tera.remotecontrol.handlers.CancelShutdownHandler; import tera.remotecontrol.handlers.DynamicInfoHandler; import tera.remotecontrol.handlers.GameInfoHandler; import tera.remotecontrol.handlers.GetAccountHandler; import tera.remotecontrol.handlers.LoadChatHandler; import tera.remotecontrol.handlers.PlayerMessageHandler; import tera.remotecontrol.handlers.RemovePlayerItemHandler; import tera.remotecontrol.handlers.SavePlayersHandler; import tera.remotecontrol.handlers.SendAnnounceHandler; import tera.remotecontrol.handlers.ServerConsoleHandler; import tera.remotecontrol.handlers.ServerRestartHandler; import tera.remotecontrol.handlers.ServerStatusHandler; import tera.remotecontrol.handlers.SetAccountHandler; import tera.remotecontrol.handlers.StartGCHandler; import tera.remotecontrol.handlers.StartRestartHandler; import tera.remotecontrol.handlers.StartShutdownHandler; import tera.remotecontrol.handlers.StaticInfoHandler; import tera.remotecontrol.handlers.UpdateAccountHandler; import tera.remotecontrol.handlers.UpdateEquipmentItemsHandler; import tera.remotecontrol.handlers.UpdateInventoryItemsHandler; import tera.remotecontrol.handlers.UpdatePlayerInfoHandler; import tera.remotecontrol.handlers.UpdatePlayerItemHandler; import tera.remotecontrol.handlers.UpdatePlayerMainInfoHandler; import tera.remotecontrol.handlers.UpdatePlayerStatInfoHandler; import tera.remotecontrol.handlers.UpdatePlayersHandler; /** * Хранилище хандлеров для пакетов * * @author Ronn * @created 26.03.2012 */ public abstract class HandlerManager { /** * список хандлеров */ private static final PacketHandler[] handlers = { new AuthHandler(), null, new ServerStatusHandler(), null, new AnnounceLoadHandler(), null, new AnnounceApplyHandler(), new SendAnnounceHandler(), new LoadChatHandler(), null, new PlayerMessageHandler(), new UpdatePlayersHandler(), null, new UpdatePlayerInfoHandler(), null, new StaticInfoHandler(), new DynamicInfoHandler(), new GameInfoHandler(), null, null, null, new ServerRestartHandler(), ServerConsoleHandler.instance, SavePlayersHandler.instance, StartGCHandler.instance, StartRestartHandler.instance, StartShutdownHandler.instance, CancelShutdownHandler.instance, LoadChatHandler.instance, UpdatePlayersHandler.instance, UpdatePlayerMainInfoHandler.instance, UpdatePlayerStatInfoHandler.instance, UpdateInventoryItemsHandler.instance, UpdateEquipmentItemsHandler.instance, null, UpdatePlayerItemHandler.instance, RemovePlayerItemHandler.instance, AddPlayerItemHandler.instance, GetAccountHandler.instance, SetAccountHandler.instance, UpdateAccountHandler.instance, }; /** * @param type тип пакета. * @return обработчик такого типа пакета. */ public static PacketHandler getHandler(PacketType type) { if(!ServerControl.authed && type != PacketType.AUTH) return null; return handlers[type.ordinal()]; } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/CancelOwerturn.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.templates.SkillTemplate; /** * Модель скила, служащего только для активирования бафа. * * @author Ronn */ public class CancelOwerturn extends Buff { /** * @param template темплейт скила. */ public CancelOwerturn(SkillTemplate template) { super(template); } @Override public AttackInfo applySkill(Character attacker, Character target) { if(target.isOwerturned()) target.cancelOwerturn(); return super.applySkill(attacker, target); } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/dialogs/GuildBankDialog.java package tera.gameserver.model.npc.interaction.dialogs; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.Guild; import tera.gameserver.model.GuildRank; import tera.gameserver.model.MessageType; import tera.gameserver.model.inventory.Bank; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.PlayerBankPanel; /** * Модель окна банка гильдии. * * @author Ronn */ public final class GuildBankDialog extends AbstractDialog implements BankDialog { /** * @param npc нпс. * @param player игрок. * @return новый диалог. */ public static final GuildBankDialog newInstance(Npc npc, Player player) { GuildBankDialog dialog = (GuildBankDialog) DialogType.GUILD_BANK.newInstance(); dialog.npc = npc; dialog.player = player; dialog.startCell = 0; return dialog; } /** стартовая ячейка */ private int startCell; @Override public synchronized void addItem(int index, int itemId, int count) { // если что-то не то ,выходим if(index < 0 || count < 1) return; // получаем игрока Player player = getPlayer(); // если игрока нет ,выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // получаем гильдию игрока Guild guild = player.getGuild(); // если ее нет, выходим if(guild == null) { player.sendMessage(MessageType.YOU_NOT_IN_GUILD); return; } // получаем инвентарь Inventory inventory = player.getInventory(); // получаем банк Bank bank = guild.getBank(); // если чего-то из этого нет, выходим if(bank == null || inventory == null) { log.warning(this, new Exception("not found bank or inventory")); return; } // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); inventory.lock(); try { // получаем ячейку, в котором лежит нужный итем Cell cell = inventory.getCell(index); // если ячейка пуста, выходим if(cell == null || cell.isEmpty()) return; // если кол-ва не хватает, выходим if(cell.getItemCount() < count) return; // получаем итем с ячейки ItemInstance item = cell.getItem(); // если его нет, что-то здесь не то о_О if(item == null) { log.warning(this , new Exception("not found item")); return; } // если итем нельзя ложить в банк, выходим if(!item.isBank()) { player.sendMessage(MessageType.THAT_ITEM_CANTT_BE_STORED_IN_THE_BANK); return; } // если не стакуемый if(!item.isStackable()) { // пробуем перенести if(bank.putItem(item)) // если перенесли, удаляем из инвенторя inventory.removeItem(item); // обновляем банк игроку eventManager.notifyGuildBankChanged(player, startCell); // обновляем инвентарь eventManager.notifyInventoryChanged(player); return; } // добавляем в банк if(bank.addItem(itemId, count)) { // удаляем итем из инвенторя inventory.removeItem(itemId, (long) count); // обновляем банк игроку eventManager.notifyGuildBankChanged(player, startCell); // обновляем инвентарь eventManager.notifyInventoryChanged(player); } } finally { inventory.unlock(); } } @Override public synchronized void addMoney(int money) { // если денег нет, выходим if(money < 1) return; // получаем игрока Player player = getPlayer(); // если игрока нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // получаем гильдию игрока Guild guild = player.getGuild(); // если ее нет, выходим if(guild == null) { player.sendMessage(MessageType.YOU_NOT_IN_GUILD); return; } // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем инвентарь Inventory inventory = player.getInventory(); // получаем банк игрока Bank bank = guild.getBank(); // если инвенторя или банка нет ,выходим if(inventory == null || bank == null) { log.warning(this, new Exception("not found bank or inventory")); return; } inventory.lock(); try { // если в инвенторе столько нет, выходим if(inventory.getMoney() < money) return; // забираем деньги inventory.subMoney(money); // ложим деньги bank.addMoney(money); // обновляем банк игроку eventManager.notifyGuildBankChanged(player, startCell); // обновляем инвентарь eventManager.notifyInventoryChanged(player); } finally { inventory.unlock(); } } @Override public synchronized boolean apply() { return false; } @Override public synchronized void getItem(int index, int itemId, int count) { index += startCell; // если что-то не то ,выходим if(index < 0 || count < 1) return; // получаем игрока Player player = getPlayer(); // если игрока нет ,выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // получаем гильдию игрока Guild guild = player.getGuild(); // если ее нет, выходим if(guild == null) { player.sendMessage(MessageType.YOU_NOT_IN_GUILD); return; } // получаем ранг в гильдии GuildRank rank = player.getGuildRank(); // если нет прав, выходим if(!rank.isAccessBank()) { player.sendMessage("У вас нет прав."); return; } // получаем инвентарь Inventory inventory = player.getInventory(); // получаем банк Bank bank = guild.getBank(); // если чего-то из этого нет, выходим if(bank == null || inventory == null) { log.warning(this, new Exception("not found bank or inventory")); return; } // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); bank.lock(); try { // получаем ячейку, в котором лежит нужный итем Cell cell = bank.getCell(index); // если ячейка пуста, выходим if(cell == null || cell.isEmpty()) return; // если кол-ва не хватает, выходим if(cell.getItemCount() < count) return; // получаем итем с ячейки ItemInstance item = cell.getItem(); // если его нет, что-то здесь не то о_О if(item == null) { log.warning(this , new Exception("not found item")); return; } // если не стакуемый if(!item.isStackable()) { // пробуем перенести if(!inventory.putItem(item)) player.sendMessage(MessageType.INVENTORY_IS_FULL); else { // если перенесли, удаляем из инвенторя bank.removeItem(item); // обновляем банк игроку eventManager.notifyGuildBankChanged(player, startCell); // обновляем инвентарь eventManager.notifyInventoryChanged(player); } return; } // добавляем в инвентарь if(!inventory.addItem(itemId, count, "Bank")) player.sendMessage(MessageType.INVENTORY_IS_FULL); else { // удаляем итем из банка bank.removeItem(itemId, count); // обновляем банк игроку eventManager.notifyGuildBankChanged(player, startCell); // обновляем инвентарь eventManager.notifyInventoryChanged(player); } } finally { bank.unlock(); } } @Override public synchronized void getMoney(int money) { // если денег нет, выходим if(money < 1) return; // получаем игрока Player player = getPlayer(); // если игрока нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // получаем гильдию игрока Guild guild = player.getGuild(); // если ее нет, выходим if(guild == null) { player.sendMessage(MessageType.YOU_NOT_IN_GUILD); return; } // получаем ранг в гильдии GuildRank rank = player.getGuildRank(); // если нет прав, выходим if(!rank.isAccessBank()) { player.sendMessage("У вас нет прав."); return; } // получаем инвентарь Inventory inventory = player.getInventory(); // получаем банк игрока Bank bank = guild.getBank(); // если инвенторя или банка нет ,выходим if(inventory == null || bank == null) { log.warning(this, new Exception("not found bank or inventory")); return; } // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); inventory.lock(); try { // если в банке столько нет, выходим if(bank.getMoney() < money) return; // забираем деньги bank.subMoney(money); // ложим деньги inventory.addMoney(money); // обновляем банк игроку eventManager.notifyGuildBankChanged(player, startCell); // обновляем инвентарь eventManager.notifyInventoryChanged(player); } finally { inventory.unlock(); } } @Override public DialogType getType() { return DialogType.GUILD_BANK; } @Override public synchronized boolean init() { if(!super.init()) return false; // получаем игрока Player player = getPlayer(); // если его нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return false; } // отправляем player.sendPacket(PlayerBankPanel.getInstance(player), true); // отправляем пакет банка PacketManager.updateGuildBank(player, startCell); return true; } @Override public void movingItem(int oldCell, int newCell) { oldCell += startCell; newCell += startCell; // получаем игрока Player player = getPlayer(); // если игрока нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // получаем гильдию игрока Guild guild = player.getGuild(); // если ее нет, выходим if(guild == null) { player.sendMessage(MessageType.YOU_NOT_IN_GUILD); return; } // получаем ранг в гильдии GuildRank rank = player.getGuildRank(); // если нет прав, выходим if(!rank.isAccessBank()) { player.sendMessage("У вас нет прав."); return; } // получаем банк игрока Bank bank = guild.getBank(); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // получаем менеджера БД DataBaseManager dbManager = DataBaseManager.getInstance(); bank.lock(); try { Cell start = bank.getCell(oldCell); Cell end = bank.getCell(newCell); if(start == null || end == null || start == end) return; ItemInstance oldItem = start.getItem(); start.setItem(end.getItem()); end.setItem(oldItem); // обновляем положение итемов в БД dbManager.updateLocationItem(end.getItem()); dbManager.updateLocationItem(start.getItem()); // обновляем банк игроку eventManager.notifyGuildBankChanged(player, startCell); } finally { bank.unlock(); } } @Override public void setStartCell(int startCell) { this.startCell = startCell; PacketManager.updateGuildBank(player, startCell); } @Override public void sort() { // получаем игрока Player player = getPlayer(); // если игрока нет, выходим if(player == null) { log.warning(this, new Exception("not found player")); return; } // получаем гильдию игрока Guild guild = player.getGuild(); // если ее нет, выходим if(guild == null) { player.sendMessage(MessageType.YOU_NOT_IN_GUILD); return; } // получаем ранг в гильдии GuildRank rank = player.getGuildRank(); // если нет прав, выходим if(!rank.isAccessBank()) { player.sendMessage("У вас нет прав."); return; } // получаем банк игрока Bank bank = guild.getBank(); // сортируем bank.sort(); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // обновляем eventManager.notifyGuildBankChanged(player, startCell); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Broadcast_Climbing.java package tera.gameserver.network.clientpackets; import tera.gameserver.model.playable.Player; /** * Клиентский пакет для указания положения во время лазания. * * @author Ronn */ public class C_Broadcast_Climbing extends ClientPacket { /** игрок */ private Player player; /** целевая точка */ private float targetX; private float targetY; private float targetZ; @Override public void finalyze() { player = null; } @Override public void readImpl() { player = owner.getOwner(); if(player == null) return; // целевая точка targetX = readFloat(); targetY = readFloat(); targetZ = readFloat(); } @Override public void runImpl() { if(player == null) return; player.setXYZ(targetX, targetY, targetZ); } @Override public String toString() { return "C_Broadcast_Climbing targetX = " + targetX + ", targetY = " + targetY + ", targetZ = " + targetZ; } }<file_sep>/java/game/tera/gameserver/model/Route.java package tera.gameserver.model; /** * Модель маршрута полета на пегасе. * * @author Ronn * @created 26.02.2012 */ public final class Route { /** целевой город */ private TownInfo target; /** код маршрута */ private int index; /** цена маршрута */ private int price; /** короткий ли перелет */ private boolean local; /** * @param index номер маршрута. * @param price цена маршрута. * @param target целевой город. * @param local является ли локальным. */ public Route(int index, int price, TownInfo target, boolean local) { this.index = index; this.price = price; this.target = target; this.local = local; } /** * @return индекс маршрута. */ public int getIndex() { return index; } /** * @return цена маршрута. */ public int getPrice() { return price; } /** * @return целевой город. */ public TownInfo getTarget() { return target; } /** * @return короткий ли перелет. */ public final boolean isLocal() { return local; } @Override public String toString() { return "Route index = " + index + ", price = " + price + ", target = " + target; } } <file_sep>/java/game/tera/gameserver/model/EmotionType.java package tera.gameserver.model; /** * Перечисление типом эмоций. * * @author Ronn */ public enum EmotionType { NULL, /** осмотреться, мбо */ INSPECTION, //1 /** быстро осмотреться, моб */ FAST_INSPECTION, //2 NONE3, //3 NULL4, //4 /** приветствие */ NONE5, //5 NULL6, //6 NULL7, //7 NULL8,//8 NULL9, //9 NULL10, //10 CHEMISTRY, //11 /** крафт */ SMITH, //12 /** шитье */ SEWS,//13 BOW,//14 NULL15, //15 /** приветсвие, игрок */ HELLO, //16 /** поклон, игрок */ BUW, //17 /** громкий смех, игрок */ LAUGHTER, //18 /** плач, игрок */ CRYING, //19 /** хвастаство, игрок */ BOASTING, //20 /** танец, игрок */ DANCE, //21 /** унылый, игрок */ DULL, //22 /** хлопание, игрок */ SLAM, //23 /** любовь, игрок */ I_LOVE_YOU, //24 /** задумчивость, игрок */ MUSE, //25 /** сердце */ HEART, //26 SHOW_ON_TERGET,//27 POINT_FINGER,//28 DISORDER,//29 FAIL,//30 INSPECT,//31 /** разминать кулаки, игрок */ KNEAD_FISTS,//32 /** попрыгивание, игрок */ BUMPING, //33 /** разговор, игрок */ TALK, //34 /** рассказ, игрок */ EXPLANATION, //35 /** рассказ, игрок */ EXPLANATION_2, //36 /** каст, игрок */ CAST, //37 /** сесть, игрок */ SIT_DOWN, //38 /** встать, игрок */ STAND_UP, //39 NONE11, //40 NONE12, //41 NONE13, //30 NONE14, //31 NONE15, //32 NONE16, //33 NONE17, //34 NONE18, //35 NONE19, //36 NONE20, //37 NONE21, //38 NONE22, //39 NONE23, //40 NONE24; //41 /** список эмоций */ public static EmotionType[] VALUES = values(); /** кол-во эмоций */ public static int SIZE = VALUES.length; /** * Получить тим эмоции по индексу. * * @param index тип эмоции. * @return тип эмоции. */ public static final EmotionType valueOf(int index) { if(index < 0 || index >= SIZE) return EmotionType.INSPECTION; return VALUES[index]; } } <file_sep>/java/game/tera/gameserver/model/skillengine/SkillGroup.java package tera.gameserver.model.skillengine; /** * Перечисление групп скилов. * * @author Ronn */ public enum SkillGroup { /** скил ближнего боя */ SHORT_ATTACK, /** скил дальнего боя */ LONG_ATTACK, /** скил супер ближнего боя */ SHORT_ULTIMATE, /** скил супер дальнего боя */ LONG_ULTIMATE, /** ловушка */ TRAP, /** щит */ SHIELD, /** прыжок */ JUMP, /** баф */ BUFF, /** дебаф */ DEBUFF, /** хил */ HEAL, /** неиспользуемый */ NONE; public static final SkillGroup[] values = values(); public static final int length = values.length; } <file_sep>/java/game/tera/remotecontrol/handlers/StartRestartHandler.java package tera.remotecontrol.handlers; import tera.gameserver.manager.ShutdownManager; import tera.remotecontrol.Packet; import tera.remotecontrol.PacketHandler; import tera.remotecontrol.PacketType; /** * Обработчик запроса на сохранение всех игроков. * * @author Ronn */ public class StartRestartHandler implements PacketHandler { public static final StartRestartHandler instance = new StartRestartHandler(); @Override public Packet processing(Packet packet) { ShutdownManager.restart(packet.nextLong()); return new Packet(PacketType.RESPONSE); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/S_Login_Arbiter.java package tera.gameserver.network.serverpackets; import tera.gameserver.network.ServerPacketType; public class S_Login_Arbiter extends ServerPacket { private static final ServerPacket instance = new S_Login_Arbiter(); private int language; public static ServerPacket getInstance(int language) { S_Login_Arbiter packet = (S_Login_Arbiter) instance.newInstance(); packet.language = language; return packet; } @Override public ServerPacketType getPacketType() { return ServerPacketType.S_LOGIN_ARBITER; } @Override protected void writeImpl() { writeOpcode(); writeByte(1);//success writeByte(0); writeShort(2); writeShort(1); writeInt(0); writeInt(language); writeByte(1);//pvp disable writeShort(0); writeShort(0); } } <file_sep>/java/game/tera/gameserver/model/quests/actions/ActionUpdateIntresting.java package tera.gameserver.model.quests.actions; import org.w3c.dom.Node; import rlib.util.VarTable; import rlib.util.array.Array; import tera.gameserver.model.World; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Condition; import tera.gameserver.model.playable.Player; import tera.gameserver.model.quests.Quest; import tera.gameserver.model.quests.QuestActionType; import tera.gameserver.model.quests.QuestEvent; import tera.util.LocalObjects; /** * Акшен обновления иконки над нпс для игрока. * * @author Ronn */ public class ActionUpdateIntresting extends AbstractQuestAction { /** ид нужного НПС */ private int npcId; /** тип нужного нпс */ private int npcType; public ActionUpdateIntresting(QuestActionType type, Quest quest, Condition condition, Node node) { super(type, quest, condition, node); VarTable vars = VarTable.newInstance(node); this.npcId = vars.getInteger("npcId", 0); this.npcType = vars.getInteger("npcType", 0); } @Override public void apply(QuestEvent event) { // получам игрока Player player = event.getPlayer(); // если игрка нет, выходим if(player == null) { log.warning(this, "not found player"); return; } if(npcId == 0 && npcType == 0) { // получаем нпс Npc npc = event.getNpc(); // если нпс нет, выходим if(npc == null) { log.warning(this, "not found npc for quest " + quest.getId()); return; } // обновляем икону npc.updateQuestInteresting(player, true); } else { // получаем локальные объекты LocalObjects local = LocalObjects.get(); // получаем список окружающих нпс Array<Npc> around = World.getAround(Npc.class, local.getNextNpcList(), player); // получаем массив нпс Npc[] array = around.array(); // перебираем for(int i = 0, length = around.size(); i < length; i++) { // получаем нпс Npc npc = array[i]; // если нпс нету, либо он не подходит, пропускаем if(npc == null || npc.getTemplateId() != npcId || npc.getTemplateType() != npcType) continue; // обновляем значек npc.updateQuestInteresting(player, true); } } } @Override public String toString() { return "ActionUpdateIntresting "; } } <file_sep>/java/game/tera/gameserver/model/npc/interaction/replyes/ReplyCityTeleport.java package tera.gameserver.model.npc.interaction.replyes; import org.w3c.dom.Node; import rlib.util.VarTable; import tera.gameserver.model.inventory.Cell; import tera.gameserver.model.npc.Npc; import tera.gameserver.model.npc.interaction.Link; import tera.gameserver.model.playable.Player; import tera.util.Location; import java.io.*; /** * Created by Luciole on 08/04/2016. */ public class ReplyCityTeleport extends AbstractReply { private float x; private float y; private float z; private int id; private int heading; public ReplyCityTeleport(Node node){ super(node); x = VarTable.newInstance(node).getFloat("x"); y = VarTable.newInstance(node).getFloat("y"); z = VarTable.newInstance(node).getFloat("z"); id = VarTable.newInstance(node).getInteger("id"); heading = VarTable.newInstance(node).getInteger("heading"); } @Override public void reply(Npc npc, Player player, Link link) { player.teleToLocation(id, x, y, z, heading); //player.teleToLocation(0, (float)-583.9613, (float)6423.1274, (float)1955.9696, 22532); } } <file_sep>/java/game/tera/gameserver/network/serverpackets/CancelTargetHp.java package tera.gameserver.network.serverpackets; import tera.gameserver.model.Character; import tera.gameserver.network.ServerPacketType; /** * Серверный пакет для удаление хп персонажа над головой. * * @author Ronn */ public class CancelTargetHp extends ServerPacket { private static final ServerPacket instance = new CancelTargetHp(); public static CancelTargetHp getInstance(Character target) { CancelTargetHp packet = (CancelTargetHp) instance.newInstance(); packet.objectId = target.getObjectId(); packet.subId = target.getSubId(); return packet; } /** ид персонажа */ private int objectId; /** саб ид персонажа */ private int subId; @Override public ServerPacketType getPacketType() { return ServerPacketType.CANCEL_TARGET_HP; } @Override protected void writeImpl() { writeOpcode(); writeInt(objectId);//обжект ид writeInt(subId);//саб ид } } <file_sep>/java/game/tera/gameserver/model/skillengine/classes/ManaStrike.java package tera.gameserver.model.skillengine.classes; import rlib.util.VarTable; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.model.AttackInfo; import tera.gameserver.model.Character; import tera.gameserver.model.skillengine.StatType; import tera.gameserver.templates.SkillTemplate; /** * Реализация удара, при котором восстанавливается процентно МП. * * @author Ronn */ public class ManaStrike extends Strike { /** кол-во получаемого МП */ private int gainMp; /** * @param template темплейт скила. */ public ManaStrike(SkillTemplate template) { super(template); // получаем таблицу переменных VarTable vars = template.getVars(); // получаем кол-во рестора МП gainMp = vars.getInteger("gainMp", 0); } @Override public AttackInfo applySkill(Character attacker, Character target) { // получаем результат удара AttackInfo info = super.applySkill(attacker, target); // рассчитываем % восстанавливаемого МП int abs = (int) attacker.calcStat(StatType.ABSORPTION_MP_ON_MAX, 0, attacker, null); // определяем итоговое кол-во восстанавливаемого МП abs = gainMp + gainMp * abs / 100; // если такое есть if(abs > 0) { // добавляем МП attacker.setCurrentMp(attacker.getCurrentMp() + abs); // получаем менеджера событий ObjectEventManager eventManager = ObjectEventManager.getInstance(); // уведомляем об изменении МП eventManager.notifyMpChanged(attacker); } return info; } } <file_sep>/java/game/tera/gameserver/network/serverpackets/EnchatItemInfo.java package tera.gameserver.network.serverpackets; import java.nio.ByteBuffer; import java.nio.ByteOrder; import tera.gameserver.model.actions.dialogs.EnchantItemDialog; import tera.gameserver.network.ServerPacketType; /** * Пакет с полной информацией об диалоге зачоравания вещи. * * @author Ronn */ public class EnchatItemInfo extends ServerPacket { private static final ServerPacket instance = new EnchatItemInfo(); public static EnchatItemInfo getInstance(EnchantItemDialog dialog) { EnchatItemInfo packet = (EnchatItemInfo) instance.newInstance(); ByteBuffer buffer = packet.prepare; int n = 8; packet.writeShort(buffer, 3);// 03 00 packet.writeShort(buffer, n);// 08 00 for (int i = 0, length = EnchantItemDialog.ITEM_COUNTER; i <= length; i++) { packet.writeShort(buffer, n);// 08 00 if (i != length) packet.writeShort(buffer, n += 126); else packet.writeShort(buffer, 0); packet.writeInt(buffer, 0);// 00 00 00 00 packet.writeInt(buffer, i);// //номер ячейки с нуля 0,1,2 packet.writeInt(buffer, dialog.getItemId(i)); packet.writeLong(buffer, dialog.getObjectId(i)); packet.writeLong(buffer, 14408);// 48 38 00 00 00 00 00 00 packet.writeLong(buffer, 76);// 4C 00 00 00 00 00 00 00 packet.writeInt(buffer, dialog.getNeedItemCount(i)); packet.writeInt(buffer, dialog.getNeedItemCount(i)); packet.writeInt(buffer, dialog.getEnchantLevel(i));// 02 00 00 00 packet.writeInt(buffer, 0);// 00 00 00 00 packet.writeInt(buffer, dialog.isEnchantItem(i) ? 1 : 0); packet.writeInt(buffer, 0);// 00 80 BC 04 иды бонусов packet.writeInt(buffer, 0);// 00 B8 BB 04 иды бонусов packet.writeInt(buffer, 0);// 00 D8 BE 04 иды бонусов packet.writeInt(buffer, 0);// 00 10 BE 04 иды бонусов packet.writeLong(buffer, 0);// 00 00 00 00 00 00 00 00 packet.writeLong(buffer, 0);// 00 00 00 00 00 00 00 00 packet.writeLong(buffer, 0);// 00 00 00 00 00 00 00 00 packet.writeLong(buffer, 0);// 00 00 00 00 00 00 00 00 packet.writeLong(buffer, 0);// 00 00 00 00 00 00 00 00 packet.writeLong(buffer, 0);// 00 00 00 00 00 00 00 00 packet.writeShort(buffer, 0);// 00 00 } buffer.flip(); return packet; } /** пати */ private final ByteBuffer prepare; public EnchatItemInfo() { this.prepare = ByteBuffer.allocate(1024).order(ByteOrder.LITTLE_ENDIAN); } @Override public void finalyze() { prepare.clear(); } @Override public ServerPacketType getPacketType() { return ServerPacketType.ENCHANT_ITEM_DIALOG_INFO; } @Override public boolean isSynchronized() { return false; } /** * @return подготавливаемый буффер. */ private ByteBuffer getPrepare() { return prepare; } @Override protected void writeImpl(ByteBuffer buffer) { writeOpcode(buffer); ByteBuffer prepare = getPrepare(); buffer.put(prepare.array(), 0, prepare.limit()); } } <file_sep>/java/game/tera/gameserver/model/skillengine/ResistType.java package tera.gameserver.model.skillengine; import tera.gameserver.model.Character; /** * Перечисление видов ресистов. * * @author Ronn */ public enum ResistType { noneResist(null, null), owerturnResist(StatType.OWERTURN_POWER, StatType.OWERTURN_RECEPTIVE), stunResist(StatType.STUN_POWER, StatType.STUN_RECEPTIVE), damageResist(StatType.DAMAGE_POWER, StatType.DAMAGE_RECEPTIVE), weakResist(StatType.WEAK_POWER, StatType.WEAK_RECEPTIVE); /** стат, увеличивающий шанс наложения дебафа */ private StatType powerStat; /** стат, уменьшающий шанс наложения дебафа */ private StatType rcptStat; /** * @param powerStat * @param rcptStat */ private ResistType(StatType powerStat, StatType rcptStat) { this.powerStat = powerStat; this.rcptStat = rcptStat; } /** * Проверка, нужно ли рассчитывать шанс. * * @param attacker атакующий. * @param attacked атакуемый. * @return считать ли прохождение. */ public boolean checkCondition(Character attacker, Character attacked) { switch(this) { case stunResist: return !attacked.isStunImmunity(); case owerturnResist: return !(attacked.isOwerturnImmunity() || attacked.isOwerturned()); default: break; } return true; } /** * @return тип стата, увеличивающий шанс дебафа. */ public final StatType getPowerStat() { return powerStat; } /** * @return тип стата, уменьшающий тип ресиста. */ public final StatType getRcptStat() { return rcptStat; } } <file_sep>/java/game/tera/gameserver/events/EventType.java package tera.gameserver.events; import tera.gameserver.events.auto.EpicBattle; import tera.gameserver.events.auto.LastHero; import tera.gameserver.events.auto.TeamDeathMatch; import tera.gameserver.events.auto.TeamVsTeam; import tera.gameserver.events.global.regionwars.RegionWars; /** * Перечисление видов ивентов * * @author Ronn * @created 04.03.2012 */ public enum EventType { /** ивет "Команда против Команды" */ TEAM_VS_TEAM(new TeamVsTeam()), /** ивент "Последний Герой" */ LAST_HERO(new LastHero()), /** ивент "Турнир" */ // TOURNAMENT(new Tournament()), /** ивент "Команда против Монстров" */ TEAM_VS_MONSTERS(new EpicBattle()), /** ивент битв за территорию */ REGION_WARS(new RegionWars()), /** ивент командный смертельный матч */ TEAM_DEATH_MATCH(new TeamDeathMatch()), ; /** экземпляр ивента */ private Event event; /** * @param event экземпляр ивента. */ private EventType(Event event) { this.event = event; } /** * @return экземпляр ивента */ public Event get() { return event; } } <file_sep>/java/game/tera/gameserver/model/actions/dialogs/EnchantItemDialog.java package tera.gameserver.model.actions.dialogs; import rlib.util.array.Arrays; import rlib.util.random.Random; import rlib.util.random.Randoms; import rlib.util.table.IntKey; import rlib.util.table.Table; import rlib.util.table.Tables; import tera.gameserver.manager.DataBaseManager; import tera.gameserver.manager.ObjectEventManager; import tera.gameserver.manager.PacketManager; import tera.gameserver.model.inventory.Inventory; import tera.gameserver.model.items.ItemInstance; import tera.gameserver.model.playable.Player; import tera.gameserver.network.serverpackets.DialogPanel; import tera.gameserver.network.serverpackets.DialogPanel.PanelType; import tera.gameserver.network.serverpackets.EnchantResult; import tera.gameserver.network.serverpackets.EnchatItemInfo; /** * Модель диалога по зачарованию вещей. * * @author Ronn */ public class EnchantItemDialog extends AbstractActionDialog { private static final int MAX_ENCHANT_LEVEL = 12; public static final int ITEM_COUNTER = 2; private static final int ALKAHEST_ITEM_INDEX = 2; private static final int CONSUME_ITEM_INDEX = 1; private static final int SOURCE_ITEM_INDEX = 0; /** * [20:25:19] BrabusX: 1-6 если белое ложишь = 5% если грин = 15% если * синька = 30% если голд = 50% * * 7-9 если белое = 3% если грин = 10% если синька = 20% если голд = 35% * * 10-12 если белое = 1% если грин = 3% если синька = 10% если голд = 25% */ private static final int[][] CHANE_TABLE = { // 1 - 3 // common/uncommon/rare/epic { 70, 80, 90, 99 }, { 70, 80, 90, 99 }, { 70, 80, 90, 99 }, // 4 - 6 { 20, 30, 50, 66 }, { 20, 30, 50, 66 }, { 20, 30, 50, 66 }, // 7 - 9 { 5, 15, 25, 40 }, { 5, 15, 25, 40 }, { 5, 15, 25, 40 }, // 10 - 12 { 1, 5, 15, 20 }, { 1, 5, 15, 20 }, { 1, 5, 15, 20 }, }; private static final Table<IntKey, int[]> ALKAHEST_TABLE; static { ALKAHEST_TABLE = Tables.newIntegerTable(); ALKAHEST_TABLE.put(15, Arrays.toIntegerArray(0, 6)); ALKAHEST_TABLE.put(446, Arrays.toIntegerArray(6, 9)); ALKAHEST_TABLE.put(448, Arrays.toIntegerArray(6, 9)); ALKAHEST_TABLE.put(447, Arrays.toIntegerArray(9, 12)); } public static EnchantItemDialog newInstance(Player player) { EnchantItemDialog dialog = (EnchantItemDialog) ActionDialogType.ENCHANT_ITEM_DIALOG.newInstance(); if(dialog == null) { dialog = new EnchantItemDialog(); } dialog.actor = player; dialog.enemy = player; return dialog; } /** рандоминайзер диалога */ private final Random random; /** целевой затачиваемый итем */ private ItemInstance consume; /** средство для заточки */ private ItemInstance alkahest; /** ресурс для заточки */ private ItemInstance source; public EnchantItemDialog() { this.random = Randoms.newRealRandom(); } @Override public boolean apply() { try { Player actor = getActor(); if(actor == null) { return false; } Inventory inventory = actor.getInventory(); if(inventory == null) { return false; } inventory.lock(); try { ItemInstance target = getSource(); ItemInstance source = inventory.getItemForObjectId(target.getObjectId()); if(source == null) { return false; } target = getConsume(); ItemInstance consume = inventory.getItemForObjectId(target.getObjectId()); if(consume == null || consume == source || !source.isEnchantable() || consume.getExtractable() < source.getExtractable()) { return false; } if(!source.getClass().isInstance(consume)) { return false; } target = getAlkahest(); ItemInstance alkahest = inventory.getItemForItemId(target.getItemId()); if(alkahest == null || alkahest.getItemCount() < source.getExtractable()) { return false; } int[] range = ALKAHEST_TABLE.get(alkahest.getItemId()); if(source.getEnchantLevel() < range[0] || source.getEnchantLevel() >= range[1]) { return false; } int chance = CHANE_TABLE[source.getEnchantLevel()][consume.getRank().ordinal()]; // actor.sendMessage("chance " + chance); boolean fail = !random.chance(chance); consume.setOwnerId(0); PacketManager.showDeleteItem(actor, consume); inventory.removeItem(consume); DataBaseManager manager = DataBaseManager.getInstance(); manager.updateLocationItem(consume); inventory.removeItem(alkahest.getItemId(), source.getExtractable()); if(fail) { actor.sendPacket(EnchantResult.getFail(), false); } else { source.setEnchantLevel(source.getEnchantLevel() + 1); manager.updateItem(source); actor.sendPacket(EnchantResult.getSuccessful(), false); } ObjectEventManager eventManager = ObjectEventManager.getInstance(); eventManager.notifyInventoryChanged(actor); return true; } finally { inventory.unlock(); } } finally { setConsume(null); } } @Override public ActionDialogType getType() { return ActionDialogType.ENCHANT_ITEM_DIALOG; } @Override public synchronized boolean init() { if(super.init()) { Player actor = getActor(); actor.sendPacket(DialogPanel.getInstance(actor, PanelType.ENCHANT_ITEM), true); updateDialog(); return true; } return false; } /** * @return разбиваемый предмет. */ public ItemInstance getConsume() { return consume; } /** * @param consume разбиваемый предмет. */ public void setConsume(ItemInstance consume) { this.consume = consume; } /** * @return используемый алкахест. */ public ItemInstance getAlkahest() { return alkahest; } /** * @param alkahest затачиваемый предмет. */ public void setAlkahest(ItemInstance alkahest) { this.alkahest = alkahest; } /** * @return затачиваемый предмет. */ public ItemInstance getSource() { return source; } /** * @param source затачиваемый предмет. */ public void setSource(ItemInstance source) { this.source = source; } /** * Обновление диалога. */ private void updateDialog() { Player actor = getActor(); if(actor != null) { actor.sendPacket(EnchatItemInfo.getInstance(this), true); } } /** * Ид шаблона предмета по указанному индексу ячейки. * * @param index индекс ячейки. * @return ид шаблона предмета. */ public int getItemId(int index) { switch(index) { case SOURCE_ITEM_INDEX: { ItemInstance source = getSource(); if(source != null) { return source.getItemId(); } break; } case CONSUME_ITEM_INDEX: { ItemInstance consume = getConsume(); if(consume != null) { return consume.getItemId(); } break; } case ALKAHEST_ITEM_INDEX: { ItemInstance alkahest = getAlkahest(); if(alkahest != null) { return alkahest.getItemId(); } break; } } return 0; } /** * Уникальный ид предмета по указанному индексу ячейки. * * @param index индекс ячейки. * @return уникальный ид предмета. */ public int getObjectId(int index) { switch(index) { case SOURCE_ITEM_INDEX: { ItemInstance source = getSource(); if(source != null) { return source.getObjectId(); } break; } case CONSUME_ITEM_INDEX: { ItemInstance consume = getConsume(); if(consume != null) { return consume.getObjectId(); } break; } case ALKAHEST_ITEM_INDEX: { ItemInstance alkahest = getAlkahest(); if(alkahest != null) { return alkahest.getObjectId(); } break; } } return 0; } /** * Кол-во необходимых предметов для заточки в ячейку по указанному индексу. * * @param index индекс ячейки. * @return кол-во вставляемых предметов. */ public int getNeedItemCount(int index) { switch(index) { case SOURCE_ITEM_INDEX: { return 1; } case CONSUME_ITEM_INDEX: { return 1; } case ALKAHEST_ITEM_INDEX: { ItemInstance source = getSource(); if(source != null) { return source.getExtractable(); } break; } } return 0; } /** * Является ли ячейка с указанным индексом ,ячейкой для затачиваемого * предмета. * * @param index индекс ячейки. * @return является ли ячейка с указанным индексом, ячейкой для * затачиваемого предмета. */ public boolean isEnchantItem(int index) { switch(index) { case SOURCE_ITEM_INDEX: { return true; } default: { return false; } } } /** * Добавление предмета в диалог. * * @param index индекс ячейки. * @param objectId уникальный ид предмета. * @param itemId ид шаблона предмета. */ public void addItem(int index, int objectId, int itemId) { Player actor = getActor(); switch(index) { case SOURCE_ITEM_INDEX: { if(getConsume() != null || getAlkahest() != null) { actor.sendMessage("Нужно очистить используемый предмет и alkshest."); return; } ItemInstance source = findItem(objectId, itemId); if(source == null) { actor.sendMessage("Unable to find item."); return; } if(source.getEnchantLevel() == 9 && source.getMasterworked() == 0){ actor.sendMessage("Item need to be masterworked."); return; } if(source.getEnchantLevel() >= MAX_ENCHANT_LEVEL) { actor.sendMessage("Item cannot be enchanted further."); return; } if(!source.isEnchantable()) { actor.sayMessage("Item cannot be enchanted."); return; } setSource(source); updateDialog(); break; } case CONSUME_ITEM_INDEX: { ItemInstance source = getSource(); if(source == null) { actor.sendMessage("Unknonw item."); return; } ItemInstance consume = findItem(objectId, itemId); if(consume == null || consume == getSource()) { actor.sendMessage("Unable to find item."); return; } if(source.getExtractable() != consume.getExtractable()) { actor.sendMessage("Item cannot be extracted"); return; } if(!source.getClass().isInstance(consume)) { actor.sendMessage("The item is not suitable for the type."); return; } setConsume(consume); updateDialog(); break; } case ALKAHEST_ITEM_INDEX: { ItemInstance source = getSource(); if(source == null || getConsume() == null) { actor.sendMessage("Fill all cells"); return; } int[] range = ALKAHEST_TABLE.get(itemId); if(range == null) { actor.sendMessage("Item isn't Alkahest"); return; } if(source.getEnchantLevel() >= range[1] || source.getEnchantLevel() < range[0]) { actor.sendMessage("This kind of Alkahest is not suitable."); return; } ItemInstance alkahest = findItem(objectId, itemId); if(alkahest == null) { actor.sendMessage("There are no Alkahest."); return; } if(alkahest.getItemCount() < source.getExtractable()) { actor.sendMessage("Insufficient number."); return; } setAlkahest(alkahest); updateDialog(); } } } /** * Поиск предмета. * * @param objectId уникальный ид предмета. * @param itemId ид шаблона прдемета. * @return предмет в инвенторе. */ public ItemInstance findItem(int objectId, int itemId) { Player actor = getActor(); if(actor == null) { return null; } Inventory inventory = actor.getInventory(); if(objectId != 0) { return inventory.getItemForObjectId(objectId); } return inventory.getItemForItemId(itemId); } /** * Уровень заточки затачиваемого предмета. * * @param index индекс ячейки. * @return уровень заточки. */ public int getEnchantLevel(int index) { if(index == SOURCE_ITEM_INDEX) { ItemInstance source = getSource(); if(source != null) { return source.getEnchantLevel(); } } return 0; } @Override public void finalyze() { setAlkahest(null); setConsume(null); setSource(null); } } <file_sep>/java/game/tera/gameserver/model/resourse/ResourseSpawn.java package tera.gameserver.model.resourse; import java.util.concurrent.ScheduledFuture; import rlib.geom.Coords; import rlib.logging.Logger; import rlib.logging.Loggers; import rlib.util.Rnd; import rlib.util.SafeTask; import tera.gameserver.manager.ExecutorManager; import tera.gameserver.templates.ResourseTemplate; import tera.util.Location; /** * Модель спавна ресурсов. * * @author Ronn */ public final class ResourseSpawn extends SafeTask { protected static final Logger log = Loggers.getLogger(ResourseSpawn.class); /** темплейт ресурса */ private ResourseTemplate template; /** точка спавна */ private Location loc; /** отспавненный ресурс */ private ResourseInstance spawned; /** ожидающий спавна ресурс */ private ResourseInstance waited; /** ссылка на таск респавна */ private ScheduledFuture<ResourseSpawn> schedule; /** время респа */ private int respawn; /** рандоминайзер времени респа */ private int randomRespawn; /** радиус спавна от точки */ private int minRadius; private int maxRadius; /** остановка спавна */ private boolean stoped; public ResourseSpawn(ResourseTemplate template, Location loc, int respawn, int randomRespawn, int minRadius, int maxRadius) { this.template = template; this.loc = loc; this.respawn = respawn; this.randomRespawn = randomRespawn; this.minRadius = minRadius; this.maxRadius = maxRadius; this.stoped = true; } /** * Запустить респавн. */ protected synchronized void doRespawn() { if(isStoped()) return; // если уже таск запущен, выходим if(schedule != null) { log.warning(this, new Exception("found duplicate respawn")); return; } // получаем время респа int delay = respawn; // если есть рандомное if(randomRespawn > 0) // расчитываем прибавку delay += Rnd.nextInt(0, randomRespawn); // получаем исполнительного менеджера ExecutorManager executor = ExecutorManager.getInstance(); // запускаем таск schedule = executor.scheduleGeneral(this, delay * 1000); } /** * Спавн ресурса. */ protected synchronized void doSpawn() { if(isStoped()) return; // зануляем schedule = null; // получаем ожидающий ресурс ResourseInstance resourse = getWaited(); // если его нет if(resourse == null) // создаем новый resourse = template.newInstance(); // запоминаем setSpawned(resourse); // забываем setWaited(null); // запоминаем спавн resourse.setSpawn(this); // если точка спавна рандоминизирована if(maxRadius > 0) // спавним в рандомной точке resourse.spawnMe(Coords.randomCoords(new Location(), loc.getX(), loc.getY(), loc.getZ(), minRadius, maxRadius)); else // иначе спавним в статичной resourse.spawnMe(loc); } /** * @return точка спавна. */ public final Location getLoc() { return loc; } /** * @return максимальный радиус спавна от точки. */ protected final int getMaxRadius() { return maxRadius; } /** * @return минимальный радиус спавна от точки. */ protected final int getMinRadius() { return minRadius; } /** * @return рандоминизированное время респа. */ protected final int getRandomRespawn() { return randomRespawn; } /** * @return базовое время респа. */ protected final int getRespawn() { return respawn; } /** * @return отспавненный инстанс. */ protected final ResourseInstance getSpawned() { return spawned; } /** * @return темплейт ресурса. */ public final ResourseTemplate getTemplate() { return template; } /** * @return ид темплейта спавненого ресурса. */ public int getTemplateId() { return template.getId(); } /** * @return ожидающий спавна инстанс. */ protected final ResourseInstance getWaited() { return waited; } /** * @return флаг остановки спавна. */ protected final boolean isStoped() { return stoped; } /** * Обработка собранного ресурса. * * @param resourse собранный ресурс. */ public synchronized void onCollected(ResourseInstance resourse) { if(isStoped()) return; // зануляемзаспавненный setSpawned(null); // заносим в ожидающий спавна setWaited(waited); // запускаем респавн doRespawn(); } @Override protected void runImpl() { doSpawn(); } /** * @param loc точка спавна. */ protected final void setLoc(Location loc) { this.loc = loc; } /** * @param maxRadius максимальный радиус спавна от точки. */ protected final void setMaxRadius(int maxRadius) { this.maxRadius = maxRadius; } /** * @param minRadius минимальный радиус спавна от точки. */ protected final void setMinRadius(int minRadius) { this.minRadius = minRadius; } /** * @param randomRespawn рандоминизированное время респа. */ protected final void setRandomRespawn(int randomRespawn) { this.randomRespawn = randomRespawn; } /** * @param respawn базовое время респа. */ protected final void setRespawn(int respawn) { this.respawn = respawn; } /** * @param spawned отспавненный инстанс. */ protected final void setSpawned(ResourseInstance spawned) { this.spawned = spawned; } /** * @param stoped флаг остановки спавна. */ protected final void setStoped(boolean stoped) { this.stoped = stoped; } /** * @param template темплейт ресурса. */ protected final void setTemplate(ResourseTemplate template) { this.template = template; } /** * @param waited ожидающий спавна инстанс. */ protected final void setWaited(ResourseInstance waited) { this.waited = waited; } /** * Запуск спавна. */ public synchronized void start() { // если уже активирован, выходим if(!isStoped()) return; // ставим флаг активности setStoped(false); // запускаем спавн doSpawn(); } /** * Остановка спавна. */ public synchronized void stop() { // если уже остановлено, выходим if(isStoped()) return; // ставим флаг остановлиности setStoped(true); // получаем отспавненный ресурс ResourseInstance resourse = getSpawned(); // если отспавненный есть if(resourse != null) { // удаляем из мира resourse.deleteMe(); // запоминаем в ожидающие setWaited(resourse); } } } <file_sep>/java/game/tera/gameserver/network/clientpackets/ClientPacket.java package tera.gameserver.network.clientpackets; import rlib.network.packets.AbstractReadeablePacket; import rlib.util.pools.FoldablePool; import tera.gameserver.network.ClientPacketType; import tera.gameserver.network.model.UserClient; /** * Базовая модель клиентского пакета. * * @author Ronn * @created 13.04.2012 */ public abstract class ClientPacket extends AbstractReadeablePacket<UserClient> { /** тип клиентского пакета */ private ClientPacketType type; public final UserClient getClient() { return getOwner(); } /** * @return тип клиентского пакета */ public final ClientPacketType getPacketType() { return type; } @Override protected final FoldablePool<ClientPacket> getPool() { return type.getPool(); } @Override public boolean isSynchronized() { return true; } @Override public final ClientPacket newInstance() { ClientPacket packet = getPool().take(); if(packet == null) try { packet = getClass().newInstance(); packet.setPacketType(type); } catch(InstantiationException | IllegalAccessException e) { log.warning(this, e); } return packet; } /** * Читаем строку */ protected final String readPassword() { StringBuilder builder = new StringBuilder(); while(buffer.hasRemaining()) builder.append((char) buffer.get()); return builder.toString(); } /** * Читаем строку */ protected final String readS() { StringBuilder builder = new StringBuilder(); byte ch; while(buffer.remaining() > 2) { buffer.get(); ch = buffer.get(); if(ch == 0) break; builder.append((char) ch); } return builder.toString(); } /** * @param type тип клиентского пакета */ public final void setPacketType(ClientPacketType type) { this.type = type; } }<file_sep>/java/game/tera/gameserver/model/skillengine/classes/PrepareStrike.java package tera.gameserver.model.skillengine.classes; import tera.gameserver.model.Character; import tera.gameserver.network.serverpackets.S_Action_Stage; import tera.gameserver.templates.SkillTemplate; /** * Модель подготовленного удара. * * @author Ronn */ public class PrepareStrike extends Strike { private int state; /** * @param template темплейт скила. */ public PrepareStrike(SkillTemplate template) { super(template); } @Override public void startSkill(Character attacker, float targetX, float targetY, float targetZ) { super.startSkill(attacker, targetX, targetY, targetZ); state = template.getStartState(); } @Override public void useSkill(Character character, float targetX, float targetY, float targetZ) { if(state <= template.getEndState()) { character.broadcastPacket(S_Action_Stage.getInstance(character, getIconId(), castId, state++)); return; } //character.broadcastPacket(S_Action_Stage.getInstance(character, getIconId(), castId, state)); state++; super.useSkill(character, targetX, targetY, targetZ); } } <file_sep>/java/game/tera/gameserver/network/clientpackets/C_Recommend_Guild.java package tera.gameserver.network.clientpackets; import tera.gameserver.manager.GuildManager; import tera.gameserver.model.MessageType; import tera.gameserver.network.serverpackets.S_Reply_Guild_List; import tera.gameserver.network.serverpackets.S_Sytem_Message; public class C_Recommend_Guild extends ClientPacket { private String guildName; @Override protected void readImpl() { readShort(); readByte(); guildName = readString(); } @Override protected void runImpl() { GuildManager.getInstance().getGuildByName(guildName).addPraise(); S_Sytem_Message packet = S_Sytem_Message.getInstance(MessageType.YOU_PRAISED_GUILD); packet.add("GuildName", guildName); packet.add("RemainCount", Integer.toString(0)); getOwner().sendPacket(packet); getOwner().sendPacket(S_Reply_Guild_List.getInstance(1)); } } <file_sep>/java/game/tera/gameserver/network/crypt/Crypt.java package tera.gameserver.network.crypt; import rlib.util.array.Arrays; import rlib.util.sha160.Sha160; /** * Модель криптора. */ public final class Crypt { public static final byte EMPTY_BYTE_ARRAY[] = new byte[0]; /** * Конвектирование байтов в беззнаковый инт. * * @param bytes исходный массив байтов. * @param offset отступ в массиве. */ private static long bytesToUInts(byte bytes[], int offset) { // получаем знаковый ИНТ int i = (0xFF & bytes[offset + 3]) << 24 | (0xFF & bytes[offset + 2]) << 16 | (0xFF & bytes[offset + 1]) << 8 | 0xFF & bytes[offset]; // убераем знак return (long) i & 0xFFFFFFFFL; } /** * Запись беззнакового инта в массив байтов * * @param containerInt массив байтов. * @param unsignedInt само ковектируемое число. * @param offset отступ в массиве. */ private static void intToBytes(byte containerInt[], long unsignedInt, int offset) { containerInt[offset + 3] = (byte)(int)((unsignedInt & 0xff000000L) >> 24); containerInt[offset + 2] = (byte)(int)((unsignedInt & 0xff0000L) >> 16); containerInt[offset + 1] = (byte)(int)((unsignedInt & 65280L) >> 8); containerInt[offset] = (byte)(int)(unsignedInt & 255L); } public static void shiftKey(byte[] src, byte[] dest, int n, boolean direction) { byte[] tmp = new byte[128]; for(int i = 0; i < 128; i++) { if(direction) tmp[(i + n) % 128] = src[i]; else tmp[i] = src[(i + n) % 128]; } for(int i = 0; i < 128; i++) dest[i] = tmp[i]; } /** * Извлечение подмассива байтов * * @param buffer исходный массив. * @param offset отступ. * @param end конец. */ public static byte[] subarray(byte buffer[], int offset, int end) { if(buffer == null) return null; if(offset < 0) offset = 0; if(end > buffer.length) end = buffer.length; int newSize = end - offset; if(newSize <= 0) return EMPTY_BYTE_ARRAY; else { // создаем новый массив byte subarray[] = new byte[newSize]; // переносим данные в новый массив System.arraycopy(buffer, offset, subarray, 0, newSize); // возвращаем его return subarray; } } public static void xorKey(byte[] src1, byte[] src2, byte[] dst) { for(int i = 0; i < 8; i++) for(int j = 0; j < 16; j++) dst[i * 16 + j] = (byte) ((src1[i * 16 + j] & 0xff) ^ (src2[i * 16 + j] & 0xff)); } private int changeData; private int changeLenght; /** массив ключей */ private CryptKey[] keys; private CryptKey first; private CryptKey second; private CryptKey thrid; /** байтовый контейнер ИНТ */ private byte[] containerInt; public Crypt() { this.first = new CryptKey(31, 55); this.second = new CryptKey(50, 57); this.thrid = new CryptKey(39, 58); this.keys = Arrays.toGenericArray(first, second, thrid); this.containerInt = new byte[4]; } /** * Приминение криптора. * * @param buffer юуфер данных * @param size длинна обрабатываемых данных. */ public void applyCryptor(byte buffer[], int size) { int changeLenght = getChangeLenght(); int changeData = getChangeData(); int pre = size >= changeLenght ? changeLenght : size; // получаем контейнер для инта byte[] containerInt = getContainerInt(); if(pre != 0) { if(pre > 0) { intToBytes(containerInt, changeData, 0); // применяем изменения for(int j = 0; j < pre; j++) buffer[j] ^= containerInt[(4 - changeLenght) + j]; } changeLenght -= pre; size -= pre; } int offset = pre; // получаем массив ключей CryptKey[] keys = getKeys(); // поучаем прямые ссылки на ключи CryptKey first = getFirst(); CryptKey second = getSecond(); CryptKey thrid = getThrid(); for(int i = 0; i < size / 4; i++) { int result = first.getKey() & second.getKey() | thrid.getKey() & (first.getKey() | second.getKey()); // перебираем ключи for(int j = 0; j < 3; j++) { // получаем ключ CryptKey key = keys[j]; // если ключ совпадает if(result == key.getKey()) { long t1 = bytesToUInts(key.getBuffer(), key.getFirstPos() * 4); long t2 = bytesToUInts(key.getBuffer(), key.getSecondPos() * 4); long t3 = t1 > t2 ? t2 : t1; long sum = t1 + t2; sum = sum > 0xFFFFFFFFL? (long)((int) t1 + (int) t2) & 0xFFFFFFFFL : sum; key.setSum(sum); key.setKey(t3 <= sum ? 0 : 1); key.setFirstPos((key.getFirstPos() + 1) % key.getSize()); key.setSecondPos((key.getSecondPos() + 1) % key.getSize()); } long unsBuf = bytesToUInts(buffer, offset + i * 4) ^ key.getSum(); intToBytes(buffer, unsBuf, offset + i * 4); } } int remain = size & 3; if(remain != 0) { int result = first.getKey() & second.getKey() | thrid.getKey() & (first.getKey() | second.getKey()); changeData = 0; for(int j = 0; j < 3; j++) { // получаем ключ CryptKey key = keys[j]; // если ключ совпадает if(result == key.getKey()) { long t1 = bytesToUInts(key.getBuffer(), key.getFirstPos() * 4); long t2 = bytesToUInts(key.getBuffer(), key.getSecondPos() * 4); long t3 = t1 > t2 ? t2 : t1; long sum = t1 + t2; sum = sum > 0xFFFFFFFFL? (long)((int) t1 + (int) t2) & 0xFFFFFFFFL : sum; key.setSum(sum); key.setKey(t3 <= sum ? 0 : 1); key.setFirstPos((key.getFirstPos() + 1) % key.getSize()); key.setSecondPos((key.getSecondPos() + 1) % key.getSize()); } changeData ^= key.getSum(); } intToBytes(containerInt, changeData, 0); for(int j = 0; j < remain; j++) buffer[((size + pre) - remain) + j] ^= containerInt[j]; changeLenght = 4 - remain; } setChangeData(changeData); setChangeLenght(changeLenght); } private void fillKey(byte src[], byte dst[]) { for(int i = 0; i < 680; i++) dst[i] = src[i % 128]; dst[0] = -128; } /** * Генерация итогового ключа по полученному. * * @param source исходный ключ. */ public void generateKey(byte source[]) { byte buffer[] = new byte[680]; fillKey(source, buffer); Sha160 sha160 = new Sha160(); for(int i = 0; i < 680; i += 20) { sha160.update(buffer, 0, 680); byte digest2[] = sha160.digest(); int j = i; for(int l = 0; j < i + 20; l++) { buffer[j] = digest2[l]; j++; } } first.setBuffer(subarray(buffer, 0, 220)); second.setBuffer(subarray(buffer, 220, 448)); thrid.setBuffer(subarray(buffer, 448, 680)); } /** * @return изменение данных. */ public int getChangeData() { return changeData; } /** * @return длинна изменений. */ public int getChangeLenght() { return changeLenght; } /** * @return байтовый контейнер инта. */ public byte[] getContainerInt() { return containerInt; } /** * @return первый ключ. */ public CryptKey getFirst() { return first; } /** * @return массив ключей. */ public CryptKey[] getKeys() { return keys; } /** * @return второй ключ. */ public CryptKey getSecond() { return second; } /** * @return третий ключ. */ public CryptKey getThrid() { return thrid; } /** * @param changeData изменение данных. */ public void setChangeData(int changeData) { this.changeData = changeData; } /** * @param changeLenght */ public void setChangeLenght(int changeLenght) { this.changeLenght = changeLenght; } }
80b292849056cb4bf3f8f76f127b06aa376fdaaa
[ "Markdown", "Java", "SQL" ]
418
Java
unnamed44/tera_2805
6c5be9fc79157b44058c816dd8f566b7cf7eea0d
70f099c4b29a8e8e19638d9b80015d0f3560b66d
refs/heads/master
<file_sep><?php namespace Rozdol\Loans; use Rozdol\Dates\Dates; class Interest { private static $hInstance; public static function getInstance() { if (!self::$hInstance) { self::$hInstance = new Interest(); } return self::$hInstance; } public function __construct() { $this->dates = new Dates(); } /** * get Iterest * * @return array */ function pre_display($text = '', $title = '', $class = '', $code = 0) { if ($_REQUEST[act]=='api') { if ($title=='') { $title='output'; } $out=json_encode(["$title"=>$text]); } else { if ($title!='') { $out.="<h3>$title</h3>";//$this->tag($title, 'foldered'); } $out.="<pre class='$class'>"; if ($code==0) { $out.=htmlspecialchars(print_r($text, true)); } else { $out.=htmlspecialchars(var_export($text, true)); } $out.= "</pre>"; } return $out; } public function getInterest($data) { //echo $this->pre_display($data,"data"); /* 0 or omitted US (NASD) 30/360 1 Actual/actual 2 Actual/360 3 Actual/365 4 European 30/360 */ $df=$data[df]; $dt=$data[dt]; //echo \util::pre_display($data,' data from interest'); //exit; // $daysinyear=(($data[base]=='366') || ($res[compound]=='t') ||($res[compound]!=0))?$this->dates->F_daysinyear($res[df]):360; $daysinyear=(($data[base]=='366'))?$this->dates->F_daysinyear($res[df]):360; if($data[base]=='365')$daysinyear=365; if ($data[base]=='') { $data[base]='30/360'; } $data[daysinyear]=$daysinyear; $res=$data; $res[days]=$this->dates->F_datediff($res[df], $res[dt], $res[base]); $res[years]=$res[days]/$daysinyear; $res[daysinyear]=$daysinyear; if (($res[compound]=='f')||($res[compound]==0)) { $res[interest]=0; $res[df1]=$res[df]; $res[dt1]="31.12.".substr($res[df], 6, 4); if ($this->dates->is_earlier($res[dt], $res[dt1])) { $res[dt1]=$res[dt]; } //Calc 1st interest $days=$this->dates->F_datediff($res[df], $res[dt1]); //$daysinyear=$this->dates->F_daysinyear($res[dt1]); $daysinyear=($data[base]=='366')?$this->dates->F_daysinyear($res[dt1]):360; if($data[base]=='365')$daysinyear=365; $years=$days/$daysinyear; $int=$res[amount]*$res[rate]*$years; $res[interest]+=$int; if ($int>0) { $res[formula].="($days / $daysinyear x $res[amount] x $res[rate]) = [".round($int, 2)."] + "; } $res[days_calc]+=$days; if ($this->dates->is_earlier($res[dt1], $res[dt])) { $res[debug].="Continue | "; $res[dt2]=$this->dates->F_dateadd($res[dt1], 1); $res[dt3]=$this->dates->F_dateadd_year($res[dt2], -1); $min_date=strtotime($res[dt3]); $max_date=strtotime($res[dt]); while (($min_date = strtotime("+1 YEAR", $min_date)) <= $max_date) { $no++; $date=date('d.m.Y', $min_date); $date_to=$this->dates->F_dateadd($this->dates->F_dateadd_year($date, 1), -1); $date_from=$date; //$daysinyear=$this->dates->F_daysinyear($date_to); $daysinyear=($data[base]=='366')?$this->dates->F_daysinyear($date_to):360; if($data[base]=='365')$daysinyear=365; if ($this->dates->is_earlier($res[dt], $date_to)) { $date_to=$res[dt]; } $days=$this->dates->F_datediff($date_from, $date_to)+1; $years=$days/$daysinyear; $int=$res[amount]*$res[rate]*$years; $res[interest]+=$int; $res[days_calc]+=$days; $res[debug].="Loop$no : ($days/$daysinyear) $date_from - $date_to | "; if ($int>0) { $res[formula].="($days / $daysinyear x $res[amount] x $res[rate]) = [".round($int, 2)."] + "; } } } $res[balance]=$res[amount]; //if(($GLOBALS[debug][stopwatch]=='calc_loan_main')){echo $this->pre_display($res,'res'); exit;} if ($GLOBALS[access][view_debug]) { $res[domain]=$GLOBALS[debug][stopwatch]; $GLOBALS[debug][calc_interest][]=$res; } } else { //$res[years]=round($res[years],1); $res[interest]=$res[amount]*pow((1+$res[rate]/$res[freq]), ($res[freq]*$res[years]))-$res[amount]; $res[interest]=round($res[interest], 2); $res[balance]=$res[amount]+$res[interest]; $res[formula]="$res[amount]*pow((1+$res[rate]/$res[freq]), ($res[freq]*$res[years]))-$res[amount] "; } //if($days==0)$res[interest]=0; $res[formula]=substr($res[formula], 0, -3); $res[csv]=implode(';', $res); // echo \util::pre_display($res,"Calc Interest $res[note]"); return $res; } } <file_sep><?php namespace Rozdol\Loans; use Rozdol\Dates\Dates; use Rozdol\Loans\interest; use Rozdol\utils\Utils; use Rozdol\Html\Html; class Planner { private static $hInstance; public static function getInstance() { if (!self::$hInstance) { self::$hInstance = new Planner(); } return self::$hInstance; } public function __construct() { $this->dates = new Dates(); $this->interest = new Interest(); $this->utils = new Utils(); $this->html = new Html(); } /** * calc Loan * * @return array */ public function getDates($data) { // echo $this->html->pre_display($data,"getDates $data[debug_info]"); $found=0; $periods=$data['periods']; $ignore_weekends=$data['ignore_weekends']; $use_eoy=$data['use_eoy']; if ($periods==0) { $periods=1; } if ($data['align']>0) $periods++; $data['periods']=$periods; $payments=$data['payments']; $payment_range=round($periods/$payments); //echo "payment_range1=$payment_range=round($periods/$payments);<br>"; if (($payment_range==0)||($payment_range==INF)) { $payment_range=1; } $data[payment_range]=$payment_range; //echo $this->html->pre_display($payment_range,"payment_range"); $days_loan=$this->dates->F_datediff($data[df], $data[dt], $data[base]); $data[days_loan]=$days_loan; $months_loan=$days_loan/365*12; $pays_per_year=$data[freq]; if (($days_loan>366)&&($data[freq]==1)&&($data[periods]==1)) { $pays_per_year=365/$days_loan; } $data[pays_per_year]=$pays_per_year; $data[months_loan]=$months_loan; $months_loan_rounded=round($months_loan); $data[months_loan_rounded]=$months_loan_rounded; $item_no=0; $no=1; $date=$data[df]; $date_initial=$data[df]; $date_prev=$date; //Check for date_check $data['date']=$this->dates->F_date($data['date'],1); $days_chk=$this->dates->F_datediff($data['date'], $date_initial); //echo $this->html->pre_display($days_chk,"days_chk"); $period_data_chk=[ 'no'=>$item_no, 'df'=>$date_prev, 'dt'=>$data['date'], 'days'=>$this->dates->F_datediff($date_prev, $data['date'], $data[base]), 't_days'=>$this->dates->F_datediff($date_initial, $data['date'], $data[base]), 'note'=>'chk', ]; if (($days_chk<=0)&&($found==0)) { $found++; $period_data_chk=[ 'no'=>$item_no, 'df'=>$date_prev, 'dt'=>$data['date'], 'days'=>$this->dates->F_datediff($date_prev, $data['date'], $data[base]), 't_days'=>$this->dates->F_datediff($date_initial, $data['date'], $data[base]), 'note'=>'chk', ]; // $period_data_arr[$item_no]=$period_data_chk; } if ($data['align']>0) { $no++; $date_prev=$date; if ($data['align']<32) { // echo "$data[align] ($date)<br>"; $day=substr($date, 0, 2); // echo "$day<br>"; if ($data['align']>=$day) { $days_add=$data['align']-$day; } else { $days_add=$data['align']-$day + $this->dates->days_in_month_date($date); } $align_text="$data[align] day of the month"; } else { $days_add=$this->dates->F_datediff($date, $this->dates->lastday_in_month($date)); $align_text="the last day of the month"; } $date=$this->dates->F_dateadd_day($date, $days_add,$ignore_weekends); $item_no++; $period_data=[ 'no'=>$item_no, 'df'=>$date_prev, 'dt'=>$date, 'days'=>$this->dates->F_datediff($date_prev, $date, $data[base]), 't_days'=>$this->dates->F_datediff($date_initial, $date, $data[base]), 'note'=>'align', ]; $period_data_arr[$item_no]=$period_data; $days=$this->dates->F_datediff($date_prev, $date, $data[base]); $t_days+=$days; $plan[]=array( 'no'=>$no, 'action'=>'Pay', 'date'=>$date, 'days'=>$days, 'info'=>'', ); } /// END ======== Align to date $date_alligned=$date; if ($pays_per_year>1) { $months=12/$pays_per_year; } else { $months=12; } $data[months]=$months; /// ======== Loop for periods for ($i=1; $i<=$periods; $i++) { $no++; $date_prev=$date; if ($months>=1) { //echo "$months / $days_loan<br>"; if ($pays_per_year>=1) { $date_before=$date; $date=$this->dates->F_dateadd_month($date_alligned, $months*$i,$ignore_weekends); //echo $this->html->pre_display($pays_per_year,"$date_before - $date pays_per_year $months ($days_add)"); } else { $date=$this->dates->F_dateadd($date, $days_loan); //echo "DL:$days_loan<br>"; } if (($days_add>0)&&($data['align']==32)) { $date=$this->dates->lastday_in_month($this->dates->F_dateadd($date, -15)); } if (($days_add>0)&&($i==$periods)) { $date=$this->dates->F_dateadd($date, -$days_add); } //if($no>=5)echo $this->html->pre_display(['Date'=>$date,'Days_add'=>$days_add],"result4"); } else { $days_in_month=$this->dates->days_in_month_date($this->dates->F_dateadd($date, 15)); if (($days_add>0)&&($i==$periods)) { $days_in_month=$days_in_month-$days_add; } $date=$this->dates->F_dateadd($date, $days_in_month); //$date=$this->dates->F_dateadd_month($date,$months); } $item_no++; $period_data=[ 'no'=>$item_no, 'df'=>$date_prev, 'dt'=>$date, 'days'=>$this->dates->F_datediff($date_prev, $date, $data[base]), 't_days'=>$this->dates->F_datediff($date_initial, $date, $data[base]), 'note'=>'maturity', ]; $period_data_arr[$item_no]=$period_data; $days=$this->dates->F_datediff($date_prev, $date, $data[base]); $t_days+=$days; } /// END ======== Loop for periods $item_no=0; $inserted=0; $item_no++; $period_data_loan=[ 'no'=>$item_no, 'df'=>$date_initial, 'dt'=>$date_initial, 'days'=>0, 't_days'=>0, 'note'=>'loan' ]; $period_data_arr2[$item_no]=$period_data_loan; // echo $this->html->array_display($period_data_arr,"period_data_arr"); $periods=0; /// ============ Loop for chk and eoy dates foreach ($period_data_arr as $key => $period_data) { // check for chk date if(($this->dates->is_earlier($period_data_chk[dt],$period_data[dt],0))&&($inserted==0)&&($period_data_chk[dt]!='')&&($this->dates->F_datediff($period_data_chk[df], $period_data_chk[dt], $data[base])>0)){ //echo $this->html->pre_display($period_data_chk,"period_data_chk"); $inserted=1; $item_no++; // $period_data_chk=[ // 'no'=>$item_no, // 'df'=>$period_data_arr2[$item_no-1][dt],//$date_prev, // 'dt'=>$period_data_chk[dt], // 'days'=>$this->dates->F_datediff($period_data_chk[df], $period_data_chk[dt], $data[base]),//$this->dates->F_datediff($date_prev, $data['date'], $data[base]), // 't_days'=>$this->dates->F_datediff($date_initial, $data['date'], $data[base]), // 'note'=>'chk', // ]; $period_data_chk[df]=$period_data_arr2[$item_no-1][dt]; $period_data_chk[days]=$this->dates->F_datediff($period_data_chk[df], $period_data_chk[dt], $data[base]); $period_data_chk['no']=$item_no; $period_data_arr2[$item_no]=$period_data_chk; } if($use_eoy>0){ // check for eoy date $year=$this->dates->F_extractyear($period_data[df])+1; $eoy="01.01.$year"; //echo $this->html->pre_display($eoy,"eoy"); if(($this->dates->is_earlier($eoy,$period_data[dt],1))&&($this->dates->is_later($eoy,$period_data[df],1))){ $item_no++; $period_data_ny=[ 'no'=>$item_no, 'df'=>$period_data[df], 'dt'=>$eoy, 'days'=>$this->dates->F_datediff($period_data[df], $eoy, $data[base]), 't_days'=>$this->dates->F_datediff($date_initial, $eoy, $data[base]), 'note'=>'eoy' ]; $period_data_arr2[$item_no]=$period_data_ny; $period_data[df]=$eoy; $period_data['days']=$this->dates->F_datediff($eoy, $period_data[dt], $data[base]); $period_data['note']='align'; } } if($use_eom>0){ // check for eom date $year=$this->dates->F_extractyear($period_data[df])+1; $month=$this->dates->F_extractmonth($period_data[df])+1; $eom="01.$month.$year"; //echo $this->html->pre_display($eom,"eom"); if(($this->dates->is_earlier($eom,$period_data[dt],1))&&($this->dates->is_later($eom,$period_data[df],1))){ $item_no++; $period_data_nm=[ 'no'=>$item_no, 'df'=>$period_data[df], 'dt'=>$eom, 'days'=>$this->dates->F_datediff($period_data[df], $eom, $data[base]), 't_days'=>$this->dates->F_datediff($date_initial, $eom, $data[base]), 'note'=>'eom' ]; $period_data_arr2[$item_no]=$period_data_nm; $period_data[df]=$eom; $period_data['days']=$this->dates->F_datediff($eom, $period_data[dt], $data[base]); $period_data['note']='align'; // echo $this->html->pre_display($period_data_nm,"period_data_nm"); } } $item_no++; $periods++; $period_data['no']=$item_no; $period_data_arr2[$item_no]=$period_data; $date_prev=$period_data[dt]; } //insert chk date at the end if(($inserted==0)&&($this->dates->F_datediff($period_data_chk[df], $period_data_chk[dt], $data[base])>0)){ $inserted=1; $item_no++; $period_data_chk['no']=$item_no; $period_data_chk[df]=$period_data_arr2[$item_no-1][dt]; $period_data_chk[days]=$this->dates->F_datediff($period_data_chk[df], $period_data_chk[dt], $data[base]); $period_data_arr2[$item_no]=$period_data_chk; } $data['periods']=$periods; $res=$data; $res[period_data]=$period_data_arr2; // echo $this->html->array_display($period_data_arr2,"period_data_arr2"); return $res; } public function getPlanV2($data) { // if($data[debug_info]=='get_loan_plan') echo $this->html->pre_display($data,"getPlanV2 data"); //exit; // echo $this->html->array_display($data[period_data],"period_data ".$data[debug_info]); if(($data[compound]) && (!$data[compound_formula])){ $data[compound]=0; $data[compounding]=1; $data[compounding_mod]=1; }else{ $data[compounding]=0; } $saved_interest_bf=$data[interest_bf]; // if($data[debug_info]=='get_loan_plan') echo $this->html->pre_display($data,"getPlanV2 data"); //exit; $period_data_arr=$data[period_data]; $balance_prev=$data[amount]; $interest_accumulated=$data[interest_bf]+$data[default_interest_bf]; $main_interest_accumulated=$data[interest_bf]; $def_interest_accumulated=$data[default_interest_bf]; $interest_balance=$data[interest_bf]+$data[default_interest_bf]; $fields=['#','Action','Date','Days','Given','Payment','Pcpl. paid','Int.paid','Balance','Main Interest']; if($data[default_interest_bf]>0){ $fields = array_merge($fields, ['Def. interest','Total Interest','Main int. Accum.','Def. int. Accum.']); } $fields = array_merge($fields, ['Int. Accum.','Interest Bal','Tot.Bal.']); if($data[maturity_id]>0){ $fields = array_merge($fields, ['Margin rate','Floating rate','Int. rate total','Rate date']); }else{ $fields = array_merge($fields, ['Int. rate']);; } if($data[default_interest_bf]>0){ $fields = array_merge($fields, ['Def. rate']); } $fields = array_merge($fields,['']); $tbl=$this->html->tablehead($what, $qry, $order, $addbutton, $fields, 'no_sort'); $m=0; $plain_interest=0; foreach ($period_data_arr as $key => $period_data) { $i++; if($period_data[note]=='maturity')$m++; $date=$period_data[dt]; $given=($period_data[note]=='loan')?$data[amount]:0; $days=$period_data[days];//$this->dates->F_datediff($date_prev, $date, $data[base]); if($period_data[note]!='chk')$t_days+=$days; $rate=$period_data['rate']; $margin_rate=$data['rate']; $data4interest=[ 'amount'=>$balance, 'rate'=>$period_data['rate'], 'freq'=>$data['compounding_freq'], 'df'=>$period_data[df], 'dt'=>$period_data[dt], 'base'=>$data[base], 'compound'=>$data[compound], 'note'=>$period_data[note], 'debug_info'=>"balance_prev=$balance_prev", ]; $calc_interest=$this->interest->getInterest($data4interest); // echo $this->html->pre_display($calc_interest[formula],"calc_interest folrmula"); // if($data[debug_info]=='get_loan_plan')echo $this->html->cols2($this->html->pre_display($data4interest,"data4interest ($i) $period_data[df] $period_data[dt] $period_data[note]"),$this->html->pre_display($calc_interest,"calc_interest $period_data[df] $period_data[dt] $period_data[note] ".$data[debug_info])); $interest=$calc_interest[interest]; $data4interest[rate]=$period_data['libor_rate'];//+$period_data['rate']; $calc_interest=$this->interest->getInterest($data4interest); $libor_interest=$calc_interest[interest]; if($data[default_interest_bf]>0){ $data4interest=[ 'amount'=>$balance,//$data[default_interest_bf],//$balance_prev, 'rate'=>$data['d_rate'],//+$period_data['libor_rate'], 'freq'=>$data['compounding_freq'], 'df'=>$period_data[df], 'dt'=>$period_data[dt], 'base'=>$data[base], 'compound'=>$data[compound], 'note'=>$period_data[note], ]; $calc_interest=$this->interest->getInterest($data4interest); $def_interest=$calc_interest[interest]; } $interest_amount=$interest; $modulus=($m) % $data[compounding_mod]; // echo "$modulus=($m) % $data[compounding_mod];<br>"; $interest_balance+=$interest_amount+$def_interest; if (($data[compounding]>0)&&($modulus == 0)&&($period_data[note]=='maturity')){ // echo "bal::$balance=$balance+$interest_balance;<br>"; $balance=$balance+$interest_balance; $interest_balance=0; } $no_str="$i"; $balance=$balance+$given-$returned; $interest_accumulated+=$interest_amount+$def_interest; $main_interest_accumulated+=$interest_amount; $def_interest_accumulated+=$def_interest; $total_balance=$balance+$interest_balance; $class=''; if($period_data[note]=='chk')$class='bold'; $tbl.="<tr class='$class'><td>$no_str</td> <td>$period_data[note]</td> <td>$date</td> <td class='n'>$days</td> <td class='n'>".$this->html->money($given)."</td> <td class='n'>".$this->html->money($payment)."</td> <td class='n'>".$this->html->money($pricipal_paid)."</td> <td class='n'>".$this->html->money($interest_paid)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money($interest_amount)."</td>"; if($data[default_interest_bf]>0){ $tbl.="<td class='n'>".$this->html->money($def_interest)."</td>"; $tbl.="<td class='n'>".$this->html->money($def_interest+$interest_amount)."</td>"; $tbl.="<td class='n'>".$this->html->money($main_interest_accumulated)."</td>"; $tbl.="<td class='n'>".$this->html->money($def_interest_accumulated)."</td>"; } $tbl.="<td class='n'>".$this->html->money($interest_accumulated)."</td> <td class='n'>".$this->html->money($interest_balance)."</td> <td class='n'>".$this->html->money($total_balance)."</td>"; if($data[maturity_id]>0){ $tbl.="<td class='n'>".$this->html->money($margin_rate*100,'','',5)."</td>"; //$tbl.="<td class='n'>".$this->html->money($libor_interest)."</td>"; $tbl.="<td class='n'>".$this->html->money($period_data['libor_rate']*100,'','',5)." %</td>"; $tbl.="<td class='n'>".$this->html->money($rate*100,'','',5)." %</td>"; $tbl.="<td>$period_data[libor_date]</td>"; }else{ $tbl.="<td class='n'>".$this->html->money($rate*100,'','',5)." %</td>"; } if($data[default_interest_bf]>0){ $tbl.="<td class='n'>".$this->html->money($data['d_rate']*100,'','',5)." %</td>"; } $tbl.="<td>$note</td>"; //$tbl.="<td class='n'>G:".$this->html->money($t_given)." A:".$this->html->money($t_amount)." p:".$this->html->money($t_paid)." I:".$this->html->money($t_interest_paid)." ".$this->html->money($t_interest_paid)."</td>"; $tbl.="</tr>"; $plan[]=[ 'no'=>$no_str, 'action'=>$period_data[note], 'date'=>$date, 'df'=>$period_data[df], 'dt'=>$period_data[dt], 'days'=>$days, 'given'=>$given, 'returned'=>$amount, 'int_paid'=>$interest_paid, 'balance'=>$balance, 'main_interest'=>$interest_amount, 'def_interest'=>$def_interest, 'main_and_def_interest'=>$def_interest+$interest_amount, 'main_interest_accumulated'=>$main_interest_accumulated, 'def_interest_accumulated'=>$def_interest_accumulated, 'interest_accumulated'=>$interest_accumulated, 'interest_balance'=>$interest_balance, 'total_balance'=>$total_balance, 'margin_rate'=>$margin_rate*100, 'libor_rate'=>$period_data['libor_rate'], 'total_rate'=>$rate*100, 'libor_date'=>$period_data[libor_date], 'def_rate'=>$data['d_rate']*100, 'period_rate'=>$period_data['rate'], 'libor_interest'=>$libor_interest, 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'', ]; if($period_data[note]=='chk'){ $data['balance_principal']=$data[amount]-$principal_paid_total; $data['balance_interest']=$total_balance-($data[amount]-$t_principal_paid); $data['balance_total']=$total_balance; $interest_accumulated-=$interest_amount; $interest_balance-=$interest_amount; $total_libor_interest-=$libor_interest; $plain_interest-=$interest_amount; $t_def_interest-=$def_interest; $t_tot_interest-=($def_interest+$interest_amount); // $t_interest-=$interest_amount; } $balance_prev=$balance+$data[interest_bf]; $data[interest_bf]=0; $t_given+=$given; $t_returned+=$returned; $total_libor_interest+=$libor_interest; $plain_interest+=$interest_amount; $t_def_interest+=$def_interest; $t_tot_interest+=$def_interest+$interest_amount; if($period_data[note]=='chk')break; } $totals=array_fill(0, 20, 0); $i=2; $totals[$i]=$t_days; $totals[$i+1]=$t_given; $totals[$i+2]=$t_returned; $totals[$i+5]=$balance; $totals[$i+6]=$plain_interest; $i=$i+6; if($data[default_interest_bf]>0){ $i++; $totals[$i]=$t_def_interest; $i++; $totals[$i]=$t_tot_interest; $i++; $totals[$i]=$plain_interest+$data[interest_bf]; $i++; $totals[$i]=$t_def_interest+$data[default_interest_bf]; } $i++; $totals[$i]=$interest_accumulated; $i++; $totals[$i]=$interest_balance; $i++; $totals[$i]=$total_balance; $tbl.=$this->html->tablefoot($i, $totals, $no); $data[interest_bf]=$saved_interest_bf; $res=$data; $res[period_data]=$period_data_arr2; $res[tbl]=$tbl; $res[plan]=$plan; // $res[interest_accumulated]=$interest_accumulated; // if($data[debug_info]!='calcLoanV2_2')echo $this->html->pre_display($res,"res"); return $res; } public function getPlan($data) { //echo $this->html->pre_display($data,"f:getPlan"); $period_data_arr=$data[period_data]; $payment_range=$data[payment_range]; $balance=$data[amount]; $pmt_amount=$data[pmt]; $payments=$data['payments']; $periods=$data['periods']; $t_init_interest=$data['interest_bf']; //$t_interest_compound=$data['interest_bf']; //$t_interest_compound_accum=$data['interest_bf']; $payments=$data['payments']; $payment_range=round($periods/$payments); //echo "payment_range=$payment_range=round($periods/$payments)<br>"; if (($payment_range==0)||($payment_range==INF)) { $payment_range=1; } //echo "pmt_amount=$pmt_amount=round($data[amount]/$payments, 2)<br>"; if (($payment_range>=1)&&($pmt_amount==0)&&($payments>0)) { $pmt_amount=round($data[amount]/$payments, 2); } //echo $this->html->pre_display($payment_range,"payment_range"); $days_loan=$this->dates->F_datediff($data[df], $data[dt], $data[base]); $data[days_loan]=$days_loan; $months_loan=$days_loan/365*12; $pays_per_year=$data[freq]; if (($days_loan>366)&&($data[freq]==1)&&($data[periods]==1)) { $pays_per_year=365/$days_loan; } $data[pays_per_year]=$pays_per_year; $data[months_loan]=$months_loan; $months_loan_rounded=round($months_loan); $data[months_loan_rounded]=$months_loan_rounded; if($data[maturity_id]>0){ $fields=array('#','Action','date','Given','Payment','Pcpl. paid','Int.paid','Balance','Interest','Int. Accum.','Interest Bal','Tot.Bal.','Int. rate total','Def.Interest','Def.rate','Days','Margin rate','Floating int.','Floating rate','Rate date',''); }else{ $fields=array('#','Action','date','Given','Payment','Pcpl. paid','int.Paid','Balance','Interest','rate','def.Interest','Def.rate','days',''); } $tbl=$this->html->tablehead($what, $qry, $order, $addbutton, $fields, 'no_sort'); foreach ($period_data_arr as $key => $period_data) { $i++; //echo "$period_data[df] $period_data[dt] $period_data[note]<br>"; $date=$period_data[dt]; $given=($period_data[note]=='loan')?$data[amount]:0; $data4interest=[ 'amount'=>$balance, 'rate'=>$period_data['rate'], 'freq'=>$data['compounding_freq'], 'df'=>$period_data[df], 'dt'=>$period_data[dt], 'base'=>$data[base], 'compound'=>$data[compound], 'note'=>$period_data[note], ]; $calc_interest=$this->interest->getInterest($data4interest); // echo $this->html->cols2($this->html->pre_display($data4interest,"data4interest $period_data[df] $period_data[dt] $period_data[note]"), // $this->html->pre_display($calc_interest,"calc_interest $period_data[df] $period_data[dt] $period_data[note]") // ); $interest=$calc_interest[interest]; $data4interest[rate]=$period_data['libor_rate'];//+$period_data['rate']; $calc_interest=$this->interest->getInterest($data4interest); $libor_interest=$calc_interest[interest]; if(!($data[int_paid_last]>0))$interest_paid=$interest; if(($period_data[note]!='chk')&&($period_data[note]!='loan')){ if($period_data[note]!='loan'){ $no++; $no_str=$no; }else{ $no_str=''; } $pmt=(($no%$payment_range)==0)?$pmt_amount:0; //echo "I.$no=".($no%$payment_range)." ($pmt)($pmt_amount)($payment_range)<br>"; if (($pmt==0)&&($no==$periods)) { $pmt=$balance+$interest; } if ($pmt>0) { $amount=$pmt-$interest; $interest_paid=$interest; if(($data[int_paid_last]>0))$interest_paid=$t_interest+$interest; } else { $amount=0; } if (($payment_range>1)&&($pmt>0)) { $amount=$pmt; } $days=$period_data[days];//$this->dates->F_datediff($date_prev, $date, $data[base]); $t_days+=$days; }else{ //echo "note:$period_data[note]<br>"; $total=0; $amount=0; $no_str=''; $interest_paid=0; if($period_data[note]=='chk'){ $days=$period_data[days]; $i--; }else{ $interest=0; $libor_interest=0; } } $t_given+=$given; $t_paid+=$pmt; $t_interest_paid+=$interest_paid; $t_interest+=$interest; $t_interest_compound_accum+=$interest; //$data['interest_bf']=0; if ((($i-1) % $data[compounding_mod] == 0)&&($period_data[note]!='chk')){ $t_interest_compound+=$t_interest_compound_accum; $t_interest_compound_accum=0; } $t_principal_paid+=$amount; $total=$amount+$interest_paid; $t_total_paid+=$total; $t_amount+=$amount; $t_default_interest+=$default_interest; $t_libor_interest+=$libor_interest; //$t_margin_interest+=$margin_interest; $balance_prev=$balance; if ($this->dates->is_earlier($date, $data['dt'],1)) { $rate=$period_data['rate']; $def_rate=0; $init_interest=$interest; $def_interest=0; }else{ $def_rate=$period_data['rate']; $rate=0; $def_interest=$interest; $init_interest=0; } if($period_data[note]!='chk'){ if ($this->dates->is_earlier($date, $data['dt'])) { if(($data[compound]>0)||($data[compounding]>0)){ //$balance=$balance-$amount+$interest-$interest_paid; $balance=$t_given-$t_amount+$t_interest_compound-$t_interest_paid; }else{ //$balance=$balance-$amount; $balance=$t_given-$t_amount-$t_paid; } }else{ if(($data[compound_default]>0)||($data[compounding_default]>0)){ //$balance=$balance-$amount+$interest-$interest_paid; $balance=$t_given-$t_amount+$t_interest-$t_interest_paid; }else{ $balance=$balance-$amount; } } }else{ // $t_interest_compound_accum+=$init_interest; } $t_init_interest+=$init_interest; $t_def_interest+=$def_interest; $t_bal=$balance+$t_interest_compound_accum; //echo \util::pre_display($period_data,"period_data"); $tbl.="<tr class='$class'><td>$no_str</td> <td>$period_data[note]</td> <td>$date</td> <td class='n'>".$this->html->money($given)."</td> <td class='n'>".$this->html->money($total)."</td> <td class='n'>".$this->html->money($amount)."</td> <td class='n'>".$this->html->money($interest_paid)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money($init_interest)."</td> <td class='n'>".$this->html->money($t_init_interest)."</td> <td class='n'>".$this->html->money($t_interest_compound_accum)."</td> <td class='n'>".$this->html->money($t_bal)."</td> <td class='n'>".$this->html->money($rate*100,'','',5)." %</td> <td class='n'>".$this->html->money($def_interest)."</td> <td class='n'>".$this->html->money($def_rate*100,'','',5)." %</td> <td class='n'>$days</td>"; if($data[maturity_id]>0){ $tbl.="<td class='n'>".$this->html->money($margin_rate*100,'','',5)."</td>"; $tbl.="<td class='n'>".$this->html->money($libor_interest)."</td>"; $tbl.="<td class='n'>".$this->html->money($period_data['libor_rate']*100,'','',5)." %</td>"; $tbl.="<td>$period_data[libor_date]</td>"; } $tbl.="<td>$note</td>"; //$tbl.="<td class='n'>G:".$this->html->money($t_given)." A:".$this->html->money($t_amount)." p:".$this->html->money($t_paid)." I:".$this->html->money($t_interest_paid)." ".$this->html->money($t_interest_paid)."</td>"; $tbl.="</tr>"; $plan[]=[ 'no'=>$no_str, 'action'=>$period_data[note], 'date'=>$date, 'df'=>$period_data[df], 'dt'=>$period_data[dt], 'given'=>$given, 'returned'=>$amount, 'int_paid'=>$interest_paid, 'balance'=>$balance, 'interest'=>$interest, 'interest_accum'=>$t_init_interest, 'interest_bal'=>$t_interest_compound_accum, 'total_bal'=>$t_bal, 'rate'=>$period_data['rate'], 'days'=>$days, 'default_interest'=>$default_interest, 'libor_interest'->$libor_interest, 'libor_rate'=>$period_data['libor_rate'], 'libor_date'=>$period_data[libor_date], 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'', ]; if($period_data[note]=='chk'){ $data['balance_principal']=$data[amount]-$t_principal_paid; $data['balance_interest']=$t_bal-($data[amount]-$t_principal_paid); $data['balance_total']=$t_bal; $t_interest_compound_accum-=$init_interest; $t_init_interest-=$init_interest; $t_interest-=$init_interest; } } $totals=array_fill(0, 20, 0); $totals[2]=$data[amount]; $totals[3]=$t_total_paid; $totals[4]=$t_principal_paid; $totals[5]=$t_interest_paid; $totals[8]=$t_init_interest; $totals[9]=$t_interest_compound_accum; $totals[12]=$t_def_interest; //$totals[6]=$balance; $totals[14]=$t_days; if($data[maturity_id]>0){ //$totals[12]=$t_default_interest; $totals[16]=$t_libor_interest; //$totals[12]=$t_margin_interest; } $tbl.=$this->html->tablefoot($i, $totals, $no); $res=$data; $res[period_data]=$period_data_arr2; $res[tbl]=$tbl; $res[plan]=$plan; //echo $this->html->pre_display($res,"res"); return $res; } public function planLoan($data) { $GLOBALS[debug][stopwatch]='plan_loan'; //echo $this->html->pre_display($data,"f:plan_loan"); //$days_add=$this->dates->F_datediff($data[df],$data[dt]); //echo "$days_add<br>"; $res=$data; if ($data[base]=='365') { $daysinyear=365; } else { $daysinyear=360; } if ($data[base]=='') { $data[base]='30/360'; } $periods=$data['periods']; if ($periods==0) { $periods=1; } if ($data['align']>0) $periods++; $payments=$data['payments']; $payment_range=round($periods/$payments); //echo "payment_range=$payment_range=round($periods/$payments)<br>"; if (($payment_range==0)||($payment_range==INF)) { $payment_range=1; } //echo $this->html->pre_display($payment_range,"payment_range"); $days_loan=$this->dates->F_datediff($data[df], $data[dt], $data[base]); $data[days_loan]=$days_loan; $months_loan=$days_loan/365*12; $pays_per_year=$data[freq]; if (($days_loan>366)&&($data[freq]==1)&&($data[periods]==1)) { $pays_per_year=365/$days_loan; } $data[pays_per_year]=$pays_per_year; $data[months_loan]=$months_loan; $months_loan_rounded=round($months_loan); $data[months_loan_rounded]=$months_loan_rounded; //echo $this->html->pre_display($data,"F:plan_loan"); //echo "D:$payment_range<br>"; $fields=array('#','Action','date','Given','Payment','Pcpl. paid','int.Paid','Balance','Interest','rate','days',''); $tbl=$this->html->tablehead($what, $qry, $order, $addbutton, $fields, $sort); $i=0; $no=1; $date=$data[df]; $pmt_amount=$data[pmt]; if (($payment_range>=1)&&($pmt_amount==0)&&($payments>0)) { $pmt_amount=round($data[amount]/$payments, 2); } $pmt=0; $balance=$data[amount]; $tbl.="<tr class='$class'><td>$no</td> <td>Loan</td> <td>$date</td> <td class='n'>".$this->html->money($data[amount])."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($data['rate']*100)." %</td> <td class='n'>0</td> <td>$notes</td> </tr>"; $found=0; if ($this->dates->is_earlier($data['date'], $data['df'])) { $found=1; } $plan[]=array( 'no'=>$no, 'action'=>'Loan', 'date'=>$date, 'given'=>$data[amount], 'returned'=>0, 'int_paid'=>0, 'balance'=>$balance, 'interest'=>0, 'rate'=>$data['rate'], 'days'=>0, 't_given'=>$data[amount], 't_returned'=>0, 't_interest'=>0, 't_paid'=>0, 'info'=>'', ); $ignore_weekends=($data['ignore_weekends']=='t')?1:0; $date_initial=$date; /// ======== Align to date if ($data['align']>0) { $no++; $date_prev=$date; if ($data['align']<32) { $day=substr($date, 0, 2); //echo "$day<br>"; if ($data['align']>=$day) { $days_add=$data['align']-$day; } else { $days_add=$data['align']-$day + $this->days_in_month($date); } $align_text="$data[align] day of the month"; } else { $days_add=$this->dates->F_datediff($date, $this->dates->lastday_in_month($date)); $align_text="the last day of the month"; } $date=$this->dates->F_dateadd_day($date, $days_add,$ignore_weekends); $data4interest=array( 'amount'=>$balance, 'rate'=>$data['rate'], 'freq'=>$data['freq'], 'df'=>$date_prev, 'dt'=>$date, 'base'=>$data[base], 'compound'=>$data[compound], 'interest_margin'=>$data[interest_margin], 'maturity_id'=>$data[maturity_id], 'source_id'=>$data[source_id], 'note'=>'Plan Loan. Allign.', ); $calc_interest=$this->interest->getInterest($data4interest); $interest=$calc_interest[interest]; if ($pmt>0) { $amount=$pmt-$interest; } else { $amount=0; } $balance_prev=$balance; $balance=$balance-$amount; $days=$this->dates->F_datediff($date_prev, $date, $data[base]); $days_chk=$this->dates->F_datediff($date, $data['date']); $notes=''; //$notes=$this->html->pre_display($calc_interest); if (($days_chk<=0)&&($found==0)) { $found=1; $res[balance]=$balance_prev; $res[interest]=$interest; $res[t_paid]=$t_paid; $res[t_interest_paid]=$t_interest_paid; $res[t_principal_paid]=$t_principal_paid; $res[next_payment]=$date; $res[days_till_next]=-$days_chk; //$info=$this->html->pre_display($res); //$notes="<span class='badge red'>DATE $data[date]</span> $info"; } $t_paid+=$pmt; $t_interest_paid+=$interest; $t_principal_paid+=$amount; $total=$amount+$interest; $t_days+=$days; $tbl.="<tr class='$class'><td>$no</td> <td>Pay</td> <td>$date</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($total)."</td> <td class='n'>".$this->html->money($amount)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($data['rate']*100)." %</td> <td class='n'>$days</td> <td>Aligned to $align_text $notes</td> </tr>"; $plan[]=array( 'no'=>$no, 'action'=>'Pay', 'date'=>$date, 'given'=>0, 'returned'=>$amount, 'int_paid'=>$interest, 'balance'=>$balance, 'interest'=>$interest, 'rate'=>$data['rate'], 'days'=>$days, 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'', ); } /// END ======== Align to date $date_alligned=$date; //if($pays_per_year>1)$months=12/$months_loan; else $months=12; if ($pays_per_year>1) { $months=12/$pays_per_year; } else { $months=12; } //echo "pays_per_year=$pays_per_year / $months_loan ($months)<br>"; /// ======== Loop for periods for ($i=1; $i<=$periods; $i++) { $no++; $date_prev=$date; if ($months>1) { //echo "$months / $days_loan<br>"; if ($pays_per_year>=1) { $date_before=$date; $date=$this->dates->F_dateadd_month($date_alligned, $months*$i,$ignore_weekends); //echo $this->html->pre_display($pays_per_year,"$date_before - $date pays_per_year $months ($days_add)"); } else { $date=$this->dates->F_dateadd($date, $days_loan); //echo "DL:$days_loan<br>"; } if (($days_add>0)&&($data['align']==32)) { $date=$this->dates->lastday_in_month($this->dates->F_dateadd($date, -15)); } if (($days_add>0)&&($i==$periods)) { $date=$this->dates->F_dateadd($date, -$days_add); } //if($no>=5)echo $this->html->pre_display(['Date'=>$date,'Days_add'=>$days_add],"result4"); } else { $days_in_month=$this->dates->days_in_month_date($this->dates->F_dateadd($date, 15)); if (($days_add>0)&&($i==$periods)) { $days_in_month=$days_in_month-$days_add; } $date=$this->dates->F_dateadd($date, $days_in_month); //$date=$this->dates->F_dateadd_month($date,$months); } $days_chk=$this->dates->F_datediff($date, $data['date']); $notes=''; //$notes=$this->html->pre_display($calc_interest); if (($days_chk<=0)&&($found==0)) { $data4interest=array( 'amount'=>$balance, 'rate'=>$data['rate'], 'freq'=>$data['freq'], 'df'=>$date_prev, 'dt'=>$data[date], 'base'=>$data[base], 'compound'=>$data[compound], 'interest_margin'=>$data[interest_margin], 'maturity_id'=>$data[maturity_id], 'source_id'=>$data[source_id], 'note'=>'Plan Loan. Main No '.$no, ); $calc_interest=$this->interest->getInterest($data4interest); $found=1; $res[balance]=$balance_prev; $res[interest]=$calc_interest[interest]; $res[t_paid]=$t_paid; $res[t_interest_paid]=$t_interest_paid+$res[interest]; $res[t_principal_paid]=$t_principal_paid; $res[next_payment]=$date; $res[days_till_next]=-$days_chk; //$info=$this->html->pre_display($res); $info.="<table> <tr><td>Balance:</td><td class='n'>".$this->html->money($res[balance])."</td></tr> <tr><td>Interest:</td><td class='n'>".$this->html->money($res[interest])."</td></tr> <tr><td>Interest acc:</td><td class='n'>".$this->html->money($res[t_interest_paid])."</td></tr> <tr><td>DTNP:</td><td class='n'>$res[days_till_next]</td></tr> </table>"; $notes="<span class='label'>DATE $data[date]</span><br><span class=''>$info</span>"; } $data4interest=array( 'amount'=>$balance, 'rate'=>$data['rate'], 'freq'=>$data['freq'], 'df'=>$date_prev, 'dt'=>$date, 'base'=>$data[base], 'compound'=>$data[compound], 'interest_margin'=>$data[interest_margin], 'maturity_id'=>$data[maturity_id], 'source_id'=>$data[source_id], 'note'=>'Plan Loan. Final', ); $calc_interest=$this->interest->getInterest($data4interest); //echo $this->html->pre_display($calc_interest,"calc_interest"); $interest=$calc_interest[interest]; $pmt=(($i%$payment_range)==0)?$pmt_amount:0; //echo "I.$i=".($i%$payment_range)." ($pmt)($pmt_amount)($payment_range)<br>"; if (($pmt==0)&&($i==$periods)) { $pmt=$balance+$interest; } if ($pmt>0) { $amount=$pmt-$interest; } else { $amount=0; } if (($payment_range>1)&&($pmt>0)) { $amount=$pmt; } $balance_prev=$balance; $balance=$balance-$amount; $days=$this->dates->F_datediff($date_prev, $date, $data[base]); $t_paid+=$pmt; $t_interest_paid+=$interest; $t_principal_paid+=$amount; $total=$amount+$interest; $t_total_paid+=$total; $t_days+=$days; $tbl.="<tr class='$class'><td>$no</td> <td>Pay</td> <td>$date</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($total)."</td> <td class='n'>".$this->html->money($amount)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($data['rate']*100)." %</td> <td class='n'>$days</td> <td>$notes</td> </tr>"; $plan[]=array( 'no'=>$no, 'action'=>'Pay', 'date'=>$date, 'given'=>0, 'returned'=>$amount, 'int_paid'=>$interest, 'balance'=>$balance, 'interest'=>$interest, 'rate'=>$data['rate'], 'days'=>$days, 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'', ); } /// END ======== Loop for periods $totals=array_fill(0, 10, 0); $totals[2]=$data[amount]; $totals[3]=$t_total_paid; $totals[4]=$t_principal_paid; $totals[5]=$t_interest_paid; //$totals[6]=$balance; $totals[9]=$t_days; $tbl.=$this->html->tablefoot($i, $totals, $no); $res[rows]=$no; $res[amount_total]=$plan[$no-1][t_given]; $res[amount_returned_total]=$plan[$no-1][t_returned]; $res[amount_interest_total]=$plan[$no-1][t_interest]; $res[amount_paid_total]=$plan[$no-1][t_paid]; if (($res[interest]==0)&&($found==0)) { $res[interest]=$res[amount_interest_total]; } if ($found==0) { $res[balance]=$res[amount_total]-$res[amount_returned_total]; $res[interest]=$interest; $res[t_paid]=$res[amount_paid_total]; $res[t_interest_paid]=$res[amount_interest_total]; $res[t_principal_paid]=$res[amount_returned_total]; $res[next_payment]=$dt; $res[days_till_next]=0; } $res[amount_returned_total]=round($res[amount_returned_total], 2); $res[amount_interest_total]=round($res[amount_interest_total], 2); $res[balance]=round($res[balance], 2); $res[interest]=round($res[interest], 2); $res[t_paid]=round($res[t_paid], 2); $res[t_interest_paid]=round($res[t_interest_paid], 2); $res[t_principal_paid]=round($res[t_principal_paid], 2); $res[amount_paid_total]=round($res[amount_paid_total], 2); $res[days]=$t_days; $res[tbl]=$tbl; $res[plan]=$plan; return $res; } } <file_sep><?php namespace Test\Rozdol\Loans; use Rozdol\Loans\Interest; use PHPUnit\Framework\TestCase; class InterestTest extends TestCase { protected function setUp() { //$this->interest = Interest::getInstance(); $this->interest = new Interest(); } /** * @dataProvider transactionsProvider */ public function testIneterst($data, $expected) { $result = $this->interest->getInterest($data); $this->assertEquals($expected, $result['interest']); } /** * @dataProvider datesProvider */ // public function testDateDiff($df, $dt, $base, $res) // { // //$result = Interest::F_datediff($df, $dt, $base); // //$this->assertEquals($res, $result); // } public function transactionsProvider() { $data=[ 'amount'=>1000000, 'rate'=>0.1, 'freq'=>12, 'df'=>'01.01.2010', 'dt'=>'01.01.2011', 'base'=>'365', 'compound'=>1, 'note'=>'Calc Loan test' ]; return [ [$data, 104713.07] ]; } public function datesProvider() { return [ ['01.01.2018','01.02.2018','365',31], ['01.02.2018','01.03.2018','365',28], ['01.02.2020','01.03.2020','365',29], ]; } } <file_sep><?php namespace Rozdol\Loans; class Calculator { /** * get random number * * @return array */ public static function sum2num($a, $b) { $b = $a + $b; return [ 'result' => $b, 'rnd' => rand() ]; } } <file_sep><?php namespace Test\Rozdol\Loans; use Rozdol\Loans\Planner; use PHPUnit\Framework\TestCase; class PlannerTest extends TestCase { protected function setUp() { $this->planner = Planner::getInstance(); //$this->planner = new Interest(); } // public function testPlanner() // { // $result = $this->planner->planLoan($data); // //$this->getActualOutput($result); // fwrite(STDERR, print_r($result, true)); // $this->assertEquals(0, $result['given']); // } /** * @dataProvider transactionsProvider */ public function testLoan($data, $expected1, $expected2, $expected3, $expected4) { $result = $this->planner->planLoan($data); unset($result[plan]); unset($result[tbl]); //fwrite(STDERR, print_r($result, true)); $this->assertEquals($expected1, $result[amount_total]); $this->assertEquals($expected2, $result[days]); $this->assertEquals($expected3, $result[rows]); $this->assertEquals($expected4, $result[amount_interest_total]); } public function transactionsProvider() { $data=array ( 'amount' => '1000000', 'rate' => 0.10, 'freq' => '12', 'df' => '01.01.2020', 'dt' => '01.01.2021', 'base' => '30/360', 'p_rate' => 0.10, 'date' => '01.01.2020', 'compound' => 'f', 'payments' => '12', 'periods' => 12.0, 'period_rate' => (.1/12), 'pmt' => 87915.89, 'align' => '0', ); $data2=$data; $data3=$data; $data2[compound]='t'; $data3[base]='365'; return [ [$data,1000000,360,13,54865.13], [$data2,1000000,360,13,54990.65], [$data3,1000000,366,13,54865.13] ]; } } <file_sep><?php namespace Rozdol\Loans; use Rozdol\Dates\Dates; use Rozdol\Loans\Interest; use Rozdol\Utils\Utils; use Rozdol\Html\Html; //use Rozdol\Loans\Planner; class Loan { private static $hInstance; public static function getInstance() { if (!self::$hInstance) { self::$hInstance = new Loan(); } return self::$hInstance; } public function __construct() { $this->dates = new Dates(); $this->interest = new Interest(); $this->utils = new Utils(); $this->html = new Html(); $this->planner = new Planner(); } public function getInterest($data) { return $this->interest->getInterest($data); } public function planLoan($data) { return $this->planner->planLoan($data); } public function getDates($data) { return $this->planner->getDates($data); } public function getPlan($data) { return $this->planner->getPlan($data); } public function getPlanV2($data) { return $this->planner->getPlanV2($data); } public function calcPmt($data) { //unset($data); //$data['amount']=234000; //$data['period_rate']=0.035/12; //$data['payments']=240; //echo $this->html->pre_display($data,'calc_pmt'); //M = monthly mortgage payment //P = the principal, or the initial amount you borrowed. //r = your monthly interest rate. Your lender likely lists interest rates as an annual figure, so you’ll need to divide by 12, for each month of the year. So, if your rate is 5%, then the monthly rate will look like this: 0.05/12 = 0.004167. //n = the number of payments, or the payment period in months. If you take out a 30-year fixed rate mortgage, this means: n = 30 years x 12 months per year, or 360 payments. //echo $this->html->pre_display($data,"result"); $p=$data['amount']; $r=$data['period_rate']; $n=$data['payments']; //$M = $P*( $r*(1 + $r)^$n ) / ((1 + $r)^$n – 1); $m1=$r*(pow((1+$r), $n)); $m2=pow((1+$r), $n)-1; if($m2!=0)$m=$p*($m1/$m2); //echo $this->html->pre_display(['m1'=>$m1, 'm2'=>$m2, 'm'=>$m],"calcPmt"); return $m*1; } /** * calc Loan * * @return array */ public function calcLoan($data) { // Debug related code $GLOBALS[debug][stopwatch]='calc_loan'; if ($GLOBALS[access][view_debug]) { $data[domain]=$GLOBALS[debug][stopwatch]; $GLOBALS[debug][calc_loan][]=$data; } //echo $this->html->pre_display($data,'data'); //exit; $totals=array_fill(0, 19, 0); $expired=0; if ($data[loan_data][base]=='365') { $daysinyear=365; } else { $daysinyear=360; } if ($data[loan_data][base]=='') { $data[loan_data][base]='30/360'; } $res=$data; $res[err]=''; // initial data $loan_data=$res[loan_data]; $res[days]=$this->dates->F_datediff($loan_data[df], $loan_data[dt], $loan_data[base]); $base=$loan_data[base]; $rate=$loan_data[rate]; $freq=$loan_data[freq]; $days_allowed=$daysinyear/$freq; $max_amount=$loan_data[amount]; $date=$this->dates->F_date($loan_data[date], 1); $data=array( 'amount'=>$loan_data[amount], 'rate'=>$loan_data[rate], 'freq'=>$loan_data[freq], 'df'=>$loan_data[df], 'dt'=>$loan_data[dt], 'base'=>$loan_data[base], 'compound'=>$loan_data[compound], 'maturity_id'=>$loan_data[maturity_id], 'source_id'=>$loan_data[source_id], 'note'=>'Calc Loan. Initial', ); $whole_loan=$this->getInterest($data); //echo $this->html->pre_display($whole_loan,"whole_loan"); $transactions=$res[transactions]; //echo \util::pre_display($transactions,"transactions"); //$bal=$transactions[0][given]; $notes=$transactions[0][descr]; $last_intpaid=$transactions[0][date]; $fields=array('#','Action','date','Given','returned','int.Paid','int.adj.','Balance','Interest','Interest bal','Margin rate','Floating rate' ,'Int. rate total','days',''); $tbl=$this->html->tablehead($what, $qry, $order, $addbutton, $fields, $sort); //transactions $GLOBALS[debug][stopwatch]='calc_loan_main'; // Transactions loop foreach ($transactions as $transaction) { $days=$this->dates->F_datediff($transaction[date], $loan_data['date']); //echo "TR: days:$days ($loan_data[date] - $transaction[date])<br>"; if($days<0) continue; $type=''; $i++; $descr=''; $class=''; $rate=$transaction[rate_margin]+$transaction[rate_float]; if ($transaction[given]>0) { $descr.='Give'; $type='GIV'; } if ($transaction[returned]>0) { $descr.='Return'; $type='RET'; } if ($transaction[paid]>0) { $descr.='Pay'; $last_intpaid=$transaction[date]; $type='INT'; } if ($transaction[adjustment]!=0) { $descr.='Interest Adjustment'; $last_intpaid=$transaction[date]; $type='ADJ'; } if (($transaction[given]==0)&&($transaction[returned]==0)&&($transaction[paid]==0)&&($transaction[adjustment]==0)&&(($transaction[descr]!='chk')||($transaction[descr]!='matur'))) { $type='ADD'; $descr.='Addendum'; //$rate=$transaction[rate_margin]+$transaction[rate_float]; if($transaction[freq]>0)$freq=$transaction[freq]; $days_allowed=$daysinyear/$freq; } if (($transaction[given]==0)&&($transaction[returned]==0)&&($transaction[paid]==0)&&($transaction[adjustment]==0)&&($transaction[descr]=='chk')) { $type='CHK'; $descr='Check'; $rate=$transaction[rate_margin]+$transaction[rate_float]; // $freq=$transaction[freq]; //$days_allowed=$daysinyear/$freq; } if (($transaction[given]==0)&&($transaction[returned]==0)&&($transaction[paid]==0)&&($transaction[adjustment]==0)&&($transaction[descr]=='matur')) { $type='MTRT'; $descr='Maturity'; $rate=$transaction[rate_margin]+$transaction[rate_float]; // $freq=$transaction[freq]; //$days_allowed=$daysinyear/$freq; } $totals[2]+=$transaction[given]; $totals[3]+=$transaction[returned]; $totals[4]+=$transaction[paid]; $totals[5]+=$transaction[adjustment]; //echo "$i. $transaction[date] $descr B:$bal<br>"; //First transdaction is special if ($i==1) { //first transaction $amount=$transaction[given]-$transaction[returned]; $loan[dt]=$transaction[date]; $amount1=$amount; $bal=$transaction[given]; //echo $this->html->pre_display($loan, "$i $loan[dt] $descr"); $tbl.="<tr class='$class'><td>$i</td> <td>$descr</td> <td>$loan[dt]</td> <td class='n'>".$this->html->money($transaction[given])."</td> <td class='n'>".$this->html->money($transaction[returned])."</td> <td class='n'>".$this->html->money($transaction[paid])."</td> <td class='n'>".$this->html->money($transaction[paid])."</td> <td class='n'>".$this->html->money($transaction[paid])."</td> <td class='n'>".$this->html->money($transaction[paid])."</td> <td class='n'>".$this->html->money($transaction[paid])."</td> <td class='n'>".$this->html->money($transaction[rate_margin]*100,'','',5)." %</td> <td class='n'>".$this->html->money($transaction[rate_float]*100,'','',5)." %</td> <td class='n'>".$this->html->money($rate*100)." %</td> <td class='n'>$loan[days]</td> <td>$notes</td> </tr>"; $totals[12]+=$loan[days]; $plan[$i]=array( 'no'=>$i, 'action'=>'Pay', 'date'=>$loan[dt], 'given'=>$transaction[given], 'returned'=>$transaction[returned], 'int_paid'=>$transaction[paid], 'balance'=>$transaction[paid], 'interest'=>$transaction[paid], 'rate'=>$rate, 'days'=>$loan[days], 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>$notes, ); } else { // Rest of transactions //check if transaction was after the loan expiration $days=$this->dates->F_datediff($transaction[date], $loan_data[dt]); //echo "Expiration Days:$days $transaction[date] - $loan_data[dt]<br>"; if (($days<0)&&($bal>0)&&($expired==0)) { // Transaction was after expiration of the loan $expired++; $i++; $rate=$loan_data[p_rate]+$transaction[rate_float]; $class='red'; $df=$loan[dt]; $dt=$loan_data[dt]; $data=array( 'amount'=>$bal, 'rate'=>$rate, 'freq'=>$freq, 'df'=>$df, 'dt'=>$dt, 'base'=>$base, 'compound'=>$loan_data[compound], 'maturity_id'=>$loan_data[maturity_id], 'source_id'=>$loan_data[source_id], 'note'=>'Calc Loan. Expired', ); $descr="Expired1" ; $loan=$this->getInterest($data); if (($loan_data[compound]=='f')||($loan_data[compound]==0)) { //$bal=round(($loan[balance]+$transaction[given]-$transaction[returned]),2); $int_bal=$int_bal+$loan[interest];//-$transaction[paid]; } else { $bal=round(($loan[balance]+$transaction[given]-$transaction[returned]-$transaction[paid]), 2); $int_bal=$loan[interest]; } // echo $this->html->cols2($this->html->pre_display($data,"$loan_data[date] data EXP1"),$this->html->pre_display($loan,"loan EXP1 $int_bal")); //$bal=round(($bal+$loan[interest]),2); $totals[8]+=$loan[interest]; $totals[7]+=$loan[interest]; //echo $this->html->pre_display($loan, "$i $dt $descr"); $tbl.="<tr class='$class'><td>$i</td> <td>$descr</td> <td>$dt</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($bal)."</td> <td class='n'>".$this->html->money($loan[interest])."</td> <td class='n'>".$this->html->money($int_bal)."</td> <td class='n'>".$this->html->money($transaction[rate_margin]*100,'','',5)." %</td> <td class='n'>".$this->html->money($transaction[rate_float]*100,'','',5)." %</td> <td class='n'>".$this->html->money($rate*100)." %</td> <td class='n'>$loan[days]</td> <td>Expired period</td> </tr>"; $totals[12]+=$loan[days]; $plan[$i]=array( 'no'=>$i, 'action'=>$descr, 'date'=>$dt, 'given'=>0, 'returned'=>0, 'int_paid'=>0, 'balance'=>$bal, 'interest'=>$loan[interest], 'rate'=>$rate, 'days'=>$loan[days], 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'Expired period', ); $expired_interest=$loan[interest]; } // end of loan expiration block //*** //Repeted code //*** // if ($transaction[given]>0) { // $descr='Give'; // $type='GIV'; // $bal=; // } // if ($transaction[returned]>0) { // $descr='Return'; // $type='RET'; // } // if ($transaction[paid]>0) { // $descr='Pay'; // $last_intpaid=$transaction[date]; // $type='INT'; // } // if ($transaction[adjustment]!=0) { // $descr='Interest Adjustment'; // $last_intpaid=$transaction[date]; // $type='ADJ'; // } // if (($transaction[given]==0)&&($transaction[returned]==0)&&($transaction[paid]==0)&&($transaction[adjustment]==0)) { // $type='ADD'; // $descr='Addendum'; // //$rate=$transaction[rate_margin]+$transaction[rate_float]; // $freq=$transaction[freq]; // $days_allowed=$daysinyear/$freq; // } $df=$loan[dt]; $dt=$transaction[date]; if(isset($transaction[rate]))$rate=$transaction[rate_margin]+$transaction[rate_float]; $days=$this->dates->F_datediff($df, $loan_data[dt]); $notes=$transaction[descr]; // Check for penalties if (($days<0)&&($bal*.9>0)) { $rate=$loan_data[p_rate]+$transaction[rate_float]; $class='roze'; $res[err].="$df Penalty rate of ".($rate*100)." % is applied (Bal:$bal).<br>"; } $data=array( 'amount'=>$bal, 'rate'=>$rate, 'freq'=>$freq, 'df'=>$df, 'dt'=>$dt, 'base'=>$base, 'compound'=>$loan_data[compound], 'maturity_id'=>$loan_data[maturity_id], 'source_id'=>$loan_data[source_id], 'note'=>'Calc Loan. Rest Transactions', ); //echo $this->html->pre_display($data,'data'); $loan=$this->getInterest($data); //echo $this->html->cols2($this->html->pre_display($data,'data '.$i),$this->html->pre_display($loan,'loan')); //exit; //$notes="<span class='badge info'>".$this->html->money($int_bal)." + ".$this->html->money($loan[interest])."</span> $notes"; if (($loan_data[compound]=='f')||($loan_data[compound]==0)) { $bal=round(($loan[balance]+$transaction[given]-$transaction[returned]), 2); $int_bal=$int_bal+$loan[interest]-$transaction[paid]+$transaction[adjustment]; } else { $bal=round(($loan[balance]+$transaction[given]-$transaction[returned]-$transaction[paid]+$transaction[adjustment]), 2); $int_bal=$loan[interest]; } // echo $this->html->cols2($this->html->pre_display($data,"$loan_data[date] data REST"),$this->html->pre_display($loan,"loan REST $int_bal")); if ($bal>$max_amount*1.2) { $class='red'; $notes="$bal>$max_amount Exceeds allowed amount. ".$notes; $res[err].="$df Exceeds allowed amount (Bal:$bal).<br>"; } if ($bal<0) { $class='orange'; $notes='Overpaid. '.$notes; $res[err].="$df Overpaid (Bal:$bal).<br>"; } $days_notpaid=$this->dates->F_datediff($last_intpaid, $dt, $base); $i_periods=floor($days_notpaid/$days_allowed); if (($days_notpaid>$days_allowed)&&($bal>0)&&($i_periods>0)&&($loan[interest]>0)&&($loan_data[int_paid_last]!='t')) { $res[err].="$dt Failed to pay interest for $i_periods periods $last_intpaid - $dt (Bal:".round($loan[interest], 2).").<br>"; } //echo $this->html->pre_display($loan, "$i $dt $descr"); $tbl.="<tr class='$class'><td>$i</td> <td>$descr</td> <td>$dt</td> <td class='n'>".$this->html->money($transaction[given])."</td> <td class='n'>".$this->html->money($transaction[returned])."</td> <td class='n'>".$this->html->money($transaction[paid])."</td> <td class='n'>".$this->html->money($transaction[adjustment])."</td> <td class='n'>".$this->html->money($bal)."</td> <td class='n'>".$this->html->money($loan[interest])."</td> <td class='n'>".$this->html->money($int_bal)."</td> <td class='n'>".$this->html->money($transaction[rate_margin]*100,'','',5)." %</td> <td class='n'>".$this->html->money($transaction[rate_float]*100,'','',5)." %</td> <td class='n'>".$this->html->money($rate*100,'','',5)." %</td> <td class='n'>$loan[days]</td> <td>$notes</td> </tr>"; $totals[12]+=$loan[days]; $plan[$i]=array( 'no'=>$i, 'action'=>$descr, 'date'=>$dt, 'given'=>$transaction[given], 'returned'=>$transaction[returned], 'int_paid'=>$transaction[paid], 'balance'=>$bal, 'interest'=>$int_bal, 'rate'=>$rate, 'days'=>$loan[days], 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>$notes, ); if ($type=='ADD') { $rate=$transaction[rate_margin]+$transaction[rate_float]; } } $totals[8]+=$loan[interest]; $totals[7]+=$loan[interest]; //echo ", B2:$bal, days:$days<br>"; } // End transactions loop // expired period $days=$this->dates->F_datediff($date, $loan_data[dt]); if (($days<0)&&($bal>0)&&($expired==0)) { $expired++; $i++; $rate=$loan_data[rate]; $class='red'; $df=$loan[dt]; $dt=$loan_data[dt]; $data=array( 'amount'=>$bal, 'rate'=>$rate, 'freq'=>$freq, 'df'=>$df, 'dt'=>$dt, 'base'=>$base, 'compound'=>$loan_data[compound], 'maturity_id'=>$loan_data[maturity_id], 'source_id'=>$loan_data[source_id], 'note'=>'Calc Loan. Expired Period', ); $descr="Expired2" ; $loan=$this->getInterest($data); if (($loan_data[compound]=='f')||($loan_data[compound]==0)) { //$bal=round(($loan[balance]+$transaction[given]-$transaction[returned]),2); $int_bal=$int_bal+$loan[interest];//-$transaction[paid]; } else { $bal=round(($loan[balance]+$transaction[given]-$transaction[returned]-$transaction[paid]), 2); $int_bal=$loan[interest]; } // echo $this->html->cols2($this->html->pre_display($data,"$loan_data[date] data EXP2"),$this->html->pre_display($loan,"loan EXP2 $int_bal")); $totals[8]+=$loan[interest]; $totals[7]+=$loan[interest]; //echo $this->html->pre_display($data, "DATA: $i $dt $descr"); echo $this->html->pre_display($loan, "RES: $i $dt $descr"); $tbl.="<tr class='$class'><td>$i</td> <td>$descr</td> <td>$dt</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($bal)."</td> <td class='n'>".$this->html->money($loan[interest])."</td> <td class='n'>".$this->html->money($int_bal)."</td> <td class='n'>".$this->html->money($transaction[rate_margin]*100,'','',5)." %</td> <td class='n'>".$this->html->money($transaction[rate_float]*100,'','',5)." %</td> <td class='n'>".$this->html->money($rate*100)." %</td> <td class='n'>$loan[days]</td> <td>Expired period 2</td> </tr>"; $totals[12]+=$loan[days]; $plan[$i]=array( 'no'=>$i, 'action'=>$descr, 'date'=>$dt, 'given'=>0, 'returned'=>0, 'int_paid'=>0, 'balance'=>$bal, 'interest'=>$loan[interest], 'rate'=>$rate, 'days'=>$loan[days], 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'Expired period 2', ); $expired_interest=$loan[interest]; } //Up to now $i++; $class=''; $descr='Now '; $transaction[date]=$date; $df=$loan[dt]; $dt=$transaction[date]; $days=$this->dates->F_datediff($df, $loan_data[dt]); if ($days<=0) { $rate=$loan_data[p_rate]+$transaction[rate_float]; } if($loan_data[compound_default]>0){ $calc_amount=$bal+$int_bal; }else{ $calc_amount=$bal; } $days=$this->dates->F_datediff($df, $dt); //echo $this->html->pre_display($days,"days"); $data=array( 'amount'=>$calc_amount, 'rate'=>$rate, 'freq'=>$freq, 'df'=>$df, 'dt'=>$dt, 'base'=>$base, 'compound'=>$loan_data[compound], 'maturity_id'=>$loan_data[maturity_id], 'source_id'=>$loan_data[source_id], 'note'=>'Calc Loan. Up to Now', ); $loan=$this->getInterest($data); if($loan_data[compound_default]>0){ $calc_amount=$calc_amount+$loan[interest]; }else{ $calc_amount=$calc_amount; } $df_calc=$dt_calc; if (($loan_data[compound_default]=='t')||($loan_data[compound_default]==1)) { //$bal=round(($loan[balance]+$transaction[given]-$transaction[returned]),2); $int_bal=$int_bal+$loan[interest]; } else { //$bal=round(($loan[balance]+$transaction[given]-$transaction[returned]-$transaction[paid]),2); $int_bal=$loan[interest]; } /* $periods=floor(($loan[days]/365)/$freq)+1; $months=intval(round(12/($periods-1))); $df_calc=$df; for ($period=0; $period < $periods; $period++) { $dt_calc=$this->dates->F_dateadd_month($df_calc, $months); if($this->dates->is_later($dt_calc,$dt))$dt_calc=$dt; $data=array( 'amount'=>$calc_amount, 'rate'=>$rate, 'freq'=>$freq, 'df'=>$df_calc, 'dt'=>$dt_calc, 'base'=>$base, 'compound'=>$loan_data[compound], 'maturity_id'=>$loan_data[maturity_id], 'source_id'=>$loan_data[source_id], 'note'=>'Calc Loan. Up to Now', ); $loan=$this->getInterest($data); if($loan_data[compound_default]>0){ $calc_amount=$calc_amount+$loan[interest]; }else{ $calc_amount=$calc_amount; } $df_calc=$dt_calc; if (($loan_data[compound_default]=='t')||($loan_data[compound_default]==1)) { //$bal=round(($loan[balance]+$transaction[given]-$transaction[returned]),2); $int_bal=$int_bal+$loan[interest]; } else { //$bal=round(($loan[balance]+$transaction[given]-$transaction[returned]-$transaction[paid]),2); $int_bal=$loan[interest]; } //echo $this->html->pre_display([$data,$loan], "DATA: period:$period days:$loan[days] periods:$periods i:$i dt:$dt $descr"); //echo $this->html->pre_display($loan, "RES: $i $dt $descr"); } */ // echo $this->html->cols2($this->html->pre_display($data,"$loan_data[date] data NOW"),$this->html->pre_display($loan,"loan NOW $int_bal")); if (($days<=0)&&($bal*.9>0)) { $rate=$loan_data[p_rate]+$transaction[rate_float]; $class='roze'; $res[err].="$df Penalty rate of ".($rate*100)." % is applied (Bal:$bal).<br>"; } if ($bal<=0) { $class='green'; } if ($bal>0) { $class='roze'; } if ($bal>100) { $class='red'; } if ($int_bal>100) { $class='red'; } //$totals[8]+=$loan[interest]+$totals[5]; $totals[8]=$int_bal;//+$expired_interest; //$totals[7]=$int_bal; $totals[0]=$bal+$totals[8]; //echo $this->html->pre_display($loan, "$i $dt $descr"); $tbl.="<tr class='$class'><td>$i</td> <td>$descr</td> <td>$dt</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($bal)."</td> <td class='n'>".$this->html->money($loan[interest])."</td> <td class='n'>".$this->html->money($int_bal)."</td> <td class='n'>".$this->html->money($transaction[rate_margin]*100,'','',5)." %</td> <td class='n'>".$this->html->money($transaction[rate_float]*100,'','',5)." %</td> <td class='n'>".$this->html->money($rate*100)." %</td> <td class='n'>$loan[days]</td> <td>Up to now </td> </tr>"; $totals[12]+=$loan[days]; $plan[$i]=array( 'no'=>$i, 'action'=>$descr, 'date'=>$dt, 'given'=>0, 'returned'=>0, 'int_paid'=>0, 'balance'=>$bal, 'interest'=>$int_bal, 'rate'=>$rate, 'days'=>$loan[days], 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'Up to now', ); $totals[6]=$bal; if (($loan_data[compound]=='f')||($loan_data[compound]==0)) { $totals[9]=$totals[7]; }else{ $totals[9]=$totals[7]+$totals[8]; } //echo "$i. $transaction[date] $descr B:$bal<br>"; $tbl.=$this->html->tablefoot($i, $totals, $i); $res[tbl]=$tbl; $res[csv]=$this->utils->tbl2csv($tbl); $res[data]=$plan; $res[balance]=round($totals[6], 2); $res[given]=$totals[2]; $res[returned]=$totals[3]; $res[returned_i]=$totals[4]; $res[interest]=round($totals[8], 2);//+$expired_interest; $res[interest_accrued]=round($totals[9], 2); $res[interest_due]=$res[interest_accrued]-$res[returned_i]; $res[interest_predict]=round($whole_loan[interest]); $res[completion]=round((($res[given]+$res[returned]+$res[returned_i]))/(($whole_loan[amount]*2+$res[interest_accrued])), 2); $res[completion_prc]=$res[completion]*100; $res[progress]=$this->html->draw_progress($res[completion_prc]); $res[completion1]=round(($res[given])/($whole_loan[amount]), 2)*100; $res[completion2]=round((($res[returned]+$res[returned_i]))/(($res[given]+$res[interest_accrued])), 2)*100; $res[progress2]=$this->html->draw_progress($res[completion1]).$this->html->draw_progress($res[completion2]); $out.= "<table class='table table-morecondensed table-notfull'>"; $out.="<tr><td class='mr'><b>Completion: </b></td><td class='mt'>$res[completion_prc] %</td></tr>"; $out.="<tr><td class='mr'><b>Amount: </b></td><td class='mr'>".$this->html->money($whole_loan[amount])."</td></tr>"; $out.="<tr><td class='mr'><b>Amount given: </b></td><td class='mr'>".$this->html->money($res[given])."</td></tr>"; $out.="<tr><td class='mr'><b>Amount returned: </b></td><td class='mr'>".$this->html->money($res[returned])."</td></tr>"; $out.="<tr><td class='mr'><b>Amount interest accrued: </b></td><td class='mr'>".$this->html->money($res[interest_accrued])."</td></tr>"; $out.="<tr><td class='mr'><b>Amount interest paid: </b></td><td class='mr'>".$this->html->money($res[returned_i])."</td></tr>"; $out.="<tr><td class='mr'><b>Amount interest due: </b></td><td class='mr'>".$this->html->money($res[interest_due])."</td></tr>"; $out.="<tr><td class='mr'><b>Amount interest planned (max): </b></td><td class='mr'>".$this->html->money($res[interest_predict])."</td></tr>"; $out.="</table>"; $res[details]=$out; return $res; } } <file_sep><?php ///=========================================== $data_plan=[]; $given=0; $returned=0; $int_paid=0; $i=0; $out.="<h3>Analysis results by plan</h3>"; $fields=array('#','Action','date','executed','should be','difference'); $out.= $this->tablehead($what,$qry, $order, $addbutton, $fields,$sort); $sql="SELECT * FROM plan p where date_YMD<='".$this->F_USdate($GLOBALS[today])."'"; $plan2=$this->sql_to_array($sql); //echo $this->html->pre_display($plan2,"plan2 ".$GLOBALS[today]);exit; foreach($plan2 as $no=>$row){ $i++; $data=[]; $info=[]; //echo "$i<br>"; $row[given]=round($row[given],2); $row[returned]=round($row[returned],2); $row[int_paid]=round($row[int_paid],2); unset($row[id]); //echo $this->html->pre_display($row,"result"); $sql="SELECT * FROM calc p where date_YMD='$row[date_YMD]'"; $transactions=$this->sql_to_array($sql); $transaction=$transaction[0]; unset($transaction_tmp); foreach ($transactions as $key => $transaction_loop) { $transaction_tmp[given]+=round($transaction_loop[given],2); $transaction_tmp[returned]+=round($transaction_loop[returned],2); $transaction_tmp[int_paid]+=round($transaction_loop[int_paid],2); } $transaction[given]=round($transaction_tmp[given],2); $transaction[returned]=round($transaction_tmp[returned],2); $transaction[int_paid]=round($transaction_tmp[int_paid],2); unset($transaction[id]); //$out.= $this->html->pre_display($transaction,"plan $row[no]"); //echo $this->html->cols2($this->html->pre_display($row),$this->html->pre_display($transaction),"Plan","Real"); $alerted=0; if(($row[given]!=$transaction[given])&&($row[given]>0)){ $given=$given+$row[given]-$transaction[given]; $diff=$transaction[given]-$row[given]; $out.= "<tr><td>$row[no]</td><td>Wrong <b>amount</b> borrowed</td><td>$row[date]</td><td class='n'><span class='badge red'>".$this->money($transaction[given])."</span></td><td class='n'><span class='badge green'> ".$this->money($row[given])."</span></td><td class='n'><span class='badge red'>".$this->money($diff)."</span></td></tr>"; $alerted=1; $info[message]="Wrong amount borrowed"; $info[executed]=$transaction[given]; $info[shoulbe]=$row[given]; $info[diff]=$diff; } if(($row[returned]!=$transaction[returned])&&($row[returned]>0)){ $returned=$returned+$row[returned]-$transaction[returned]; $diff=$transaction[returned]-$row[returned]; $out.= "<tr><td>$row[no]</td><td>Wrong <b>principal</b> returned</td><td>$row[date]</td><td class='n'><span class='badge red'>".$this->money($transaction[returned])."</span></td><td class='n'><span class='badge green'>".$this->money($row[returned])."</span></td><td class='n'><span class='badge red'>".$this->money($diff)."</span></td></tr>"; $alerted=1; $info[message]="Wrong principal returned"; $info[executed]=$transaction[returned]; $info[shoulbe]=$row[returned]; $info[diff]=$diff; } if(($row[int_paid]!=$transaction[int_paid])&&($row[int_paid]>0)){ $int_paid=$int_paid+$row[int_paid]-$transaction[int_paid]; $diff=$transaction[int_paid]-$row[int_paid]; $out.= "<tr><td>$row[no]</td><td>Wrong <b>interest</b> paid</td><td>$row[date]</td><td class='n' ><span class='badge red'>".$this->money($transaction[int_paid])."</span></td><td class='n'><span class='badge green'>".$this->money($row[int_paid])."</span></td><td class='n'><span class='badge red'>".$this->money($diff)."</span></td></tr>"; $alerted=1; $info[message]="Wrong interest paid"; $info[executed]=$transaction[int_paid]; $info[shoulbe]=$row[int_paid]; $info[diff]=$diff; } if(($int_paid!=0)&&($alerted==0)){ $out.= "<tr><td>$row[no]</td><td>Wrong <b>interest</b> balance</td><td>$row[date]</td><td> </td><td> </td><td class='n'><span class='badge red'>".$this->money($int_paid)."</span></td></tr>"; $info[message]="Wrong interest balance"; $info[executed]=$int_paid; } if(($returned!=0)&&($alerted==0)){ $out.= "<tr><td>$row[no]</td><td>Wrong <b>principal</b> balance</td><td>$row[date]</td><td> </td><td> </td><td class='n'><span class='badge red'>".$this->money($returned)."</span></td></tr>"; $info[message]="Wrong principal balance"; $info[executed]=$returned; } $data[info]=$info; $data[plan]=$row; $data[trans]=$transaction; $data_plan[]=$data; //if($returned!=0) //if($given!=0) //if(($given!=0)||($returned!=0)||($int_paid!=0))$out.= "$row[no] - $row[date] (G:$given;R:$returned;I:$int_paid) $row[given]=".$transaction[given]." | $row[returned]=".$transaction[returned]." | $row[int_paid]=".$transaction[int_paid]."<br>"; } $out.= "<table>"; ///=========================================== $data_trans=[]; $given=0; $returned=0; $int_paid=0; $i=0; $rows=count($calc[data]); $out.="<h3>Analysis results by transactions</h3>"; $fields=array('#','Action','date','executed','should be','difference'); $out.= $this->tablehead($what,$qry, $order, $addbutton, $fields,$sort); $sql="SELECT * FROM calc p"; $plan3=$this->sql_to_array($sql); //echo $this->pre_display($plan3,"plan3"); foreach($plan3 as $no=>$transaction){ $i++; $data=[]; $info=[]; //echo "$i<br>"; //echo $this->pre_display($transaction,"result"); $sql="SELECT * FROM plan p where date='$transaction[date]'"; $plan=$this->sql_to_array($sql); $plan=$plan[0]; unset($plan[id]); //$out.= $this->html->pre_display($plan,"plan $transaction[no]"); //echo $this->html->cols2($this->html->pre_display($plan),$this->html->pre_display($transaction),"Plan","Real"); $transaction[given]=round($transaction[given],2); $transaction[returned]=round($transaction[returned],2); $transaction[int_paid]=round($transaction[int_paid],2); $plan[given]=round($plan[given],2); $plan[returned]=round($plan[returned],2); $plan[int_paid]=round($plan[int_paid],2); $alerted=0; if(($transaction[given]!=$plan[given])&&($transaction[given]>0)){ $given=$given+$transaction[given]-$plan[given]; $diff=$transaction[given]-$plan[given]; $out.= "<tr><td>$transaction[no]</td><td>Wrong <b>amount</b> borrowed</td><td>$transaction[date]</td><td class='n'><span class='badge red'>".$this->money($transaction[given])."</span></td><td class='n'><span class='badge green'> ".$this->money($plan[given])."</span></td><td class='n'><span class='badge red'>".$this->money($diff)."</span></td></tr>"; $alerted=1; $info[message]="Wrong amount borrowed"; $info[executed]=$transaction[given]; $info[shoulbe]=$plan[given]; $info[diff]=$diff; } if(($transaction[returned]!=$plan[returned])&&($transaction[returned]>0)){ $returned=$returned+$transaction[returned]-$plan[returned]; $diff=$transaction[returned]-$plan[returned]; $out.= "<tr><td>$transaction[no]</td><td>Wrong <b>principal</b> returned</td><td>$transaction[date]</td><td class='n'><span class='badge red'>".$this->money($transaction[returned])."</span></td><td class='n'><span class='badge green'>".$this->money($plan[returned])."</span></td><td class='n'><span class='badge red'>".$this->money($diff)."</span></td></tr>"; $alerted=1; $info[message]="Wrong principal returned"; $info[executed]=$transaction[given]; $info[shoulbe]=$plan[given]; $info[diff]=$diff; } if(($transaction[int_paid]!=$plan[int_paid])&&($transaction[int_paid]>0)){ $int_paid=$int_paid+$transaction[int_paid]-$plan[int_paid]; $diff=$transaction[int_paid]-$plan[int_paid]; $out.= "<tr><td>$transaction[no]</td><td>Wrong <b>interest</b> paid</td><td>$transaction[date]</td><td class='n' ><span class='badge red'>".$this->money($transaction[int_paid])."</span></td><td class='n'><span class='badge green'>".$this->money($plan[int_paid])."</span></td><td class='n'><span class='badge red'>".$this->money($diff)."</span></td></tr>"; $alerted=1; $info[message]="Wrong interest paid"; $info[executed]=$transaction[given]; $info[shoulbe]=$plan[given]; $info[diff]=$diff; } if(($int_paid!=0)&&($alerted==0)){ $out.= "<tr><td>$transaction[no]</td><td>Wrong <b>interest</b> balance</td><td>$transaction[date]</td><td> </td><td> </td><td class='n'><span class='badge red'>".$this->money($int_paid)."</span></td></tr>"; $info[message]="Wrong interest balance"; $info[executed]=$int_paid; } if(($returned!=0)&&($alerted==0)){ $out.= "<tr><td>$transaction[no]</td><td>Wrong <b>principal</b> balance</td><td>$transaction[date]</td><td> </td><td> </td><td class='n'><span class='badge red'>".$this->money($returned)."</span></td></tr>"; $info[message]="Wrong principal balance"; $info[executed]=$returned; } //if($returned!=0) //if($given!=0) //if(($given!=0)||($returned!=0)||($int_paid!=0))$out.= "$transaction[no] - $transaction[date] (G:$given;R:$returned;I:$int_paid) $transaction[given]=".$plan[given]." | $transaction[returned]=".$plan[returned]." | $transaction[int_paid]=".$plan[int_paid]."<br>"; $data[info]=$info; $data[plan]=$row; $data[trans]=$transaction; $data_trans[]=$data; } $out.= "<table>"; ///=========================================== $res[data_trans]=$data_trans; $res[data_plan]=$data_plan; $res[html]=$out; return $res;<file_sep><?php namespace Test\Rozdol\Loans; use Rozdol\Loans\Calculator; use PHPUnit\Framework\TestCase; class CalulatorTest extends TestCase { /** * @dataProvider transactiionsProvider */ public function testSum2num($a, $b, $c) { $result = Calculator::sum2num($a, $b); $this->assertEquals($c, $result['result']); } public function transactiionsProvider() { return [ [1,1,2], [-1,1,0], [1,-1,0], [4.5, 1.3, 5.8] ]; } } <file_sep><?php namespace Test\Rozdol\Loans; use Rozdol\Loans\Loan; use PHPUnit\Framework\TestCase; class LoanTest extends TestCase { protected function setUp() { //$this->loan = Loan::getInstance(); $this->loan = new Loan(); } // public function testLoan() // { // $result = $this->loan->calcLoan($data); // //$this->getActualOutput($result); // fwrite(STDERR, print_r($result, true)); // $this->assertEquals(0, $result['given']); // } /** * @dataProvider transactionsProvider */ public function testLoan($data, $expected1, $expected2, $expected3) { $result = $this->loan->calcLoan($data); //$this->getActualOutput($result); //fwrite(STDERR, print_r($result, true)); $this->assertEquals($expected1, $result[given]); $this->assertEquals($expected2, $result[interest_accrued]); $this->assertEquals($expected3, $result[interest_predict]); } public function transactionsProvider() { $data=array ( 'loan_data' => array ( 'amount' => '20000000', 'rate' => 0.02, 'freq' => '0', 'df' => '24.06.2016', 'dt' => '31.12.2018', 'base' => '365', 'p_rate' => 0.02, 'date' => '15.06.2018', 'compound' => 'f', ), 'transactions' => array ( '0' => array ( 'date' => '24.06.2016', 'given' => 4540000, 'returned' => 0, 'paid' => 0, 'adjustment' => 0, 'descr' => ' Loan Drawdown', ), '1' => array ( 'date' => '15.07.2016', 'given' => 5006100, 'returned' => 0, 'paid' => 0, 'adjustment' => 0, 'descr' => ' Loan Drawdown', ), '2' => array ( 'date' => '20.07.2016', 'given' => 4198620, 'returned' => 0, 'paid' => 0, 'adjustment' => 0, 'descr' => ' Loan Drawdown', ), '3' => array ( 'date' => '22.07.2016', 'given' => 4958100, 'returned' => 0, 'paid' => 0, 'adjustment' => 0, 'descr' => ' Loan Drawdown', ), '4' => array ( 'date' => '26.07.2016', 'given' => 1297180, 'returned' => 0, 'paid' => 0, 'adjustment' => 0, 'descr' => ' Loan Drawdown', ), '5' => array ( 'date' => '31.12.2016', 'given' => 0, 'returned' => 0, 'paid' => 187178.76, 'adjustment' => 0, 'descr' => ' Interest Paid', ), '6' => array ( 'date' => '31.12.2016', 'given' => 0, 'returned' => 20000000, 'paid' => 0, 'adjustment' => 0, 'descr' => ' Loan Paid', ), '7' => array ( 'date' => '31.12.2016', 'given' => 0, 'returned' => 0, 'paid' => 0, 'adjustment' => -1092.90, 'descr' => ' ', ), ), ); $data2=array ( 'loan_data' => array ( 'amount' => '1000000', 'rate' => 0.10000000000000001, 'freq' => '12', 'df' => '01.01.2018', 'dt' => '01.01.2019', 'base' => '30/360', 'p_rate' => 0.10000000000000001, 'date' => '01.01.2019', 'compound' => 'f', ), 'transactions' => array ( 0 => array ( 'date' => '01.07.2018', 'given' => 1000000, 'returned' => 0, 'paid' => 0, 'adjustment' => 0, 'descr' => ' ', ), ), ); $data3=$data2; $data3[loan_data][compound]='t'; return [ [$data, 20000000,187178.76,1007650], [$data2, 1000000,50410.96,100000], [$data3, 1000000,51053.31,104713] ]; } } <file_sep><?php namespace Rozdol\Loans; use Rozdol\Dates\Dates; use Rozdol\Loans\interest; use Rozdol\utils\Utils; use Rozdol\Html\Html; class Planner { private static $hInstance; public static function getInstance() { if (!self::$hInstance) { self::$hInstance = new Planner(); } return self::$hInstance; } public function __construct() { $this->dates = new Dates(); $this->interest = new Interest(); $this->utils = new Utils(); $this->html = new Html(); } /** * calc Loan * * @return array */ public function planLoan($data) { $GLOBALS[debug][stopwatch]='plan_loan'; echo $this->html->pre_display($data,"f:plan_loan"); //$days_add=$this->dates->F_datediff($data[df],$data[dt]); //echo "$days_add<br>"; $res=$data; if ($data[base]=='365') { $daysinyear=365; } else { $daysinyear=360; } if ($data[base]=='') { $data[base]='30/360'; } $periods=$data['periods']; if ($periods==0) { $periods=1; } $payments=$data['payments']; $payment_range=round($periods/$payments); if (($payment_range==0)||($payment_range==INF)) { $payment_range=1; } //echo $this->html->pre_display($payment_range,"payment_range"); $days_loan=$this->dates->F_datediff($data[df], $data[dt], $data[base]); $data[days_loan]=$days_loan; $months_loan=$days_loan/365*12; $pays_per_year=$data[freq]; if (($days_loan>366)&&($data[freq]==1)&&($data[periods]==1)) { $pays_per_year=365/$days_loan; } $data[pays_per_year]=$pays_per_year; $data[months_loan]=$months_loan; $months_loan_rounded=round($months_loan); $data[months_loan_rounded]=$months_loan_rounded; //echo $this->html->pre_display($data,"F:plan_loan"); //echo "D:$payment_range<br>"; $fields=array('#','Action','date','Given','Payment','Pcpl. paid','int.Paid','Balance','Ineterest','rate','days',''); $tbl=$this->html->tablehead($what, $qry, $order, $addbutton, $fields, $sort); $i=0; $no=1; $date=$data[df]; $pmt_amount=$data[pmt]; if (($payment_range>=1)&&($pmt_amount==0)&&($payments>0)) { $pmt_amount=round($data[amount]/$payments, 2); } $pmt=0; $balance=$data[amount]; $tbl.="<tr class='$class'><td>$no</td> <td>Loan</td> <td>$date</td> <td class='n'>".$this->html->money($data[amount])."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($data['rate']*100)." %</td> <td class='n'>0</td> <td>$notes</td> </tr>"; $found=0; if ($this->dates->is_earlier($data['date'], $data['df'])) { $found=1; } $plan[]=array( 'no'=>$no, 'action'=>'Loan', 'date'=>$date, 'given'=>$data[amount], 'returned'=>0, 'int_paid'=>0, 'balance'=>$balance, 'interest'=>0, 'rate'=>$data['rate'], 'days'=>0, 't_given'=>$data[amount], 't_returned'=>0, 't_interest'=>0, 't_paid'=>0, 'info'=>'', ); if ($data['align']>0) { $no++; $date_prev=$date; if ($data['align']<32) { $day=substr($date, 0, 2); //echo "$day<br>"; if ($data['align']>=$day) { $days_add=$data['align']-$day; } else { $days_add=$data['align']-$day + $this->days_in_month($date); } $align_text="$data[align] day of the month"; } else { $days_add=$this->dates->F_datediff($date, $this->dates->lastday_in_month($date)); $align_text="the last day of the month"; } $date=$this->dates->F_dateadd($date, $days_add); $data4interest=array( 'amount'=>$balance, 'rate'=>$data['rate'], 'freq'=>$data['freq'], 'df'=>$date_prev, 'dt'=>$date, 'base'=>$data[base], 'compound'=>$data[compound], 'note'=>'Plan Loan. Allign.', ); $calc_interest=$this->interest->getInterest($data4interest); $interest=$calc_interest[interest]; if ($pmt>0) { $amount=$pmt-$interest; } else { $amount=0; } $balance_prev=$balance; $balance=$balance-$amount; $days=$this->dates->F_datediff($date_prev, $date, $data[base]); $days_chk=$this->dates->F_datediff($date, $data['date']); $notes=''; //$notes=$this->html->pre_display($calc_interest); if (($days_chk<=0)&&($found==0)) { $found=1; $res[balance]=$balance_prev; $res[interest]=$interest; $res[t_paid]=$t_paid; $res[t_interest_paid]=$t_interest_paid; $res[t_principal_paid]=$t_principal_paid; $res[next_payment]=$date; $res[days_till_next]=-$days_chk; //$info=$this->html->pre_display($res); //$notes="<span class='badge red'>DATE $data[date]</span> $info"; } $t_paid+=$pmt; $t_interest_paid+=$interest; $t_principal_paid+=$amount; $total=$amount+$interest; $t_days+=$days; $tbl.="<tr class='$class'><td>$no</td> <td>Pay</td> <td>$date</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($total)."</td> <td class='n'>".$this->html->money($amount)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($data['rate']*100)." %</td> <td class='n'>$days</td> <td>Aligned to $align_text $notes</td> </tr>"; $plan[]=array( 'no'=>$no, 'action'=>'Pay', 'date'=>$date, 'given'=>0, 'returned'=>$amount, 'int_paid'=>$interest, 'balance'=>$balance, 'interest'=>$interest, 'rate'=>$data['rate'], 'days'=>$days, 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'', ); } //if($pays_per_year>1)$months=12/$months_loan; else $months=12; if ($pays_per_year>1) { $months=12/$pays_per_year; } else { $months=12; } //echo "pays_per_year=$pays_per_year / $months_loan ($months)<br>"; for ($i=1; $i<=$periods; $i++) { $no++; $date_prev=$date; if ($months>1) { //echo "$months / $days_loan<br>"; if ($pays_per_year>=1) { $date=$this->dates->F_dateadd_month($date, $months); } else { $date=$this->dates->F_dateadd($date, $days_loan); //echo "DL:$days_loan<br>"; } if ($days_add>0) { $date=$this->dates->lastday_in_month($this->dates->F_dateadd($date, -15)); } if (($days_add>0)&&($i==$periods)) { $date=$this->dates->F_dateadd($date, -$days_add); } //if($no>=5)echo $this->html->pre_display(['Date'=>$date,'Days_add'=>$days_add],"result4"); } else { $days_in_month=$this->dates->days_in_month_date($this->dates->F_dateadd($date, 15)); if (($days_add>0)&&($i==$periods)) { $days_in_month=$days_in_month-$days_add; } $date=$this->dates->F_dateadd($date, $days_in_month); //$date=$this->dates->F_dateadd_month($date,$months); } $days_chk=$this->dates->F_datediff($date, $data['date']); $notes=''; //$notes=$this->html->pre_display($calc_interest); if (($days_chk<=0)&&($found==0)) { $data4interest=array( 'amount'=>$balance, 'rate'=>$data['rate'], 'freq'=>$data['freq'], 'df'=>$date_prev, 'dt'=>$data[date], 'base'=>$data[base], 'compound'=>$data[compound], 'note'=>'Plan Loan. Main No '.$no, ); $calc_interest=$this->interest->getInterest($data4interest); $found=1; $res[balance]=$balance_prev; $res[interest]=$calc_interest[interest]; $res[t_paid]=$t_paid; $res[t_interest_paid]=$t_interest_paid+$res[interest]; $res[t_principal_paid]=$t_principal_paid; $res[next_payment]=$date; $res[days_till_next]=-$days_chk; //$info=$this->html->pre_display($res); $info.="<table> <tr><td>Balance:</td><td class='n'>".$this->html->money($res[balance])."</td></tr> <tr><td>Interest:</td><td class='n'>".$this->html->money($res[interest])."</td></tr> <tr><td>Interest acc:</td><td class='n'>".$this->html->money($res[t_interest_paid])."</td></tr> <tr><td>DTNP:</td><td class='n'>$res[days_till_next]</td></tr> </table>"; $notes="<span class='label'>DATE $data[date]</span><br><span class=''>$info</span>"; } $data4interest=array( 'amount'=>$balance, 'rate'=>$data['rate'], 'freq'=>$data['freq'], 'df'=>$date_prev, 'dt'=>$date, 'base'=>$data[base], 'compound'=>$data[compound], 'note'=>'Plan Loan. Final', ); $calc_interest=$this->interest->getInterest($data4interest); $interest=$calc_interest[interest]; $pmt=(($i%$payment_range)==0)?$pmt_amount:0; //echo "I.$i=".($i%$payment_range)."<br>"; if (($pmt==0)&&($i==$periods)) { $pmt=$balance+$interest; } if ($pmt>0) { $amount=$pmt-$interest; } else { $amount=0; } if (($payment_range>1)&&($pmt>0)) { $amount=$pmt; } $balance_prev=$balance; $balance=$balance-$amount; $days=$this->dates->F_datediff($date_prev, $date, $data[base]); $t_paid+=$pmt; $t_interest_paid+=$interest; $t_principal_paid+=$amount; $total=$amount+$interest; $t_total_paid+=$total; $t_days+=$days; $tbl.="<tr class='$class'><td>$no</td> <td>Pay</td> <td>$date</td> <td class='n'>".$this->html->money(0)."</td> <td class='n'>".$this->html->money($total)."</td> <td class='n'>".$this->html->money($amount)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($balance)."</td> <td class='n'>".$this->html->money($interest)."</td> <td class='n'>".$this->html->money($data['rate']*100)." %</td> <td class='n'>$days</td> <td>$notes</td> </tr>"; $plan[]=array( 'no'=>$no, 'action'=>'Pay', 'date'=>$date, 'given'=>0, 'returned'=>$amount, 'int_paid'=>$interest, 'balance'=>$balance, 'interest'=>$interest, 'rate'=>$data['rate'], 'days'=>$days, 't_given'=>$data[amount], 't_returned'=>$t_principal_paid, 't_interest'=>$t_interest_paid, 't_paid'=>$t_interest_paid+$t_principal_paid, 'info'=>'', ); } $totals=array_fill(0, 10, 0); $totals[2]=$data[amount]; $totals[3]=$t_total_paid; $totals[4]=$t_principal_paid; $totals[5]=$t_interest_paid; //$totals[6]=$balance; $totals[9]=$t_days; $tbl.=$this->html->tablefoot($i, $totals, $no); $res[rows]=$no; $res[amount_total]=$plan[$no-1][t_given]; $res[amount_returned_total]=$plan[$no-1][t_returned]; $res[amount_interest_total]=$plan[$no-1][t_interest]; $res[amount_paid_total]=$plan[$no-1][t_paid]; if (($res[interest]==0)&&($found==0)) { $res[interest]=$res[amount_interest_total]; } if ($found==0) { $res[balance]=$res[amount_total]-$res[amount_returned_total]; $res[interest]=$interest; $res[t_paid]=$res[amount_paid_total]; $res[t_interest_paid]=$res[amount_interest_total]; $res[t_principal_paid]=$res[amount_returned_total]; $res[next_payment]=$dt; $res[days_till_next]=0; } $res[amount_returned_total]=round($res[amount_returned_total], 2); $res[amount_interest_total]=round($res[amount_interest_total], 2); $res[balance]=round($res[balance], 2); $res[interest]=round($res[interest], 2); $res[t_paid]=round($res[t_paid], 2); $res[t_interest_paid]=round($res[t_interest_paid], 2); $res[t_principal_paid]=round($res[t_principal_paid], 2); $res[amount_paid_total]=round($res[amount_paid_total], 2); $res[days]=$t_days; $res[tbl]=$tbl; $res[plan]=$plan; return $res; } }
d9617ca5e8fee01105f9df3a6263fa5539378dfd
[ "PHP" ]
10
PHP
rozdol/loans
d8ddbd519ba84520ca5b955df15ad71565ed9226
08c140e0826043644a9a6e30be5eee7a5914f5ce
refs/heads/master
<file_sep>var gulp = require('gulp'), webpack = require('webpack-stream'), serve = require('gulp-serve'); // Webpack gulp.task('webpack', function() { return gulp.src('./src/app/app.js') .pipe(webpack(require('./webpack.config.js'))) .pipe(gulp.dest('./dist')); }); // Web Server gulp.task('serve:web', serve({ root: ['dist'], port: 2424 })); // Watch gulp.task('watch', function() { gulp.watch('./src/app/**/*', ['webpack']) }); gulp.task('default', ['serve:web', 'webpack', 'watch']); <file_sep># The Quiz Machine # Install npm install # Launch app gulp <file_sep>var path = require('path'), CopyWebpackPlugin = require('copy-webpack-plugin'); var config = { entry: path.resolve(__dirname, 'src/app/app.js'), output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: /(node_modules|bower_components)/, query: { presets: [ 'react', 'es2015', 'stage-3' ] } } ] }, plugins: [ new CopyWebpackPlugin([ { from: path.resolve(__dirname, 'src/index.html'), to: path.resolve(__dirname, 'dist/index.html') }, { from: path.resolve(__dirname, 'src/vendor'), to: path.resolve(__dirname, 'dist/vendor'), } ]) ] }; module.exports = config; <file_sep>import React from 'react'; import {render} from 'react-dom'; class Question extends React.Component { render () { return <div className="row"> <div className="col s12 m12"> <div className="card blue-grey lighten-5"> <div className="card-content black-text"> <p>{this.props.text}</p> </div> </div> </div> </div> } }; export default Question;<file_sep>import React from 'react'; import {render} from 'react-dom'; import Navbar from './components/Navbar'; import Question from './components/Question'; class App extends React.Component { constructor(props) { super(props); this.state = { questions: [] }; } componentDidMount () { this.serverRequest = $.get("http://jservice.io/api/clues", function (results) { this.setState({ questions: results }); }.bind(this)); } componentWillUnmount () { this.serverRequest.abort(); } render () { var rows = []; this.state.questions.forEach(function(item) { if (item.question != "") { rows.push(<Question key={item.id} text={item.question} />); } }); return <div> <Navbar/> <div className="container"> {rows} </div> </div> } } render(<App/>, document.getElementById('app'));
3fe4b86157bb6cc95094f362f0049f8532c7fb97
[ "JavaScript", "Markdown" ]
5
JavaScript
thecodingmachine/thequizmachine
0be783ad9dea7a3915fd5ced27ef1f2a7fce634b
5556fa2bffe8afda433bdb08b3e24155c591a085
refs/heads/master
<repo_name>notks/uni-webdev-lab-final<file_sep>/tptpobrazac.js var ime = document.getElementById("ime"); var email = document.getElementById("email"); var telefon = document.getElementById("telefon"); var poruka = document.getElementById("poruka"); var form = document.getElementById("form"); var cartBtn = document.getElementById("addToCart"); var a = (e) => { console.log(localStorage.getItem("cart")); let storageCart = JSON.parse(localStorage.getItem("cart")); let cart = storageCart ? storageCart : []; let cartItem = { item: e.path[2].accessKey, img: e.path[2].childNodes[1].href, }; cart.push(cartItem); localStorage.setItem("cart", JSON.stringify(cart)); }; try { cartBtn.addEventListener("click", () => { console.log("click"); }); } catch (error) {} try { form.addEventListener("submit", (e) => { e.preventDefault(); console.log("aaaaaaaaaa"); if (ime.value && email.value && telefon.value && poruka.value) { if (isNaN(telefon.value)) { alert("Niste ispravno popunili sva polja"); } else { alert("Uspjesno ste poslali poruku"); window.location.reload(true); } } }); } catch (error) {} var loadCart = () => { let totalPrice = 0; let main = document.getElementById("main_cart"); let cart = JSON.parse(localStorage.getItem("cart")); cart.forEach((item) => { let proizvod = document.createElement("div"); proizvod.classList.add("proizvod_cart"); let img_link = document.createElement("a"); img_link.href = item.img; let img = document.createElement("img"); img.src = item.img; img_link.appendChild(img); proizvod.appendChild(img_link); let title = document.createElement("span"); title.textContent = item.item; proizvod.appendChild(title); let price = document.createElement("div"); price.classList.add("price_cart"); let amount = document.createElement("span"); amount.textContent = "20"; price.appendChild(amount); let currency = document.createElement("p"); currency.textContent = "KM"; price.appendChild(currency); proizvod.appendChild(price); main.appendChild(proizvod); console.log(main); totalPrice = totalPrice + 20; }); let price = document.createElement("div"); price.classList.add("price_cart"); let amount = document.createElement("span"); amount.textContent = totalPrice; price.appendChild(amount); let currency = document.createElement("p"); currency.textContent = "KM"; price.appendChild(currency); main.appendChild(price); }; var buy = () => { localStorage.removeItem("cart"); alert("Uspjesno ste izvrsili kupovinu"); window.location.reload(true); }; let clearBtn = document.getElementById("clear"); clearBtn.addEventListener("click", () => { clear(); }); var clear = () => { localStorage.removeItem("cart"); window.location.reload(true); };
d108de631becd99c63fb2239aa81950a9ec49b55
[ "JavaScript" ]
1
JavaScript
notks/uni-webdev-lab-final
24f428f30b69e1aa99daae883407e629d1de5e5e
cb8095cd01c24a3c2deb001cead535c9cba71b70
refs/heads/master
<repo_name>natni/SIgnUpFormOnAndroidStudio<file_sep>/app/src/androidTest/java/com/example/form/MainActivityTest.java package com.example.form; import androidx.test.ext.junit.rules.ActivityScenarioRule; import com.example.signup.MainActivity; import com.example.signup.R; import org.junit.Rule; import org.junit.Test; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; public class MainActivityTest { @Rule public ActivityScenarioRule<MainActivity> activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class); @Test public void hasTextOnScreen() { onView(withId(R.id.developedDate)) .check(matches(withText("App was developed on 04/24/2020 by <NAME>"))); } }
a2042f77752b32d1979c97c023c83c494fac0249
[ "Java" ]
1
Java
natni/SIgnUpFormOnAndroidStudio
aee5246a7e7b78f91ae4bfcde8e1c076a4c6d541
d37c7d66b6e1e481ae7a3b49dd18e2274747ffd0
refs/heads/master
<repo_name>torbedosquadron/Photo_Gallery<file_sep>/assets/scripts/jquery-func.js $(document).ready(function(){ new_layer("#gallery .image a"); $("#gallery .image a").fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, 'speedOut' : 200, 'overlayShow' : true, "showCloseButton" : true, "showNavArrows" : true }); }); function new_layer(div) { $.each($(div),function(){ original = $(this).html(); $(this).html(original+"<span class='overlay'></span>"); }); }
e469abae1f25aacba4d89702414589d8eddea0b6
[ "JavaScript" ]
1
JavaScript
torbedosquadron/Photo_Gallery
c8d5a3b94e944ee9075abb38169bb25ef1dd7158
fe347da5f0cf8386df7eecd2d36c72c65de1e97d
refs/heads/master
<repo_name>dkgv/priority-queue<file_sep>/README.md # priority-queue A Java Priority Queue implementation with O(log n) time complexity for `remove(T)`. ## Example ```java PriorityQueue<Integer> queue = new PriorityQueue<>(Integer::compareTo); queue.offer(1); queue.offer(2); if (!queue.isEmpty()) { queue.remove(2); } if (queue.peek() == 1) { int one = queue.poll(); } if (queue.size() > 0) { queue.clear(); } List<Integer> heap = queue.getHeap(); ``` ## Benchmarks The following benchmarks were performed on a MBP 2013 with JMH using the benchmark suite found in the `benchmarks` directory. Score unit is ms/op. ``` (item order) (n) Mode Java.remove This.remove RANDOM 1 ss 0.025 0.022 <---- RANDOM 100 ss 0.394 0.501 RANDOM 1000 ss 5.266 4.209 <---- RANDOM 10000 ss 48.121 13.317 <---- RANDOM 100000 ss 3891.546 69.880 <---- INCREASING 1 ss 0.031 0.039 INCREASING 100 ss 0.631 2.278 INCREASING 1000 ss 4.525 16.019 INCREASING 10000 ss 9.039 42.658 INCREASING 100000 ss 61.324 140.316 DECREASING 1 ss 0.029 0.036 DECREASING 100 ss 0.444 1.731 DECREASING 1000 ss 2.013 8.465 DECREASING 10000 ss 5.803 34.368 DECREASING 100000 ss 49.606 144.530 ``` <file_sep>/src/main/java/com/gustavvy/priorityqueue/PriorityQueue.java package com.gustavvy.priorityqueue; import java.util.*; /** * PriorityQueue.java * * @author <NAME>. */ public class PriorityQueue<T> { private final HashMap<T, Integer> indices; private final Comparator<T> comparator; private final ArrayList<T> heap; public PriorityQueue(final Comparator<T> comparator) { this(11, comparator); } public PriorityQueue(final int initialCapacity, final Comparator<T> comparator) { this.indices = new HashMap<>(initialCapacity); this.heap = new ArrayList<>(initialCapacity); this.comparator = comparator; } public void clear() { indices.clear(); heap.clear(); } public T poll() { return removeAt(0); } private T removeAt(final int index) { final T result = heap.get(index); final int lastIndex = heap.size() - 1; swap(index, lastIndex); indices.remove(result); heap.remove(lastIndex); minHeapify(index); return result; } private void swap(final int i, final int j) { final T tmp = heap.get(i); heap.set(i, heap.get(j)); heap.set(j, tmp); indices.put(tmp, j); indices.put(heap.get(i), i); } public List<T> getHeap() { return heap; } public boolean isEmpty() { return heap.isEmpty(); } public void remove(final T entry) { if (!indices.containsKey(entry)) { return; } final int lastIndex = heap.size() - 1; final int entryIndex = indices.get(entry); // Is entry the last element? Remove and we are done (think heap visually) if (entryIndex >= lastIndex) { heap.remove(lastIndex); indices.remove(entry); } else { removeAt(entryIndex); } } public boolean offer(final Collection<T> collection) { for (final T t : collection) { if (!offer(t)) { return false; } } return true; } public boolean offer(final T t) { if (t == null) { throw new NullPointerException(); } heap.add(t); final int last = heap.size() - 1; indices.put(t, last); siphonUp(last); return true; } public T peek() { return heap.get(0); } public boolean contains(final T t) { return indices.containsKey(t); } public int size() { return heap.size(); } private void siphonUp(int index) { // Continue swapping until we reach the root as long as comparison with our parent is met while (index > 0 && cmp(heap.get(index), heap.get(parentOf(index))) < 0) { swap(index, parentOf(index)); index = parentOf(index); } } private void minHeapify(final int index) { final int shift = index << 1; final int left = shift + 1; final int right = shift + 2; final int n = heap.size(); int min = index; // Ensure a left child exists and compare index with it if (left < n && cmp(heap.get(left), heap.get(index)) < 0) { min = left; } if (right < n && cmp(heap.get(right), heap.get(min)) < 0) { min = right; } if (min != index) { swap(index, min); minHeapify(min); } } private int cmp(final T one, final T two) { return comparator.compare(one, two); } private int parentOf(final int index) { return (index - 1) / 2; } } <file_sep>/build.gradle plugins { id 'java' id 'maven-publish' } group 'com.gustavvy' version '0.0.1' sourceCompatibility = 14 repositories { mavenCentral() } dependencies { testImplementation group: 'junit', name: 'junit', version: '4.12' } publishing { repositories { maven { name = "GitHubPackages" url = "https://maven.pkg.github.com/dkgv/priority-queue" credentials { username = System.getenv("GITHUB_ACTOR") password = System.<PASSWORD>("GITHUB_TOKEN") } } } publications { gpr(MavenPublication) { from(components.java) } } }
af75220bed38968ea97dee52fa5c1552049f8acb
[ "Markdown", "Java", "Gradle" ]
3
Markdown
dkgv/priority-queue
c678898eaf48308f540f0e30ed36091f1bb1a49b
319110ab351c654c015bb1c7faceb5b4bac72df9
refs/heads/master
<file_sep>#include <Keyboard.h> void kbd_set_keys(); int row_col_key(int row, int col); #define NUMCOLS 14 int cols[] = { PIN_F0, /* ESC */ PIN_F1, /* F1 */ PIN_F4, /* F2 */ PIN_F5, /* F3 */ PIN_F6, /* F4 */ PIN_F7, /* F5 */ PIN_B6, /* F6 */ PIN_B5, /* F7 */ PIN_B4, /* F8 */ PIN_D7, /* F9 */ PIN_D6, /* F10 */ PIN_D4, /* F11 */ PIN_D5, /* F12 */ PIN_C7 /* DEL */ }; #define NUMROWS 7 int rows[] = { PIN_B0, /* ESC */ PIN_B1, /* ~ ` */ PIN_B2, /* TAB */ PIN_B3, /* CAPS*/ PIN_B7, /* SHIFT */ PIN_D0, /* PGUP */ PIN_D1 /* PGDN */ }; #define NUMKEYS 6 int keys[NUMKEYS]; int mods; void setup() { /* COLUMNS */ for (int c = 0; c < NUMCOLS; ++c) { pinMode(cols[c], INPUT_PULLUP); digitalWrite(cols[c], HIGH); /* high means off */ } /* ROWS */ for (int r = 0; r < NUMROWS; ++r) { pinMode(rows[r], OUTPUT); } Keyboard.begin(); delayMicroseconds(10); Keyboard.releaseAll(); } void loop() { /* remove pressed keys */ mods = 0; for (int i = 0; i < NUMKEYS; ++i) { keys[i] = 0; } int spot = 0; /* allows mutiple keys at the same time */ /* scan matrix */ for (int r = 0; r < NUMROWS; ++r) { digitalWrite(rows[r], LOW); /* send power to the current column */ for (int c = 0; c < NUMCOLS; ++c) { if (!digitalRead(cols[c])) { /* try to read low signal from column */ int key = row_col_qwerty(r, c); /* get key value */ if (key != 0 && spot < NUMKEYS) { /* not modifier */ keys[spot] = key; /* save key */ spot += 1; /* move to next key */ } } } digitalWrite(rows[r], HIGH); /* remove power from current column */ } /* press keys */ Keyboard.set_modifier(mods); kbd_set_keys(); /* apply the keys */ Keyboard.send_now(); } void kbd_set_keys() { Keyboard.set_key1(keys[0]); Keyboard.set_key2(keys[1]); Keyboard.set_key3(keys[2]); Keyboard.set_key4(keys[3]); Keyboard.set_key5(keys[4]); Keyboard.set_key6(keys[5]); } int row_col_qwerty(int row, int col) { int key = 0; if (row == 0 && col == 0) { key = KEY_ESC; } else if (row == 0 && col == 1) { key = KEY_F1; } else if (row == 0 && col == 2) { key = KEY_F2; } else if (row == 0 && col == 3) { key = KEY_F3; } else if (row == 0 && col == 4) { key = KEY_F4; } else if (row == 0 && col == 5) { key = KEY_F5; } else if (row == 0 && col == 6) { key = KEY_F6; } else if (row == 0 && col == 7) { key = KEY_F7; } else if (row == 0 && col == 8) { key = KEY_F8; } else if (row == 0 && col == 9) { key = KEY_F9; } else if (row == 0 && col == 10) { key = KEY_F10; } else if (row == 0 && col == 11) { key = KEY_F11; } else if (row == 0 && col == 12) { key = KEY_F12; } else if (row == 0 && col == 13) { key = KEY_DELETE; } else if (row == 1 && col == 0) { key = KEY_TILDE; } else if (row == 1 && col == 1) { key = KEY_1; } else if (row == 1 && col == 2) { key = KEY_2; } else if (row == 1 && col == 3) { key = KEY_3; } else if (row == 1 && col == 4) { key = KEY_4; } else if (row == 1 && col == 5) { key = KEY_5; } else if (row == 1 && col == 6) { key = KEY_6; } else if (row == 1 && col == 7) { key = KEY_7; } else if (row == 1 && col == 8) { key = KEY_8; } else if (row == 1 && col == 9) { key = KEY_9; } else if (row == 1 && col == 10) { key = KEY_0; } else if (row == 1 && col == 11) { key = KEY_MINUS; } else if (row == 1 && col == 12) { key = KEY_EQUAL; } else if (row == 1 && col == 13) { key = KEY_BACKSPACE; } else if (row == 2 && col == 0) { key = KEY_TAB; } else if (row == 2 && col == 1) { key = KEY_Q; } else if (row == 2 && col == 2) { key = KEY_W; } else if (row == 2 && col == 3) { key = KEY_E; } else if (row == 2 && col == 4) { key = KEY_R; } else if (row == 2 && col == 5) { key = KEY_T; } else if (row == 2 && col == 6) { key = KEY_Y; } else if (row == 2 && col == 7) { key = KEY_U; } else if (row == 2 && col == 8) { key = KEY_I; } else if (row == 2 && col == 9) { key = KEY_O; } else if (row == 2 && col == 10) { key = KEY_P; } else if (row == 2 && col == 11) { key = KEY_LEFT_BRACE; } else if (row == 2 && col == 12) { key = KEY_RIGHT_BRACE; } else if (row == 2 && col == 13) { key = KEY_BACKSLASH; } else if (row == 3 && col == 0) { key = KEY_CAPS_LOCK; } else if (row == 3 && col == 1) { key = KEY_A; } else if (row == 3 && col == 2) { key = KEY_S; } else if (row == 3 && col == 3) { key = KEY_D; } else if (row == 3 && col == 4) { key = KEY_F; } else if (row == 3 && col == 5) { key = KEY_G; } else if (row == 3 && col == 6) { key = KEY_H; } else if (row == 3 && col == 7) { key = KEY_J; } else if (row == 3 && col == 8) { key = KEY_K; } else if (row == 3 && col == 9) { key = KEY_L; } else if (row == 3 && col == 10) { key = KEY_SEMICOLON; } else if (row == 3 && col == 11) { key = KEY_QUOTE; } else if (row == 3 && col == 12) { key = 0; } else if (row == 3 && col == 13) { key = KEY_ENTER; } else if (row == 4 && col == 0) { mods |= MODIFIERKEY_SHIFT; } else if (row == 4 && col == 1) { key = 0; } else if (row == 4 && col == 2) { key = KEY_Z; } else if (row == 4 && col == 3) { key = KEY_X; } else if (row == 4 && col == 4) { key = KEY_C; } else if (row == 4 && col == 5) { key = KEY_V; } else if (row == 4 && col == 6) { key = KEY_B; } else if (row == 4 && col == 7) { key = KEY_N; } else if (row == 4 && col == 8) { key = KEY_M; } else if (row == 4 && col == 9) { key = KEY_COMMA; } else if (row == 4 && col == 10) { key = KEY_PERIOD; } else if (row == 4 && col == 11) { key = KEY_SLASH; } else if (row == 4 && col == 12) { key = 0; } else if (row == 4 && col == 13) { mods |= MODIFIERKEY_RIGHT_SHIFT; } else if (row == 5 && col == 0) { key = KEY_PAGE_UP; } else if (row == 5 && col == 1) { key = 0x65; } /* MENU */ else if (row == 5 && col == 2) { mods |= MODIFIERKEY_CTRL | MODIFIERKEY_ALT | MODIFIERKEY_GUI; } /* FN */ else if (row == 5 && col == 3) { key = 0; } else if (row == 5 && col == 4) { mods |= MODIFIERKEY_ALT; } else if (row == 5 && col == 5) { key = 0; } else if (row == 5 && col == 6) { key = KEY_SPACE; } else if (row == 5 && col == 7) { key = 0; } else if (row == 5 && col == 8) { mods |= MODIFIERKEY_RIGHT_ALT; } else if (row == 5 && col == 9) { key = 0; } else if (row == 5 && col == 10) { mods |= MODIFIERKEY_CTRL | MODIFIERKEY_ALT | MODIFIERKEY_GUI; } /* FN */ else if (row == 5 && col == 11) { key = KEY_HOME; } else if (row == 5 && col == 12) { key = KEY_UP; } else if (row == 5 && col == 13) { key = KEY_END; } else if (row == 6 && col == 0) { key = KEY_PAGE_DOWN; } else if (row == 6 && col == 1) { key = KEY_INSERT; } else if (row == 6 && col == 2) { mods |= MODIFIERKEY_GUI; } else if (row == 6 && col == 3) { key = 0; } else if (row == 6 && col == 4) { mods |= MODIFIERKEY_CTRL; } else if (row == 6 && col == 5) { key = 0; } else if (row == 6 && col == 6) { mods |= MODIFIERKEY_RIGHT_GUI; } /* HYPER: right super. Make xkb interpret right super as hyper by editing entry in /usr/share/X11/xkb/symbols/pc */ else if (row == 6 && col == 7) { key = 0; } else if (row == 6 && col == 8) { mods |= MODIFIERKEY_RIGHT_CTRL; } else if (row == 6 && col == 9) { key = 0; } else if (row == 6 && col == 10) { mods |= MODIFIERKEY_GUI; } else if (row == 6 && col == 11) { key = KEY_LEFT; } else if (row == 6 && col == 12) { key = KEY_DOWN; } else if (row == 6 && col == 13) { key = KEY_RIGHT; } return key; } int row_col_colemak(int row, int col) { int key = 0; if (row == 0 && col == 0) { key = KEY_ESC; } else if (row == 0 && col == 1) { key = KEY_F1; } else if (row == 0 && col == 2) { key = KEY_F2; } else if (row == 0 && col == 3) { key = KEY_F3; } else if (row == 0 && col == 4) { key = KEY_F4; } else if (row == 0 && col == 5) { key = KEY_F5; } else if (row == 0 && col == 6) { key = KEY_F6; } else if (row == 0 && col == 7) { key = KEY_F7; } else if (row == 0 && col == 8) { key = KEY_F8; } else if (row == 0 && col == 9) { key = KEY_F9; } else if (row == 0 && col == 10) { key = KEY_F10; } else if (row == 0 && col == 11) { key = KEY_F11; } else if (row == 0 && col == 12) { key = KEY_F12; } else if (row == 0 && col == 13) { key = KEY_DELETE; } else if (row == 1 && col == 0) { key = KEY_TILDE; } else if (row == 1 && col == 1) { key = KEY_1; } else if (row == 1 && col == 2) { key = KEY_2; } else if (row == 1 && col == 3) { key = KEY_3; } else if (row == 1 && col == 4) { key = KEY_4; } else if (row == 1 && col == 5) { key = KEY_5; } else if (row == 1 && col == 6) { key = KEY_6; } else if (row == 1 && col == 7) { key = KEY_7; } else if (row == 1 && col == 8) { key = KEY_8; } else if (row == 1 && col == 9) { key = KEY_9; } else if (row == 1 && col == 10) { key = KEY_0; } else if (row == 1 && col == 11) { key = KEY_MINUS; } else if (row == 1 && col == 12) { key = KEY_EQUAL; } else if (row == 1 && col == 13) { key = KEY_BACKSPACE; } else if (row == 2 && col == 0) { key = KEY_TAB; } else if (row == 2 && col == 1) { key = KEY_Q; } else if (row == 2 && col == 2) { key = KEY_W; } else if (row == 2 && col == 3) { key = KEY_F; } else if (row == 2 && col == 4) { key = KEY_P; } else if (row == 2 && col == 5) { key = KEY_G; } else if (row == 2 && col == 6) { key = KEY_J; } else if (row == 2 && col == 7) { key = KEY_L; } else if (row == 2 && col == 8) { key = KEY_U; } else if (row == 2 && col == 9) { key = KEY_Y; } else if (row == 2 && col == 10) { key = KEY_SEMICOLON; } else if (row == 2 && col == 11) { key = KEY_LEFT_BRACE; } else if (row == 2 && col == 12) { key = KEY_RIGHT_BRACE; } else if (row == 2 && col == 13) { key = KEY_BACKSLASH; } else if (row == 3 && col == 0) { key = KEY_CAPS_LOCK; } else if (row == 3 && col == 1) { key = KEY_A; } else if (row == 3 && col == 2) { key = KEY_R; } else if (row == 3 && col == 3) { key = KEY_S; } else if (row == 3 && col == 4) { key = KEY_T; } else if (row == 3 && col == 5) { key = KEY_D; } else if (row == 3 && col == 6) { key = KEY_H; } else if (row == 3 && col == 7) { key = KEY_N; } else if (row == 3 && col == 8) { key = KEY_E; } else if (row == 3 && col == 9) { key = KEY_I; } else if (row == 3 && col == 10) { key = KEY_O; } else if (row == 3 && col == 11) { key = KEY_QUOTE; } else if (row == 3 && col == 12) { key = 0; } else if (row == 3 && col == 13) { key = KEY_ENTER; } else if (row == 4 && col == 0) { mods |= MODIFIERKEY_SHIFT; } else if (row == 4 && col == 1) { key = 0; } else if (row == 4 && col == 2) { key = KEY_Z; } else if (row == 4 && col == 3) { key = KEY_X; } else if (row == 4 && col == 4) { key = KEY_C; } else if (row == 4 && col == 5) { key = KEY_V; } else if (row == 4 && col == 6) { key = KEY_B; } else if (row == 4 && col == 7) { key = KEY_K; } else if (row == 4 && col == 8) { key = KEY_M; } else if (row == 4 && col == 9) { key = KEY_COMMA; } else if (row == 4 && col == 10) { key = KEY_PERIOD; } else if (row == 4 && col == 11) { key = KEY_SLASH; } else if (row == 4 && col == 12) { key = 0; } else if (row == 4 && col == 13) { mods |= MODIFIERKEY_RIGHT_SHIFT; } else if (row == 5 && col == 0) { key = KEY_PAGE_UP; } else if (row == 5 && col == 1) { key = 0x65; } /* MENU */ else if (row == 5 && col == 2) { mods |= MODIFIERKEY_CTRL | MODIFIERKEY_ALT | MODIFIERKEY_GUI; } /* FN */ else if (row == 5 && col == 3) { key = 0; } else if (row == 5 && col == 4) { mods |= MODIFIERKEY_ALT; } else if (row == 5 && col == 5) { key = 0; } else if (row == 5 && col == 6) { key = KEY_SPACE; } else if (row == 5 && col == 7) { key = 0; } else if (row == 5 && col == 8) { mods |= MODIFIERKEY_RIGHT_ALT; } else if (row == 5 && col == 9) { key = 0; } else if (row == 5 && col == 10) { mods |= MODIFIERKEY_CTRL | MODIFIERKEY_ALT | MODIFIERKEY_GUI; } /* FN */ else if (row == 5 && col == 11) { key = KEY_HOME; } else if (row == 5 && col == 12) { key = KEY_UP; } else if (row == 5 && col == 13) { key = KEY_END; } else if (row == 6 && col == 0) { key = KEY_PAGE_DOWN; } else if (row == 6 && col == 1) { key = KEY_INSERT; } else if (row == 6 && col == 2) { mods |= MODIFIERKEY_GUI; } else if (row == 6 && col == 3) { key = 0; } else if (row == 6 && col == 4) { mods |= MODIFIERKEY_CTRL; } else if (row == 6 && col == 5) { key = 0; } else if (row == 6 && col == 6) { mods |= MODIFIERKEY_RIGHT_GUI; } /* HYPER: right super. Make xkb interpret right super as hyper by editing entry in /usr/share/X11/xkb/symbols/pc */ else if (row == 6 && col == 7) { key = 0; } else if (row == 6 && col == 8) { mods |= MODIFIERKEY_RIGHT_CTRL; } else if (row == 6 && col == 9) { key = 0; } else if (row == 6 && col == 10) { mods |= MODIFIERKEY_GUI; } else if (row == 6 && col == 11) { key = KEY_LEFT; } else if (row == 6 && col == 12) { key = KEY_DOWN; } else if (row == 6 && col == 13) { key = KEY_RIGHT; } return key; }
4353170c8c8612d0db37082832b1fb33c9008faf
[ "C++" ]
1
C++
charJe/power-user
eeaa72c0c180e6de57d34b411a66cf1af00e42d2
d274371efe02883526aa530526803ff676863004
refs/heads/master
<repo_name>PIH/openmrs-module-mirebalaismetadata<file_sep>/api/src/main/resources/messages_fr.properties openmrs.property.MESSAGE_PROPERTY_ALLOW_KEYS_OUTSIDE_OF_MODULE_NAMESPACE = true ${project.parent.artifactId}.title=Module de métadonnées Mirebalais disposition.emrapi.admitToHospital=Admission disposition.emrapi.admitToHospital.admissionLocation=Admettre dans le service disposition.emrapi.leftWithoutSeeingAClinician=A quitté sans voir un clinicien disposition.emrapi.leftWithoutCompletionOfTreatment= A quitté sans terminer le traitement disposition.emrapi.transferOutOfHospital=Transfert hors de l'hôpital disposition.emrapi.transferOutOfHospital.sites=Sites disposition.emrapi.transferOutOfHospital.sites.zlSite=Sites soutenus par ZL disposition.emrapi.transferOutOfHospital.sites.nonZlSite=Sites non ZL disposition.emrapi.transferInHospital=Transfert dans l'hôpital disposition.emrapi.outpatientTransferInHospital=Transfert de patient externe au sein de l'hôpital disposition.emrapi.transferInHospital.transferToLocation=vers le lieu disposition.emrapi.death=Décès disposition.emrapi.death.deathDate=Date de décès disposition.emrapi.discharge=Sortie disposition.mirebalais.edObservation=Service des Urgences Observation disposition.mirebalais.stillHospitalized=Toujours hospitalisé disposition.mirebalais.admitToHospital.boardingFor=Hébergement pour <file_sep>/api/src/main/java/org/openmrs/module/mirebalaismetadata/MirebalaisMetadataActivator.java /** * The contents of this file are subject to the OpenMRS Public License * Version 1.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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.mirebalaismetadata; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Concept; import org.openmrs.api.ConceptService; import org.openmrs.api.context.Context; import org.openmrs.module.BaseModuleActivator; import org.openmrs.module.Module; import org.openmrs.module.ModuleActivator; import org.openmrs.module.ModuleFactory; import org.openmrs.module.emrapi.EmrApiProperties; import org.openmrs.module.pihcore.config.Config; import org.openmrs.module.pihcore.config.ConfigDescriptor; /** * This class contains the logic that is run every time this module is either started or stopped. */ public class MirebalaisMetadataActivator extends BaseModuleActivator { protected Log log = LogFactory.getLog(getClass()); private ConceptService conceptService; private Config config; /** * @see ModuleActivator#contextRefreshed() */ public void contextRefreshed() { log.info("Mirebalais Metadata module refreshed"); } /** * @see ModuleActivator#started() */ public void started() { if (config == null) { // hack to allow injecting a mock config for testing config = Context.getRegisteredComponents(Config.class).get(0); // currently only one of these } if (conceptService == null) { conceptService = Context.getConceptService(); } try { if (config.getCountry().equals(ConfigDescriptor.Country.HAITI)) { retireOldConcepts(); } } catch (Exception e) { Module mod = ModuleFactory.getModuleById("mirebalaismetadata"); ModuleFactory.stopModule(mod, true, true); throw new RuntimeException("Failed to start the mirebalaismetadata module", e); } log.info("Mirebalais Metadata module started"); } private EmrApiProperties getEmrApiProperties() { return Context.getRegisteredComponents(EmrApiProperties.class).iterator().next(); } private void retireOldConcepts() { // we need to retire this old concept if it exists because another concept we will install later has the same French name // #UHM-1789 - Removed concept "cerebellar infarction”from HUM ED set, and added “cerebral infarction" Concept concept = conceptService.getConceptByUuid("145906AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); if (concept != null) { conceptService.retireConcept(concept, "replaced with by 155479AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); } } // hack to allow us to inject a mock config during testing public void setConfig(Config config) { this.config = config; } } <file_sep>/api/src/test/java/org/openmrs/module/mirebalaismetadata/BaseMirebalaisMetadataContextSensitiveTest.java package org.openmrs.module.mirebalaismetadata; import org.openmrs.test.BaseModuleContextSensitiveTest; import java.util.Properties; public abstract class BaseMirebalaisMetadataContextSensitiveTest extends BaseModuleContextSensitiveTest { @Override public Properties getRuntimeProperties() { Properties p = super.getRuntimeProperties(); p.setProperty("pih.config", "pihcore"); return p; } } <file_sep>/api/src/main/resources/messages_ht.properties openmrs.property.MESSAGE_PROPERTY_ALLOW_KEYS_OUTSIDE_OF_MODULE_NAMESPACE = true ${project.parent.artifactId}.title=Modil Metadone pou Mibalè disposition.emrapi.admitToHospital=Admisyon disposition.emrapi.admitToHospital.admissionLocation=Admèt nan Sal disposition.emrapi.leftWithoutSeeingAClinician=Ale san ou pa wè doktè disposition.emrapi.leftWithoutCompletionOfTreatment= Ale san ou pa fini ak tretman yo disposition.emrapi.transferOutOfHospital=Transfè nan lòt lopital disposition.emrapi.transferOutOfHospital.sites=Sit yo disposition.emrapi.transferOutOfHospital.sites.zlSite=Sit ZL sipòte yo disposition.emrapi.transferOutOfHospital.sites.nonZlSite=Sit ki pa pou ZL yo disposition.emrapi.transferInHospital=Transfè anndan lopital la disposition.emrapi.outpatientTransferInHospital=Pasyan Ekstèn Transfere anndan lopital la disposition.emrapi.transferInHospital.transferToLocation=nan zòn disposition.emrapi.death=Mouri disposition.emrapi.death.deathDate=Dat Lanmò a disposition.emrapi.discharge=Egzeyat disposition.mirebalais.edObservation=Ijans Obsèvasyon disposition.mirebalais.stillHospitalized=Toujou Entène disposition.mirebalais.admitToHospital.boardingFor=An Atant Pou <file_sep>/api/src/main/resources/messages.properties openmrs.property.MESSAGE_PROPERTY_ALLOW_KEYS_OUTSIDE_OF_MODULE_NAMESPACE = true ${project.parent.artifactId}.title=Mirebalais Metadata Module disposition.emrapi.admitToHospital=Admission disposition.emrapi.admitToHospital.admissionLocation=Admit to Ward disposition.emrapi.leftWithoutSeeingAClinician=Left without seeing a clinician disposition.emrapi.leftWithoutCompletionOfTreatment= Left without completion of treatment disposition.emrapi.transferOutOfHospital=Transfer out of hospital disposition.emrapi.transferOutOfHospital.sites=Sites disposition.emrapi.transferOutOfHospital.sites.zlSite=ZL-supported sites disposition.emrapi.transferOutOfHospital.sites.nonZlSite=Non-ZL sites disposition.emrapi.transferInHospital=Transfer within hospital disposition.emrapi.outpatientTransferInHospital=Outpatient transfer within hospital disposition.emrapi.transferInHospital.transferToLocation=to location disposition.emrapi.death=Death disposition.emrapi.death.deathDate=Death Date disposition.emrapi.discharge=Discharge disposition.emrapi.referToKGH=Refer to KGH disposition.emrapi.medsPrescribed=Medication prescribed disposition.emrapi.waitingForLabs=Laboratory tests outstanding disposition.emrapi.inactive=No action taken disposition.mirebalais.edObservation=ED Observation disposition.mirebalais.stillHospitalized=Still Hospitalized disposition.mirebalais.admitToHospital.boardingFor=Boarding For<file_sep>/README.md # Deprecation Notice This is no longer used as of March 2020. Please see [openmrs-config-pihemr](https://github.com/PIH/openmrs-config-pihemr/) for up-to-date information about PIH EMR configuration. ## Managing Metadata for a PIH EMR instance of OpenMRS Metadata is packaged for deployment across PIH EMR instances using two OpenMRS modules: [Metadata Sharing](https://wiki.openmrs.org/display/docs/Metadata+Sharing+Module) and [Metadata Deploy](https://wiki.openmrs.org/display/docs/Metadata+Deploy+Module). Please read the documentation in the links. ### Metadata Server Management This is described on the [OpenMRS wiki](https://wiki.openmrs.org/display/docs/Metadata+Server+Management). ### MDS Package Search Tool You will at some point want to look up whether a concept exists in some or another package. To accomplish this you can use the tool in mds-search. `cd` into `mds-search`. Then run `./update.sh` to unzip all the MDS packages in this repo into the mds-search directory. Then use `./find-concept.sh 123` to find the MDS packages that contain the concept with PIH concept ID `123`. The other `find-concept-` scripts work similarly. Execute any one of them with no arguments to see usage info. The script `find-package-by-name.sh <name>` will show you which of the header.xml and metadata.xml files (which only have number suffixes) has `<name>` in the name. Try `find-package-by-name.sh ncd`. ### PIH Concept Managers There are two people at PIH who are "Concept Managers" in the sense intended below: - <NAME> - <NAME> ### PIH EMR Concept Management Process This is a process for defining a new form. The main idea of the process is 1. Identify suitable concepts in the [HUM-CI Concept Dictionary](https://humci.pih-emr.org/mirebalais/dictionary/index.htm) and the CIEL concepts in [mdsbuilder](https://mdsbuilder.openmrs.org/openmrs/). 1. Get the concept onto the [Concept Server](https://concepts.pih-emr.org/openmrs/dictionary/index.htm) 1. Export the concept from the Concept Server and add it to your distribution. Here's a workflow that breaks that down into concrete steps. 1. Start a requirements spreadsheet based on [this template](https://docs.google.com/spreadsheets/d/1vdY95gN2fuGIMZlHadC4eAa8299RatsenIj06pa8p9E/edit#gid=0) (see, for example, the [CES sheet](https://docs.google.com/spreadsheets/d/1fZEeeEku8YWC-uHEZ0HPsa5NY23m2sWLIIonE7u-sZs/edit#gid=815234747)). 1. Write down your required question/answer/diagnosis in a row in your requirements spreadsheet. 1. Go to the [HUM-CI Concept Dictionary](https://humci.pih-emr.org/mirebalais/dictionary/index.htm) and, for each question/answer/diagnosis/etc, search for a concept that might be appropriate. 1. If there is a suitable concept in HUM-CI, then it already also exists in the Concept Server. 1. If there is a CIEL mapping, add that to your requirements sheet. 1. If there is no CIEL mapping, add the PIH "name" mapping to your requirements sheet. 1. If there is no suitable concept in HUM-CI, search for a suitable CIEL concept in [mdsbuilder](https://mdsbuilder.openmrs.org/openmrs/). 1. If the concept exists in CIEL, add it to the [CIEL request sheet]. Tag Ellen in a comment to request that she import it to the Concept Server. 1. If there is no suitable concept in CIEL, add it to the [CIEL request sheet](https://docs.google.com/spreadsheets/d/1hAJLuKBVwzJEvo3hDp2tRqeRWKMSlxgphK1rc-Nm3IA/edit#gid=0). Either <NAME> will either add it to CIEL and we'll import it to the Concept Server, or he won't and we'll create it on the Concept Server. In the meantime, after running it by a Concept Manager, feel free to add it to the Concept Server. 1. Once you have the concept in the Concept Server, make sure it has PIH or CIEL reference term mappings. The ones imported from CIEL should certainly have the CIEL code as a mapping -- if it isn't present, definitely ask Ellen about it. Concepts which don't correspond to anything in CIEL should at least have a PIH reference term mappings (e.g. "PIH:HAS BOO BOO"). 1. Check that a translation of the concept name exists in your implementation’s language. If it doesn't, evaluate whether or not the display name you want for the concept is a direct translation of the English concept name. 1. If it is, add the display name as the translation for the concept. 1. If it isn't, translate the English concept name as best you (or a bilingual colleague) can. Instead of adding the display name to the concept, you'll add it to the `messages.properties` file later. Note that this only works for some kinds of concepts (e.g. those referenced directly in an HTML Form) and not others (e.g. diagnoses in the diagnosis list), so you might have to just settle with using the translation of the concept as the display name. 1. Use the MDS Package Search Tool (mds-search), documented above, to find out whether the concept you want is already in an MDS package. 1. If the concept is new or is for some other reason is not yet in an MDS package, you or someone from MedInfo will have to add it to one. 1. Identify the MDS package it should go in. Ask a Concept Manager if you're not sure. 1. Each package should correspond to a single concept set, which contains a tree of concept sets and concepts that go into that package. Add your concept to one of the concept sets that goes into that package. 1. Go to Administration > Export Metadata. 1. Click on "New Version" next to the package that the concept set you chose is part of. 1. Check "2. Publish package." Click "Next." 1. Click "Export." 1. Download this newly created MDS package. 1. Open the "openmrs-module-mirebalaismetadata" repository on your computer. If you don't have it, check it out from [GitHub](https://github.com/PIH/openmrs-module-mirebalaismetadata). If you are using the OpenMRS SDK, be sure to watch it with `openmrs-sdk:watch`. 1. Drop the new version of the MDS package into `api/src/main/resources`. 1. Update the filename in `api/src/main/resources/packages.xml` to reflect the new version number. 1. To make sure that your site is importing that MDS package, look at `mirebalaismetadata/.../MirebalaisMetadataActivator.java`. It should have a list of MDS packages under your country's name. Make sure your MDS package is named there, adding it if necessary. 1. Now that you know that the concept is being imported via an MDS package, you can use it in a form (or whatever). Refer to your concept by Reference Term Mapping. If a CIEL Metadata Term Mapping ("CIEL:3456") is available, always prefer that. If it's not obvious from context what the concept is, add a comment with the concept's name. If the concept is not a CIEL concept, use the PIH name mapping ("PIH:TUMMY ACHE"), creating it if necessary. 1. Add the display name to the correct `messages.properties` file, with the correct key. They key to use will depend on the context in which the concept is being used. For HTML Form Entry, the key will be something you code into the form. ### Importing Concepts from CIEL to PIH Server Use Metadata Sharing (mds) to add the concept to the PIH EMR package. 1. Create mds package with select CIEL concepts from [mdsbuilder](https://mdsbuilder.openmrs.org/openmrs/). 1. Download/Export the CIEL mds package. 1. Import the CIEL mds package into the PIH concepts server. 1. Use "From peer" 1. Uncheck "dates differ" 1. Review the matches identified by the importer 1. Add the concepts to one of the PIH EMR mds packages. Zip file updates are pushed to the repo [https://github.com/PIH/openmrs-module-mirebalaismetadata](https://github.com/PIH/openmrs-module-mirebalaismetadata) ### Metadata Sharing (mds) Currently used for deploying concepts. Each mirebalaismetadata mds package is [described](https://github.com/PIH/openmrs-module-mirebalaismetadata/blob/master/api/src/main/resources/README.md). New concepts are created using the Concept Dictionary Maintenance UI: [https://concepts.pih-emr.org/openmrs/dictionary/index.htm](https://concepts.pih-emr.org/openmrs/dictionary/index.htm)** (NOTE: Do not add/edit concepts without first consulting Ellen Ball)** Concepts are bundled into zip files using the Metadata Sharing module in the admin UI. For transparency of the contents of each mds package, we are improving the packages to include only one ConvSet concepts for each mds. For example, to add APGAR score to the MCH mds package, APGAR score is added to the "Maternal Child Health concept set". See [README](https://github.com/PIH/openmrs-module-mirebalaismetadata/blob/master/api/src/main/resources/README.md). Zip file updates are pushed to the repo [https://github.com/PIH/openmrs-module-mirebalaismetadata](https://github.com/PIH/openmrs-module-mirebalaismetadata) The metadata module is built daily using Bamboo and deployed to all configured servers. #### Examples This commit adds the concept "Name of community health worker": [https://github.com/PIH/openmrs-module-mirebalaismetadata/commit/9d5cc404e8c96dcb40ca1bd9a8f0c57e693a6fd7](https://github.com/PIH/openmrs-module-mirebalaismetadata/commit/9d5cc404e8c96dcb40ca1bd9a8f0c57e693a6fd7) Open HUM_Dispensing_Concepts-35.zip to view the concept XML file. As a reference, the concept can also be viewed in the administrative UI: [https://concepts.pih-emr.org/openmrs/dictionary/concept.htm?conceptId=11631](https://concepts.pih-emr.org/openmrs/dictionary/concept.htm?conceptId=11631) ### Metadata Deploy Used for code level configuration of ALL other metadata. Metadata is set up programmatically in pih-core via methods provided by the metadata deploy module. [https://github.com/PIH/openmrs-module-pihcore](https://github.com/PIH/openmrs-module-pihcore) #### Examples Location and Patient Identifier Type for Mexico: [https://github.com/PIH/openmrs-module-pihcore/tree/master/api/src/main/java/org/openmrs/module/pihcore/metadata/mexico](https://github.com/PIH/openmrs-module-pihcore/tree/master/api/src/main/java/org/openmrs/module/pihcore/metadata/mexico) Other common metadata: [https://github.com/PIH/openmrs-module-pihcore/tree/master/api/src/main/java/org/openmrs/module/pihcore/metadata/core](https://github.com/PIH/openmrs-module-pihcore/tree/master/api/src/main/java/org/openmrs/module/pihcore/metadata/core) ### Configuring Concepts for Chiapas 1. On the concepts server (concepts.pih-emr.org), create a "Mexico MoH (Ministry of Health, or equivalent..) concept set", similar to the “[Liberia MoH diagnosis set](https://concepts.pih-emr.org/openmrs/dictionary/concept.htm?conceptId=10595)”. Create child sets, e.g. “Mexico MoH diagnosis”, “Mexico MoH Labs”, etc. Add concepts to these subsets. 2. For each concept in the source data dictionary: 1. If there is an existing concept in the concepts server that is an exact match, add a mapping to the "Mexico MoH" vocabulary item, and a Spanish translation if required. 2. If there is no existing concept, create it and add vocabulary mapping and translation. 3. Add this concept to appropriate concept set. 3. In the Metadata Sharing module, create a package called "Mexico Concepts" and create a new version. See example here for “[Liberia Concepts](https://concepts.pih-emr.org/openmrs/module/metadatasharing/export/details.form?group=c0dc491e-a26e-4dee-99c4-c4dc5cb2e787)”. 4. Download the zipped package of this version. 5. Add the zip file to the PIH openmrs-module-mirebalais-metadata Github repo [here](https://github.com/PIH/openmrs-module-mirebalaismetadata/tree/master/api/src/main/resources). This will add the metadata concepts to our build pipeline. 6. The concepts should then be available companero staging server. #### Diagnoses Add diagnoses concept set setting here: [https://github.com/PIH/openmrs-module-pihcore/blob/master/api/src/main/java/org/openmrs/module/pihcore/deploy/bundle/mexico/MexicoMetadataBundle.java](https://github.com/PIH/openmrs-module-pihcore/blob/master/api/src/main/java/org/openmrs/module/pihcore/deploy/bundle/mexico/MexicoMetadataBundle.java) Example: [https://github.com/PIH/openmrs-module-pihcore/blob/master/api/src/main/java/org/openmrs/module/pihcore/deploy/bundle/haiti/HaitiMetadataBundle.java#L100](https://github.com/PIH/openmrs-module-pihcore/blob/master/api/src/main/java/org/openmrs/module/pihcore/deploy/bundle/haiti/HaitiMetadataBundle.java#L100) <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.openmrs.module</groupId> <artifactId>mirebalaismetadata</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>Mirebalais Metadata Module</name> <description>Contains metadata and configuration settings for PIH's Mirebalais implementation</description> <url>https://wiki.openmrs.org/display/docs/Mirebalais+Metadata+Module+Module</url> <developers> <developer> <name>PIH</name> </developer> </developers> <organization> <name>PIH</name> <url>http://pih.org</url> </organization> <scm> <connection>scm:git:git@github.com:PIH/openmrs-module-mirebalaismetadata.git</connection> <developerConnection>scm:git:git@github.com:PIH/openmrs-module-mirebalaismetadata.git</developerConnection> <url>scm:git:git<EMAIL>:PIH/openmrs-module-mirebalaismetadata.git</url> </scm> <distributionManagement> <repository> <id>openmrs-repo-modules-pih</id> <name>Modules</name> <url>http://mavenrepo.openmrs.org/nexus/content/repositories/modules-pih/</url> </repository> <snapshotRepository> <id>openmrs-repo-modules-pih-snapshots</id> <name>OpenMRS Snapshots</name> <url>http://mavenrepo.openmrs.org/nexus/content/repositories/modules-pih-snapshots</url> </snapshotRepository> </distributionManagement> <modules> <module>api</module> <module>omod</module> </modules> <properties> <openMRSVersion>2.3.0-SNAPSHOT</openMRSVersion> <openMRSwebVersion>2.3.0-SNAPSHOT</openMRSwebVersion> <pihcoreVersion>1.1.0-SNAPSHOT</pihcoreVersion> <emrapiVersion>1.28.0</emrapiVersion> <paperrecordVersion>1.3.0</paperrecordVersion> <emrVersion>2.2.0</emrVersion> <uiframeworkVersion>3.16.0</uiframeworkVersion> <appframeworkVersion>2.14.0</appframeworkVersion> <metadatasharingVersion>1.6.0</metadatasharingVersion> <metadatamappingVersion>1.3.4</metadatamappingVersion> <metadatadeployVersion>1.11.0</metadatadeployVersion> <htmlformentryVersion>3.9.2</htmlformentryVersion> <htmlformentry19extVersion>1.7</htmlformentry19extVersion> <htmlformentryuiVersion>1.10.0</htmlformentryuiVersion> <calculationVersion>1.2</calculationVersion> <reportingVersion>1.19.0</reportingVersion> <reportinguiVersion>1.0</reportinguiVersion> <reportingrestVersion>1.10.0</reportingrestVersion> <htmlwidgetsVersion>1.9.0</htmlwidgetsVersion> <serializationxstreamVersion>0.2.14</serializationxstreamVersion> <idgenVersion>4.5.0</idgenVersion> <namephoneticsVersion>1.6.0</namephoneticsVersion> <pacsintegrationVersion>1.7.0</pacsintegrationVersion> <addresshierarchyVersion>2.11.0</addresshierarchyVersion> <providermanagementVersion>2.10.0</providermanagementVersion> <eventVersion>2.5</eventVersion> <logicVersion>0.5.2</logicVersion> <importpatientfromwsVersion>1.0</importpatientfromwsVersion> <uilibraryVersion>1.5</uilibraryVersion> <appuiVersion>1.4</appuiVersion> <dispensingVersion>1.1.0</dispensingVersion> <uicommonsVersion>2.7.0-SNAPSHOT</uicommonsVersion> <registrationcoreVersion>1.9.0</registrationcoreVersion> <registrationappVersion>1.15.0</registrationappVersion> <radiologyappVersion>1.5.0</radiologyappVersion> <coreappsVersion>1.27.0</coreappsVersion> <webservicesRestVersion>2.23.0-SNAPSHOT</webservicesRestVersion> <appointmentschedulingVersion>1.9.0</appointmentschedulingVersion> <appointmentschedulinguiVersion>1.7.0</appointmentschedulinguiVersion> <testutilsVersion>1.7.0-SNAPSHOT</testutilsVersion> <printerVersion>1.4.0</printerVersion> <allergyuiVersion>1.8.1</allergyuiVersion> <chartsearchVersion>1.5</chartsearchVersion> <haiticoreVersion>1.0.0</haiticoreVersion> <!-- Need to phase this out. --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- Begin OpenMRS core --> <dependency> <groupId>org.openmrs.api</groupId> <artifactId>openmrs-api</artifactId> <version>${openMRSVersion}</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.api</groupId> <artifactId>openmrs-api</artifactId> <version>${openMRSVersion}</version> <type>test-jar</type> <scope>test</scope> </dependency> <dependency> <groupId>org.openmrs.web</groupId> <artifactId>openmrs-web</artifactId> <version>${openMRSVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.test</groupId> <artifactId>openmrs-test</artifactId> <version>${openMRSVersion}</version> <type>pom</type> <scope>test</scope> </dependency> <!-- End OpenMRS core --> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>metadatasharing-api</artifactId> <version>${metadatasharingVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>metadatasharing-api-common</artifactId> <version>${metadatasharingVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>metadatadeploy-api</artifactId> <version>${metadatadeployVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>metadatadeploy-api-1.10</artifactId> <version>${metadatadeployVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>metadatamapping-api</artifactId> <version>${metadatamappingVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>pihcore-api</artifactId> <version>${pihcoreVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>emrapi-api</artifactId> <version>${emrapiVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>emrapi-api-1.12</artifactId> <version>${emrapiVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>emrapi-api-2.2</artifactId> <version>${emrapiVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>addresshierarchy-api</artifactId> <version>${addresshierarchyVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>registrationcore-api</artifactId> <version>${registrationcoreVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>radiologyapp-api</artifactId> <version>${radiologyappVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>providermanagement-api</artifactId> <version>${providermanagementVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>emr-api</artifactId> <version>${emrVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>htmlformentry-api</artifactId> <version>${htmlformentryVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>htmlformentry-api-1.10</artifactId> <version>${htmlformentryVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>htmlformentry-api-2.0</artifactId> <version>${htmlformentryVersion}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>reporting-api</artifactId> <version>${reportingVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>calculation-api</artifactId> <version>${calculationVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>serialization.xstream-api</artifactId> <version>${serializationxstreamVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>serialization.xstream-api-2.0</artifactId> <version>${serializationxstreamVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>uiframework-api</artifactId> <version>${uiframeworkVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>idgen-api</artifactId> <version>${idgenVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>namephonetics-api</artifactId> <version>${namephoneticsVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>paperrecord-api</artifactId> <version>${paperrecordVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>printer-api</artifactId> <version>${printerVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>coreapps-api</artifactId> <version>${coreappsVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>pacsintegration-api</artifactId> <version>${pacsintegrationVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs</groupId> <artifactId>event-api</artifactId> <version>${eventVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs</groupId> <artifactId>event-api-2.x</artifactId> <version>${eventVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>dispensing-api</artifactId> <version>${dispensingVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>appframework-api</artifactId> <version>${appframeworkVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>htmlformentryui-api</artifactId> <version>${htmlformentryuiVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>registrationapp-api</artifactId> <version>${registrationappVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.openmrs.module</groupId> <artifactId>haiticore-api</artifactId> <version>${haiticoreVersion}</version> <scope>provided</scope> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <target>1.6</target> <source>1.6</source> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.openmrs.maven.plugins</groupId> <artifactId>maven-openmrs-plugin</artifactId> <version>1.0.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.17</version> <configuration> <runOrder>alphabetical</runOrder> <!-- https://talk.openmrs.org/t/error-could-not-find-or-load-main-class-org-apache-maven-surefire-booter-forkedbooter/20509 --> <argLine>-Xmx1024m -Xms1024m -XX:MaxPermSize=512m -Djdk.net.URLClassPath.disableClassPathURLCheck=true</argLine> <includes> <include>**/*Test.java</include> </includes> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>versions-maven-plugin</artifactId> <version>2.1</version> <configuration> <generateBackupPoms>false</generateBackupPoms> <properties> <property> <name>openMRSVersion</name> <version>[2.2.0-SNAPSHOT,2.3.0-!)</version> <banSnapshots>true</banSnapshots> </property> <property> <name>openMRSwebVersion</name> <version>[2.2.0-SNAPSHOT,2.3.0-!)</version> <banSnapshots>true</banSnapshots> </property> </properties> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>openmrs-repo</id> <name>OpenMRS Nexus Repository</name> <url>http://mavenrepo.openmrs.org/nexus/content/repositories/public</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>openmrs-repo</id> <name>OpenMRS Nexus Repository</name> <url>http://mavenrepo.openmrs.org/nexus/content/repositories/public</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </project> <file_sep>/api/src/main/resources/README.md # Customization packages ## Medication lists Modify the MirebalaisMetadataActivator.java with the latest version number of these files: * Mexico/CES: CES_Drug_List-m.csv * Haiti/ZL/HUM: HUM_Drug_List-n.csv * Sierra Leone/Wellbody: SL_Drug_List-o.csv ## Metadata Sharing packages Metadata sharing packages include these: * HIV (includes all concepts for Haiti including iSantePlus): Haiti_HIV-x.zip (1 concept) * Zika: Haiti_Zika-x.zip (1 concept: Zika study concept set) * Diagnoses, symptoms, etc: HUM_Clinical_Concepts-x.zip (1 concept: Clinical concept set) * Dispensing: HUM_Dispensing_Concepts-x.zip (1 concept: Dispensing concept set) * Disposition: HUM_Disposition_Concepts-x.zip (1 concept: PIH EMR Disposition concept set) * ED triage: HUM_Emergency_Triage-x.zip (1 concept: HUM Triage set) * Medications: HUM_Medication-x.zip (1 concept: PIH medication concept set) * Miscellaneous: HUM_Metadata-x.zip (1 concept: PIH metadata mds concept set) * NCD: HUM_NCD-x.zip (1 concept: NCD concept set) * Oncology: HUM_Oncology-x.zip (1 concept: PIH Oncology concept set; 3 htmlforms) * Pathology: HUM_Pathology-x.zip (1 concept: Pathology concept set) * Providers/Roles: HUM_Provider_Roles-x.zip (?) * Radiology orders: HUM_Radiology_Orderables-x.zip (2 concepts including Radiology concept set) * Appointment scheduling: HUM_Scheduling-x.zip (1 concept) * Surgery: HUM_Surgery-x.zip (1 concept; 1 htmlform) * Liberia only: Liberia_Concepts-x.zip (1 concept: Liberia concept set) * Mexico only: Mexico_Concepts-x.zip (1 concept: ) * Oncology: Oncology-x.zip * Allergies: PIH_Allergies-x.zip (1 concept: PIH allergy concept set) * Concept sources: PIH_Concept_Sources-x.zip (27 sources) * Physical exam: PIH_Exam-x.zip (1 concept: Physical system concept set) * Intake history: PIH_History-x.zip (1 concept: PIH History Form Concept Set) * Labs: PIH_Labs-x.zip (1 concept: Laboratory concept set) * Maternal child health: PIH_Maternal_Child_Health-x.zip (1 concepts: MCH concept set) * Mental health: PIH_Mental_Health-x.zip (1 concept: Mental Health concept sets) * Pediatric feeding: PIH_Pediatric_Feeding-x.zip (1 concept: Pediatric feeding concept set) * Pediatric supplements: PIH_Pediatric_Supplements-x.zip (1 concept: Supplement history construct ?) * Socioeconomics: PIH_Socio_Economics-x.zip (1 concept: Socioeconomics concept set) * Sierra Leone only: Sierra_Leone_Concepts-x.zip (1 concept: Sierra Leone concept set) NOTE: x is the version number and modified in the packages.xml file
6177c06b5107a9f25bc2120ab45669d07cfde8f3
[ "Markdown", "Java", "Maven POM", "INI" ]
8
INI
PIH/openmrs-module-mirebalaismetadata
524f7c9c27754a2869878fdd5c049dbd8983c45f
abb6119c1658142e4a36e27ed598a655e2155f7a
refs/heads/master
<file_sep># Dislexic Los autores no se hacen responsables de ningún daño producido por el uso incorrecto de este programa ni por el mal funcionamiento del mismo.   ## Descripción : El script recorre el árbol de directorios del home, y para los archivos de texto plano (.txt), word (.docx) y openoffice (.odt) mezcla las letras de las palabras exceptuando la primera y la última de cada una de ellas. Compatible con Windows y Linux.   ## USO: En una máquina virtual, iniciar una consola y ejecutar el main.py con Python 3. <file_sep>__author__ = 'Joel' __author__ = 'Mar' __author__ = 'Samu' import pydoc import time import random import platform import os from zipfile import ZipFile import xml.etree.ElementTree as ET import tempfile import sys import zipfile from shutil import copyfile # Se coge la palabra, # se mantiene la primera y la ultima letra y las de en medio se intercambian de forma aleatoria # El proceso de intercambiado es: se coloca en una posicion aleatoria de las letras y se intercambia de forma aleatoria # con otra posicion aleatoria si calculando el timestamp con el modulo de la fecha de creacion de linux # (25 de agosto de 1991 = 25081991), se suman todas las cifras hasta que quede un numero y si ese numero es multiplo # de 7, el número mágico. Entonces intercambia con otra letra aleatoria de la palabra linuxCreationTime = 25081991 conditionChange = 7 # elemntos basicos docx = 'docx' odt = 'odt' txt = 'txt' org = 'org' etiOdt = './/*{urn:oasis:names:tc:opendocument:xmlns:text:1.0}p' etiDocx = './/*{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t' writeEtiDocx = 'w:t' writeEtiOdt = 'text:p' documentDocx = 'word/document.xml' documentOdt = 'content.xml' attribDocx = ' xml:' attribOdt = ' text:' backupFolder = os.getenv('HOME')+'/.magic' doBackup = False if '--no-bakup' in sys.argv else True def copyFile(fileDir): copyfile(fileDir, backupFolder+'/'+fileDir) def updateZip(zipname, filename, data): # generate a temp file tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname)) os.close(tmpfd) # create a temp copy of the archive without filename with zipfile.ZipFile(zipname, 'r') as zin: with zipfile.ZipFile(tmpname, 'w') as zout: zout.comment = zin.comment # preserve the comment for item in zin.infolist(): if item.filename != filename: zout.writestr(item, zin.read(item.filename)) # replace with the temp archive os.remove(zipname) os.rename(tmpname, zipname) # now add filename with its new data with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(filename, data) def calcCondition(): modulo = int(time.time()) + random.randint(1, 10) % linuxCreationTime #print(modulo) #numCondition = random.randrange(1, len(str(linuxCreationTime))-4) numCondition = 1 res = 0 while len(str(modulo)) > numCondition: #print('miau2') for cifra in str(modulo): #print(cifra) res += int(cifra) modulo = res res = 0 return modulo def twistWord(word): if len(word) < 3: return word #print(word) twisted = list(word) while (calcCondition() % conditionChange) != 0: aux1 = random.randrange(1, len(word)-1) aux2 = random.randrange(1, len(word)-1) aux3 = twisted[aux1] twisted[aux1] = twisted[aux2] twisted[aux2] = aux3 finishText = '' for elem in twisted: try: finishText += elem #print(''.join(twisted)) except: print(elem) return ''.join(twisted) def twistText(file, sentence=False): text = '' if not sentence: readFile = open(file, 'r') text = list(readFile.read()) else: text = file newList = list() #print(text) aux = '' cont = 0 for t in text: cont += 1 if t.isalnum(): aux += t else: newList.append(twistWord(aux) if len(aux) > 3 else aux) newList.append(t) aux = '' if cont == len(text): newList.append(twistWord(aux) if len(aux) > 3 else aux) aux = '' #print(''.join(newList)) if not sentence: readFile.close() writeFile = open(file, 'w') writeFile.write(''.join(newList)) writeFile.close() else: return ''.join(newList) def twistDocuments(file, extension): with ZipFile(file) as myzip: textFile = '' document = '' findEti = '' writeEti = '' attribText = '' if extension == docx: document = documentDocx findEti = etiDocx writeEti = writeEtiDocx attribText = attribDocx elif extension == odt: document = documentOdt findEti = etiOdt writeEti = writeEtiOdt attribText = attribOdt dictOcurrences = dict() with myzip.open(document) as myfile: stringFile = myfile.read().decode('utf-8') root = ET.fromstring(stringFile) listaEtis=root.findall(findEti) for element in listaEtis: if element.text is None: continue etiq = '' if len(element.attrib) != 0: for key in element.attrib.keys(): etiq = '<' + writeEti + '>' if (len(element.attrib) == 0) else '<' + writeEti + attribText + key.split('}')[1] + '="' + element.attrib[key] + '">' dictOcurrences[etiq + element.text + '</' + writeEti + '>'] = etiq + twistText(element.text, True) + '</' + writeEti + '>' myfile.close() with myzip.open(document) as fileInRaw: textFile = fileInRaw.read().decode('utf-8') for key in dictOcurrences.keys(): #print(key) #print(dictOcurrences[key]) textFile = textFile.replace(key, dictOcurrences[key]) #print(textFile) fileInRaw.close() myzip.close() updateZip(file, document, textFile) def searchTextFiles(): OS = platform.system() #rootDir = '.' rootDir = './pruebas' if OS == 'Windows': pass #os.chdir('USERPROFILE') elif OS == 'Linux': pass #os.chdir(os.getenv('HOME')) for dirName, subdirList, fileList in os.walk(rootDir): #print(dirName) #print(fileList) for fname in fileList: print(fname) finalFile = os.path.join(dirName, fname) if fname.split('.')[-1].lower() == txt or org: print(finalFile) if doBackup: copyFile(finalFile) twistText(finalFile) elif fname.split('.')[-1].lower() == docx: print(finalFile) if doBackup: copyFile(finalFile) twistDocuments(finalFile, docx) elif fname.split('.')[-1].lower() == odt: print(finalFile) if doBackup: copyFile(finalFile) twistDocuments(finalFile, odt) if not os.path.exists(backupFolder): os.mkdir(backupFolder) searchTextFiles()
2727e1f5e395114c973fdfca07e882a1801f1b03
[ "Markdown", "Python" ]
2
Markdown
jbelamor/dislexic-program
cc3b74b1718fe5e7b654c5c475afe5cd1273e15d
c2c24f0ab359c726d3b29e97a53f2a5aa4f1f343
refs/heads/master
<file_sep>#!/usr/bin/env python def draw_digit(segments): digit = """ memo O O 1 AAA HHH OO OO 1 F B M I bank O O O 2 FGGGB MNNNI a Y O O 2 E C L J b Z O O 2 EDDDC LKKKJ """ allsegments = set() for c in digit: allsegments.add(c) w = digit for c in allsegments: if c == "\n" or c == " " or c == ":" or c.islower(): continue if c in segments: w = w.replace(c, "#") else: w = w.replace(c, ".") return w data_rit = { "blank_a": "4c435341b12ba00006000ba99a781cc00fff10000000a99ae18fe18e1001181e0408", "blank_b": "4c435341a12aa000081001000ad81ec81f0000000000a99aa081e18e0001e1040408", "bp2": "4c435341b12bab6378100ba99a781cc00fff10000000a99a618de18c1001181e0408", "bp1": "4c435341b12ba60378100ba99a781cc00fff10000000a99a618fe18c1001181e0408", "b198": "4c435341a12aaf7fb81001000ad81ec81f0000000000a99aa081e18e0001e1040408", "b193": "4c435341a12aaf2fb81001000ad81ec81f0000000000a99aa081e18e0001e1040408", "00": "4c435341a12aaf5f501001000ad81ec81f0000000000a99aa001e18e0001e1040408", "15": "4c435341a12aad36001001000ad81ec81f0000000000a99a618fe18e0001e1040408", "27": "4c435341a12aa70b601001000ad81ec81f0000000000a99aa081e18e0001e1040408", "a12": "4c435341a12aab66041001000ad81ec81f0000000000a99a618de18e0001e1040408", "memoa00": "4c435341fa512f5f55000ba99a781cc00ff800000000a000618fe18cb081138c0408", "memoa00-2": "4c435341ea502f5f55000aa99a781cc00f0000000000e18c718de18ea08b038d0400", "memoa00-3": "4c435341b12a2f5f55000aa99a781cc00f0000000000a99a718de18e0001081e0400", } data = data_rit segments = { "blank_a": "Y", "blank_b": "Z", "bp2": "ZFEABGHINLK", "bp1": "ZFEABGIJ", "b198": "Z12ABCDFGHIJKLMN", "b193": "Z12ABCDFGHIJKN", "00": "ABCDEFHIJKLM", "memoa00": "OYABCDEFHIJKLM", "memoa00-2": "OYABCDEFHIJKLM", "memoa00-3": "OYABCDEFHIJKLM", "15": "BCHMNJK", "27": "ABGEDHIJ", "a12": "YBCHINLK", } all_segments = set() for v in segments.values(): for c in v: all_segments.add(c) def splitbits(s): bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] b0 = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) bits_lit = set() bits_out = set() for i,b in enumerate(b0): if b == "1": bits_lit.add(i) else: bits_out.add(i) return (bits_lit, bits_out) data_bits = {} for k,v in data.iteritems(): data_bits[k] = splitbits(v) decode = {} # bitno => array of segments for c in sorted(all_segments): candidate_bits = set( range(len(data.values()[0])/2*8) ) #candidate_bits = set( range(32,200) ) for digit, bitsets in data_bits.iteritems(): seglit = (-1 != segments[digit].find(c)) # is this segment lit? if seglit: candidate_bits -= bitsets[1] else: candidate_bits -= bitsets[0] print "Segment: %s, candidates: %s" % (c, str(candidate_bits)) for b in candidate_bits: if not b in decode: decode[b] = [] decode[b].append(c) print str(decode) for k,segs in segments.iteritems(): print k + ": " + segs print draw_digit(segs) def print_line(s): segmap = { 160: ['2'], 161: ['1', '3'], 162: ['C', 'B'], 163: ['A', 'E', 'D', 'F'], 166: ['T'], 167: ['R'], 168: ['G'], 169: ['H'], 170: ['I'], 171: ['J'], 172: ['M'], 173: ['L'], 174: ['K'], 175: ['N'] } bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] segs = "" for b, lights in segmap.iteritems(): byte_offset = b/8 bit_offset = (b%8) candidate = bytes[byte_offset] if candidate & 1<<bit_offset: for l in lights: if l not in segs: segs += l print segs print draw_digit(segs) for k,l in data.iteritems(): print k print_line(l) def unpack_segments(s, offset, segmap): byte_offset = offset/8 bytes = s[byte_offset:(byte_offset+2)] mask = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) print mask print segmap retval = "".join([ s if b == "1" else "" for (s,b) in zip(segmap, mask)]) return retval #print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") #print_line("4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2000 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2080 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") print_line("4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400") print_line("4c43534112502d760a0a5ee0a00a51a42b000000000004a0e8104004038de1840400") print_line("4c43534112502d360a0c161a40400500010000000000a99aa99ae18e038de1840400") print_line("4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400") print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0000001081e0400") #print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa00 1e1840001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa99 be1840001081e0400") #for k,v in segments.iteritems(): # print "===== %s =====" % k # print draw_digit(v) # print <file_sep>#!/usr/bin/env python # Emulate the head side of the connection, to poke/prod at the radio import serial ser = serial.Serial('/dev/tty.usbserial-A700eEqF', 38400) curline = "" while True: x = ser.readline() print x ser.write(x) ser.close() <file_sep>#!/usr/bin/env python # Pulling apart the bits for the first digit of the frequency display, # the others look to follow a very similar pattern. # Sixteen segment displays # YY <-- arrow # AAAAAAAAA # HK M NC # H K M N C # H K M N C # UUU PPP # G T S R D # G T S R D # GT S RD # EEEEEEEEE XX <-- decimal def draw_digit(segments): digit = """ aaaaaa iiiiii uuuuuuu f g b n o pj zA B Cv f g b n o p j z A B C v e hhhhc mtttqqqj y EDDDw e c m s r k y E w e c ms r k y E w dddddd llllll xxxxxx """ allsegments = set() for c in digit: allsegments.add(c) w = digit for c in allsegments: if c == "\n" or c == " ": continue if c in segments: w = w.replace(c, "#") else: w = w.replace(c, ".") return w # Segment: A, candidates: set([91]) # Segment: C, candidates: set([99]) # Segment: E, candidates: set([100]) # Segment: D, candidates: set([97]) # Segment: G, candidates: set([93]) # Segment: H, candidates: set([95]) # Segment: K, candidates: set([90]) # Segment: M, candidates: set([69, 89, 102]) # Segment: N, candidates: set([103]) # Segment: P, candidates: set([98]) # Segment: S, candidates: set([69, 89, 102]) # Segment: R, candidates: set([101, 121]) # Segment: U, candidates: set([94]) # Segment: T, candidates: set([88]) # Segment: Y, candidates: set([]) # Segment: X, candidates: set([]) # ---91--- # | | 3| # 9 9 8 0 9 # 5 0 9 1 9 # -94- -98- # 9 8 1 1 9 # 3 8 0 0 7 # | 2 1 | # EEEEEEEE # 0 T # 88 # 1 MS # 2 K # 3 A # 4 # 5 G # 6 U # 7 H # # 0 # 96 # 1 D # 2 P # 3 C # 4 E #100 # 5 R # 6 MS # 7 N # 0 E # 208 # 1 K? # 2 M? # 3 N # 4 R # 5 D # 6 P # 7 C # # 0 # 216 # 1 G # 2 U # 3 H # 4 T # 5 # 6 # 7 A # 223 # "0": "4c435341 b12a20800 a000a b99ab99ba99b0000000000a99aa99ba99a0001081e0400", mode_lcd = """ aaaaaa iiiiii uuuuuuu f g b n o pj zA B Cv f g b n o p j z A B C v e hhhhc mtttqqqj y EDDDw e c m s r k y E w e c ms r k y E w dddddd llllll xxxxxx """ data_mode = { # "CWL": "4c435341080aa0000a000a000ab99b000b0000000000a99ae18da000a181a84b0400", # "CWU": "4c435341a80aa0000a000a000ab99b000b0000000000a99ae18da000a181a84b0400", # "LSB": "4c435341fa50a0000a000a000ab99b000b0000000000a99ae18da000a081038c0400", # "USB": "4c435341fa50a0000a000a000ab99b000b0000000000a99ae18da000a08b038c0400", # "AM": "4c435341b12aa0000a000a000ab99b000b0000000000a99ae18da0000001081e0400", # "FM": "4c435341a12aa0000a000a000ab99b000b0000000000a99ae18da0000001e1040400", # "SET": "4c43534102502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400" # "FM": "4c435341a12a20800a681c100bb99b080b0000000000a99a618d618e0001e1040400", #FM, no agc "CWL": "4c435341080a20800a681c100bb99b080b0000000000a99a618d618ea181a84b0400", # CWL, agcf "CWU": "4c435341a80a20800a681c100bb99b080b0000000000a99a618d618ea181a84b0400", # CWU, agcf "LSB": "4c435341fa5020800a681c100bb99b080b0000000000a99a618d618ea081038c0400", # LSB, agcs "lsb": "4c435341ea50a0000a681c100bb99b080b0000000000a99a618d618ea081038d0400", # LSB, agcf "USB": "4c435341ea50a0000a681c100bb99b080b0000000000a99a618d618ea08b038d0400", # USB, agcf "AM": "4c435341a12aa0000a681c100bb99b080b0000000000a99a618d618e0001081f0400", # AM, agcs "SET": "4c435341025026060a0a4005a10a510a410000000000a24aa18a4004038de1840400", "SET2": "4c43534102512f360a0c16e80ce00f40050000000000408e408ea18a138df1840400", "SET3": "4c43534102512f5b6ae80c0a400a41b0110000000000408ea18a4004138df1840400", "SET4": "4c4353410251260b6a018ee80ca81b40050000000000408e408ea18a138df1840400", "SET5": "4c43534102512b6b6aa01a0a5a4005e82d0000000000000004a0c08e138df1840400", "SET6": "4c43534102512f2b6ae804a01aa42ba8110000000000a24aa84a4004138df1840400", "SET7": "4c43534102502f5f5ae804a48a4005000100000000000000618dc186038de1840400", "AM2": "4c435341b12aa0000a681de81e100ac00f0000000000a99a618fe00c0001081e0408", "AM3": "4c435341b12aa0000a681de81e100ac81f0000000000a99a618fe1840001081e0408", "AM4": "4c435341b12ba0000a681de81e100ac81fff00000000a99ae00de00c1001181e0408", "AM5": "4c435341b12ba0000a681df81e100ac81fff70000000a99ae00de00c1001181e0408", } data = data_mode segments = { "SET": "aghcdinmltquBE", "SET2": "aghcdinmltquBE", "SET3": "aghcdinmltquBE", "SET4": "aghcdinmltquBE", "SET5": "aghcdinmltquBE", "SET6": "aghcdinmltquBE", "SET7": "aghcdinmltquBE", "FM": "inmtqyzACvw", "AM": "spqjkyzACvw", "AM2": "spqjkyzACvw", "AM3": "spqjkyzACvw", "AM4": "spqjkyzACvw", "AM5": "spqjkyzACvw", "USB": "fedcbioqkluBEDxvw", "LSB": "fedioqkluBEDxvw", "lsb": "fedioqkluBEDxvw", "CWL": "afednmsrkjzyx", "CWU": "afednmsrkjzyxvw", } all_segments = set() for v in segments.values(): for c in v: all_segments.add(c) def splitbits(s): bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] b0 = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) bits_lit = set() bits_out = set() for i,b in enumerate(b0): if b == "1": bits_lit.add(i) else: bits_out.add(i) return (bits_lit, bits_out) data_bits = {} for k,v in data.iteritems(): data_bits[k] = splitbits(v) decode = {} # bitno => array of segments for c in all_segments: candidate_bits = set( range(len(data["USB"])/2*8) ) #candidate_bits = set( range(32,200) ) for digit, bitsets in data_bits.iteritems(): seglit = (-1 != segments[digit].find(c)) # is this segment lit? if seglit: candidate_bits -= bitsets[1] else: candidate_bits -= bitsets[0] print "Segment: %s, candidates: %s" % (c, str(candidate_bits)) for b in candidate_bits: if not b in decode: decode[b] = [] decode[b].append(c) print str(decode) for k,segs in segments.iteritems(): print k + ": " + segs print draw_digit(segs) def print_line(s): segmap = { # 49: ['g', 'h'], #bogons based on patterns # 57: ['g', 'h'], # bogons based on patterns 225: ['g'], 234: ['h'], 32: ['A', 'C'], 45: ['A', 'C'], 37: ['w', 'v'], 39: ['w', 'v'], 41: ['y', 'z'], 43: ['y', 'z'], 38: ['D'], 241: ['o'], 249: ['j'], 243: ['s'], 245: ['m', 'n'], 247: ['m', 'n'], 224: ['a'], 233: ['b'], 235: ['c'], 239: ['d'], 240: ['i'], 246: ['t'], 250: ['q'], 251: ['k'], 252: ['p'], 254: ['r'], # These three are confirmed 35: ['x'], 229: ['e', 'f'], 231: ['e', 'f'], # These four are confirmed, oddly enough 33: ['B', 'E', 'u'], 44: ['B', 'E', 'u'], 46: ['B', 'E', 'u'], 255: ['l'], # based on patterns } bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] segs = "" for b, lights in segmap.iteritems(): byte_offset = b/8 bit_offset = (b%8) candidate = bytes[byte_offset] if candidate & 1<<bit_offset: for l in lights: if l not in segs: segs += l print segs print draw_digit(segs) for k,l in data_mode.iteritems(): print k print_line(l) def unpack_segments(s, offset, segmap): byte_offset = offset/8 bytes = s[byte_offset:(byte_offset+2)] mask = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) print mask print segmap retval = "".join([ s if b == "1" else "" for (s,b) in zip(segmap, mask)]) return retval #print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") #print_line("4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2000 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2080 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") print_line("4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400") print_line("4c43534112502d760a0a5ee0a00a51a42b000000000004a0e8104004038de1840400") print_line("4c43534112502d360a0c161a40400500010000000000a99aa99ae18e038de1840400") print_line("4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400") print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0000001081e0400") #print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa00 1e1840001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa99 be1840001081e0400") #for k,v in segments.iteritems(): # print "===== %s =====" % k # print draw_digit(v) # print print_line("4c43534102502f3f55a01b0180a010404c43534102502f3f55a01b0180a010400500") <file_sep>#!/usr/bin/env python def draw_digit(segments): digit = """ txit: TTT 1 FAAB GGGG 222 E B M H 3 E B MLLH rxit: RRR E C K I EDDC N JJJJ """ allsegments = set() for c in digit: allsegments.add(c) w = digit for c in allsegments: if c == "\n" or c == " " or c == ":" or c.islower(): continue if c in segments: w = w.replace(c, "#") else: w = w.replace(c, ".") return w data_rit = { "blank": "4c435341a12aa000060000000ad81ec81f0000000000a99ac187e18e0001e1040400", "rit00": "4c435341a12aa000060000000ad81ec81f0000008cdfa99ac187e18e0001e1040400", "txrit-05": "4c435341a12aa000060000000ad81ec81f000000cdbda99ae18de18e0001e1040400", "rit+07": "4c435341a12aa000060000000ad81ec81f0000008f87a99ac187e18e0001e1040400", "rit-07": "4c435341a12aa000060000000ad81ec81f0000008d87a99a618fe18e0001e1040400", "rit-11": "4c435341a12aa000060000000ad81ec81f0000008586a99a618fe18e0001e1040400", "rit-12": "4c435341a12aa000060000000ad81ec81f00000085eba99a618fe18e0001e1040400", "rit-08": "4c435341a12aa000060000000ad81ec81f0000008dffa99a618fe18e0001e1040400", "rit-09": "4c435341a12aa000060000000ad81ec81f0000008dbfa99a618fe18e0001e1040400", "txrit-11": "4c435341a12aa000060000000ad81ec81f000000c586a99ae18de18e0001e1040400", } data = data_rit segments = { "blank": "", "rit00": "RABCDEFGHIJKMN", "rit+07": "R123ABCDEFGHIN", "txrit-05": "TR2ABCDEFGMLIJN", "rit-07": "R2ABCDEFGHIN", "rit-08": "R2ABCDEFGHIMLKJN", "rit-09": "R2ABCDEFGHIMLJN", "rit-11": "R2BCNHI", "rit-12": "R2BCNGHLKJ", "txrit-11": "TR2BCNHI", } all_segments = set() for v in segments.values(): for c in v: all_segments.add(c) def splitbits(s): bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] b0 = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) bits_lit = set() bits_out = set() for i,b in enumerate(b0): if b == "1": bits_lit.add(i) else: bits_out.add(i) return (bits_lit, bits_out) data_bits = {} for k,v in data.iteritems(): data_bits[k] = splitbits(v) decode = {} # bitno => array of segments for c in all_segments: candidate_bits = set( range(len(data.values()[0])/2*8) ) #candidate_bits = set( range(32,200) ) for digit, bitsets in data_bits.iteritems(): seglit = (-1 != segments[digit].find(c)) # is this segment lit? if seglit: candidate_bits -= bitsets[1] else: candidate_bits -= bitsets[0] print "Segment: %s, candidates: %s" % (c, str(candidate_bits)) for b in candidate_bits: if not b in decode: decode[b] = [] decode[b].append(c) print str(decode) for k,segs in segments.iteritems(): print k + ": " + segs print draw_digit(segs) def print_line(s): segmap = { 160: ['2'], 161: ['1', '3'], 162: ['C', 'B'], 163: ['A', 'E', 'D', 'F'], 166: ['T'], 167: ['R'], 168: ['G'], 169: ['H'], 170: ['I'], 171: ['J'], 172: ['M'], 173: ['L'], 174: ['K'], 175: ['N'] } bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] segs = "" for b, lights in segmap.iteritems(): byte_offset = b/8 bit_offset = (b%8) candidate = bytes[byte_offset] if candidate & 1<<bit_offset: for l in lights: if l not in segs: segs += l print segs print draw_digit(segs) for k,l in data.iteritems(): print k print_line(l) def unpack_segments(s, offset, segmap): byte_offset = offset/8 bytes = s[byte_offset:(byte_offset+2)] mask = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) print mask print segmap retval = "".join([ s if b == "1" else "" for (s,b) in zip(segmap, mask)]) return retval #print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") #print_line("4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2000 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2080 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") print_line("4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400") print_line("4c43534112502d760a0a5ee0a00a51a42b000000000004a0e8104004038de1840400") print_line("4c43534112502d360a0c161a40400500010000000000a99aa99ae18e038de1840400") print_line("4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400") print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0000001081e0400") #print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa00 1e1840001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa99 be1840001081e0400") #for k,v in segments.iteritems(): # print "===== %s =====" % k # print draw_digit(v) # print <file_sep>#!/usr/bin/env python def _get_bit(bytes, offset): i = int(offset)/8 j = offset % 8 if (bytes[i] & (1<<j)) != 0: return 1 return 0 def _set_bit(bytes, offset): i = int(offset)/8 j = offset % 8 bytes[i] |= (1<<j); return bytes def decode_SWDV(b): rit = b[4] ifshift = b[5] squelch = b[6] vol = b[7] def decode_SWDR(b): x = b[4] if x == 0x80: return 0 if x == 0x81: return 1 #clockwise if x == 0x7f: return -1 # anticlockwise return 0 KEYS = { 'MF': 72, '1': 34, '2': 33, '3': 32, '4': 43, '5': 42, '6': 41, '7': 40, '8': 51, '9': 50, '*': 49, '0': 35, 'ENT': 48, 'FUNC': 75, 'RIT': 74, 'KEY': 73, 'MODE': 67, 'V/M': 66, 'M/KHz': 65, 'RF': 64, 'UP': 83, 'DOWN': 82, } def decode_SWDS(b): retval = [] bytes = [ ord(c) for c in b ] for key,bit in KEYS.iteritems(): if 1 == _get_bit(bytes, bit): retval.append(key) return retval def encode_SWDS(button): keyblank = "SWDS000000000100\r\n" if button == None: return keyblank blank_bytes = [ ord(c) for c in keyblank ] o = KEYS[button] bytes = _set_bit(blank_bytes, o) return "".join([chr(c) for c in bytes]) <file_sep>#!/usr/bin/env python from decode_screen import * def intWithCommas(x): if type(x) not in [type(0), type(0L)]: raise TypeError("Parameter must be an integer.") if x < 0: return '-' + intWithCommas(-x) result = '' while x >= 1000: x, r = divmod(x, 1000) result = ",%03d%s" % (r, result) return "%d%s" % (x, result) screens = [ "4<KEY>038de1840400", "4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400", "4c435341b12a20000a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400", "4c435341b12a20800a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400", "4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400", "4c43534112502d760a0a5ee0a00a51a42b000000000004a0e8104004038de1840400", "4c43534112502d360a0c161a40400500010000000000a99aa99ae18e038de1840400", "4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400", "<KEY>00408ea18a4004038de1840400", "<KEY>000a100ab99b000b0000000000a99aa99ba0000001081e0400", "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400", "<KEY>0000a000a000ab99b000b0000000000a99aa001e1840001081e0400", "4c435341b12aa0000a000a000ab99b000b0000000000a99aa99be1840001081e0400", "4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400", "4c435341b12a20800a0000d00eb99ba99b0000000000a99aa99ba99a0001081e0400", "4c435341b12a2f5f55000aa99a781cc00f0000000000a99a718de18e0001081e0400", "4c43534102502f3f55a01b0180a010404c43534102502f3f55a01b0180a010400500", ] fdisp = FrequencyDisplay() mdisp = ModeDisplay() rfdisp = RFPowerDisplay() agcdisp = AGCDisplay() smeterdisp = SMeterDisplay() def print_state(sin): s = [ int(sin[i:i+2], 16) for i in range(0, len(sin)-1, 2) ] try: mode = mdisp.decode(s) rxstate = "%s RF:%+2d %s" % (agcdisp.decode(s), rfdisp.decode(s), smeterdisp.decode_string(s)) if fdisp.is_freq(s): print "[%s] f = %d %s" % (mode, fdisp.freq(s), rxstate) else: print "[%s] > %s < %s" % (mode, fdisp.decode(s), rxstate) except Exception, e: print "Caught exception: " + str(e) print print "Input #%d: %s" % (i, s) for i,s in enumerate(screens): print_state(s) <file_sep>#!/usr/bin/env python def hex2bytes(s): return [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] def which_bits_differ(s, t): mpb = hex2bytes(s) mpe = hex2bytes(t) delta = [ a^b for (a,b) in zip(mpb, mpe) ] retval = [] for i,p in list(enumerate(delta)): if p != 0: for j in range(8): if 0 != p & (1<<j): retval.append(8*i+j) return retval cases = [ ( "lock", "4c435341b12aa000060000000ad81ec81f000000cfafa99ae18de18c0001081e0400", "4c435341b12aa000060000100ad81ec81f000000cfafa99ae18fe18c0001081e0400"), ("star", "4c435341a12aa000060000000ad81ec81f000000ccdfa99aa081e18c0001e1040400", "4c435341a12aa000060000000ad81ec81f000000ccdfa99aa081e18c0000e1040400"), ] for name,a,b in cases: print name + ": " + str(which_bits_differ(a,b)) <file_sep>#!/usr/bin/env python meter_partial = "4c435341b12aa000060001100ab99a000bffff000000a99aa99ba0000001081e0408" meter_empty = "4c435341b12aa000060000100ab99a000b0000000000a99aa99ba0000001081e0400" # 26 segments def hex2bytes(s): return [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] mpb = hex2bytes(meter_partial) mpe = hex2bytes(meter_empty) delta = [ a^b for (a,b) in zip(mpb, mpe) ] for i,p in list(enumerate(delta)): if p != 0: print str( (i,p) ) # Looks like the smeter is at byte 17, probably has 26b from there. <file_sep>#!/usr/bin/env python # Takes the output of Salae Logic's Async serial decoder and # restitches it into ASCII sequences import sys if len(sys.argv) != 3: print "Usage: logic_to_dump.py head_to_radio.txt radio_to_head.txt" sys.exit(1) def parse_char_ascii(c): if c[0] == "'": return "\\x%02x" % int(c[1:-1]) if c == "\\r": return "\r" if c == "\\n": return "\n" return c def parse_char_hex(c): x = None if c == "' '": x = " " if c == "\\r": x = "\r" if c == "\\n": x = "\n" nl = "" if c == "\\n": nl = "\n" nl = "" if None == x: if c[0] == "'": try: return "%02x" % int(c[1:-1]) except Exception, e: print "Exception: " + str(e) print "Input: %s" % c raise e else: x = c[0] return "%02x%s" % (ord(x), nl) def parse_char_literal(c): x = None if c == "' '": return ' ' if c == "\\r": return "\r" if c == "\\n": return "\n" if None == x: if c[0] == "'": try: return chr(int(c[1:-1])) except Exception, e: print "Exception: " + str(e) print "Input: %s" % c raise e else: return c[0] parse_char = parse_char_hex import struct def packet_h(a): if a[0] != 'h' or a[1] != "\x1d": return Exception("Invalid header") if a[-1] != '\x0a' or a[-2] != '\x00': return Exception("Invalid header") if len(a) != 34: return {} v2 = struct.unpack("<i", a[2:6]) v9 = struct.unpack("<i", a[9:13]) # usually all zeroes v13 = struct.unpack("<", a[13:17]) v6 = struct.unpack("B", a[6]) v7 = struct.unpack("B", a[7]) v8 = struct.unpack("B", a[8]) v17 = "".join([ "%02x" % ord(c) for c in a[17:33] ]) return { "v2": v2, "v9": v9, "v13": v13, "v6": v6, "v7": v7, "v8": v8, "v17": v17 } BREAKLEN = 0.01 def stitch_lines(path, prefix): retval = [] f = file(path) f.readline() # drop header t0 = None tp = None curline = "" for l in f: r = l.split(",") t = float(r[0]) c = r[1] if t0 == None: t0 = t tp = t cp = parse_char(c) if t - tp > BREAKLEN: # if cp[-1] == "\n": retval.append( (t0, prefix, curline) ) t0 = None curline = "" if cp == "4c" and len(curline) == 34*2: curline = curline[0:(34*2)] retval.append( (t0, prefix, curline) ) t0 = t tp = t curline = "" curline += cp tp = t if t0 != None: retval.append( (t0, prefix, curline) ) f.close() return retval h2r = stitch_lines(sys.argv[1], " -->") r2h = stitch_lines(sys.argv[2], "<--") flow = h2r + r2h flow.sort() t0 = None for t,d,s in flow: if None == t0: t0 = t print "%0.2f %s %s" % (t-t0,d, s.strip()) <file_sep>#!/usr/bin/env python def _get_bit(bytes, offset): i = int(offset)/8 j = offset % 8 if (bytes[i] & (1<<j)) != 0: return 1 return 0 class LCD16: """A 16 segment LCD display Layout is per Lite-On's naming convention: AAA BBB HK M NC H K M N C UU PP G T S R D GT S RD FFF EEE The alphabet is shown on page 54 of the DX-SR8 manual. """ ALPHABET = { " " : "", "_" : "FE", "/" : "TN", "-" : "PU", "*" : "TKUPRN", "&" : "SUDPCEMF", "+" : "SUPM", "\\": "KR", "=" : "UPEF", "(" : "RN", ")" : "TK", "$" : "SAUHDPEMBF", # This is cyrillic, apparently. transliterating to the best of my ability "z" : "AUERNBF", "g" : "AGHB", "d" : "TDCENF", "s" : "TKAPEBF", "zh": "TSKRMN", "i" : "TGHDCN", "j" : "TAGHDCNB", "l" : "TDCN", "p" : "AGHDCB", "ch": "TKN", "|X|": "TSKGHDCRMN", "ts": "SGHEMF", "sh": "SGHDCEMF", "f": "SAERMBF", "yu": "GUHDCRN", "ya": "TAUHDPCB", "~": "ADPCEBF", "!": "TGUHDC", "@": "TGUH", "A": "TNPCD", "B": "ABCDMSFEP", "C": "ABHGFE", "D": "ABCDFEMS", "E": "ABHGFEUP", "F": "ABGHUP", "G": "BAHGFEDP", "H": "HGCDUP", "I": "ABMSFE", "J": "GFECD", "K": "HGUNR", "L": "HGFE", "M": "HGCDKN", "N": "HGKRCD", "O": "ABCDFEGH", "P": "ABCPUHG", "Q": "ABCDEFGHR", "R": "ABCUPGHR", "S": "ABKPDEF", "T": "ABMS", "U": "HGEFCD", "V": "HGTN", "W": "HGCDTR", "X": "KNRT", "Y": "KNS", "Z": "ABNTFE", "0": "ABCDEFGHNT", "1": "CD", "2": "ABCPUGFE", "3": "ABUPFECD", "4": "HUPCD", "5": "ABHUPDEF", "6": "ABHGFEDUP", "7": "ABCD", "8": "ABCDEFGHUP", "9": "ABHCUPDFE", } def fixup(self, l): """Fudges segments the same way the radio seems to. A and B are hardwired together, as are E and F""" fudges = [ ('A', 'B'), ('E', 'F') ] for x,y in fudges: if x in l and y not in l: l += y if y in l and x not in l: l += x return l def __init__(self, lit=""): self.lit = self.fixup(lit) # create the alphabet lookup table. Yes, I want to do this # every runtime, since I have no proper tests, this makes me # feel much better about the delusion that everything is # working. self.lookup = {} # mask => character for c,m in self.ALPHABET.iteritems(): m_sorted = "".join(sorted(list(m))) if m_sorted in self.lookup: raise Exception("Non-unique mask to character mapping: %s goes to both %s and %s" % (m, self.lookup[m_sorted], c)) self.lookup[m_sorted] = c def draw(self): digit=""" AAA BBB HK M NC H K M N C UU PP G T S R D GT S RD FFF EEE""" allsegments = set() for c in digit: allsegments.add(c) w = digit for c in allsegments: if c == "\n" or c == " " or c == ":" or c.islower(): continue if c in self.lit: w = w.replace(c, "#") else: w = w.replace(c, ".") return w def decode(self): lit_key = "".join(sorted([ c if c.isupper() else "" for c in self.lit])) if lit_key not in self.lookup: print ">>> %s MISSING: %s" % (str(self.__class__), self.lit ) print self.draw() return None return self.lookup[lit_key] class LCD16_a(LCD16): # This is the segment associated with each bit in the input, in # ascending bit order. SEGMENT_MAP = "TSKAyGUHxDPCERMN" @classmethod def from_bytes(cls, bytes, offset): lit = "" for k in range(16): if 1 == _get_bit(bytes, offset+k): lit += cls.SEGMENT_MAP[k] return cls(lit) class LCD16_b(LCD16_a): """This is the same as the other 16 segment display, just wired differently. """ SEGMENT_MAP = "ERMNyDPCaGUHTSKA" class LCD16_c(LCD16_a): SEGMENT_MAP = "FRMNEDPCxGUHTSKA" class LCD16_d(LCD16_a): SEGMENT_MAP = "ERMNyDPCxGUHTSKA" class FrequencyDisplay: def decode(self, b): digits = [ LCD16_a.from_bytes(b, o) for o in [72, 88, 104, 120] ] digits += [ LCD16_b.from_bytes(b, 208) ] digits += [ LCD16_c.from_bytes(b, 192) ] digits += [ LCD16_d.from_bytes(b, 176) ] return "".join([d.decode() for d in digits]) def is_freq(self, b): disp = self.decode(b) for c in disp: if c not in list(" 0123456789"): return False inspace = True for i in range(len(disp)): c = disp[i] if c != " ": inspace = False if not inspace and c not in "0123456789": return False if inspace: return False return True def freq(self, b): if not self.is_freq(b): return None return int(self.decode(b))*10 ################################################################################ class LCD16_mode_a(LCD16_a): SEGMENT_MAP = "AKcdeGgHiCPDmnoE" class LCD16_mode_b(LCD16_a): SEGMENT_MAP = "AKcTeGUHiCPDNnRE" class LCD16_mode_c(LCD16_a): SEGMENT_MAP = "KAcEqCPDiGkHSNMp" class ModeDisplay: def decode(self, b): digits = [ LCD16_mode_a.from_bytes(b, 224), LCD16_mode_b.from_bytes(b, 240), LCD16_mode_c.from_bytes(b, 32) ] return "".join([d.decode() for d in digits]) ################################################################################ class RFPowerDisplay: def decode(self, b): # It's not clear which bit is RF-20, so we just assume it's # lit. We can't tell which one it is because it never goes # off, so this seems like a safe assumption. rf10 = _get_bit(b, 40) rf0 = _get_bit(b, 244) rfp10 = _get_bit(b, 228) if rfp10 == 1: return 10 if rf0 == 1: return 0 if rf10 == 1: return -10 return -20 class AGCDisplay(): def decode(self, b): if 1 == _get_bit(b, 36): return "AGC-S" if 1 == _get_bit(b, 248): return "AGC-F" return "" class SMeterDisplay(): def decode(self, b): busy = _get_bit(b, 80) if 0 == busy: return None maxtick = max([ i-136 if 1 == _get_bit(b, i) else 0 for i in range(136, 162) ]) if maxtick == 0: return 0 if maxtick < 9*2: return 1 + float(maxtick-1)/2 step = 1.259921 # 2^(1/3) db = 10 for i in range(18, maxtick): db *= step return db def decode_string(self, b): g = self.decode(b) if None == g: return "squelch" return "%.2f" % g ################################################################################ class BacklightDisplay: def decode(self, b): return b[32] # hurray, a trivial one! ################################################################################ class MiscDisplay: def decode(self, b): retval = [] sets = { "FUNC": 76, "KEY": 92, "STAR": 232, "NB": 212, # "Nar": 200, # XXX TODO Narrow is lost! "T": 184, "TUNE": 52, "SPLIT": 54, } for name,i in sets.iteritems(): if 1 == _get_bit(b, i): retval.append(name) return retval <file_sep>#!/usr/bin/env python # Emulate the radio side of the connection, to poke/prod at the head # unit. import serial ser = serial.Serial('/dev/tty.usbserial-A4006Dyk', 38400) curline = "" while True: x = ser.read(1) curline += x[0] if -1 != curline.find("AL~READY"): print "GOT AL~READY." n = curline.find("AL~READY") curline = curline[n+8+1:] if 1 <= curline.find("LCSA"): print "SEEK to LCSA: %d" % curline.find("LCSA") n = curline.find("LCSA") ser.write(curline[0:n]) curline = curline[n:] while len(curline) >= 34: print "line: " + "".join([ "%02x" % ord(c) for c in curline ]) ser.write(curline[0:34]) curline = curline[34:] ser.close() <file_sep>#!/usr/bin/env python """This is just a quick one-off script to read in the alphabet for the display, along with a quick confirmation check that I haven't bollocksed the input. """ import sys import tempfile import os from decode_screen import LCD16 (fd, path) = tempfile.mkstemp() print "Writing output to %s" % path print f = os.fdopen(fd, "w") for c in " _ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789": conf = "N" segs = "" while conf != "": print print "Segments for '" + c + "':" segs = sys.stdin.readline() d = LCD16(segs) print d.draw() print "Input empty line to confirm, anything else to redo input:" conf = sys.stdin.readline() conf = conf.strip() segs = segs.strip() f.write('"%s": "%s",\n' % (c, segs)) f.close() <file_sep>#!/usr/bin/env python # Given an array of arrays in which the area of interest is held # constant while others are varied, return bit ranges that could # contain the area of interest. data = { "SET": ["4c43534102512f360a0c16e80ce00f40050000000000408e408ea18a138df1840400", "4c43534102512f5b6ae80c0a400a41b0110000000000408ea18a4004138df1840400", "4c4353410251260b6a018ee80ca81b40050000000000408e408ea18a138df1840400", "4c43534102512b6b6aa01a0a5a4005e82d0000000000000004a0c08e138df1840400", "4c43534102512f2b6ae804a01aa42ba8110000000000a24aa84a4004138df1840400", "4c43534102502f5f5ae804a48a4005000100000000000000618dc186038de1840400", "4c43534102502f3f5aa01a0180a01140050000000000408e408ea18a038de1840400", "4c43534102502f560a018ea816a811400500000000000000a24aa18a038de1840400", "4c43534102502f560a018ea817a811400500000000000000a24aa18a038de1840400", "4c43534102502f560a018ea817a81140050000000000408e408ea18a038de1840400", "4c435341025026060a0a4005a10a510a410000000000a24aa18a4004038de1840400", "4c435341125026060a0a4105a10a510a41ffff700000a24aa18a4004038de1840408", "4c435341125026060a0a4105a00a500a410000000000a24aa18a4004038de1840408", ], "AM": [ "4c435341b12aa0000a681de81e100ac00f0000000000a99a618fe00c0001081e0408", "<KEY>aa0000a681de81e100ac81f0000000000a99a618fe1840001081e0408", "4c435341b12ba0000a681de81e100ac81fff00000000a99ae00de00c1001181e0408", "4c435341b12ba0000a681df81e100ac81fff70000000a99ae00de00c1001181e0408", "<KEY>", "4c435341b12ba0000a0001100af81e481fffff100000<KEY>0801001181e0408" "<KEY>001100af81e481ffffe000000a99ab001a0801001181e0408", "<KEY>01100af81e481fffff100000<KEY>0801001181e0408", "4c435341a12b20000a0001100af81e481fffff100000a99aa001a0801001181f0408", "4c435341a12b20000a0001100af81e481fffff108cdfa99aa001a0801001181f0408", "4c435341a12b20800a0001100af81e481fffff10ccdfa99aa001a0801001181f0408", ], "FM": [ "4c435341a12b20800a0001100af81e481fffff10ccdfa99aa001a0801001f1040408", "4c435341a12b20800a681c100ab99a080b000000ccdfa99a618d618e1001f1040400", "4c435341a12a20800a681c100ab99a080b0000000000a99a618d618e0001e1040400", "<KEY>", "<KEY>", ] } data2 = [ # anti-contrast: find what _doesn't_ change with mode "<KEY>c100bb99b080b0000000000a99a618d618e0001e1040400", #FM, no agc "4c435341080a20800a681c100bb99b080b0000000000a99a618d618ea181a84b0400", # CWL, agcf "4c435341a80a20800a681c100bb99b080b0000000000a99a618d618ea181a84b0400", # CWU, agcf "4c435341fa5020800a681c100bb99b080b0000000000a99a618d618ea081038c0400", # LSB, agcs "4c435341ea50a0000a681c100bb99b080b0000000000a99a618d618ea081038d0400", # LSB, agcf "4c435341ea50a0000a681c100bb99b080b0000000000a99a618d618ea08b038d0400", # USB, agcf "4c435341a12aa0000a681c100bb99b080b0000000000a99a618d618e0001081f0400", # AM, agcs ] def contrast_set(byteses): # Winnow down: # Create a blank "mask" of mismatched bits # xor 1 vs 2, and OR the result against the mask # xor 2 vs 3, and OR that against the mask # xor 3 vs 4, and OR and so on and so forth mask = [ 0 for b in byteses[0] ] for i in range(len(byteses)-1): xor_res = [ x_i ^ y_i for (x_i, y_i) in zip(byteses[i], byteses[i+1]) ] mask = [ m_i | x_i for (m_i, x_i) in zip(mask, xor_res) ] return mask overall_mask = None for k,v in data.iteritems(): byteses = [ [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] for s in v ] mask = contrast_set(byteses) if None == overall_mask: overall_mask = mask else: overall_mask = [ o|m for (o,m) in zip(overall_mask, mask) ] print k print str(mask) print str(overall_mask) print for s in data2: bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] bytes = [ b & ~m for (m,b) in zip(overall_mask, bytes) ] bytes = bytes[29:] b0 = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) print b0 byteses2 = [ [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] for s in data2 ] same_bits = contrast_set(byteses2) print str(same_bits) <file_sep>#!/usr/bin/env python import sys def label_line(l): fields = l.split(" ") label = fields[0] retval = {} changed = False # print str(fields) if label != "idle": changed = True for i,v in enumerate(fields): val = 0 if v == "X": val = 1 retval["f%d-%s" % (i,str(changed))] = [val, 1] return retval def merge_result(d, dp): for k,v in dp.iteritems(): if not k in d: d[k] = [0,0] d[k][0] += v[0] d[k][1] += v[1] return d def summarize(d): retval = {} for k,v in d.iteritems(): p = float(v[0])/float(v[1]) retval[k] = p return retval lines = 0 idles = 0 data = {} for l in sys.stdin: dp = label_line(l) data = merge_result(data, dp) lines += 1 if l.startswith("idle"): idles += 1 s = summarize(data) myks = data.keys() fields = set() for k in myks: fname,val = k.split("-") fields.add(fname) def pof(d,f,v): keyname = f + "-" + str(v) if not keyname in d: return 0 r = d[keyname] return r[0]/float(r[1]) for f in fields: p_true = pof(data, f, True) p_false = pof(data, f, False) print "%s %.3g %.3g" % (f, p_true, p_false) #print str(summarize(data)) <file_sep>#!/usr/bin/env python # Takes hex dumps of packets as input on stdin, outputs parses on stdout import sys import struct def packet_h(a): if a[0] != 'h' or a[1] != "\x1d": raise Exception("Invalid header") if a[-1] != '\x0a' or a[-2] != '\x00': raise Exception("Invalid header") if len(a) != 34: return {} def intat(i): rawv = struct.unpack("<I", a[i:i+4])[0] return rawv return int('{:032b}'.format(rawv)[::-1], 2) freq = intat(13) smeter = intat(0) agcish = intat(7) # Frequency seems to be at 13 on # Something at a[7] changes when idling # Also something at a[9]: signal strength? AGC strength? v18 = "".join([ "%02x" % ord(c) for c in a[18:33] ]) return { "freq": freq, "smeter": smeter, } f0 = None df = 0 for l in sys.stdin: line = "".join([ chr(int(l[i:i+2], 16)) for i in range(0, len(l)-1, 2) ]) p = packet_h(line) if p != {}: if f0 == None: df = 0 else: df = p["freq"] - f0 print "%d %d" % (p["freq"], df) f0 = p["freq"] <file_sep>#!/usr/bin/env python # Pulling apart the bits for the first digit of the frequency display, # the others look to follow a very similar pattern. # Sixteen segment displays # YY <-- arrow # AAAAAAAAA # HK M NC # H K M N C # H K M N C # UUU PPP # G T S R D # G T S R D # GT S RD # EEEEEEEEE XX <-- decimal def draw_digit(segments): digit = """ YY AAAAAAAAA HK M NC H K M N C H K M N C UUU PPP G T S R D G T S R D GT S RD EEEEEEEEE XX""" allsegments = set() for c in digit: allsegments.add(c) w = digit for c in allsegments: if c == "\n" or c == " ": continue if c in segments: w = w.replace(c, "#") else: w = w.replace(c, ".") return w # Segment: A, candidates: set([91]) # Segment: C, candidates: set([99]) # Segment: E, candidates: set([100]) # Segment: D, candidates: set([97]) # Segment: G, candidates: set([93]) # Segment: H, candidates: set([95]) # Segment: K, candidates: set([90]) # Segment: M, candidates: set([69, 89, 102]) # Segment: N, candidates: set([103]) # Segment: P, candidates: set([98]) # Segment: S, candidates: set([69, 89, 102]) # Segment: R, candidates: set([101, 121]) # Segment: U, candidates: set([94]) # Segment: T, candidates: set([88]) # Segment: Y, candidates: set([]) # Segment: X, candidates: set([]) # ---91--- # | | 3| # 9 9 8 0 9 # 5 0 9 1 9 # -94- -98- # 9 8 1 1 9 # 3 8 0 0 7 # | 2 1 | # EEEEEEEE # 0 T # 88 # 1 MS # 2 K # 3 A # 4 # 5 G # 6 U # 7 H # # 0 # 96 # 1 D # 2 P # 3 C # 4 E #100 # 5 R # 6 MS # 7 N # 0 E # 208 # 1 K? # 2 M? # 3 N # 4 R # 5 D # 6 P # 7 C # # 0 # 216 # 1 G # 2 U # 3 H # 4 T # 5 # 6 # 7 A # 223 # "0": "4c435341 b12a20800 a000a b99ab99ba99b0000000000a99aa99ba99a0001081e0400", data_2 = { # This is for the fifth number from the right, the MHz one's place "0": "4c435341b12a20800a000ab99ab99ba99b0000000000a99aa99ba99a0001081e0400", "2": "4c435341b12a20800a0000781cb99ba99b0000000000a99aa99ba99a0001081e0400", "3": "4c435341b12a20800a0000581eb99ba99b0000000000a99aa99ba99a0001081e0400", "4": "4c435341b12a20800a0000d00eb99ba99b0000000000a99aa99ba99a0001081e0400", "5": "4c435341b12a20800a0000d816b99ba99b0000000000a99aa99ba99a0001081e0400", "6": "4c435341b12a20800a0000f816b99ba99b0000000000a99aa99ba99a0001081e0400", "7": "4c435341b12a20800a0000180ab99ba99b0000000000a99aa99ba99a0001081e0400", "8": "4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400", "9": "4c435341b12a20800a0000d81eb99ba99b0000000000a99aa99ba99a0001081e0400", "ED": "4c435341b12a20000a001010100011001100000000000100010001000001081e0400", "E": "4c435341b12a20000a001010101011001100000000000100010101000001081e0400", "1": "4c435341b12a20800a0000100ab99ba99b0000000000a99aa99ba99a0001081e0400", "1A": "4c435341b12a20800a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400", "1NA": "4c435341b12aa0000a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400", "D": "4c43534112502b6b6aa01a1a5a4005e82d0000000000000004a0c08e038de1840400", "T": "4c43534112502f5b6ae80c1a400a41b0110000000000408ea18a4004038de1840400", "M": "4c43534112502f5f5a018eb48a4005000100000000000000a99ba000038de1840400", "R": "<KEY>00000000408ea18a4004038de1840400", "S": "4c43534112502d3f5a0c161c16a81140050000000000a99a618c0000038de1840400", "K": "<KEY>00040<KEY>038de1840400", } data_kHz = { # third digit from the right, kHz, one's place, looks like a different layout, ugh. "0": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400", "2": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99bc1860001081e0400", "3": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99be1840001081e0400", "4": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99be00c0001081e0400", "5": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99b618c0001081e0400", "6": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99b618e0001081e0400", "7": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0800001081e0400", "8": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99be18e0001081e0400", "9": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99be18c0001081e0400", "ED": "4c435341b12a20000a001010101011001100000000000100010101000001081e0400", "E": "4c435341b12a20000a001010100011001100000000000100010001000001081e0400", "1": "4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0000001081e0400", } data = { # second digit from the right, hundreds place "O": "4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400", "0": "4c43534112502f260aa12af80ca48b400500000000000000a99ac186038de1840400", "-": "4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400", "A": "4c43534112502d760a0a5ef0a00a51a42b000000000004a0e8104004038de1840400", "2": "4c435341b12aa0000a000a000ab99b000b0000000000a99ac187a0000001081e0400", "3": "4c435341b12aa0000a000a000ab99b000b0000000000a99ae185a0000001081e0400", "4": "4c435341b12aa0000a000a000ab99b000b0000000000a99ae00da0000001081e0400", "5": "4c435341b12aa0000a000a000ab99b000b0000000000a99a618da0000001081e0400", "6": "4c435341b12aa0000a000a000ab99b000b0000000000a99a618fa0000001081e0400", "7": "4c435341b12aa0000a000a000ab99b000b0000000000a99aa081a0000001081e0400", "8": "4c435341b12aa0000a000a000ab99b000b0000000000a99ae18fa0000001081e0400", "9": "4c435341b12aa0000a000a000ab99b000b0000000000a99ae18da0000001081e0400", "ED": "4c435341b12a20000a001000101011001100000000000100010101000001081e0400", "E": "4c435341b12a20000a001000100011001100000000000100010001000001081e0400", "1": "4c435341b12aa0000a000a000ab99b000b0000000000a99aa001a0000001081e0400", "F": "4c43534112502f360a0c16f80ce00f40050000000000408e408ea18a038de1840400", "T": "4c43534112502b6b6aa01a1a5a4005e82d0000000000000004a0c08e038de1840400", "M": "4c43534112502f2b6ae804b01aa42ba8110000000000a24aa84a4004038de1840400", "R": "4c4353411250263b6a0c1650040a51e805000000000004a0c28e4004038de1840400", "S": "4c43534112502f2f5a0c16b810400500010000000000000061c0a000038de1840400", "N": "4c4353411250263f5a0a5e50040c17a81100000000000000a24ae810038de1840400", " ": "4c43534112502d7f5a00001c16e0a10a51000000000000000000c08e038de1840400", } segments = { "0": "ACDEGHTNXY", "O": "ACDEGH", "-": "UP", " ": "", "A": "TNPCD", "1": "CDXY", "2": "ACEGUPXY", "3": "ACDEUPXY", "4": "HCUPDXY", "5": "AHUPDE", "6": "AHGEDUPXY", "7": "ACDXY", "8": "ACDEGHUPXY", "9": "HACDEUPXY", "ED": "EXY", "E": "EY", "F": "AHGUP", "1A": "CDXY", "1NA": "CDX", "D": "ACDEMS", "T": "AMS", "M": "HGKNCD", "N": "HGKRCD", "R": "GHACUPR", "S": "AKPDE", "K": "HGUNR", } all_segments = set() for v in segments.values(): for c in v: all_segments.add(c) def splitbits(s): bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] b0 = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) bits_lit = set() bits_out = set() for i,b in enumerate(b0): if b == "1": bits_lit.add(i) else: bits_out.add(i) return (bits_lit, bits_out) data_bits = {} for k,v in data.iteritems(): data_bits[k] = splitbits(v) for c in all_segments: candidate_bits = set( range(len(data["0"])/2*8) ) #candidate_bits = set( range(32,200) ) for digit, bitsets in data_bits.iteritems(): seglit = (-1 != segments[digit].find(c)) # is this segment lit? if seglit: candidate_bits -= bitsets[1] else: candidate_bits -= bitsets[0] print "Segment: %s, candidates: %s" % (c, str(candidate_bits)) def print_line(s): bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] for offset in range(0,4): segmap = "TSKAXGUHxDPCERMN" segs = unpack_segments(bytes, 8*(9+2*offset), segmap) print segs print draw_digit(segs) print print "SHIFT" print for offset in range(0,1): segmap = "EKMNRDPCxGUHTxxA" segs = unpack_segments(bytes, 8*(26+2*offset), segmap) print "kHz: " + segs print draw_digit(segs) for offset in range(0,1): segmap = "ERMNRDPCxGUHTSKA" segs = unpack_segments(bytes, 8*(24+2*offset), segmap) print "100: " + segs print draw_digit(segs) for offset in range(0,1): segmap = "ERMNRDPCxGUHTSKA" segs = unpack_segments(bytes, 8*(22+2*offset), segmap) print "100: " + segs print draw_digit(segs) def unpack_segments(s, offset, segmap): byte_offset = offset/8 bytes = s[byte_offset:(byte_offset+2)] mask = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) print mask print segmap retval = "".join([ s if b == "1" else "" for (s,b) in zip(segmap, mask)]) return retval #print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") #print_line("4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2000 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2080 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") print_line("4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400") print_line("4c43534112502d760a0a5ee0a00a51a42b000000000004a0e8104004038de1840400") print_line("4c43534112502d360a0c161a40400500010000000000a99aa99ae18e038de1840400") print_line("4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400") print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0000001081e0400") #print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa00 1e1840001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa99 be1840001081e0400") #for k,v in segments.iteritems(): # print "===== %s =====" % k # print draw_digit(v) # print <file_sep>#!/usr/bin/env python import sys def byteses(l): l = l.replace(" ", "") a = [ int(l[i:i+2], 16) for i in range(0, len(l)-1, 2) ] return a l0 = sys.stdin.readline() # prime it h0 = byteses(l0) for l in sys.stdin: h = byteses(l) def cof_delta(a,b): if a == b: return " " return " %3d" % (a-b) def cof_sign(a,b): if a == b: return " " if a < b: return "d" if a > b: return "U" def cof_mask(a,b): if a == b: return ". " return "X " cof = cof_sign toprint = "".join([ cof(a,b) for (a,b) in zip(h0,h)]) print toprint l0 = l h0 = h <file_sep>#!/usr/bin/env python import sys def byteses(l): l = l.replace(" ", "") a = [ int(l[i:i+2], 16) for i in range(0, len(l)-1, 2) ] return a l0 = sys.stdin.readline() # prime it h0 = byteses(l0) #h0 = h0[13:17] b0 = "".join([ '{:08b}'.format(i)[::-1] for i in h0 ]) def cof(x,y): if x == y: return " " if x < y: return "U" if x > y: return "d" #print "".join([ cof(x,y) for (x,y) in zip(b0, b0) ]) #+ "\t" + "".join(["%02x" % i for i in h0]) toggles = [0] * len(b0) netchange = [0] * len(b0) for l in sys.stdin: h = byteses(l) #h = h[13:17] b = "".join([ '{:08b}'.format(i)[::-1] for i in h ]) darr = [ cof(x,y) for (x,y) in zip(b0, b) ] #print "".join(darr) #+ "\t" + "".join(["%02x" % i for i in h]) for i in range(0, len(b0)): if darr[i] != " ": toggles[i] += 1 if darr[i] == "U": netchange[i] += 1 else: netchange[i] -= 1 b0 = b print str(toggles) print str(netchange) <file_sep>#!/usr/bin/env python # Emulate the radio side of the connection, to poke/prod at the head # unit. import serial ser = serial.Serial('/dev/tty.usbserial-A4006Dyk', 38400, timeout=1) curline = "" ser.write("AL~READY") disp = "4c435341a12aa000060000100ad81ec81f000000cdbda99aa99be18c0001e1040400" disp = "".join([ chr(int(disp[i:i+2], 16)) for i in range(0, len(disp)-1, 2) ]) while True: x = ser.read(1) if len(x) > 0: curline += x[0] if -1 != curline.find("AL~READY"): print "GOT AL~READY." n = curline.find("AL~READY") curline = curline[n+8+1:] if 1 <= curline.find("LCSA"): print "SEEK to LCSA: %d" % curline.find("LCSA") n = curline.find("LCSA") ser.write(curline[0:n]) curline = curline[n:] while len(curline) >= 34: print "line: " + "".join([ "%02x" % ord(c) for c in curline ]) ser.write(curline[0:34]) disp = curline[0:34] curline = curline[34:] ser.write(disp) ser.close() <file_sep>#!/usr/bin/env python keys = [ "MF", "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "ENT", "FUNC", "RIT", "KEY", "MODE", "V/M", "M/KHz", "RF", "UP", "DOWN" ] keycaps = [ "SWDS000001000100", "SWDS400000000100", "SWDS200000000100", "SWDS100000000100", "SWDS080000000100", "SWDS040000000100", "SWDS020000000100", "SWDS010000000100", "SWDS008000000100", "SWDS004000000100", "SWDS002000000100", "SWDS800000000100", "SWDS001000000100", "SWDS000008000100", "SWDS000004000100", "SWDS000002000100", "SWDS000080000100", "SWDS000040000100", "SWDS000020000100", "SWDS000010000100", "SWDS000000800100", "SWDS000000400100", ] def bytes_of(s): bytes = [ ord(c) for c in s ] return bytes def newlit(s): keyblank = "SWDS000000000100" blank_bytes = bytes_of(keyblank) s_bytes = bytes_of(s) diffs = [ x^y for (x,y) in zip(blank_bytes, s_bytes) ] bits = [] for i in range(len(diffs)): for j in range(8): if 0 != (diffs[i] & (1<<j)): bits.append(8*i+j) return bits if len(keys) != len(keycaps): print "Mismatch in lens: %d vs %d" % (len(keys), len(keycaps)) for keyname,s in zip(keys,keycaps): bits = newlit(s) print " '%s': %s," % (keyname, str(bits[0])) <file_sep>#!/usr/bin/env python # Emulate the head side of the connection, to poke/prod at the radio import serial import os import os.path import time from decode_head import * ser = serial.Serial('/dev/tty.usbserial-A700eEqF', 38400, timeout=1) curline = "" while True: x = ser.readline() print x if x.startswith("SWDS"): print " KEYS DOWN: " + str(decode_SWDS(x)) ser.write(x) if os.path.exists("/tmp/buttons"): f = file("/tmp/buttons") for l in f: l = l.strip() try: bdown = encode_SWDS(l) ser.write(bdown) time.sleep(0.01) bup = encode_SWDS(None) ser.write(bup) time.sleep(0.01) except Exception, e: print "Got exception: %s" + str(e) f.close() os.remove("/tmp/buttons") ser.close() <file_sep>#!/usr/bin/env python # Emulate the head side of the connection, to poke/prod at the radio import serial from decode_head import * ser = serial.Serial('/dev/tty.usbserial-A700eEqF', 38400, timeout=1) curline = "" while True: x = ser.readline() print x if x.startswith("SWDS"): print "KEYS DOWN: " + str(decode_SWDS(x)) ser.write(x) ser.close() <file_sep>#!/usr/bin/env python # Emulate the radio side of the connection, to poke/prod at the head # unit. import serial ser = serial.Serial('/dev/tty.usbserial-A4006Dyk', 38400) from decode_screen import * fdisp = FrequencyDisplay() mdisp = ModeDisplay() rfdisp = RFPowerDisplay() agcdisp = AGCDisplay() smeterdisp = SMeterDisplay() backlightdisp = BacklightDisplay() miscdisp = MiscDisplay() def intWithCommas(x): if type(x) not in [type(0), type(0L)]: raise TypeError("Parameter must be an integer.") if x < 0: return '-' + intWithCommas(-x) result = '' while x >= 1000: x, r = divmod(x, 1000) result = ",%03d%s" % (r, result) return "%d%s" % (x, result) def print_state(sin): if not sin.startswith("LCSA"): return s = [ ord(c) for c in sin ] try: mode = mdisp.decode(s) rxstate = "%s RF:%+2d %s" % (agcdisp.decode(s), rfdisp.decode(s), smeterdisp.decode_string(s)) line = "" # "%2d>" % backlightdisp.decode(s) # if you care about the backlight intensity. if fdisp.is_freq(s): line += "[%s] f = %s %s" % (mode, intWithCommas(fdisp.freq(s)), rxstate) else: line += "[%s] > %s < %s" % (mode, fdisp.decode(s), rxstate) line += str(sorted(miscdisp.decode(s))) print line except Exception, e: print print "Caught exception: " + str(e) print print "Input %s" % (s) print curline = "" while True: x = ser.read(1) curline += x[0] if -1 != curline.find("AL~READY"): print "GOT AL~READY." n = curline.find("AL~READY") curline = curline[n+8+1:] if 1 <= curline.find("LCSA"): print "SEEK to LCSA: %d" % curline.find("LCSA") print n = curline.find("LCSA") ser.write(curline[0:n]) curline = curline[n:] while len(curline) >= 34: #print "line: " + "".join([ "%02x" % ord(c) for c in curline ]) print_state(curline[0:34]) ser.write(curline[0:34]) curline = curline[34:] ser.close() <file_sep>#!/usr/bin/env python def draw_digit(segments): digit = """ vfo VVV AA BB busy:SSSS key:KKKK nb:NN nar:WW star:TTT func:FFFF t/r led: LLL tone:EEE tune:UUU split:III """ allsegments = set() for c in digit: allsegments.add(c) w = digit for c in allsegments: if c == "\n" or c == " " or c == ":" or c.islower(): continue if c in segments: w = w.replace(c, "#") else: w = w.replace(c, ".") return w data_misc = { "vfoabusykey": "4c435341b80aa00006000bd00eb99a080b0000000000e18ce18d618ca181a84a0408", "vfoasqlkey": "4c435341b80aa00006000ad00eb99a080b0000000000e18ce18d618ca181a84a0400", "vfobsqlkey": "4c435341ea51a0000a000ad00eb99b080b0000000000a99aa99b618ea081038d0400", "vfobsqlnb": "4c435341b80aa0000a000ac00eb99a080b0000000000e18ce18d718ca181a84a0400", "vfobsqlnar": "<KEY>a99ab99b618ea181a84a0400", "vfobnostar": "4c435341fa50a0000a000ac00eb99a080b0000000000a99aa99b618ea080038c0400", "func": "4c435341fa50a00000100ac00eb99a080b0000000000a99aa99b618ea081038c0400", "vfobtone": "4c435341a12ba0000a000ad00eb99b080b0000000000a99ba99b618e0001e1040400", "vfobfmnotone": "4c435341a12ba0000a000ad00eb99b080b0000000000a99aa99b618e0001e1040400", "vfobtune": "4c435341000130000a000ad00eb99b080b0000000000a99aa99b618e000100000400", "vfobsplit": "4c435341a12be0000a000ad00eb99b080b0000000000a99aa99b618e0001e1040400", "foo": "4c4353410251260b65018ee80ca81a40050000000000408e408ea18a138df1850a00", "foo2": "4c435341a80b2fdf550000c81e781ce81f0000000000618cd187618ca181b84b0a00", "foo3": "<KEY>aa99a781ce81f0000000000e00cc187618ca181b84b0a00", } data = data_misc segments = { "foo": "AT", "foo2": "ATW", "foo3": "AT", "vfoabusykey": "VASKT", "vfoasqlkey" : "VAKT", "vfobsqlkey": "VBKT", "vfobsqlnb": "BVNT", "vfobsqlnar": "VBWT", "vfobnostar": "VB", "func": "F", "vfobtone": "VBTE", "vfobfmnotone": "VBT", "vfobtune": "VBTU", "vfobsplit": "VBTI", } all_segments = set() for v in segments.values(): for c in v: all_segments.add(c) def splitbits(s): bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] b0 = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) bits_lit = set() bits_out = set() for i,b in enumerate(b0): if b == "1": bits_lit.add(i) else: bits_out.add(i) return (bits_lit, bits_out) data_bits = {} for k,v in data.iteritems(): data_bits[k] = splitbits(v) decode = {} # bitno => array of segments for c in all_segments: candidate_bits = set( range(len(data.values()[0])/2*8) ) #candidate_bits = set( range(32,200) ) for digit, bitsets in data_bits.iteritems(): seglit = (-1 != segments[digit].find(c)) # is this segment lit? if seglit: candidate_bits -= bitsets[1] else: candidate_bits -= bitsets[0] print "Segment: %s, candidates: %s" % (c, str(candidate_bits)) for b in candidate_bits: if not b in decode: decode[b] = [] decode[b].append(c) print str(decode) for k,segs in segments.iteritems(): print k + ": " + segs print draw_digit(segs) def print_line(s): segmap = { 65: ['V'], 66: ['A'], 67: ['B'], 196: ['W'], 267: ['S'], 76: ['F'], 80: ['S'], 212: ['N'], 54: ['I'], 184: ['E'], 52: ['U'] } bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] segs = "" for b, lights in segmap.iteritems(): byte_offset = b/8 bit_offset = (b%8) candidate = bytes[byte_offset] if candidate & 1<<bit_offset: for l in lights: if l not in segs: segs += l print segs print draw_digit(segs) for k,l in data.iteritems(): print k print_line(l) def unpack_segments(s, offset, segmap): byte_offset = offset/8 bytes = s[byte_offset:(byte_offset+2)] mask = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) print mask print segmap retval = "".join([ s if b == "1" else "" for (s,b) in zip(segmap, mask)]) return retval #print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") #print_line("4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2000 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2080 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") print_line("4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400") print_line("4c43534112502d760a0a5ee0a00a51a42b000000000004a0e8104004038de1840400") print_line("4c43534112502d360a0c161a40400500010000000000a99aa99ae18e038de1840400") print_line("4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400") print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0000001081e0400") #print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa00 1e1840001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa99 be1840001081e0400") #for k,v in segments.iteritems(): # print "===== %s =====" % k # print draw_digit(v) # print <file_sep>#!/usr/bin/env python # Pulling apart the bits for the first digit of the frequency display, # the others look to follow a very similar pattern. # Sixteen segment displays # YY <-- arrow # AAAAAAAAA # HK M NC # H K M N C # H K M N C # UUU PPP # G T S R D # G T S R D # GT S RD # EEEEEEEEE XX <-- decimal def draw_digit(segments): digit = """ 2222>111>000>333 sSS lowLLL agc sOOO fFFF """ allsegments = set() for c in digit: allsegments.add(c) w = digit for c in allsegments: if c == "\n" or c == " " or c.islower(): continue if c in segments: w = w.replace(c, "#") else: w = w.replace(c, ".") return w data_rf_amp = { "-20": "4c435341ea50a0000a000ad00fb99b080b0000000000a99aa99b618ea081038d0400", "-20b": "4c435341a12a20000a001010100010001100000000000100010001000001e1040400", "-20c": "4c435341a12aa0000a000a100a100a000b0000000000a99aa001a0000001e1040400", "-20d": "4c435341b80aa00006000ad00eb99a080b0000000000a000e18d618ca181a84a0400", "-20e": "4c435341b12aa00006000ad00eb99a080b0000000000a99ac187a0800000081e0400", "-10": "4c435341ea51a0000a000ad00eb99b080b0000000000a99aa99b618ea081038d0400", "0": "4c435341ea51a0000a000ad00eb99b080b0000000000a99aa99b618ea081138d0400", "+10": "4c435341ea51a0000a000ad00eb99b080b0000000000a99aa99b618eb081138d0400", "-20lo": "4c435341ea50a0000a000ad00eb99b080b0000000000a99aa99b618ea081038d0400", "-20hi-agcs": "4c435341fa50a0000a000ac00eb99a080b0000000000a99aa99b618ea081038c0400", "-20hi-agcf": "4c435341ea50a0000a000ac00eb99a080b0000000000a99aa99b618ea081038d0400", } data = data_rf_amp segments = { "-20": "2SLF", "-20b": "2", "-20c": "2", "-20d": "2", "-20e": "2O", "-20lo": "2LF", "-10": "21SLF", "0": "210LF", "+10": "2103LF", "-20hi-agcs": "2O", "-20hi-agcf": "2F" } all_segments = set() for v in segments.values(): for c in v: all_segments.add(c) def splitbits(s): bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] b0 = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) bits_lit = set() bits_out = set() for i,b in enumerate(b0): if b == "1": bits_lit.add(i) else: bits_out.add(i) return (bits_lit, bits_out) data_bits = {} for k,v in data.iteritems(): data_bits[k] = splitbits(v) decode = {} # bitno => array of segments for c in all_segments: candidate_bits = set( range(len(data.values()[0])/2*8) ) #candidate_bits = set( range(32,200) ) for digit, bitsets in data_bits.iteritems(): seglit = (-1 != segments[digit].find(c)) # is this segment lit? if seglit: candidate_bits -= bitsets[1] else: candidate_bits -= bitsets[0] print "Segment: %s, candidates: %s" % (c, str(candidate_bits)) for b in candidate_bits: if not b in decode: decode[b] = [] decode[b].append(c) print str(decode) for k,segs in segments.iteritems(): print k + ": " + segs print draw_digit(segs) def print_line(s): segmap = {128: ['2'], 129: ['2'], 2: ['2'], 3: ['2'], 214: ['2'], 6: ['2'], 8: ['2'], 9: ['2'], 258: ['2'], 14: ['2'], 16: ['2'], 17: ['2'], 131: ['2'], 20: ['2'], 22: ['2'], 24: ['2'], 239: ['2'], 30: ['2'], 231: ['2'], 33: ['2'], 191: ['2'], 35: ['2'], 36: ['O'], 37: ['2'], 38: ['2'], 39: ['2'], 40: ['1'], 44: ['2'], 240: ['2'], 46: ['2'], 176: ['2'], 179: ['2'], 53: ['2'], 55: ['2'], 116: ['2'], 187: ['2'], 188: ['2'], 232: ['2'], 241: ['2'], 181: ['2'], 192: ['2'], 65: ['2'], 67: ['2'], 197: ['2'], 199: ['2'], 200: ['2'], 201: ['2'], 183: ['2'], 204: ['2'], 207: ['2'], 208: ['2'], 81: ['2'], 83: ['2'], 251: ['2'], 213: ['2'], 203: ['2'], 185: ['2'], 217: ['2'], 218: ['2'], 219: ['2'], 92: ['L'], 94: ['2'], 95: ['2'], 97: ['2'], 98: ['2'], 99: ['2'], 228: ['3'], 229: ['2'], 195: ['2'], 223: ['2'], 104: ['2'], 107: ['2'], 108: ['2'], 109: ['2'], 111: ['2'], 112: ['L'], 113: ['2'], 115: ['2'], 244: ['0'], 119: ['2'], 248: ['F'], 250: ['2'], 123: ['2'], 255: ['2']} bytes = [ int(s[i:i+2], 16) for i in range(0, len(s)-1, 2) ] segs = "" for b, lights in segmap.iteritems(): byte_offset = b/8 bit_offset = (b%8) candidate = bytes[byte_offset] if candidate & 1<<bit_offset: for l in lights: if l not in segs: segs += l print segs print draw_digit(segs) for k,l in data.iteritems(): print k print_line(l) def unpack_segments(s, offset, segmap): byte_offset = offset/8 bytes = s[byte_offset:(byte_offset+2)] mask = "".join(['{:08b}'.format(i)[::-1] for i in bytes ]) print mask print segmap retval = "".join([ s if b == "1" else "" for (s,b) in zip(segmap, mask)]) return retval #print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") #print_line("4c435341b12a20800a0000f81eb99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2000 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341 b12a2080 0a000a100ab99ba99b0000000000a99aa99ba99a0001081e0400") print_line("4c43534112502f2b6ae804a01aa42ba8110000000000a24aa84a4004038de1840400") print_line("4c43534112502d760a0a5ee0a00a51a42b000000000004a0e8104004038de1840400") print_line("4c43534112502d360a0c161a40400500010000000000a99aa99ae18e038de1840400") print_line("4c435341125026360ae80c118e0a5b0a5b0000000000a24a4004010a038de1840400") print_line("4c43534112502b660ae814f0a0e81506810000000000408ea18a4004038de1840400") print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba0000001081e0400") #print_line("4c435341b12aa0000a000a100ab99b000b0000000000a99aa99ba99a0001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa00 1e1840001081e0400") #print_line("4c435341b12aa0000a000a000ab99b000b0000000000a99aa99 be1840001081e0400") #for k,v in segments.iteritems(): # print "===== %s =====" % k # print draw_digit(v) # print
88545d301220b32defd1b3423a2cad7b7be8650e
[ "Python" ]
25
Python
jbm9/dxsr8_serial
bb89f4df63c782ceabce35e2978ee7de55beee4b
4407245447d4b2e99a8ca8d1d895cc635f0c1f59
refs/heads/master
<file_sep>package galekop.be.RC; import java.io.IOException; import controller.ManagerWindowController; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class App extends Application { private Stage primaryStage; private BorderPane rootLayout; public static void main( String[] args ) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/ManagerView.fxml")); AnchorPane page = (AnchorPane)loader.load(); Scene scene = new Scene(page); primaryStage.setScene(scene); primaryStage.setTitle("Remote Control Manager"); primaryStage.show(); ManagerWindowController controller = loader.getController(); controller.setApp(this); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package controller; import com.jfoenix.controls.JFXButton; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.stage.Stage; import model.Remote; public class QuestionDialogController { private Remote remoteToAlter; private boolean okClicked = false; @FXML private Label labelRemove; @FXML private JFXButton ButtonOK; @FXML private JFXButton ButtonCancel; public void setRemote(Remote remote) { this.remoteToAlter = remote; labelRemove.setText("Are you sure"); } public boolean isOkClicked() { return okClicked; } @FXML void CancelDeleteRemote(ActionEvent event) { Stage stage = (Stage) ButtonOK.getScene().getWindow(); stage.close(); } @FXML void OKDeleteRemote(ActionEvent event) { Stage stage = (Stage) ButtonOK.getScene().getWindow(); okClicked = true; stage.close(); } } <file_sep>package model; import junit.framework.TestCase; public class GateTest extends TestCase { private Gate gate = new Gate(); protected void setUp() throws Exception { super.setUp(); } public void testGateHandleRequestTrue() { gate.setFrequency(100.00); assertEquals(true, gate.handleRequest(100.00, true)); } public void testGateHandleRequesFalseFrequency() { gate.setFrequency(100.00); assertFalse(gate.handleRequest(200.00, true)); } public void testGateHandleRequesFalseIsActive() { gate.setFrequency(100.00); assertFalse(gate.handleRequest(100.00, false)); } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>galekop.be</groupId> <artifactId>RC</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>RC</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Added to get the hibernate dependencies downloaded automatically --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.12.Final</version> </dependency> <!--hibernate entity manager--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.2.12.Final</version> </dependency> <!-- Added to get the MySQL dependencies downloaded automatically --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.10.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.10.0</version> </dependency> <!-- Failsafe plugin --> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.20.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.jfoenix</groupId> <artifactId>jfoenix</artifactId> <version>9.0.3</version> </dependency> <dependency> <groupId>com.jfoenix</groupId> <artifactId>jfoenix</artifactId> <version>8.0.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>de.jensd</groupId> <artifactId>fontawesomefx</artifactId> <version>8.9</version> </dependency> </dependencies> </project>
f4085e31c8613f7552d02e3b4c04c64382a7d2d2
[ "Java", "Maven POM" ]
4
Java
MrGMan133/RC
d68f1404fa10808169c5c99f3a6b7419214afb32
0956874ebd82d927695f307a216f6bce35b9cf4e
refs/heads/master
<repo_name>ichan8493/EternalDarkness<file_sep>/README.md # EternalDarkness <h2>Requirements</h2> <a href="https://www.python.org/downloads/">Python<a/><br> <a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame">PyGame<a/><br> <a href="https://www.youtube.com/watch?v=_GikMdhAhv0">How To Download<a/><br> <img src="https://github.com/ichan8493/EternalDarkness/blob/master/game%20pic%201.PNG"> <img src="https://github.com/ichan8493/EternalDarkness/blob/master/game%20pic%202.PNG"> <img src="https://github.com/ichan8493/EternalDarkness/blob/master/game%20pic%203.PNG"> <img src="https://github.com/ichan8493/EternalDarkness/blob/master/game%20pic%204.PNG"> <p> Eternal Darkness is an RPG shooter with a top-down view. Using WASD keys to move and space to shoot. The first wave you must push all the Zombies into the containment unit. However, the Zombies escape from the unit. The second wave you must shoot the Zombies that have escaped from the containment unit and prevent them from fleeing the facility and infecting more people. In the third wave you have to kill the source Zombies. </p> <file_sep>/Eternal Darkness.py from gamelib import * game=Game(1280,720, "Eternal Darkness") bk=Image("background.png",game) game.setBackground(bk) bk.resizeTo(1280,720) #TITLE ed = Image('Eternal-Darkness.png', game) ed.y-=100 #HOW TO PLAY htp = Image("How-To-Play.png", game) key=Image("kb.png",game) #STORY story = Image("Story.png", game) story.y+=100 ts = Image("TS.png", game) ts.y+=100 #PLAY play = Image("Play.png", game) play.y+=200 #Hero hero=Animation("herorun.png",12,game,487/12,40) hero.stop() heror=Animation("herorunright.png",12,game,487/12,40) heror.stop() heros=Animation("hero-shoot.png",10,game,471/10,48) heros.stop() herosr=Animation("hero-shootr.png",10,game,471/10,48) herosr.stop() #CONTAINMENT ZONE cont=Image("containement.png",game) cont.moveTo(1061,168) #Zombies zombies=[] for index in range(50): zombies.append(Animation("zimbie-walk.png",3,game,80/3,46)) x=randint(-10,1290) y=randint(-10,730) zombies[index].moveTo(x,y) zombiew1=[] for index in range(15): zombiew1.append(Animation("zimbie-walk.png",3,game,80/3,46)) x=randint(-10,1290) y=randint(-10,730) zombiew1[index].moveTo(x,y) minions=[] for index in range(5): minions.append(Animation("zimbie-walk.png",3,game,80/3,46)) x=randint(-10,1290) y=randint(-10,730) minions[index].moveTo(x,y) minions2=[] for index in range(6): minions2.append(Animation("zimbie-walk.png",3,game,80/3,46)) x=randint(-10,1290) y=randint(-10,730) minions2[index].moveTo(x,y) minions3=[] for index in range(7): minions3.append(Animation("zimbie-walk.png",3,game,80/3,46)) x=randint(-10,1290) y=randint(-10,730) minions3[index].moveTo(x,y) minions4=[] for index in range(8): minions4.append(Animation("zimbie-walk.png",3,game,80/3,46)) x=randint(-10,1290) y=randint(-10,730) minions4[index].moveTo(x,y) #Bullet bullet=Image("bullet.png",game) bullet.resizeBy(-90) bullet.visible=False bulletl=Image("bulletl.png",game) bulletl.resizeBy(-90) bulletl.visible=False #BOSS boss=Animation("boss.png",9,game,561/9,66) boss.stop() boss.resizeBy(150) bossr=Animation("bossr.png",9,game,561/9,66) bossr.stop() bossr.resizeBy(150) slapr=Animation("slapr.png",6,game,384/6,58) slapr.stop() slapr.resizeBy(150) slapl=Animation("slapl.png",6,game,378/6,59) slapl.stop() slapl.resizeBy(150) plasma=Animation("plasmaball2.png",10,game,640/10,64) #Sounds gun=Sound("Gun.wav",1) ZombieDie=Sound("ZombieDie.wav",2) #TITLE SCREEN while not game.over: game.processInput() bk.draw() ed.draw() htp.draw() story.draw() play.draw() key.draw() ts.draw() key.visible=False ts.visible= False if play.collidedWith(mouse)and mouse.LeftClick: game.over=True if htp.collidedWith(mouse,"rectangle"): key.visible=True if story.collidedWith(mouse,"rectangle"): ts.visible=True game.update(30) game.over=False #LEVEL 1 GAME LOOP x = hero.x y = hero.y status = "walkleft" zombiesContained=0 while not game.over: game.processInput() bk.draw() cont.draw() for index in range(50): zombies[index].moveTowards(hero,2.5) if zombies[index].collidedWith(cont): zombies[index].moveTo(1061,168) zombiesContained+=1 zombies[index].visible=False if zombies[index].collidedWith(hero): hero.health -=5 if zombiesContained>=50: game.over=True print(zombiesContained) #Hero Controls if status == "walkright": heror.draw() if status == "walkleft" : hero.draw() if keys.Pressed[K_a]: hero.moveTo(x,y) hero.nextFrame() hero.visible=True x -=4 status = "walkleft" elif keys.Pressed[K_d]: heror.moveTo(x,y) heror.nextFrame() hero.moveTo(heror.x,heror.y) hero.visible=False x +=4 status = "walkright" if keys.Pressed[K_w]: hero.moveTo(x,y) hero.nextFrame() hero.visible=True y -=4 status = "walkleft" elif keys.Pressed[K_s]: heror.moveTo(x,y) heror.nextFrame() hero.moveTo(heror.x,heror.y) hero.visible=False y +=4 status = "walkright" if hero.health<=0: game.over = True game.drawText("Health: " + str(hero.health),hero.x, hero.y + 50) game.update(30) game.over=False #LEVEL2 GAME LOOP zombiesw1=0 x = hero.x y = hero.y status = "walkleft" while not game.over: game.processInput() bk.draw() cont.draw() bulletl.move() bullet.move() #Hero Controls if keys.Pressed[K_a]: hero.moveTo(x,y) hero.nextFrame() hero.visible=True x -=4 status = "walkleft" elif keys.Pressed[K_d]: heror.moveTo(x,y) heror.nextFrame() hero.moveTo(heror.x,heror.y) hero.visible=False x +=4 status = "walkright" else: if status == "walkleft" and keys.Pressed[K_SPACE]: heros.moveTo(x,y) heros.nextFrame() bulletl.moveTo(x, y) bulletl.setSpeed(24,90) bulletl.visible = True gun.play() elif status == "walkleft" : hero.draw() if status == "walkright" and keys.Pressed[K_SPACE]: herosr.moveTo(x,y) herosr.nextFrame() bullet.moveTo(x,y) bullet.setSpeed(24,270) bullet.visible=True gun.play() elif status == "walkright": heror.draw() if keys.Pressed[K_w]: hero.moveTo(x,y) hero.nextFrame() hero.visible=True y -=4 status = "walkleft" elif keys.Pressed[K_s]: heror.moveTo(x,y) heror.nextFrame() hero.moveTo(heror.x,heror.y) hero.visible=False y +=4 status = "walkright" #Zombie Control for index in range(15): zombiew1[index].moveTowards(hero,2) if zombiew1[index].collidedWith(hero): hero.health -=5 if bullet.collidedWith(zombiew1[index]) or bulletl.collidedWith(zombiew1[index]): zombiew1[index].health-=100 bullet.visible=False bulletl.visible=False zombiesw1+=1 ZombieDie.play() if zombiew1[index].health<=0: zombiew1[index].visible=False if zombiesw1>=15: game.over=True print(zombiesw1) if hero.health<=0: game.over = True game.drawText("Health: " + str(hero.health),hero.x, hero.y + 50) game.update(30) #LEVEL 3 game.over=False x = hero.x y = hero.y status = "walkleft" invincible = False miniondead = 0 miniondead2 = 0 miniondead3 = 0 miniondead4 = 0 hero.health=150 while not game.over: game.processInput() bk.draw() bulletl.move() bullet.move() plasma.forward(8) plasma.move() boss.draw() if (bullet.collidedWith(boss) or bulletl.collidedWith(boss)) and not invincible: boss.health-=5 bullet.visible=False bulletl.visible=False if boss.health<=0: game.over=True game.drawText("Boss Health: " + str(boss.health),boss.x,boss.y) if boss.health<=80 and boss.health > 60: if miniondead == 0: invincible = True for index in range(5): minions[index].moveTowards(hero,2) if minions[index].collidedWith(hero): hero.health -=5 if bullet.collidedWith( minions[index]) or bulletl.collidedWith( minions[index]): minions[index].visible=False bullet.visible=False bulletl.visible=False miniondead+=1 ZombieDie.play() if miniondead >= 5: invincible = False if boss.health<=60 and boss.health > 40: if miniondead2 == 0: invincible = True for index in range(6): minions2[index].moveTowards(hero,2) if minions2[index].collidedWith(hero): hero.health -=5 if bullet.collidedWith( minions2[index]) or bulletl.collidedWith( minions2[index]): minions2[index].visible=False bullet.visible=False bulletl.visible=False miniondead2+=1 ZombieDie.play() if miniondead2 >= 6: invincible = False if boss.health<=40 and boss.health > 20: if miniondead3 == 0: invincible = True for index in range(7): minions3[index].moveTowards(hero,2) if minions3[index].collidedWith(hero): hero.health -=5 if bullet.collidedWith( minions3[index]) or bulletl.collidedWith( minions3[index]): minions3[index].visible=False bullet.visible=False bulletl.visible=False miniondead3 += 1 ZombieDie.play() if miniondead3 >= 7: invincible = False if boss.health<=20 and boss.health > 0: if miniondead4 == 0: invincible = True for index in range(8): minions4[index].moveTowards(hero,2) if minions4[index].collidedWith(hero): hero.health -=5 if bullet.collidedWith( minions4[index]) or bulletl.collidedWith( minions4[index]): minions4[index].visible=False bullet.visible=False bulletl.visible=False miniondead4 += 1 ZombieDie.play() if miniondead4 >= 8: invincible = False if plasma.collidedWith(hero) or plasma.collidedWith(heror): hero.health-=10 if plasma.isOffScreen() or plasma.collidedWith(hero) or plasma.collidedWith(heror): plasma.moveTo( boss.x, boss.y ) a = boss.angleTo(hero) plasma.rotateTo(a) #Hero Controls if keys.Pressed[K_a]: hero.moveTo(x,y) hero.nextFrame() hero.visible=True x -=4 status = "walkleft" elif keys.Pressed[K_d]: heror.moveTo(x,y) heror.nextFrame() hero.moveTo(heror.x,heror.y) hero.visible=False x +=4 status = "walkright" else: if status == "walkleft" and keys.Pressed[K_SPACE]: heros.moveTo(x,y) heros.nextFrame() bulletl.moveTo(x, y) bulletl.setSpeed(24,90) bulletl.visible = True gun.play() elif status == "walkleft" : hero.draw() if status == "walkright" and keys.Pressed[K_SPACE]: herosr.moveTo(x,y) herosr.nextFrame() bullet.moveTo(x,y) bullet.setSpeed(24,270) bullet.visible=True gun.play() elif status == "walkright": heror.draw() if keys.Pressed[K_w]: hero.moveTo(x,y) hero.nextFrame() hero.visible=True y -=4 status = "walkleft" elif keys.Pressed[K_s]: heror.moveTo(x,y) heror.nextFrame() hero.moveTo(heror.x,heror.y) hero.visible=False y +=4 status = "walkright" game.drawText("Health: " + str(hero.health),hero.x, hero.y + 50) if hero.health<=0: game.over=True game.update(30) game.quit()
ab6c379a57695dd7cc935b383e7bb875992b01c4
[ "Markdown", "Python" ]
2
Markdown
ichan8493/EternalDarkness
b54b42fc73af69533afae4bad5e623bd1514a11b
0e66a1569502170f54b527f5b16bdc58d188655d
refs/heads/master
<file_sep># Test Broccolli CO. ## How to use 1. Download the example [or clone the repo] 2. Install it and run: ```bash npm install npm run start ``` ## Why does this repository exist? This is the result of a code challenge that involved the following technologies: ReactJS, UI material, Flexbox and Rest API. The structure is simple, but it follows good practices from the first commit such as the use of javascript linter (ESLint) and the use of propTypes, it also shows a clear separation and definition of components. See the screenshots at the end of this document to see the results. ## Code Challenge Content *Broccoli & Co., an upcoming online service company, would like to let people to "Request an invitation" on their website.* ### The functionality Create a simple yet clean homepage for them that allow users to enter their name and email to receive email invitations. ### Visual Requirements - The UI should occupy the full height of the screen. - Shows a fixed header that is always on top of the window and a footer that is always on the bottom of the window (assuming a reasonable window height). - The page content is sandwiched in the middle, containing just a heading, a small piece of text and a button to request an invite. - The solution must be mobile friendly (users won't need to pinch and zoom on their mobile devices). ### UI Behaviour / Validation - When the Request Invite button is clicked, a popup shows containing the Full name, Email and Confirm Email input fields. - The user needs to fill in all three fields to request an invite. Full name needs to be at least 3 characters long, Email needs to be in validation email format and Confirm Email needs to match Email. - If the user clicks Send and one or more fields do not validate properly, the app should not contact the backend but instead provide appropriate feedback to the user (use your judgement on what this UX should be). - If the user clicks Send and all fields validate properly, the app should send the request to the backend server (see specs below) and inform the user that the request is being sent. - If the server returns 200 OK, it should switch to another popup, indicating that everything went through OK. This popup can be dismissed and will simply close - revealing the homepage again. - The server may return 400 Bad Request, in which case the app should simply display the error message from the server. - The Send button can be clicked again to re-attempt the submission. ### Backend API - The API endpoint is available on https://l94wc2001h.execute-api.ap-southeast-2.amazonaws.com/prod/fake-auth - The request is in the form of a JSON payload { "name": "XXX", "email": "XXX" } - The request must use the POST method. ## Screenshots ![Landing](/screenshots/1.png?raw=true) ![Modal to request](/screenshots/2.png?raw=true) ![Modal answer](/screenshots/3.png?raw=true) ## Template based on create-react-app [Create React App](https://github.com/facebookincubator/create-react-app) with no build configuration. <file_sep>import React from "react"; import PropTypes from "prop-types"; import Header from "./components/Header"; import Content from "./components/Content"; import Footer from "./components/Footer"; import { withStyles } from "@material-ui/core/styles"; import withRoot from "../withRoot"; import banner from "../resources/banner-bg.jpg"; const styles = { root: { display: "flex", minHeight: "100vh", flexDirection: "column", background: `url(${banner}) center`, backgroundSize: "cover" } }; class Index extends React.Component { render() { const { classes } = this.props; return ( <div className={classes.root}> <Header /> <Content /> <Footer /> </div> ); } } Index.propTypes = { classes: PropTypes.object.isRequired }; export default withRoot(withStyles(styles)(Index)); <file_sep>function validateEmail(email) { return !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email); } export default function(values) { const errors = {}; const requiredFields = ["name", "email", "confirmEmail"]; requiredFields.forEach(field => { errors[field] = ''; if (values[field] === '') { errors[field] = "Required"; } }); if(values.name && values.name.length <= 3){ errors.name = "Name length minimum is 3 chars" } if (values.email && validateEmail(values.email)) { errors.email = "Invalid email address"; } if (values.email && values.confirmEmail && values.email !== values.confirmEmail) { errors.confirmEmail = "The emails don't match"; } if (values.confirmEmail && validateEmail(values.confirmEmail)) { errors.confirmEmail = "Invalid email address"; } return errors; } <file_sep>import React from "react"; import PropTypes from "prop-types"; import Dialog from "@material-ui/core/Dialog"; import DialogTitle from "@material-ui/core/DialogTitle"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogActions from "@material-ui/core/DialogActions"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import * as api from "../../api"; import { withStyles } from "@material-ui/core/styles"; import validate from "../../validate"; import isEqual from "lodash/isEqual"; const styles = { container: { display: "flex", justifyContent: "center", alignItems: "center", flex: "0 0 auto", margin: "8px 4px" }, dialogActions: { display: "flex", flexDirection: "column" } }; function removeByKey(myObj, deleteKey) { return Object.keys(myObj) .filter(key => key !== deleteKey) .reduce((result, current) => { result[current] = myObj[current]; return result; }, {}); } class RequestDialog extends React.Component { constructor(props) { super(props); this.state = { open: false, values: { name: null, email: null, confirmEmail: null }, errors: { name: "", email: "", confirmEmail: "" }, formError: "" }; // Store the initial state for reset the dialog this.baseState = Object.assign({}, this.state); this.handleClickSubscribe = this.handleClickSubscribe.bind(this); this.handleChanges = this.handleChanges.bind(this); } componentWillReceiveProps(nextProps) { // The parent open/closes the dialog if (nextProps.open !== this.props.open) { this.setState({ ...this.baseState, open: nextProps.open }); } } handleClickSubscribe = () => { const { name, email } = this.state.values; this.setState({ formError: "" }); this.auth(name, email); }; handleChanges = (nameInput, event) => { const value = event.target.value; const updatedValue = {}; updatedValue[nameInput] = value; this.setState({ values: { ...this.state.values, ...updatedValue } }, () => { const errors = validate(this.state.values); this.setState({ errors }); }); }; auth = (name, email) => { api .postRequest({ name, email }) .then(response => { if (response.success) { this.props.handler(response); } else { this.setState({ formError: response.message }); } }); }; render() { const { classes } = this.props; const { open, values, errors, formError } = this.state; const canSubmit = values.confirmEmail && values.email && values.name && !errors.confirmEmail && !errors.email && !errors.name; return ( <Dialog open={open} onClose={this.props.handler}> <DialogTitle>Request an invite</DialogTitle> <DialogContent> <DialogContentText> To subscribe to this website, please enter your email address here. We will send updates occasionally. </DialogContentText> <TextField margin="dense" id="name" label="Full name" type="string" error={!!errors.name} helperText={errors.name ? errors.name : null} onChange={e => this.handleChanges("name", e)} required fullWidth /> <TextField margin="dense" id="email" label="Email" type="email" error={!!errors.email} helperText={errors.email ? errors.email : null} onChange={e => this.handleChanges("email", e)} required fullWidth /> <TextField margin="dense" id="confirm_email" label="Confirm email" type="email" error={!!errors.confirmEmail} helperText={errors.confirmEmail ? errors.confirmEmail : null} onChange={e => this.handleChanges("confirmEmail", e)} required fullWidth /> </DialogContent> <DialogActions classes={{ root: classes.container }}> <div className={classes.dialogActions}> <span>{formError}</span> <Button variant="contained" onClick={this.handleClickSubscribe} color="primary" disabled={!canSubmit} > Subscribe </Button> </div> </DialogActions> </Dialog> ); } } RequestDialog.propTypes = { classes: PropTypes.object.isRequired, open: PropTypes.bool.isRequired, handler: PropTypes.func.isRequired }; export default withStyles(styles)(RequestDialog); <file_sep>import React from "react"; import PropTypes from "prop-types"; import Dialog from "@material-ui/core/Dialog"; import DialogTitle from "@material-ui/core/DialogTitle"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogActions from "@material-ui/core/DialogActions"; import Button from "@material-ui/core/Button"; import { withStyles } from "@material-ui/core/styles"; const styles = { container: { display: "flex", justifyContent: "center", alignItems: "center", flex: "0 0 auto", margin: "8px 4px" }, buttonSuccess: { color: "white" } }; class SuccessDialog extends React.Component { constructor(props) { super(props); this.state = { open: false }; } componentWillReceiveProps(nextProps) { // The parent open/closes the dialog if (nextProps.open !== this.props.open) { this.setState({ open: nextProps.open }); } } render() { const { classes } = this.props; const { open } = this.state; return ( <Dialog open={open} onClose={this.props.handler}> <DialogTitle>All done!</DialogTitle> <DialogContent> <DialogContentText> You will be one of the firsts to experience Broccolli & Co. when we launch. </DialogContentText> </DialogContent> <DialogActions classes={{ root: classes.container }}> <Button variant="contained" onClick={this.props.handler} color="secondary" className={classes.buttonSuccess} > OK </Button> </DialogActions> </Dialog> ); } } SuccessDialog.propTypes = { classes: PropTypes.object.isRequired, open: PropTypes.bool.isRequired, handler: PropTypes.func.isRequired }; export default withStyles(styles)(SuccessDialog);
ff2e04507d0cfbf88f9729087190f2cfdd7141f7
[ "Markdown", "JavaScript" ]
5
Markdown
stvmachine/test_broccolli_co
81ff8513fdfa386f2f72d396dc2ccd9625433eb3
44150ee74487117291a63ef3162b9414471cece8
refs/heads/main
<repo_name>esjchoi/UX_UI_HW_19<file_sep>/js/index.js function myFunction(x) { x.classList.toggle("change"); } /* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } const texts=["Nurse","boba fanatic","UX Designer"]; let count=0; let index=0; let currentText= ""; let letter= ""; (function type(){ if (count === texts.length){ count=0; } currentText=texts[count]; letter=currentText.slice(0,++index); document.querySelector(".typing").textContent=letter; if (letter.length === currentText.length){ count++; index=0; } setTimeout(type,400); })();
77ed1ad5088fe5161e37b897a13abd65b7e37434
[ "JavaScript" ]
1
JavaScript
esjchoi/UX_UI_HW_19
4be768a7b09be3d7f75c86cda8bf77cad70c2a29
7d3e178eba7822d48fdf1daa6eb912eecaac6ef8
refs/heads/master
<repo_name>rohitner/flask-yolo<file_sep>/server.py from flask import Flask, url_for, render_template, Response from darkflow.net.build import TFNet from facenet.src import facenet from facenet.src.align import detect_face import cv2 import tensorflow as tf import numpy as np import pickle from scipy import misc app = Flask(__name__) options = {"model": "/home/rohitner/tensorflow/darkflow/cfg/tiny-yolo-voc.cfg", "load": "/home/rohitner/tensorflow/darkflow/bin/tiny-yolo-voc.weights", "threshold": 0.1, "gpu": 0.8} tfnet = TFNet(options) def prewhiten_and_expand(x): mean = np.mean(x) std = np.std(x) std_adj = np.maximum(std, 1.0/np.sqrt(x.size)) y = np.multiply(np.subtract(x, mean), 1/std_adj) y = np.expand_dims(y, 0) return y def gen(camera): sess = tf.Session() with sess.as_default(): pnet, rnet, onet = detect_face.create_mtcnn(sess, None) facenet.load_model('/home/rohitner/models/facenet/20180402-114759/20180402-114759.pb') images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0") embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0") phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0") classifier_filename_exp = '/home/rohitner/models/lfw_classifier.pkl' with open(classifier_filename_exp, 'rb') as infile: (model, class_names) = pickle.load(infile) print('Loaded classifier model from file "%s"' % classifier_filename_exp) minsize = 20 # minimum size of face threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold factor = 0.709 # scale factor file_index = 0 while True: success, img = camera.read() results = tfnet.return_predict(img) for result in results: cv2.rectangle(img, (result["topleft"]["x"], result["topleft"]["y"]), (result["bottomright"]["x"], result["bottomright"]["y"]), (255, 0, 0), 4) text_x, text_y = result["topleft"]["x"] - 10, result["topleft"]["y"] - 10 cv2.putText(img, result["label"], (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2, cv2.LINE_AA) if img.ndim<2: print('Unable to align') continue if img.ndim == 2: img = facenet.to_rgb(img) img = img[:,:,0:3] bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor) nrof_faces = bounding_boxes.shape[0] if nrof_faces>0: det = bounding_boxes[:,0:4] det_arr = [] img_size = np.asarray(img.shape)[0:2] if nrof_faces>1: if True:# args.detect_multiple_faces: for i in range(nrof_faces): det_arr.append(np.squeeze(det[i])) else: bounding_box_size = (det[:,2]-det[:,0])*(det[:,3]-det[:,1]) img_center = img_size / 2 offsets = np.vstack([ (det[:,0]+det[:,2])/2-img_center[1], (det[:,1]+det[:,3])/2-img_center[0] ]) offset_dist_squared = np.sum(np.power(offsets,2.0),0) index = np.argmax(bounding_box_size-offset_dist_squared*2.0) # some extra weight on the centering det_arr.append(det[index,:]) else: det_arr.append(np.squeeze(det)) for i, det in enumerate(det_arr): det = np.squeeze(det) bb = np.zeros(4, dtype=np.int32) bb[0] = np.maximum(det[0]-44/2, 0) bb[1] = np.maximum(det[1]-44/2, 0) bb[2] = np.minimum(det[2]+44/2, img_size[1]) bb[3] = np.minimum(det[3]+44/2, img_size[0]) cropped = img[bb[1]:bb[3],bb[0]:bb[2],:] scaled = misc.imresize(cropped, (160, 160), interp='bilinear') scaled = prewhiten_and_expand(scaled) emb = sess.run(embeddings, feed_dict={images_placeholder:scaled, phase_train_placeholder:False}) predictions = model.predict_proba(emb) best_class_indices = np.argmax(predictions) best_class_probabilities = predictions[0, best_class_indices] font = cv2.FONT_HERSHEY_SIMPLEX cv2.rectangle(img, (bb[0], bb[1]), (bb[2], bb[3]), (0,255,0), 5) cv2.putText(img,class_names[best_class_indices] ,(bb[0], bb[1] - 10), font, 0.5, (255,0,0),2 ,cv2.LINE_AA) else: print('No face detected') ret, jpeg = cv2.imencode('.jpg', img) frame = jpeg.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @app.route('/video_feed') def video_feed(): cam = cv2.VideoCapture(0) # cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 360) return Response(gen(cam),mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/') def webcam(): return render_template('webcam.html') if __name__ == '__main__': app.run(host='0.0.0.0', debug=False)
ac53e9f29dfcd122443d151db56f790b94e0e323
[ "Python" ]
1
Python
rohitner/flask-yolo
d0ba0695584950e355ae374c1e593973b119127e
bd55271555f1c49f2a0cc8543f4b757c3b51a1c8
refs/heads/master
<repo_name>pcendo/achieve<file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery with: :exception include SessionsHelper before_action :login_check def login_check if logged_in? @msg = "Current user:"+current_user.name else end end end <file_sep>/app/mailers/blog_mailer.rb class BlogMailer < ApplicationMailer def blog_mail(blog) @blog = blog @user = User.find(@blog.user_id) @email = ["<EMAIL>", @user.email] mail to: @email, subject: "BLOG作成の確認メール" end end <file_sep>/app/controllers/favorites_controller.rb class FavoritesController < ApplicationController before_action :authenticate_user, only: [:index] def create favorite = current_user.favorites.create(blog_id: params[:blog_id]) redirect_to blogs_path, notice: "#{favorite.blog.user.name}さんのブログをお気に入り登録しました" end def destroy favorite = current_user.favorites.find_by(blog_id: params[:blog_id]).destroy redirect_to blogs_path, notice: "#{favorite.blog.user.name}さんのブログをお気に入り解除しました" end def index @favorites_blogs = current_user.favorite_blogs end private def blog_params params.require(:blog).permit(:title, :content, :user_id) end def authenticate_user if logged_in? else redirect_to new_session_path end end end
2fac4ef4f7e6f1a49716bb1e671188464bc96ef2
[ "Ruby" ]
3
Ruby
pcendo/achieve
8e8fd32d1d9078335374aac3f64f7b29045b9b2c
ad538df414866111f52d9b56b2474886d9313508
refs/heads/master
<repo_name>MarcosEOSS/502-PHP<file_sep>/HandsOn/Cap2/upload.php <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Upload</title> </head> <body> <form method="POST" enctype="multipart/form-data" action="upload.php"> <input type="file" name="arquivo" /> <input type="submit" /> </form> </body> </html> <pre> <?php //if($_FILES){ // print_r($_FILES); //} if($_FILES){ $arqName = $_FILES["arquivo"]["name"]; $name = explode(".",$arqName)[0]; $ext = explode(".",$arqName)[1]; $newName = md5($name.time()).".".$ext; echo $newName; if (!file_exists("uploads")) { mkdir("uploads"); chmod("uploads", 0777); } move_uploaded_file($_FILES["arquivo"]["tmp_name"], "uploads/".$newName); } ?><file_sep>/HandsOn/Cap3/domdoc/domdoc_removendoelementos.php <?php $dom = new DOMDocument(); $dom->load("cursos.xml"); $remover = $dom->getElementsByTagName("teste"); $remover->item(0)->parentNode->removeChild($remover->item(0)); $dom->save("cursos.xml"); header("Content-type: text/xml"); print_r($dom->saveXML()); <file_sep>/HandsOn/Cap2/manipulacao_arquivos/spl_object_file_fgetcsv.php <?php $file = new SplFileObject('clientes.csv','r'); $file->setFlags(SplFileObject::SKIP_EMPTY); //ignorar linhas vazias echo "<pre>"; while(!$file->eof()){ $linha = $file-fgetcsv(";"); if($linha[0]){ echo "Nome: ".$linha[0]."<br />"; echo "Email: ".$linha[1]."<br />"; echo "CPF: ".$linha[2]."<br />"; echo "<hr />"; } }<file_sep>/HandsOn/Cap1/datetime/datetime_comparacoes.php <?php echo "<pre>"; $dt1 = new DateTime(); $dt2 = new DateTime("2016-12-10"); //vencimento boleto print_r($dt1); echo"<br />"; print_r($dt2); echo"<hr />"; if ($dt1 > $dt2){ echo "Boleto Vencido"; } if ($dt1 <= $dt2){ echo "Boleto Valido"; } if ($dt1 == $dt2){ echo "Datas Iguais"; }<file_sep>/HandsOn/Cap1/datetime/funcoes_datetime.php <?php echo date('d/m/Y H:i:s'); echo "<br />"; echo date('d/m/Y '); echo "<br />"; echo date('d-m-y'); echo "<br />"; echo date('Y-m-d'); echo "<br />"; echo date('d'); echo "<br />"; echo date('m'); echo "<br />"; echo date('Y'); echo "<hr />"; echo time(); echo "<br />"; echo microtime(); echo "<hr />"; $proxSemana = time() + (7 * 24 * 60 * 60); echo date('d-m-Y', $proxSemana); echo "<hr />"; echo microtime(true); echo "<hr />"; echo date("d-m-Y",strtotime("now")); echo "<br />"; echo date("d-m-Y",strtotime("next day")); echo "<br />"; echo date("d-m-Y",strtotime("next week")); echo "<br />"; echo date("d-m-Y",strtotime("+ 1 week")); echo "<br />"; echo date("d-m-Y",strtotime("tomorrow")); echo "<br />"; echo date("d-m-Y",strtotime("+ 2 days")); echo "<br />"; echo date("d-m-Y",strtotime("+ 1 month")); echo "<br />"; echo date("d-m-Y",strtotime("+ 1 year")); echo "<hr />"; echo date("d-m-Y H:i:s",mktime(15,11,11,11,20,16)); echo "<br />"; echo date("d-m-Y h:i:s",mktime(15,11,11,11,20,16)); <file_sep>/HandsOn/Cap1/datetime/date_timezone_set.php <?php setlocale(LC_ALL,"pt_BR.utf8", "portuguese"); date_default_timezone_set("Asia/Tokyo"); echo strftime("%c"); echo "<br />"; echo strftime("%A, %d de %B de %Y %R"); <file_sep>/HandsOn/Cap3/domdoc/domdoc_criandoelementos.php <?php $dom = new DOMDocument(); $dom->load("cursos.xml"); //$carga = $dom->createElement("carga_horaria", "40"); $cursos = $dom->getElementsByTagName("curso"); //$i=0; //foreach ($cursos as $item){ // $item = $dom->getElementsByTagName("curso")->item($i); // $item->appendChild($carga); // $i++; //} foreach ($cursos as $item){ $carga = $dom->createElement("carga_horaria","40"); $item->appendChild($carga); } //$dom->save("cursos.xml"); header("Content-type: text/xml"); print_r($dom->saveXML()); <file_sep>/HandsOn/Cap2/manipulacao_arquivos/spl_file_object.php <?php $file = new SplFileObject("produtos.txt","a+"); while (!$file->eof()){ $linha = $file->fgets(); echo $linha . "<br />"; } echo "<br />"; foreach($file as $linha){ echo $linha . "<br />"; } //Arquivo temporario $temp = new SplFileObject(); $temp = fwrite("Sou um arquivo temporario"); $temp = rewind(); echo $temp->fgets();<file_sep>/HandsOn/Cap2/funcoes_arquivos.php <?php $fileName = "teste.txt"; $stream = fopen($fileName,"w+"); fclose($stream); if(file_exists($fileName)){ chmod($fileName, 0777); echo ("Permissao alterada<hr />"); } $info = stat($fileName); var_dump($info); if(!file_exists("touch.txt")){ touch("touch.txt"); echo "<br />Arquivo touch.txt foi criado!"; } if(file_exists("touch.txt")){ unlink("touch.txt"); echo "<br />Arquivo touch.txt foi apagado!"; } if(file_exists($fileName)){ copy($fileName, "teste2.txt"); } rename("teste2.txt", "teste1.txt"); $consulta = glob("manipulacao_arquivos/*.txt"); echo "<pre>"; print_r($consulta); $str = fopen("teste3","w+"); if(flock($str,LOCK_EX|LOCK_NB)){ } <file_sep>/HandsOn/Cap2/manipulacao_arquivos/file_get_contents.php <?php for ($i=10; $i<100;$i++){ file_put_contents("emails.txt", "\n<EMAIL>",FILE_APPEND); } $file = file_get_contents("emails.txt"); echo nl2br($file); <file_sep>/HandsOn/Cap3/SimpleXML/xml_parser.php <?php $parser = xml_parser_create(); xml_set_element_handler($parser,"elInicio","elFinaliza"); xml_set_character_data_handler($parser, "elTexto"); $xml = new SplfileObject("cursos.xml"); foreach($xml as $linha){ xml_parse($parser,$linha); } xml_parser_free($parser); function elInicio($parser, $nome, $atributos){ echo "Inicio da tag: ". $nome ."Atributos: " . print_r($atributos,true) ."<br />"; } function elFinaliza($parser, $nome){ echo "Fim da tag: ". $nome."<hr />"; } function elTexto($parser, $texto){ If($texto){ echo "Texto: ". $texto."<br />"; } }<file_sep>/HandsOn/Cap2/manipulacao_arquivos/fopen_fread_fwrite.php <?php $file = fopen("produtos.txt","w+"); fwrite($file,"Mouse\n"); fwrite($file,"Teclado\n"); fwrite($file,"Monitor\n"); fwrite($file,"MousePad\n"); fwrite($file,"Impressora\n"); fwrite($file,"Scanner\n"); fclose($file); $file= fopen("produtos.txt","a+"); $dados = fread($file, 4096); echo nl2br($dados); //funcao "nl2br" converte /n para <br /><file_sep>/HandsOn/Cap1/datetime/datetime_diff.php <?php echo "<pre>"; $dt1 = new DateTime(); $dt2 = new DateTime("2016-09-10"); //vencimento boleto $diferenca = $dt1->diff($dt2); print_r($diferenca); echo $diferenca->format("%R %m Mes(es) %d dias"); echo "<br />"; echo $diferenca->format("%R %a dias");<file_sep>/HandsOn/Cap1/datetime/classe_DateInterval.php <?php echo "<pre>"; $dt1 = new DateInterval("P16Y11M30D"); print_r($dt1); echo $dt1->format("%y Anos, %m Meses, %d Dias"); <file_sep>/HandsOn/Cap3/domdoc/domdoc_alterando.php <?php $dom = new DOMDocument(); $dom->load("cursos.xml"); //print_r($dom->getElementsBytagName("curso")); $conteudo = $dom->getElementsBytagName("categoria"); $conteudo->item(1)->nodeValue = "PHP"; //altera o valor da categoria do curso 501 $dom->save("cursos.xml"); header("Content-type: text/xml"); print_r($dom->saveXML());
35e5311ae27b543cd38ffb836ce38f9a53d4b692
[ "PHP" ]
15
PHP
MarcosEOSS/502-PHP
0111eeea418f298545fd471777dcb70709366ce3
4dc3d2ea94e64d1ad21eafac1599a1084f8bbce0
refs/heads/master
<file_sep>var mongoose = require('mongoose'); var errors = require('../mongo/errors.js'); var keygen = require('../util/keygen.js'); var log = require('../log/log.js').getLog(__filename); /** * Sets the `shortId` to the object if it was not already set. * @param {Object} data Object to set the `shortId` field to * @param {String} field Object's property to take the name from. */ module.exports.setShortId = function(data, field) { if (typeof data.shortId === 'string') return; field = field || 'name'; var value = data[field]; data.shortId = keygen.generate(value); }; module.exports.copyProperties = function(src, dest) { for (var name in src) { if (!src.hasOwnProperty(name)) continue; if (name === '_id' || name === 'shortId') continue; var prop = src[name]; dest[name] = prop; } }; /** * Creates a callback for mongoose query. If there is an error, reports the * error using {@link errors#handleError}. * @param {http.ServerResponse} res */ module.exports.json = function(req, res) { var url = req.url; return function(err, data) { var status = err ? 'ERROR' : 'SUCCESS'; log.debug(req.url, status, data); if (err) return errors.handleError(url, err, res); res.json({ data: data }); }; };<file_sep>describe(__filename, function() { var User = require('../../src/mongo/models/user.js'); var logonHelper = require('../_helper/logon-helper.js'); describe('GET /users/list', function(done) { it('should have content type json', function(done) { request(app). get('/users/list'). set('cookie', logonHelper.sessionCookie). expect('Content-Type', /json/). //expect(/^\[\s*?\]$/m). expect(/firstName": *?"john"/). expect(/<EMAIL>/). end(function(err, res) { done(err); }); }); }); // describe('GET /users/get', function(done) { // it('should fetch the user by id', function() { // }); // }); });<file_sep>var util = require('util'); function RefError(key) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.key = key; } util.inherits(RefError, Error); module.exports = RefError;<file_sep>/* * This is a test logger which just returns the logged value */ function getStringFromArgs(args) { args = Array.prototype.slice.call(args, 0); var str = ''; for (var i in args) { str += args[i] + ' '; } return str.trim(); } module.exports = { type: 'return-logger', debug: function() { return getStringFromArgs(arguments); }, warn: function() { return getStringFromArgs(arguments); }, error: function() { return getStringFromArgs(arguments); } };<file_sep>module.exports = { mongo: { url: 'mongodb://127.0.0.1:27017/plate-express', // debug: true, // autoIndex: true }, log: { type: 'console-logger.js', level: 0 }, express: { publicFolders: [ '/www-src', // '/www-dist' ], // privateFolders: [ // '/www-private' // ], sessionSecret: '<KEY>', sessionSecure: false, port: 8000, securePort: 8443, cert: 'server', https: false, http: true }, dirname: __dirname };<file_sep>var log = require('../../src/log/console-logger.js'); describe(__filename, function() { it('should have property type set', function() { expect(log.type).to.be('console'); }); it('should have functions for logging set', function() { expect(log.debug).to.be.a('function'); expect(log.warn).to.be.a('function'); expect(log.error).to.be.a('function'); }); });<file_sep>var mongoose = require('mongoose'); var log = require('../log/log.js').getLog(__filename); var config = require('../config.js'); mongoose.set('debug', config.mongo.debug); module.exports.init = function(p_url, p_callback) { // var conn = mongoose.createConnection(p_url); mongoose.connect(p_url); var conn = mongoose.connection; conn.on('error', function(err) { p_callback(err); }); conn.once('open', function() { p_callback(undefined, conn); }); return conn; };<file_sep>var mongoose = require('mongoose'); var oibValidator = require('./src/validators/oib-validator.js'); mongoose.set('debug', true); mongoose.connect('mongodb://127.0.0.1:27017/plate-express'); var conn = mongoose.connection; conn.on('error', function(err) { throw err; }); var Schema = mongoose.Schema; var companySchema = new Schema({ shortId: { type: String, required: true, index: { unique: true } }, name: { type: String, required: true, index: { unique: true }, validate: [function(p_value) { return typeof p_value === 'string' && p_value.length > 1; }, 'error.invalid.company.name'] }, oib: { type: String, required: true, index: { unique: true }, validate: [oibValidator.validate, 'error.invalid.company.oib'] } }); mongoose.model('Company', companySchema); setTimeout(function() { console.log('end'); }, 5000);<file_sep>#Plate express Work in progress... <file_sep>describe(__filename, function() { var logonHelper = require('../_helper/logon-helper.js'); var mongoose = require('mongoose'); var keygen = require('../../src/util/keygen.js'); var plain = []; var documents = []; it('should populate initial data', function(done) { var Model = mongoose.model('Company'); var modelNames = ['model1', 'model2', 'model3']; modelNames.forEach(function(name) { plain.push({ name: name, shortId: keygen.generate(name), }); }); plain[0].oib = '38065658119'; plain[1].oib = '43889476057'; plain[2].oib = '52721853252'; Model.create(plain, function(err) { if (err) { done(err); return; } documents = [].slice.call(arguments, 1); done(); }); }); after(function(done) { var i = documents.length; function handler(err) { if (err) { throw err; } i--; if (i === 0) { done(); } } for(var j in documents) { var doc = documents[j]; doc.remove(handler); } }); describe('GET /companies/get/{id}', function(done) { it('should have content type json', function(done) { request(app) .get('/companies/get/' + plain[0].shortId) .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) // .expect(/^\{\s*?\}$/m) .expect(new RegExp('"shortId": *?"' + documents[0].shortId + '"')) .expect(new RegExp('"name": *?"' + documents[0].name + '"')) .end(function(err, res) { expect(res.body.error).to.not.be.ok(); done(err); }); }); it('should return null on non existing id', function(done) { request(app) .get('/companies/get/non-existing-id') .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) .end(function(err, res) { expect(res.body.error).to.not.be.ok(); done(err); }); }); }); describe('GET /companies/find', function() { it('should find all companies', function(done) { request(app) .get('/companies/find') .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) // .expect(//) .end(function(err, res) { expect(res.body && res.body.data).to.be.ok(); expect(res.body.data.length >= 3).to.be.ok(); done(err); }); }); it('should find filtered company', function(done) { request(app) .get('/companies/find?shortId=' + plain[0].shortId) .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) .end(function(err, res) { expect(res.body.error).to.not.be.ok(); expect(res.body.data.length).to.be(1); done(err); }); }); }); var shortId; describe('POST /companies/save', function() { var insertedCompany; it('should save company', function(done) { request(app) .post('/companies/save') .send({ name: 'a-compan23', oib: '17778321663' }) .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) .end(function(err, res) { if (err) done(err); expect(res.body.error).to.not.be.ok(); expect(res.body.data).to.be.ok(); expect(res.body.data.shortId) .to.match(/acompan23-[a-z0-9]{6}/); insertedCompany = res.body.data; shortId = insertedCompany.shortId; done(); }); }); it('should fail to insert duplicate company', function(done) { request(app) .post('/companies/save') .send({ name: 'a-compan24', oib: '17778321663' }) .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) .end(function(err, res) { if (err) done(err); expect(res.body.error).to.be.ok(); expect(res.body.error.key).to.be('error.db.duplicate'); expect(res.body.data).to.not.be.ok(); done(); }); }); it('should update company', function(done) { request(app) .post('/companies/save') .send({ shortId: shortId, name: 'a-compan20' }) .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) .end(function(err, res) { if (err) done(err); expect(res.body.error).to.not.be.ok(); expect(res.body.data).to.be.ok(); expect(res.body.data.shortId).to.be(shortId); expect(res.body.data.name).to.be('a-compan20'); done(); }); }); }); describe('POST /companies/delete', function() { it('should delete the inserted company', function(done) { request(app) .post('/companies/delete') .send({ shortId: shortId }) .set('cookie', logonHelper.sessionCookie) .expect('Content-Type', /json/) .end(function(err, res) { if (err) done(err); expect(res.body.error).to.not.be.ok(); expect(res.body.data).to.be.ok(); expect(res.body.data.shortId).to.be(shortId); done(); }); }); }); });<file_sep>module.exports.generate = function(p_name) { var name = (p_name && p_name.length > 0) ? p_name.toString() : 'undefined'; name = name.replace(/[^a-zA-Z0-9]/g, '').substring(0, 10); while(name.length < 5) { var lastchar = name[name.length - 1]; name += lastchar ? lastchar : '_'; } // create a random hex key in the form of 'a0e' var random = Math.floor(Math.random()*4095).toString(16); while(random.length < 3) { // prepend with zeroes until length is 3 hex digits random = '0' + random; } // get timestamp in hex code var timestamp = new Date().getTime().toString(16); // takey the last 3 hex digits of timestamp timestamp = timestamp.substring(timestamp.length - 3, timestamp.length); return name + '-' + random + timestamp; };<file_sep>var app = require('../app.js').instance; var CarInsurance = require('../mongo/models/car-insurance.js'); var Company = require('../mongo/models/company.js'); var checkAuth = require('./checkAuth.js'); var common = require('./common.js'); app.get('/carinsurances/find', checkAuth, function(req, res) { CarInsurance.find(req.query).populate({ path: 'company', select: 'name' }).exec(common.json(req, res)); }); app.get('/carinsurances/find/:companyShortId', function(req, res) { Company.findOne({ shortId: req.route.params.companyShortId }, function(err, company) { if (err) return errors.handleError(req.url, err, res); req.query.company = company._id; CarInsurance.find(req.query, common.json(req, res)); }); }); app.get('/carinsurances/get/:shortId', checkAuth, function(req, res) { CarInsurance.findOne({ shortId: req.route.params.shortId }, common.json(req, res)); }); app.post('/carinsurances/save', checkAuth, function(req, res) { var data = req.body; CarInsurance.findOne({shortId: data.shortId}, function(err, carInsurance) { if (err) return errors.handleError(req.url, err, res); if (!carInsurance) { carInsurance = new CarInsurance(data); common.setShortId(carInsurance); } else { common.copyProperties(data, carInsurance); } carInsurance.save(common.json(req, res)); }); }); app.post('/carinsurances/delete', checkAuth, function(req, res) { var shortId = req.body.shortId; CarInsurance.findOneAndRemove({ shortId: shortId }, {}, common.json(req, res)); });<file_sep>var User = require('../../src/mongo/models/user.js'); before(function(done) { var user = new User({ firstName: 'john', lastName: 'travolta', email: '<EMAIL>', enabled: true }); user.setPassword('<PASSWORD>'); user.save(function(err) { if (err) { done(err); } request(app). post('/login'). send({ 'email': '<EMAIL>', 'password': '<PASSWORD>' }). expect(200). expect(/<EMAIL>/). end(function(err, res) { module.exports.sessionCookie = res.header['set-cookie'][0]; done(err); }); }); }); // after(function(done) { // request(app). // get('/logout'). // set('cookie', module.exports.sessionCookie). // expect(403). // end(function() { // User.find({ // email: '<EMAIL>' // }).remove(function(err) { // module.exports.sessionCookie = undefined; // done(err); // }); // }); // }); module.exports.sessionCookie = undefined;<file_sep>var mongooseConfig = require('../../src/mongo/mongoose.js'); var config = require('../../src/config.js'); var connection; module.exports.init = function() { before(function(done) { mongooseConfig.init(config.mongo.url, function(err, conn) { if (err) { done(err); return; } expect(conn).to.be.ok(); connection = conn; console.log('mongodb connected'); done(); }); }); after(function(done) { connection.once('close', function() { console.log('mongodb disconnected'); done(); }); connection.close(); }); };<file_sep>var mongooseConfig = require('../../src/mongo/mongoose.js'); var config = require('../../src/config.js'); describe(__filename, function() { var connection; it('should connect without errors', function(done) { mongooseConfig.init(config.mongo.url, function(err, conn) { if (err) { done(err); return; } expect(conn).to.be.ok(); connection = conn; done(); }); }); it('should disconnect without errors', function(done) { if (!connection) { done(new Error('connection ' + connection)); return; } connection.once('close', function() { done(); }); connection.close(); }); });<file_sep>var User = require('../../../src/mongo/models/user.js'); describe(__filename, function() { // connect to the db before tests and disconnect afterwards require('../../_helper/mongo-helper.js').init(); it('should create and fail to save because of validation', function() { var user = new User({ firstName: 'jack', lastName: 'johnson' }); //validationFailed expect(user.save).to.throwError(); }); var user; it('should create and save new user', function(done) { user = new User({ firstName: 'jack', lastName: 'johnson', email: '<EMAIL>', enabled: false }); user.setPassword('<PASSWORD>'); expect(user.isPasswordValid('<PASSWORD>')).to.be(false); expect(user.isPasswordValid('<PASSWORD>')).to.be(true); user.save(function(err, user) { expect(err).to.not.be.ok(); expect(user._id).to.be.ok(); done(); }); }); it('should be able to fetch the user', function(done) { User.findById(user._id, function(err, foundUser) { expect(foundUser.email).to.be(user.email); done(); }); }); it('should be able to remove the user', function(done) { user.remove(function(err, user) { expect(err).to.not.be.ok(); User.findById(user._id, function(err, foundUser) { expect(err).to.not.be.ok(); expect(foundUser).to.not.be.ok(); done(); }); }); }); });<file_sep>var log = require('./log/log.js').getLog(__filename); log.debug('calling startup script'); require('./startup.js').start(); <file_sep>var mongooseConfig = require('../src/mongo/mongoose.js'); var config = require('../src/config.js'); var User = require('../src/mongo/models/user.js'); var promptly = require('promptly'); var async = require('async'); async.series({ firstName: function(callback) { promptly.prompt('first name:', callback); }, lastName: function(callback) { promptly.prompt('last name:', callback); }, email: function(callback) { promptly.prompt('email:', callback); }, password: function(callback) { promptly.password('password:', callback); } }, function(err, userData) { if (err) throw err; connectAndSave(userData); }); function connectAndSave(userData) { async.series({ connection: function(callback) { connection = mongooseConfig.init(config.mongo.url, callback); }, save: function(callback) { var user = new User(userData); user.setPassword(<PASSWORD>); user.enabled = true; user.save(callback); }, }, function(err, result) { if (err) console.log('error while saving the user', err); else console.log('successfully saved the user'); connection.close(function() { process.exit(); }); }); } <file_sep>var log = require('../log/log.js').getLog(__filename); module.exports = function(req, res, next) { log.debug('checking if user is authorized'); if (!req.session || !req.session.userId) { log.debug('user is not authorized'); res.status(401).json({ error: { key: 'error.not.authorized' } }); } else { log.debug('user is authorized. userId:', req.session.userId); next(); } };<file_sep>var log = require('./log/log.js').getLog(__filename); var config = require('./config.js'); var express = require('express'); function setStaticFolders(p_app, p_folders) { if (!p_folders || p_folders.length === 0) { log.debug('no public folders to set'); return; } for (var i in p_folders) { var folder = p_folders[i]; log.debug('setting public folder', folder); p_app.use(express.static(__dirname + folder)); } } module.exports.init = function() { var app = express(); //make this app instance available to other modules module.exports.instance = app; app.enable('trust proxy'); setStaticFolders(app, config.express.publicFolders); app.use(function(req, res) { //log request urls TODO write client's IP address log.debug('request:', req.originalUrl); req.next(); }); //cookieSession for handling user session app.use(express.cookieParser(config.express.sessionSecret)); app.use(express.cookieSession({ proxy: true, cookie: { secure: config.express.sessionSecure ? true : false, maxAge: 10*60*60*1000 // expires: new Date(Date.now() + 10*60*60*1000) } })); //to be able to read the req.body parameters on POST request log.debug('registering bodyParser'); app.use(express.bodyParser()); //middleware require('./middleware'); app.use(require('./middleware/checkAuth')); // setStaticFolders(app, config.express.privateFolders); //invalid url handler app.use(function(req, res) { res.status(404).json({ error: { name: 'NotFound', key: 'error.not.found' } }); }); // var port = p_port; // var httpServer = http.createServer(app); // httpServer.listen(port); // var httpsServer = https.createServer(credentials, app); // var server = app.listen(port); log.debug('initialized app'); return app; };<file_sep>module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js', '!src/www-dist/**/*', '!src/www-src/**/*'], }, // jsdoc : { // dist : { // src: ['src/**/*.js'], // options: { // destination: 'doc' // } // } // }, mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/test.js'] } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'mocha'] }, }); grunt.registerTask('start', 'start application', function() { var done = this.async(); require('./src/index.js'); // do not call done() to make the server keep running }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-test'); // grunt.loadNpmTasks('grunt-jsdoc'); grunt.registerTask('test', ['jshint', 'mochaTest']); // grunt.registerTask('doc', ['jshint', 'mochaTest', 'jsdoc']); grunt.registerTask('default', ['jshint', 'mochaTest']); };<file_sep>var User = require('../../src/mongo/models/user.js'); describe(__filename, function() { before(function(done) { var user = new User({ firstName: 'john', lastName: 'travolta', email: '<EMAIL>', enabled: true }); user.setPassword('<PASSWORD>'); user.save(function(err) { done(err); }); }); after(function(done) { User.find({ email: '<EMAIL>' }).remove(function(err) { done(err); }); }); describe('GET /logout', function() { it('forbidden because user was never logged in', function(done) { request(app). get('/logout'). expect(200). end(done); }); }); var sessionCookie; describe('POST /login', function() { //TODO before create test user //TODO after clear session and remove test user it('the user should not be found', function(done) { request(app). post('/login'). send({ 'email': '<EMAIL>', 'password': '<PASSWORD>' }). expect(401). expect(/error.authentication/). end(function(err, res) { //console.log('err', err); done(err); }); }); it('the user should be found, but password invalid', function(done) { request(app). post('/login'). send({ 'email': '<EMAIL>', 'password': '<PASSWORD>' }). expect(401). expect(/error.authentication/). end(function(err, res) { done(err); }); }); it('the user should be found and session set', function(done) { request(app). post('/login'). send({ 'email': '<EMAIL>', 'password' : '<PASSWORD>' }). expect(200). expect(/<EMAIL>/). end(function(err, res) { if (err) done(err); expect(res.header['set-cookie'].length).to.be(1); sessionCookie = res.header['set-cookie'][0]; expect(sessionCookie).to.be.ok(); done(); }); }); }); describe('GET /logout', function(done) { it('should logout the user', function(done) { request(app). get('/logout'). set('cookie', sessionCookie). expect(200). end(function(err, res) { //make sure that the cookie is now expired expect(res.header['set-cookie'].length).to.be(1); expect(res.header['set-cookie'][0]).to.contain( 'Expires=Thu, 01 Jan 1970 00:00:00 GMT'); done(); }); }); }); });<file_sep>var app = require('../app.js').instance; var log = require('../log/log.js').getLog(__filename); var errors = require('../mongo/errors.js'); app.get('/test/success', function(req, res) { res.json({data: 'data-received'}); }); app.get('/test/error', function(req, res) { var err = new Error('error12345'); errors.handleError('/test/error', err, res, true); }); app.post('/test/validation-error', function(req, res) { var err = { name: 'ValidationError', errors: { 'field1': {} } }; errors.handleError('/test/validationError', err, res, false); }); <file_sep>var app = require('../app.js').instance; var log = require('../log/log.js').getLog(__filename); var errors = require('../mongo/errors.js'); var User = require('../mongo/models/user.js'); var checkAuth = require('./checkAuth.js'); var common = require('./common.js'); app.get('/users/list', checkAuth, function(req, res) { User.find({}, common.json(req, res)); }); app.get('/users/get', checkAuth, function(req, res) { log.debug('requesting user with id: ', req.query.id); User.findById(req.query.id, common.json(req, res)); }); //should be post app.post('/users/add', checkAuth, function(req, res) { log.debug('adding user'); var john = new User({ firstName: 'John', lastName: 'Travolta', email: '<EMAIL>', enabled: true }); john.setPassword('<PASSWORD>'); john.save(common.json(req, res)); });<file_sep>var config = require('../config.js'); var abstractLogger = require('./abstract-logger.js'); function getLoggerInstance(p_type) { var loggerInstance; try { loggerInstance = require('./' + p_type); } catch(err) { // console.log('invalid config.log.type \'' + config.log.type + '\'' + // ', using console-logger.js'); loggerInstance = require('./console-logger.js'); loggerInstance.warn(err.message + ', using console-logger.js'); } return loggerInstance; } /** * Gets the logger with the specified log identificator * @param String p_logId the identificator of the log * @return {[type]} */ module.exports.getLog = function(p_logId) { p_logId = p_logId || '(undefined)'; var loggerInstance = getLoggerInstance(config.log.type); return Object.create(abstractLogger, { logId: { value: p_logId.replace(config.dirname, ''), enumerable: true }, level: { value: config.log.level, enumerable: true }, loggerInstance: { value: loggerInstance, enumerable: true } }); };<file_sep>var CarInsurance = require('../../../src/mongo/models/car-insurance.js'); var Company = require('../../../src/mongo/models/company.js'); var keygen = require('../../../src/util/keygen.js'); describe(__filename, function() { var carInsurance, company; before(function() { carInsurance = new CarInsurance({ name: '<NAME>', carYear: 1988, licensePlate: 'zg1234a', policyNumber: '123456789012', expires: Date.now() + 1000000000, power: 120, vehicleType: 'PERSONAL', premium: 1200 }); company = new Company({ name: 'test-company', oib: '04082175950' }); company.shortId = keygen.generate(company.name); }); after(function(done) { company.remove(function(err) { done(err); }); }); // connect to the db before tests and disconnect afterwards require('../../_helper/mongo-helper.js').init(); before(function(done) { company.save(function(err, data) { if (err) done(err); expect(data).to.be.ok(); done(); }); }); describe('save', function() { it('should save successfully', function(done) { carInsurance.shortId = keygen.generate(carInsurance.name); carInsurance.company = company._id; carInsurance.save(function(err, data) { if (err) return done(err); expect(data).to.be.ok(); done(); }); }); }); describe('find and populate', function() { it('should find car insurance and populate company', function(done) { CarInsurance.findOne(carInsurance).populate('company') .exec(function(err, data) { if (err) return done(err); expect(err).to.not.be.ok(); expect(data).to.be.ok(); expect(data.company).to.be.ok(); expect(data.company.name).to.be('test-company'); done(); }); }); }); describe('remove', function(done) { it('should remove without errors', function(done) { carInsurance.remove(function(err, data) { if (err) return done(err); expect(data).to.be.ok(); done(); }); }); }); });<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var carInsurance = new Schema({ shortId: { type: String, required: true, index: { unique: true } }, name: { type: String, required: true, index: { unique: true }, validate: [function(p_value) { return typeof p_value === 'string' && p_value.length > 1; }, 'validation.carinsurance.name'] }, carYear: { type: Number, // required: true, validate: [function(p_value) { return p_value && p_value > 1900 && p_value < 2100; }, 'validation.carinsurance.carYear'] }, licensePlate: { type: String, uppercase: true // required: true, // validate: [function(p_value) { // if (!p_value) return false; // // license plate must be in the form of // // AB123C, AB123CD, AB1234C or AB1234CD // return p_value.match(/^[A-Za-z]{2}[0-9]{3,4}[A-Za-z]{1,2}$/) ? // true : false; // }, 'validation.carinsurance.licensePlate'] }, policyNumber: { type: String, required: true // validate: [function(p_value) { // if (!p_value) return false; // return p_value.match(/^[0-9]{12}$/) ? true : false; // }, 'validation.carinsurance.policyNumber'] }, expires: { type: Date, required: true, validate: [function(p_value) { if (!p_value || typeof p_value.getTime !== 'function') return false; return p_value.getTime() > Date.now() ? true : false; }, 'validation.date'] }, power: { type: Number, required: true }, maxAllowedMass: { type: Number }, vehicleType: { type: String, required: true }, company: { type: String, ref: 'Company', required: true }, bonus: { type: Number }, premium: { type: Number, required: true }, accident: { type: Boolean }, leasing: { type: Boolean } }); // carInsurance.set('autoIndex', falsea); var CarInsurance = mongoose.model('CarInsurance', carInsurance); module.exports = mongoose.model('CarInsurance'); <file_sep>global.expect = require('expect.js'); // global.proxyquire = require('proxyquire'); global.request = require('supertest'); require('./config-test.js'); //automatically included require('./log/console-logger-test.js'); // this test sets the logger to return-logger which suppresses the output // during tests require('./log/log-test.js'); // util require('./util/keygen-test.js'); // mongo require('./mongo/mongoose-test.js'); require('./mongo/models/user-test.js'); require('./mongo/models/company-test.js'); require('./mongo/models/car-insurance-test.js'); require('./validators/oib-validator-test.js'); describe('START SERVER', function() { it('starting server...', function(done) { // start the server for testing middleware require('../src/startup.js').start(function(err) { global.app = require('../src/app.js').instance; done(err); }); }); }); // add modules which test app middleware here require('./middleware/users-test.js'); require('./middleware/login-test.js'); require('./middleware/companies-test.js'); describe('STOP SERVER', function() { require('./_helper/logout-helper.js'); it('stopping server...', function(done) { require('../src/startup.js').stop(done); }); });<file_sep>var expect = require('expect.js'); var config = require('../src/config.js'); // disable secure cookie for testing config.express.sessionSecure = false; describe(__filename, function() { it('should be ok', function() { expect(config).to.be.ok(); }); it('should have set mongo.url', function() { expect(config.mongo).to.be.ok(); expect(config.mongo.url).to.be.a('string'); }); it('should have set log.type', function() { expect(config.log).to.be.ok(); expect(config.log.type).to.be.a('string'); expect(config.log.type.length).to.be.greaterThan(0); }); it('should have set express params', function() { expect(config.express).to.be.ok(); expect(config.express.publicFolders).to.be.an('array'); expect(config.express.sessionSecret).to.be.a('string'); expect(config.express.port).to.be.a('number'); }); });<file_sep>var User = require('../mongo/models/user.js'); var app = require('../app.js').instance; var log = require('../log/log.js').getLog(__filename); app.get('/logout', function(req, res) { // if (!req.session || !req.session.userId) { // res.json(403, { // err: 'error.logout' // }); // req.session = null; // return; // } req.session = null; res.json({ err: undefined, data: 'logout.success' }); }); app.post('/login', function(req, res) { var email = req.body.email; var password = req.body.password || ''; log.debug('trying to find an user with email', email); User.findOne({ email: email }, function(err, user) { if (err) { log.debug('an error ocurred while finding user with email', email); res.json(500, { error: { name: 'Server', key: 'error.internal' } }); return; } if (!user) { log.debug('user with email', email, 'not found'); res.json(401, { error: { name: 'Authentication', key: 'error.authentication' } }); return; } if (!user.isPasswordValid(password)) { log.debug('user with email', email, 'found, but invalid password'); req.session = null; //TODO use json format res.json(401, { error: { name: 'Authentication', key: 'error.authentication' } }); return; } log.debug('user with email', email, 'found. logging in...'); console.log('req.session.cookie', req.session.cookie); // 10 hrs // var age = 10*60*60*1000; // req.session.cookie.expires = new Date(Date.now() + age); // req.session.cookie.maxAge = age; req.session.userId = email; res.json({err: undefined, data: user.toObject()}); }); });<file_sep>var config = require('./config.js'); var log = require('./log/log.js').getLog(__filename); var mongooseConfig = require('./mongo/mongoose.js'); var fs = require('fs'); var http = require('http'); var https = require('https'); var app = require('./app.js'); var httpServer; var httpsServer; var dbConn; module.exports = { _startHttp: function(expressApp, port) { httpServer = http.createServer(expressApp); httpServer.listen(port); log.debug('started http server on port ' + port); }, _startHttps: function(expressApp, port) { var privateKey = fs.readFileSync( __dirname + '/../ssl/' + config.express.cert + '.key', 'utf8'); var certificate = fs.readFileSync( __dirname + '/../ssl/' + config.express.cert + '.crt', 'utf8'); var credentials = { key: privateKey, cert: certificate }; httpServer = https.createServer(credentials, expressApp); httpServer.listen(port); log.debug('started https server on port ' + port); }, start: function(p_callback) { log.debug('application starting'); var self = this; //create a mongodb connection and start application dbConn = mongooseConfig.init(config.mongo.url, function(err, conn) { if (!p_callback && err) throw err; if (err) { p_callback(err); return; } var expressApp = app.init(); // process.env.port || config.express.port if (config.express.http) { self._startHttp(expressApp, config.express.port); } if (config.express.https) { self._startHttps(expressApp, config.express.securePort); } //success log.debug('application started'); if (p_callback) { p_callback(); } }); }, stop: function(p_callback) { log.debug('attempting to stop application'); try { if (httpServer) httpServer.close(); if (httpsServer) httpsServer.close(); dbConn.once('close', function() { log.debug('application stopped'); if (p_callback) { //success p_callback(); } }); dbConn.close(); } catch(err) { if (!p_callback) throw err; p_callback(err); } } };<file_sep>function f(x) { var val = x % 10; return val === 0 ? 10 : val; } function verify(digits) { if (digits.length !== 11) { return false; } var checkDigit = parseInt(digits[digits.length - 1]); var t = 10; for(var i = 0; i < digits.length - 1; i++) { t = (2 * f(t + parseInt(digits[i]))) % 11; } return ((t + checkDigit) % 10) === 1; } module.exports.validate = function(p_oib) { if (typeof p_oib !== 'string') { return false; } return verify(p_oib + ''); };<file_sep>var Company = require('../../../src/mongo/models/company.js'); var keygen = require('../../../src/util/keygen.js'); describe(__filename, function() { var company; before(function() { company = new Company({ name: '1', oib: 123, shortId: keygen.generate(this.name) }); }); after(function(done) { // remove the company from the database company.remove(function(err) { done(err); }); }); // connect to the db before tests and disconnect afterwards require('../../_helper/mongo-helper.js').init(); it('should fail to save because name invalid', function(done) { company.save(function(err, company) { expect(err && err.errors && err.errors.oib).to.be.ok(); expect(err.errors.name).to.be.ok(); expect(err.errors.name.message).to.be('validation.company.name'); expect(err.errors.oib.message).to.be('validation.company.oib'); done(); }); }); it('should fail to save because of invalid oib', function(done) { company.name = '12'; company.shortId = keygen.generate(company.name); company.save(function(err, company) { expect(err && err.errors && err.errors.oib).to.be.ok(); expect(err.errors.name).to.not.be.ok(); expect(err.errors.oib.message).to.be('validation.company.oib'); done(); }); }); it('should save successfully', function(done) { company.oib = '04082175950'; company.save(function(err, company) { expect(err).to.not.be.ok(); expect(company).to.have.property('_id'); expect(company).to.have.property('shortId'); expect(company.shortId).to.match(/12222-[0-9a-f]{6}/); done(); }); }); it('should update successfully', function(done) { company.name = 'changed name'; company.save(function(err, company) { expect(err).to.not.be.ok(); expect(company).to.have.property('_id'); expect(company).to.have.property('shortId'); expect(company.shortId).to.match(/12222-[0-9a-f]{6}/); expect(company.name).to.be('changed name'); done(); }); }); });<file_sep>var User = require('../../src/mongo/models/user.js'); var logonHelper = require('./logon-helper.js'); before(function(done) { request(app). get('/logout'). set('cookie', module.exports.sessionCookie). expect(200). end(function(err) { if (err) { done(err); } User.find({ email: '<EMAIL>' }).remove(function(err) { logonHelper.sessionCookie = undefined; done(err); }); }); });<file_sep>/* * An abstract module for logging. * Expects to have set logDebug, logWarn and LogError methods */ function prependArgs(p_severity, p_logId, args) { args = Array.prototype.slice.call(args, 0); args.splice(0, 0, p_severity, p_logId + '>'); return args; } function checkInstance(p_loggerInstance) { if (!p_loggerInstance) { throw new Error('loggerInstance not set. did you use the ' + 'require(\'log.js\').getLog() function to get the logger?'); } } module.exports = { logId: '', debug: function() { checkInstance(this.loggerInstance); if (this.level > 0) { return; } var args = prependArgs('DEBUG', this.logId, arguments); return this.loggerInstance.debug.apply(this, args); }, warn: function() { checkInstance(this.loggerInstance); if (this.level > 1) { return; } var args = prependArgs('WARN ', this.logId, arguments); return this.loggerInstance.warn.apply(this, args); }, error: function() { checkInstance(this.loggerInstance); if (this.level > 2) { return; } var args = prependArgs('ERROR', this.logId, arguments); return this.loggerInstance.error.apply(this, args); }, };
06eb3112dfc9f273157383a824b08f8c480006ce
[ "JavaScript", "Markdown" ]
35
JavaScript
jeremija/plate-express
5bd5aa7267e67c48ee4547d34ad0ae5fb148ae45
cc3f2bcf7866c50be005d062aac08ce79c3146c9
refs/heads/master
<repo_name>rikonor/betterbot<file_sep>/index.js var slackbot = require('node-slackbot'); function BetterBot(botToken, botId) { this.botToken = botToken; this.botId = botId; // Use node-slackbot as api client this.bot = new slackbot(this.botToken); this.bot.use(this.handleEvent.bind(this)); this.handlers = [this.defaultHandler]; } BetterBot.prototype.sendMessage = function(channel, message) { this.bot.sendMessage(channel, message); }; // Cute function to have - given a message, check if the user is mentioned // Or give back a list of the mentioned users // So not as it's implemented right now because that's just based on the userId // In a cooler scenario you would parse the message for userIds and make an api call for each // getting his name, then you can get a list of all user names BetterBot.prototype.mentionsUser = function(message, userId) { return message.indexOf('<@' + userId + '>') !== -1; }; // Check that the message is for pomodoro BetterBot.prototype.isMessageForMe = function(message) { // checks if the message addresses the bot return this.mentionsUser(message, this.botId); }; BetterBot.prototype.getUserInfo = function(userId, cb) { this.bot.api('users.info', {user: userId}, function(res) { cb(res.user); }); }; BetterBot.prototype.getUserName = function(userId, cb) { this.getUserInfo(userId, function(userInfo) { cb(userInfo.real_name || res.user.name); }); }; BetterBot.prototype.parseMessage = function(message) { // Given a message, try to give back a command and it's arguments fields = message.split(' ') return { cmd: fields[0], args: fields.slice(1) } } BetterBot.prototype.defaultHandler = function(message) { var self = this; if (self.isMessageForMe(message.text)) { self.getUserName(message.user, function(userName) { var msgToSend = "Hi, " + userName + ". What's up?" self.sendMessage(message.channel, msgToSend); }); } } BetterBot.prototype.addHandler = function(handler) { // Remove the default handler if ((this.handlers[0]) === this.defaultHandler) { this.handlers.shift(); } this.handlers.push(handler); }; BetterBot.prototype.handleEvent = function(evt, cb) { if (evt.type === 'message') { this.handlers.forEach(function(handler) { handler(evt); }); } cb(); }; BetterBot.prototype.start = function() { console.log("Starting bot"); this.bot.connect(); } module.exports = BetterBot; <file_sep>/README.md BetterBot --------- A better slack bot Helper methods: 1. sendMessage(channel, message) 2. mentionsUser(message, userId) 3. isMessageForMe(message) 4. getUserInfo(userId, callback) 5. getUserName(userId, callback) 6. parseMessage(message) 7. addHandler(handler)
5d9fa95e51539b2935aed7021d6117aa1a9d083a
[ "JavaScript", "Markdown" ]
2
JavaScript
rikonor/betterbot
1af6d33746c92e29c307851b24da944c1fe38e5e
d3706fd1ee392817e56d8259fbb482cc7449e4b3
refs/heads/master
<repo_name>SkeltonMod/chatsite<file_sep>/chatapp/index.php <?php session_start (); function loginForm() { echo ' <div class="form-group"> <th class="nav" align="center"><img src="images/logo.jpg" width="200" height="150"></th> <strong><marquee behavior="alternate">WELCOME TO COMPUTER SCIENCE DEPARTMENT F.C.E - YOLA CHAT SITE</marquee></span></font></div></strong> <div id="loginform"> <form action="index.php" method="post"> <h1>Live Chat</h1><hr/> <label for="name">Please Enter Your Name To Continue</label> <input type="text" name="name" id="name" class="form-control" placeholder="Enter Your Name"/> <input type="submit" class="btn btn-default" name="enter" id="enter" value="Enter" /> </form> </div> </div> '; } if (isset ( $_POST ['enter'] )) { if ($_POST ['name'] != "") { $_SESSION ['name'] = stripslashes ( htmlspecialchars ( $_POST ['name'] ) ); $fp = fopen ( "log.html", 'a' ); fwrite ( $fp, "<div class='msgln'><i>User " . $_SESSION ['name'] . " has joined the chat session.</i><br></div>" ); fclose ( $fp ); } else { echo '<span class="error">Please type in a name</span>'; } } if (isset ( $_GET ['logout'] )) { // Simple exit message $fp = fopen ( "log.html", 'a' ); fwrite ( $fp, "<div class='msgln'><i>User " . $_SESSION ['name'] . " has left the chat session.</i><br></div>" ); fclose ( $fp ); session_destroy (); header ( "Location: index.php" ); // Redirect the user } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link type="text/css" rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"> <title>Chat - Customer Module</title> </head> <body> <video poster="image/poster.jpg" autoplay = true loop> <source src="video/hacker.mp4" type="video/mp4"> </video> <?php if (! isset ( $_SESSION ['name'] )) { loginForm (); } else { ?> <div id="wrapper"> <div id="menu"> <p class="welcome"> Welcome, <b><?php echo $_SESSION['name']; ?></b> </p> <p class="logout"> <a id="exit" href="#">Exit Chat</a> </p> <div style="clear: both"></div> </div> <div id="chatbox" class="fullscreen"><?php if (file_exists ( "log.html" ) && filesize ( "log.html" ) > 0) { $handle = fopen ( "log.html", "r" ); $contents = fread ( $handle, filesize ( "log.html" ) ); fclose ( $handle ); echo $contents; } ?></div> <form name="message" action=""> <input name="usermsg" type="text" id="usermsg" size="63" onkeypress="setTimeout(isTyping(),1000); setInterval(notTyping,4000)" /> <input name="submitmsg" type="submit" id="submitmsg" value="Send" /> <div id="typing_on">No one is typing at the moment.</div> </form> </div> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript"> // jQuery Document $(document).ready(function(){ }); //jQuery Document $(document).ready(function(){ //If user wants to end session $("#exit").click(function(){ var exit = confirm("Are you sure you want to end the session?"); if(exit==true){window.location = 'index.php?logout=true';} }); }); //If user submits the form $("#submitmsg").click(function(){ var clientmsg = $("#usermsg").val(); $.post("post.php", {text: clientmsg}); $("#usermsg").attr("value", ""); loadLog; return false; }); function loadLog(){ var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20; $.ajax({ url: "log.html", cache: false, success: function(html){ $("#chatbox").html(html); var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20; if(newscrollHeight > oldscrollHeight){ $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); } }, }); } var timer = 0; function reduceTimer(){ timer = timer - 1; isTyping(true); } function isTyping() { document.getElementById('typing_on').innerHTML = " Typing...."; } function notTyping (){ document.getElementById('typing_on').innerHTML = ""; } setInterval (loadLog, 55) </script> <?php } ?> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript"> </script> </body> </html><file_sep>/README.md # chatsite PHP, Jquery, Bootstrap and AJAX
90fa16d28416c1b008d49acc4244068f03857ec6
[ "Markdown", "PHP" ]
2
PHP
SkeltonMod/chatsite
c7b6126b243515dfe49a8bbfbace871a3d71c457
af503e5d049836d76e86f1352792c5afa6b8ed47
refs/heads/master
<file_sep>tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/core" brew "fzf" brew "jq" brew "p7zip" brew "python" brew "ssh-copy-id" brew "sshuttle" brew "tmux" cask "android-platform-tools" cask "google-cloud-sdk" cask "firefox" cask "google-chrome" cask "iterm2" cask "postman" cask "visual-studio-code" cask "vmware-fusion" cask "zoom" <file_sep>export LANG=en_US.UTF-8 export EDITOR=nano export PAGER=less typeset -U path typeset -U fpath path=( ~/.opt/*/(s|)bin(N-/) ~/.local/(s|)bin(N-/) ~/.(s|)bin(N-/) /opt/homebrew/opt/*/(s|)bin(N-/) /opt/homebrew/(s|)bin(N-/) /usr/local/opt/*/(s|)bin(N-/) /usr/local/*/(s|)bin(N-/) /usr/local/(s|)bin(N-/) /opt/*/(s|)bin(N-/) /usr/(s|)bin(N-/) /(s|)bin(N-/) $path ) fpath=( /opt/homebrew/share/zsh/site-functions(N-/) /usr/local/share/zsh/site-functions(N-/) $fpath ) setopt always_to_end setopt auto_cd setopt auto_list setopt auto_menu setopt auto_param_keys setopt auto_param_slash setopt auto_pushd setopt correct setopt correct_all setopt extended_history setopt glob_subst setopt hist_expand setopt hist_ignore_all_dups setopt hist_ignore_dups setopt hist_reduce_blanks setopt interactive_comments setopt list_packed setopt list_rows_first setopt list_types setopt magic_equal_subst setopt no_nomatch setopt prompt_subst setopt pushd_ignore_dups setopt share_history setopt transient_rprompt autoload -Uz colors && colors autoload -Uz compinit && compinit autoload -Uz promptinit && promptinit autoload -Uz select-word-style && select-word-style bash autoload -Uz vcs_info && precmd () { vcs_info } bindkey -e bindkey "^p" history-beginning-search-backward bindkey "^n" history-beginning-search-forward zstyle ":completion:*:default" menu select=2 zstyle ":completion:*" matcher-list "m:{a-z}={A-Z}" zstyle ":vcs_info:*" formats "[%b]" zstyle ":vcs_info:*" actionformats "[%b|%a]" zstyle ":vcs_info:git:*" check-for-changes false HISTFILE=~/.zsh_history HISTSIZE=10000 SAVEHIST=10000 alias grep="grep --color=auto" case "$OSTYPE" in darwin*) alias ls="ls -G" # alias tar="COPYFILE_DISABLE=1 tar" ;; linux*) alias ls="ls --color=auto" ;; esac if [[ -n $SSH_CONNECTION ]]; then prompt fade red && setopt prompt_sp else prompt fade blue && setopt prompt_sp fi RPROMPT='%F{yellow}${vcs_info_msg_0_}' ZPLUG_HOME=~/.zplug if [[ -d $ZPLUG_HOME ]]; then source $ZPLUG_HOME/init.zsh zstyle ":zplug:tag" depth 1 zplug "zsh-users/zsh-completions" zplug "zsh-users/zsh-syntax-highlighting" zplug "zsh-users/zsh-autosuggestions" zplug "yutayamate/bin", as:command, use:"bin/*" # Install plugins if there are plugins that have not been installed if ! zplug check --verbose; then printf "Install? [y/N]: " if read -q; then echo; zplug install fi fi zplug load ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=5' fi alias get-zplug='git clone https://github.com/zplug/zplug $ZPLUG_HOME && source ~/$(basename ${(%):-%N})' command -v xclip > /dev/null 2>&1 && alias pbcopy="xclip -selection primary" && alias pbpaste="xclip -selection primary -o" command -v fzf > /dev/null 2>&1 && export FZF_DEFAULT_OPTS="--reverse" command -v pyenv > /dev/null 2>&1 && eval "$(pyenv init - zsh)" command -v rbenv > /dev/null 2>&1 && eval "$(rbenv init - zsh)" command -v minikube > /dev/null 2>&1 && source <(minikube completion zsh) command -v pomerium-cli > /dev/null 2>&1 && source <(pomerium-cli completion zsh) && compdef _pomerium-cli pomerium-cli command -v syft > /dev/null 2>&1 && source <(syft completion zsh) && compdef _syft syft command -v grype > /dev/null 2>&1 && source <(grype completion zsh) && compdef _grype grype command -v gobuster > /dev/null 2>&1 && source <(gobuster completion zsh) && compdef _gobuster gobuster command -v roc > /dev/null 2>&1 && source <(roc completion zsh) && compdef _roc roc test -e ~/.iterm2_shell_integration.zsh && source ~/.iterm2_shell_integration.zsh test -e ~/.zshrc.local && source ~/.zshrc.local <file_sep>XDG_CONFIG_HOME ?= ${HOME}/.config .DEFAULT_GOAL := help all: install install: xdg emacs git matploitlib tmux ssh vim groovy sqlite screen zsh .PHONY: xdg xdg: @mkdir -p ${XDG_CONFIG_HOME} .PHONY: emacs emacs: @ln -sFinv ${PWD}/.config/emacs ${XDG_CONFIG_HOME}/emacs .PHONY: git git: @ln -sFinv ${PWD}/.config/git ${XDG_CONFIG_HOME}/git .PHONY: matploitlib matploitlib: @ln -sFinv ${PWD}/.config/matplotlib ${XDG_CONFIG_HOME}/matplotlib .PHONY: tmux tmux: @ln -sFinv ${PWD}/.config/tmux ${XDG_CONFIG_HOME}/tmux .PHONY: ssh ssh: @mkdir -p ${HOME}/.ssh @ln -sinv ${PWD}/.ssh/config ${HOME}/.ssh/config .PHONY: vim vim: @mkdir -p ${HOME}/.vim @ln -sinv ${PWD}/.vim/vimrc ${HOME}/.vim/vimrc .PHONY: groovy groovy: @mkdir -p ${HOME}/.groovy @ln -sinv ${PWD}/.groovy/groovysh.rc ${HOME}/.groovy/groovysh.rc .PHONY: sqlite sqlite: @ln -sinv ${PWD}/.sqliterc ${HOME}/.sqliterc .PHONY: screen screen: @ln -sinv ${PWD}/.screenrc ${HOME}/.screenrc .PHONY: zsh zsh: @ln -sinv ${PWD}/.zshrc ${HOME}/.zshrc .PHONY: help help: @echo "Usage: make all | make install | make help" <file_sep>#!/bin/sh exec < /dev/tty cat << EOF Author: $(git config --get user.name) <$(git config --get user.email)> Date: $(date -R) $(cat $1) EOF while true; do read -p "Do you want to finalize this change (y/n)? " yn case $yn in [Yy]* ) exit 0;; [Nn]* ) exit 1;; * ) echo "Please answer 'y' or 'n'";; esac done <file_sep>autopep8 ipython pylint virtualenv <file_sep># dotfiles [![workflows/main.yml](https://github.com/yutayamate/dotfiles/actions/workflows/main.yml/badge.svg)](https://github.com/yutayamate/dotfiles/actions/workflows/main.yml) ![GitHub top language](https://img.shields.io/github/languages/top/yutayamate/dotfiles) Configuration files for my *nix environments ## Usage Run following command on the cloned directory to install the configuration files: ```bash make install ```
b082a251f04191d8a265c1eeaf597d41d28b72fa
[ "Ruby", "Markdown", "Makefile", "Text", "Shell" ]
6
Ruby
yutayamate/dotfiles
5a63f8c6d8433ed59245022fa062dbbd6ef5efa8
b6bfd078583b65b5001ac9930de24c07022b483d
refs/heads/master
<repo_name>andrewdownie/stat2040_majorassignment<file_sep>/Question 1/Question 1.R # # Read in the rice data # riceData <- read.csv(file="C:\\Users\\comma\\OneDrive\\School\\STAT2040\\stat2040_majorassignment\\STAT2040_Rice.csv",head=TRUE,sep=",") # # Q1a) Create box plots for both kinds of rice # boxplot(riceData$ShootDryMass~riceData$variety, ylab='Shoot Dry Mass', xlab="Rice Variety", main="Dry Shoot Weight Against Rice Variety") # # Q1a) Create subsets of the rice data based on the variety of rice # wtData = subset(riceData, riceData$variety=='wt') ANU843Data = subset(riceData, riceData$variety=='ANU843') # # Q1a) Create qqplot for the wt subset # qqnorm(wtData$ShootDryMass, ylab="Actual Shoot Dry Mass", xlab="Theoretical Shoot Dry Mass", main="Q-Q Plot of Shoot Dry Mass for Rice Variety wt") qqline(wtData$ShootDryMass, col='red') # # Q1a) Create qqplot for the anu843 subset # qqnorm(ANU843Data$ShootDryMass, ylab="Actual Shoot Dry Mass", xlab="Theoretical Shoot Dry Mass", main="Q-Q Plot of Shoot Dry Mass for Rice Variety ANU843") qqline(ANU843Data$ShootDryMass, col='red') # # Q1c) pooled variance t procedure # t.test(wtData$ShootDryMass, ANU843Data$ShootDryMass)
cb21f0ebdeb33e192c8b4185c3f4246b3a8d2c88
[ "R" ]
1
R
andrewdownie/stat2040_majorassignment
b71e7f8a4c8fd31d03808b68d6e7bf65eeabcec5
1ea4f936066bf7c661b8246f29983089b1dea562
refs/heads/master
<repo_name>zhenmin-peng/MedGateDeployment<file_sep>/remove.sh echo '--------------' echo '- MedGATE -' echo '--------------' echo '' echo '==> Removing MedGATE service' docker-compose -f ~/MedGateDeployment/docker/docker-compose.yml rm<file_sep>/run.sh #!/bin/bash echo '--------------' echo '- MedGATE -' echo '--------------' echo '' export host_ip=$(ip address | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | grep -v '172.' ) # FOR DEMO, easier # export host_ip=localhost # stop all the running services echo '==> Stopping any running MedGATE services' if [[ -s ~/MedGateDeployment/docker/docker-compose.yml ]] then docker-compose -f ~/MedGateDeployment/docker/docker-compose.yml stop fi echo '==> Configuring enviroment' # create gcp related directories for initialization mkdir -p /gcp/instances/gcp_1/in mkdir -p /gcp/applications mkdir -p /gcp/data mkdir -p /gcp/output echo '==> Pulling containers for MedGATE services' #remove medgate-service container and pull the latest medgate-service image if [ "$(docker ps -aq -f name='medgate-service')" ]; then # cleanup # ?? pull should update - so why delete, docker-compose rm -f medgate-service # pull the latest image docker-compose pull medgate-service fi echo '==> Building Docker Images' docker-compose -f ~/MedGateDeployment/docker/docker-compose.yml up --build -d clear echo '==> Running Docker Images' docker ps <file_sep>/docker/docker-compose.yml version: "3" services: tika: image: logicalspark/docker-tikaserver:latest ports: - "9998:9998" restart: on-failure redis: image: redis:4.0.8 container_name: redis-server # command: ["redis-server", "--appendonly", "yes"] #volumes: # - redis-data:/data ports: - 6379:6379 restart: on-failure elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.1.2 container_name: elasticsearch env_file: ../medgate.config environment: - discovery.type=single-node - xpack.security.enabled=false - xpack.monitoring.enabled=true - xpack.ml.enabled=false - xpack.graph.enabled=false - xpack.watcher.enabled=false - ES_JAVA_OPTS=-Xms512m -Xmx512m volumes: - "esdata:/usr/share/elasticsearch/data" ports: - "9200:9200" - "9300:9300" restart: on-failure kibana: image: docker.elastic.co/kibana/kibana:6.1.2 container_name: kibana environment: - elasticsearch.url= http://elasticsearch:9200 - xpack.monitoring.ui.container.elasticsearch.enabled=true ports: - "5601:5601" depends_on: - elasticsearch #command: ["./wait-for-it.sh", "elasticsearch:9200", "-t 0"] postgres: image: postgres:alpine container_name: postgres env_file: ../medgate.config volumes: - "pgdata:/var/lib/postgresql/data" ports: - "5432:5432" restart: on-failure ftp_server: image: fauria/vsftpd env_file: ../medgate.config container_name: ftpserver volumes: - "ftpdata:/home/vsftpd" environment: - PASV_ADDRESS=${host_ip} - PASV_MIN_PORT=21100 - PASV_MAX_PORT=21110 ports: - "21:21" - "21100-21110:21100-21110" restart: on-failure medgate-service: image: swanseauniversitymedical/medgate-dev:latest container_name: medgate-service env_file: ../medgate.config environment: - ASPNETCORE_ENVIRONMENT=Production - no_proxy=vault,localhost,elasticsearch,tika,postgres,127.0.0.0/8,192.0.0.0/8,172.18.0.0/8 - host_ip=${host_ip} volumes: - "ftpdata:/data" - "/gcp:/gcp" ports: - "80:80" depends_on: - postgres restart: on-failure filebeat: build: ./filebeat/ container_name: filebeat volumes: - /var/run/docker.sock:/var/run/docker.sock # "//var/run/docker.sock" for windows, "/var/run/docker.sock" for linux - /var/lib/docker/containers/:/var/log/monitor/docker/ restart: on-failure depends_on: - elasticsearch metricbeat: build: ./metricbeat/ container_name: metricbeat restart: unless-stopped volumes: - /proc:/hostfs/proc:ro - /sys/fs/cgroup:/hostfs/sys/fs/cgroup:ro - /:/hostfs:ro - /var/run/docker.sock:/var/run/docker.sock depends_on: - elasticsearch command: - "-system.hostfs=/hostfs" gcp_8.4.1: image: swanseauniversitymedical/gcp container_name: gcp_8.4.1 volumes: - "/gcp/instances/gcp_1:/control" - "/gcp/data:/control/data" - "/gcp/output:/control/output" - "/gcp/applications:/control/application" depends_on: - medgate-service command: ["-d","/control"] #- "C:/tmp/inbound:/home/ftpusers/NRDAInbound" #- data-volume:/home/ftpusers/NRDAInbound restart: on-failure nrdagateway: image: swanseauniversitymedical/nrdagateway-dev:latest ports: - "88:80" restart: on-failure pgadmin: image: fenglc/pgadmin4 ports: - "5050:5050" restart: on-failure volumes: esdata: pgdata: ftpdata: <file_sep>/README.md # This is the server installation script to support the MedGATE project ## Get Started Set credentials for PostgreSQL, FTP, WebDAV and ElasticSearch in `medgate.config` as well as the proxy. If docker is not installed run `installdocker.sh` run in console `run.sh` run as server `install.sh` stop server `stop.sh` ### Kibana http://youIP:5601 ### Elasticsearch http://youIP:9200 ## Note gcp-2.8.1 is for test use ONLY. It is **NOT** used in the docker-compose file until the official gcp docker image is released.
718faecd9995ca1e495560fd9626dacdea510dcb
[ "Markdown", "YAML", "Shell" ]
4
Shell
zhenmin-peng/MedGateDeployment
db84214bfa7d1dbf3ba2a0239b77443f196833b4
1b82ba51d588767e95883028498b0ab1ffa97f27
refs/heads/master
<repo_name>ommyo/ommyo-rails<file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController respond_to :html, :json layout 'member' before_action :set_user, only: [:show] def show @omms = @user.omms#.paginate(page: params[:page]) if current_user == @user @omm = Omm.new @omm.messages.build end end def current respond_to do |format| format.html { redirect_to current_user } format.json do @user = current_user @omms = current_user.omms#.paginate(page: params[:page]) render 'show' end end end private def set_user @user = User.find(params[:id]) end end <file_sep>/db/migrate/20131024155037_add_brand_messageid_to_omms.rb class AddBrandMessageidToOmms < ActiveRecord::Migration def change add_column :omms, :brand_messageid, :string end end <file_sep>/app/models/omm_courier.rb class OmmCourier < ActiveRecord::Observer observe :message def after_save(message) if message.author_type == 'User' if message.omm.brand_email.present? || message.omm.brand.email.present? MessageMailer.outgoing_message(message.omm.brand, message).deliver elsif message.omm.brand.iim.present? Romeo.new.outgoing_message(message.omm.brand, message).deliver end end end end <file_sep>/app/mailers/ommceptionist.rb class Ommceptionist def self.process(email) meaningful_recipient = email.to.find { |recipient| recipient[:host] == 'mailer.ommyo.com' } brand, omm = EmailIdentifier.disassemble meaningful_recipient[:token] if brand && omm omm.assign_attributes brand_email: email.from, brand_messageid: email.headers['Message-Id'] omm.assign_attributes brand_subject: email.subject unless email.subject.start_with? "You've been Omm'd!" omm.messages.build author_id: brand.id, author_type: 'Brand', text: email.body omm.save end end end <file_sep>/db/migrate/20131106030311_add_brand_subject_to_omms.rb class AddBrandSubjectToOmms < ActiveRecord::Migration def change add_column :omms, :brand_subject, :string end end <file_sep>/config/routes.rb OmmYo::Application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) resources :messages, :only => [:create] resources :omms, :only => [:show, :index, :new, :create] get 'brand_suggest' => 'brands#new', :as => :new_brand_suggestion post 'brand_suggest' => 'brands#create', :as => :brand_suggestion resources :brands, :only => [:index, :show] devise_for :users, :skip => [:sessions, :registrations] devise_scope :user do get 'sign_in' => 'users/sessions#new', :as => :new_user_session post 'sign_in' => 'users/sessions#create', :as => :user_session match 'sign_out' => 'users/sessions#destroy', :as => :destroy_user_session, :via => [:get, Devise.mappings[:user].sign_out_via] get 'users/cancel' => 'users/registrations#cancel', :as => :cancel_user_registration post 'sign_up' => 'users/registrations#create', :as => :user_registration get 'sign_up' => 'users/registrations#new', :as => :new_user_registration get 'users/edit' => 'users/registrations#edit', :as => :edit_user_registration patch 'users' => 'users/registrations#update', :as => nil put 'users' => 'users/registrations#update', :as => nil delete 'users' => 'users/registrations#destroy', :as => nil end get 'users/current' resources :users, :only => [:show] get 'ommyo-for-businesses' => 'pages#show', id: 'businesses' get 'iim_test' => 'iim_test#get', :as => :get_iim_test post 'iim_test' => 'iim_test#post', :as => :post_iim_test end <file_sep>/db/seeds.rb [ [ 'pdiddy', 'McDonalds', 'McDonald’s coffee is slacking today. I want to have something more...' ], [ 'matt543', 'Starbucks', "I've been waiting in this line for what seems like forever. Starbucks..." ], [ 'johnboy12', 'Burger King', 'I love the whopper at Burger King...' ], [ 'rainbowwarrior', 'Chevrolet', 'The dealer in Charlotte was rude and not helpful. It...' ], [ 'matt543', 'Starbucks', 'Iced coffee at Starbucks gets the people going...' ], [ 'mary-beth', 'American Airlines', 'These delays are killing me. Would it be too much to ask if a real...' ] ].each do |username, brand_name, text| user = User.where(username: username).first_or_initialize(email: <EMAIL>") user.save(validate: false) brand = Brand.where(name: brand_name).first_or_create(logo: File.new("#{Rails.root}/db/seeds/#{brand_name.parameterize}.png", 'rb')) text.sub!(/\.{3}\z/, ' lorem ipsum dolor sit amet, consectetur adipisicing elit,'\ ' sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,'\ ' quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute'\ ' irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.'\ ' Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt'\ ' mollit anim id est laborum.') omm = user.omms.build(brand_id: brand.id) omm.messages.build(text: text, author_id: omm.user_id, author_type: 'User') omm.save end User.new(username: 'drewbug', email: '<EMAIL>').save(validate: false) AdminUser.new(email: '<EMAIL>').save(validate: false) Brand.create(name: 'Email_Test', email: '<EMAIL>', logo: File.new("#{Rails.root}/db/seeds/email_test.png", 'rb')) Brand.create(name: 'IIM_Test', logo: File.new("#{Rails.root}/db/seeds/iim_test.png", 'rb')) <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery with: :null_session prepend_before_action :authenticate_user! def after_sign_in_path_for(resource) resource.is_a?(User) ? omms_path : super end end <file_sep>/app/admin/dashboard.rb ActiveAdmin.register_page "Dashboard" do menu :priority => 1, :label => proc{ I18n.t("active_admin.dashboard") } content :title => proc{ I18n.t("active_admin.dashboard") } do columns do column do panel "Recent Omms" do ul do Omm.order("created_at desc").limit(5).map do |omm| li link_to("(#{ time_ago_in_words(omm.created_at) } ago) #{ truncate(omm.messages.last.text, length: 150, separator: ' ') }", [:admin, omm]) end end end end column do panel "Recent Users" do ul do User.order("created_at desc").limit(5).map do |user| li link_to("(#{ time_ago_in_words(user.created_at) } ago) #{ user.email }", [:admin, user]) end end end end end end end <file_sep>/app/controllers/messages_controller.rb class MessagesController < ApplicationController respond_to :html, :json def create @omm = Omm.find message_params[:omm_id] @omm.messages.build message_params.merge(author_id: @omm.user_id, author_type: 'User') @omm.save if @omm.user == current_user respond_with(@omm) end private def message_params params.require(:message).permit(:omm_id, :text, :recaptcha_challenge_field, :recaptcha_response_field) end end <file_sep>/db/migrate/20131010024400_add_terms_to_brands.rb class AddTermsToBrands < ActiveRecord::Migration def change add_column :brands, :terms, :text, default: '' end end <file_sep>/db/migrate/20130804052630_add_recaptcha_key_options_to_brand.rb class AddRecaptchaKeyOptionsToBrand < ActiveRecord::Migration def up change_column :brands, :recaptcha_public_key, :string, default: "", null: false end def down change_column :brands, :recaptcha_public_key, :string, default: nil, null: true end end <file_sep>/app/controllers/users/registrations_controller.rb class Users::RegistrationsController < Devise::RegistrationsController def sign_up_params devise_parameter_sanitizer.for(:sign_up).delete :login devise_parameter_sanitizer.for(:sign_up).push :username, :email devise_parameter_sanitizer.sanitize(:sign_up) end end <file_sep>/app/models/omm.rb class Omm < ActiveRecord::Base belongs_to :user validates :user, presence: true belongs_to :brand validates :brand, presence: true has_many :messages, inverse_of: :omm accepts_nested_attributes_for :messages validates :messages, presence: true default_scope -> { order('created_at DESC') } end <file_sep>/app/views/brands/index.json.rabl Rabl.configure { |config| config.include_json_root = false } collection @brands node do |b| { id: b.id, keywords: [b.name].concat(b.terms_array), logo: b.logo.url(:w88h88) } end <file_sep>/app/views/users/sessions/create.json.rabl glue resource do attributes :authentication_token => Devise.token_authentication_key end <file_sep>/Gemfile source 'https://rubygems.org' ruby '2.0.0' gem 'rails', '4.0.0' gem 'sass-rails', '~> 4.0.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails' gem 'turbolinks' group :doc do gem 'sdoc', require: false end gem 'devise' gem 'omniauth' gem 'omniauth-facebook' gem 'rabl' gem 'responders', github: 'plataformatec/responders' gem 'inherited_resources', github: 'josevalim/inherited_resources' gem 'ransack', github: 'ernie/ransack' gem 'activeadmin', github: 'gregbell/active_admin', branch: 'rails4' gem 'formtastic', github: 'justinfrench/formtastic' gem 'faraday', github: 'lostisland/faraday' gem 'rails-observers', github: 'rails/rails-observers' gem 'bootstrap-sass' gem 'will_paginate' gem 'bootstrap-will_paginate' gem 'paperclip' gem 'griddler' gem 'nokogiri' gem 'high_voltage' group :development, :test do gem 'sqlite3' gem 'debugger' end group :production do gem 'pg' gem 'aws-sdk' gem 'rails_12factor' end <file_sep>/config/initializers/griddler.rb Griddler.configure do |config| config.processor_class = Ommceptionist config.email_service = :mandrill end module Griddler module Adapters class MandrillAdapter def normalize_params events.map do |event| { to: recipients(event), from: event[:from_email], subject: event[:subject], text: if event[:text].to_s == '' if event[:html].to_s == '' '' else Nokogiri::HTML(event[:html]).text.strip end else event[:text] end, html: '', raw_body: event[:raw_msg], attachments: attachment_files(event), headers: event[:headers] } end end end end class Email def initialize(params) @params = params @to = recipients @from = extract_address(params[:from], config.from) @subject = params[:subject] @body = extract_body @raw_text = params[:text] @raw_html = params[:html] @raw_body = @raw_text || @raw_html @headers = params[:headers] @attachments = params[:attachments] end end end <file_sep>/app/admin/message.rb ActiveAdmin.register Message do actions :index, :show, :destroy end <file_sep>/app/controllers/iim_test_controller.rb class IimTestController < ApplicationController skip_before_action :authenticate_user! respond_to :html def get end def post ActionMailer::Base.mail(from: params[:email], to: '<EMAIL>', body: params[:text].reverse).deliver if params[:email].end_with? '@mailer.ommyo.com' head :ok end end <file_sep>/db/migrate/20130804012257_create_messages.rb class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.text :text t.integer :omm_id t.integer :author_id t.string :author_type t.datetime :created_at end remove_column :omms, :body, :string end end <file_sep>/app/admin/brand.rb ActiveAdmin.register Brand do index do selectable_column id_column column :logo do |brand| link_to(image_tag(brand.logo.url(:w88h88)), admin_brand_path(brand)) end column :name column :email column :iim do |brand| brand.iim.present?.to_s.titlecase end column :created_at column :updated_at column :hidden do |brand| check_box_tag(nil, nil, brand.hidden?, disabled: true, id: nil) end column :disabled do |brand| check_box_tag(nil, nil, brand.disabled?, disabled: true, id: nil) end default_actions end form html: { enctype: "multipart/form-data" } do |f| f.inputs "Brand Details" do f.input :name f.input :logo, as: :file, hint: f.template.image_tag(f.object.logo.url(:w88h88)) f.input :email f.input :iim, as: :file, hint: f.template.text_area_tag(nil, f.object.iim, id: nil, rows: f.object.iim.to_s.lines.count+1, disabled: true) f.input :terms, placeholder: 'Please place each term on a separate line in this textbox; no other separator neccesary (or desired).', input_html: { style: 'width: 125px; height:: 200px' } f.input :recaptcha_public_key f.input :hidden, as: :boolean f.input :disabled, as: :boolean end f.actions end show do |s| attributes_table do row :id row :name row :logo do image_tag(s.logo.url(:w88h88)) end row :created_at row :updated_at row :recaptcha_public_key row :email row :iim do if s.iim.present? content_tag 'form', text_area_tag(nil, s.iim, id: nil, rows: s.iim.to_s.lines.count+1, disabled: true) else span I18n.t('active_admin.empty'), :class => "empty" end end row :terms do if s.terms.present? s.terms_array.each do |term| span term, style: 'padding: 5px; font-weight: bold; color: #ffffff; border-radius: 3px; background-color: #5bc0de' end else span I18n.t('active_admin.empty'), :class => "empty" end end row :hidden do check_box_tag nil, nil, s.hidden?, disabled: true, id: nil end row :disabled do check_box_tag nil, nil, s.disabled?, disabled: true, id: nil end end end controller do def permitted_params params.permit brand: [:name, :recaptcha_public_key, :logo, :email, :iim, :terms, :hidden, :disabled] end end end <file_sep>/db/migrate/20130803131528_remove_admin_from_users.rb require_relative '20130802164859_add_admin_to_users' class RemoveAdminFromUsers < ActiveRecord::Migration def change revert AddAdminToUsers end end <file_sep>/app/mailers/message_mailer.rb class MessageMailer < ActionMailer::Base def outgoing_message(brand, message) @brand = brand @message = message mail to: "#{@brand.name} <#{@message.omm.brand_email or @brand.email}>", from: "OmmYo! <#{ EmailIdentifier.assemble(@brand, @message) }>", subject: @message.omm.brand_subject.is_a?(String) ? @message.omm.brand_subject : "You've been Omm'd! (##{ @brand.omms.reverse.index(@message.omm)+1 })" if @message.omm.brand_messageid headers['In-Reply-To'] = @message.omm.brand_messageid end end end <file_sep>/app/views/omms/index.json.rabl Rabl.configure { |config| config.include_json_root = false } collection @omms node do |omm| { id: omm.id, logo: omm.brand.logo.url(:w88h88), author: omm.messages.first.author.name, text: omm.messages.first.text, age: time_ago_in_words(omm.messages.first.created_at) + ' ago' } end <file_sep>/config/initializers/high_voltage.rb HighVoltage.tap do |config| config.routes = false config.layout = false end <file_sep>/app/assets/javascripts/member.js // //= require jquery //= require autogrow.min //= require_self //= require_tree ./member // <file_sep>/app/controllers/omms_controller.rb class OmmsController < ApplicationController respond_to :html, :json layout 'member' before_action :set_omm, only: [:show] def index @omms = Omm.joins(:brand).where brands: { hidden: false } @omm = Omm.new @omm.messages.build respond_with(@omms) end def show render template: 'errors/forbidden', status: :forbidden and return if @omm.user != current_user @omm.update_attributes unread: false if @omm.unread? @messages = @omm.messages.paginate(page: params[:page]) if current_user == @omm.user @message = @omm.messages.build end respond_with(@omm) end def new @omm = Omm.new @omm.messages.build respond_with(@omm) end def create params['omm']['brand_id'] = params['omm']['brand_id'].first @omm = current_user.omms.build omm_params @omm.messages.build message_params.merge(author_id: @omm.user_id, author_type: 'User') @omm.save respond_with(@omm) end private def set_omm @omm = Omm.find(params[:id]) end def omm_params params.require(:omm).permit(:brand_id) end def message_params params.require(:message).permit(:text, :recaptcha_challenge_field, :recaptcha_response_field) end end <file_sep>/app/mailers/romeo.rb class Romeo def outgoing_message(brand, message) @brand = brand @message = message soliloquize end def soliloquize dynamic_iim = @brand.iim.dup @brand.iim.scan(/<omm(OP)?>(.+?)<\/yo>/) do |tag| method = "_#{tag[1]}" # Because some of our tags start with a number, something Ruby methods can't do :( method_op = "#{method}_OP" replacement = if tag[0] == "OP" respond_to?(method_op, true) ? send(method_op) : :delete_line elsif respond_to?(method, true) send(method) end case replacement when :delete_line dynamic_iim = dynamic_iim.split("\n").delete_if { |line| line.include? "<omm#{tag[0]}>#{tag[1]}</yo>" }.join("\n") else replacement = replacement.to_s replacement.gsub!(' ', '<SP>') replacement.gsub!("\r\n", '<BR>') replacement.gsub!("\r", '<BR>') replacement.gsub!("\n", '<BR>') dynamic_iim.gsub!("<omm#{tag[0]}>#{tag[1]}</yo>", replacement) end end dynamic_iim << "\nURL GOTO=about:blank" Soliloquy.new dynamic_iim end private def _omm text = @message.text text << "\n\n" text << 'What is OmmYo and How Can It Help Your Business? Find out at:' + "\n" + 'http://www.ommyo.com/ommyo-for-businesses' end def _subject 'OmmYo' end def _addressee @brand.name end def _title 'Mr' # TODO # either Mr or Ms (capitalized no period) end def _title_allcaps 'MR' # TODO # either MR or MS end def _title_alllower 'mr' # TODO # either mr or ms end def _gender 'male' # TODO # all lowercase... either male or female end def _fullname_OP send('_fullname') end def _fullname @message.author.name end def _firstname_OP send('_firstname') end def _firstname @message.author.name end def _lastname_OP send('_lastname') end def _lastname 'Yo' # TODO # lastname end def _middlename :delete_line # TODO # middlename end def _middlename_initial :delete_line # TODO # first character of the middlename, (capitalized) end def _email EmailIdentifier.assemble(@brand, @message) end def _address_1 '123 OmmYo Street' # TODO # housenumber and street name. No periods (in the case of St. you must write out Street) end def _address_1_street 'OmmYo Street' # TODO # the street name on its own (required by some forign forms) end def _address_1_num '123' # TODO # the house number on its own (required by some forign forms) end def _address_2 :delete_line # TODO # second line (this one is not required on a single form) end def _city 'Harrisburg' # TODO # city end def _state 'PA' # TODO # state abbreviation (capitalized like PA) end def _state_lowercase 'pa' # TODO # state abbreviation (lowercase like pa) end def _state_full 'Pennsylvania' # TODO # state written out, first character capitalized (like Pennsylvania) end def _state_full_caps 'PENNSYLVANIA' # TODO # state written out as above except all caps end def _zip '17111' # TODO # zip code end def _zip_underscore '1711_1' # TODO # zip code written XXXX_X end def _zip_sp '1711 1' # TODO # zip code written XXXX<SP>X end def _country_name 'USA' # TODO # this is occasionally required. If it is, let's just put in USA end def _7178675309 '7179876543' # TODO # full phone number, just numbers end def _717 '717' # TODO # area code end def _867 '987' # TODO # first part of phone# end def _5309 '6543' # TODO # second part of phone# end def _530_9 '654_3' # TODO # second part of phone # with underscore end def _DOB_month '01' # TODO # Date of Birth, month, two digits (ex 08) end def _DOB_day '01' # TODO # Date of Birth, day, two digits (ex 08) end def _DOB_year '1981' # TODO # Date of Birth, year, four digits (ex 1908) end def _DOB_month_short '1' # TODO # Date of Birth, month, as is (ex 8) end def _DOB_day_short '1' # TODO # Date of Birth, day, as is (ex 8) end def _DOB_year_short '81' # TODO # Date of Birth, year, two digits (ex 98) end def _age '21' # TODO # the age... could be calculated from DOB, i guess end def _company 'OmmYo' end def _DOT_month '01' # TODO # Date to Transaction month, two digits (ex 08) end def _DOT_day '01' # TODO # Date to Transaction day, two digits (ex 08) end def _DOT_year '2013' # TODO # Date to Transaction month, four digits (ex 1908) end def _DOT_month_short '1' # TODO # Date to Transaction month, as is (ex 8) end def _DOT_day_short '1' # TODO # Date to Transaction day, as is (ex 8) end def _DOT_year_short '13' # TODO # Date to Transaction month, last two digits (ex 98) end def _DOT_time_hour '09' # TODO # Date to Transaction hour, two digits (ex 08) end def _DOT_time_minute '00' # TODO # Date to Transaction minute, two digits (ex 08) end def _DOT_time_hour_short '9' # TODO # Date to Transaction hour, as is (ex 8) end def _DOT_time_minute_short '0' # TODO # Date to Transaction minute, as is (ex 8) end def _DOT_time_am_pm 'AM' # TODO # Date to Transaction AM or PM ... just like that. one or the other. end def _event_zip '17111' # TODO # zip code of the transaction... for now we probably want to use the default zip but ultimately we want to use the GPS of the omm end def _event_location 'Harrisburg' # TODO # location of the transaction... takes any short string. We probably want to use the default city. end def _event_state 'PA' # TODO # state of the transaction end def _store_number :delete_line # TODO # store number end def _order_num :delete_line # TODO # order number end def _member_num :delete_line # TODO # member number end def _flight_num :delete_line # TODO # airlines only. the flight number if we ever take this info. end def _product_name :delete_line # TODO # the name of the product or service end class Soliloquy def initialize(iim) @base64 = Base64.strict_encode64(iim) end def deliver Faraday.post 'http://172.16.17.32:7977/run_macro', { base64: @base64 } end end end <file_sep>/app/models/message.rb class Message < ActiveRecord::Base belongs_to :omm validates :omm, presence: true belongs_to :author, :polymorphic => true default_scope -> { order('created_at ASC') } attr_accessor :recaptcha_challenge_field attr_accessor :recaptcha_response_field validate :recaptcha_presence def recaptcha_presence if omm.brand.recaptcha_public_key.present? if @recaptcha_challenge_field.blank? || @recaptcha_response_field.blank? errors.add(:recaptcha_public_key, omm.brand.recaptcha_public_key) errors.add(:recaptcha_challenge_field, omm.brand.recaptcha_challenge_field) end end end end <file_sep>/app/models/user.rb class User < ActiveRecord::Base devise :database_authenticatable, :token_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :authentication_keys => [:login], :reset_password_keys => [:login] before_save :ensure_authentication_token has_many :omms, :dependent => :destroy attr_accessor :login validates :username, presence: true, uniqueness: { case_sensitive: false } validates :email, presence: true, uniqueness: { case_sensitive: false } def name username end def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where("lower(username) = :login OR lower(email) = :login", login: login.downcase).first else where(conditions).first end end end <file_sep>/app/models/brand.rb class Brand < ActiveRecord::Base has_many :omms, :dependent => :destroy has_attached_file :logo, :path => ":rails_root/public/system/:attachment/:id/:style", :url => "/system/:attachment/:id/:style", :styles => { :w88h88 => "88x88#" } before_save do self.iim = iim.read if iim.is_a? ActionDispatch::Http::UploadedFile end before_save do self.terms = terms.strip.gsub("\r", '') end validate :recaptcha_public_key_validation def recaptcha_public_key_validation if recaptcha_public_key.present? api_response = Faraday.get 'http://www.google.com/recaptcha/api/challenge', { :k => recaptcha_public_key } error = api_response.body.match(/^(?:document.write\('Input error: )(.*)(?:\\n'\);)$/) errors.add(:recaptcha_public_key, error[1]) if error end end def recaptcha_challenge_field api_response = Faraday.get 'http://www.google.com/recaptcha/api/challenge', { :k => recaptcha_public_key } match = api_response.body.match(/^(?: challenge : ')(.*)(?:',)$/) return match[1] end def terms_array terms.split("\n") end end <file_sep>/db/migrate/20130907024246_add_unread_to_omms.rb class AddUnreadToOmms < ActiveRecord::Migration def change add_column :omms, :unread, :boolean, default: false end end <file_sep>/app/views/omms/show.json.rabl Rabl.configure { |config| config.include_json_root = false } collection @messages node do |message| { author: message.author.name, text: message.text, age: time_ago_in_words(message.created_at) + ' ago' } end <file_sep>/app/controllers/brands_controller.rb class BrandsController < ApplicationController respond_to :html, :json layout 'member' before_action :set_brand, only: [:show] def show @omms = @brand.omms.paginate(page: params[:page]) respond_with(@brand) end def index @brands = Brand.where(disabled: false) respond_with(@brands) end def new end def create redirect_to omms_path, flash: { success: "Thanks, #{ params[:name] } has been added to our to-do list!" } end private def set_brand @brand = Brand.find(params[:id]) end end <file_sep>/app/mailers/email_identifier.rb module EmailIdentifier KEY = 456 module_function def assemble(brand, message) token = "#{brand.id+KEY}_#{message.omm.id+KEY}" return "#{<EMAIL>" end def disassemble(token) brand_id, omm_id = token.split('_') brand_id = brand_id.to_i - KEY omm_id = omm_id.to_i - KEY brand = Brand.find_by_id brand_id omm = Omm.find_by_id omm_id return brand, omm end end <file_sep>/db/migrate/20130908054549_add_brand_email_to_omms.rb class AddBrandEmailToOmms < ActiveRecord::Migration def change add_column :omms, :brand_email, :string end end <file_sep>/db/migrate/20130803215921_remove_trackable_from_admin_users.rb class RemoveTrackableFromAdminUsers < ActiveRecord::Migration def change remove_column :admin_users, :sign_in_count, :integer remove_column :admin_users, :current_sign_in_at, :datetime remove_column :admin_users, :last_sign_in_at, :datetime remove_column :admin_users, :current_sign_in_ip, :string remove_column :admin_users, :last_sign_in_ip, :string end end
9b50d20ec88eb9a2abc670ca8aeb727afada37df
[ "JavaScript", "Ruby" ]
38
Ruby
ommyo/ommyo-rails
98fc743fd4bc9e7dc28ba04ab16181a96d0a2da1
3aae355a0b09a6ed6130434d2f66a6da38d36c97
refs/heads/main
<repo_name>Brostix/caja-de-excusas-1<file_sep>/index.js function linea1(){ let who = ['The dog','My grandma','His turtle','My bird']; let action = ['ate','peed','crushed','broke']; let what = ['my homework', 'the keys', 'the car']; let when = ['before the class','right on time','when I finished','during my lunch','while I was praying']; return who[Math.floor(Math.random()*who.length)]+ " " + action[Math.floor(Math.random()*action.length)]+ " " +what[Math.floor(Math.random()*what.length)]+ " " +when[Math.floor(Math.random()*when.length)]; } console.log(linea1())
61835274f99a06a159b21acdfe40524bdbf1a0bf
[ "JavaScript" ]
1
JavaScript
Brostix/caja-de-excusas-1
2958da596dc4405ac83ce91ff6a4cf195d986186
02d9864f1eaaa9733218f875bbd8f593e869d452
refs/heads/master
<repo_name>nychollas09/Curso-Alga-Works<file_sep>/Front-End/AlgaWorksUI/src/app/shared/services/validar-formulario.service.ts import { Injectable } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { MessageService } from 'primeng/components/common/messageservice'; @Injectable({ providedIn: 'root' }) export class ValidarFormularioService { constructor(private messageService: MessageService) { } validarFormulario(formulario: FormGroup) { console.log(formulario.errors); /*for (let campo of formulario.controls) { }*/ } } <file_sep>/Back-End/algamoney-api/src/main/java/br/com/falcao/algamoney/api/config/ResourceServerConfig.java package br.com.falcao.algamoney.api.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler; @Profile("oauth-security") @Configuration @EnableWebSecurity @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) // Habilitar segurança nos métodos public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; // Seta a senha do usuário cryptografada @Autowired public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } /* Configuração de autoriazação das requisições */ @Override public void configure(HttpSecurity http) throws Exception { /* Tradução = Para qualuqer requisição, é necessário estrar autenticado */ http.authorizeRequests() .antMatchers("/categorias").permitAll() // Somente "/categorias" não necessita de autenticação .anyRequest().authenticated() .and() // Desabilitando a criação de seção no servidor (Não ira manter estado de nada) STATELESS) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() // Desabilidando o Cros Side Request (Previne ataques javascript na aplicação) .csrf().disable(); } // Define que por parte do servidor também vai ser stateless @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.stateless(true); } // Gera a senha cryptografada @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } //Segurança nos métodos @Bean public MethodSecurityExpressionHandler createExpressionHandler() { return new OAuth2MethodSecurityExpressionHandler(); } } <file_sep>/Front-End/AlgaWorksUI/src/app/lancamento-cadastro/lancamento-cadastro.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ValidarFormularioService } from '../shared/services/validar-formulario.service'; @Component({ selector: 'app-lancamento-cadastro', templateUrl: './lancamento-cadastro.component.html', styleUrls: ['./lancamento-cadastro.component.css'] }) export class LancamentoCadastroComponent implements OnInit { constructor( private formBuilder: FormBuilder, private validarFormularioService: ValidarFormularioService ) { } ngOnInit() { this.iniciarFormulario(); } formularioLancamento: FormGroup; iniciarFormulario() { this.formularioLancamento = this.formBuilder.group({ vencimento: ['', [Validators.required]], pagamentoOuRecebimento: [''], descricao: ['', [Validators.required, Validators.minLength(5)]], valor: ['', [Validators.required]], categoria: ['', [Validators.required]], pessoa: ['', [Validators.required]], observacao: [''] }); } salvarLancamento() { let retorno = this.validarFormularioService.validarFormulario(this.formularioLancamento); } /* Temporário */ tipos = [ { label: 'Receita', value: 'RECEITA' }, { label: 'Despesa', value: 'DESPESA' }, ]; categorias = [ { label: 'Alimentação', value: 1 }, { label: 'Transporte', value: 2 }, ]; pessoas = [ { label: '<NAME>', value: 4 }, { label: '<NAME>', value: 9 }, { label: '<NAME>', value: 3 }, ]; } <file_sep>/README.md # Curso Alga Works <file_sep>/Front-End/AlgaWorksUI/src/app/pessoas-pesquisa/pessoas-pesquisa.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-pessoas-pesquisa', templateUrl: './pessoas-pesquisa.component.html', styleUrls: ['./pessoas-pesquisa.component.css'] }) export class PessoasPesquisaComponent implements OnInit { constructor() { } ngOnInit() { } pessoas = [ { nome: '<NAME>', cidade: 'Uberlândia', estado: 'MG', ativo: true }, { nome: '<NAME>', cidade: 'São Paulo', estado: 'SP', ativo: false }, { nome: '<NAME>', cidade: 'Florianópolis', estado: 'SC', ativo: true }, { nome: '<NAME>', cidade: 'Curitiba', estado: 'PR', ativo: true }, { nome: '<NAME>', cidade: 'Rio de Janeiro', estado: 'RJ', ativo: false }, { nome: '<NAME>', cidade: 'Uberlândia', estado: 'MG', ativo: true } ]; } <file_sep>/Back-End/algamoney-api/src/main/java/br/com/falcao/algamoney/api/service/PessoaService.java package br.com.falcao.algamoney.api.service; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import br.com.falcao.algamoney.api.model.Pessoa; import br.com.falcao.algamoney.api.repository.PessoaRepository; @Service // Diz que vai ser um componente do Spring, assim, habilidando injeções. public class PessoaService { @Autowired private PessoaRepository pessoaRepository; public Pessoa atualizar(Long codigo, Pessoa pessoa) { Pessoa pessoaSalva = buscarPessoaPeloCodigo(codigo); // BeansUtils copia a propriedade de um alvo para o outro (Pessoa para pessoaBuscada) e, // Como opção, podemos passar um parâmetro a ser iguinorado como código no exemplo do PUT BeanUtils.copyProperties(pessoa, pessoaSalva, "codigo"); return pessoaRepository.save(pessoaSalva); } public void atualizarPropriedadeAtivo(Long codigo, Boolean ativo) { Pessoa pessoaSalva = buscarPessoaPeloCodigo(codigo); pessoaSalva.setAtivo(ativo); pessoaRepository.save(pessoaSalva); } public Pessoa buscarPessoaPeloCodigo(Long codigo) { Pessoa pessoaSalva = pessoaRepository.findOne(codigo); if (pessoaSalva == null) { // Usando o tratamento de exceção criado no ExceptionHandler // O número um é a quantidade mínima de linhas que esperamos encontrar, // mas não vai ter caso o código fornecido não exista no banco de dados throw new EmptyResultDataAccessException(1); } return pessoaSalva; } } <file_sep>/Back-End/algamoney-api/src/main/java/br/com/falcao/algamoney/api/token/RefreshTokenPostProcessor.java package br.com.falcao.algamoney.api.token; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import br.com.falcao.algamoney.api.config.property.AlgamoneyApiProperty; //Vai ser executado depois do acesse token ser criado (Funciona de forma semelhando ao Intercepter) @Profile("oauth-security") @ControllerAdvice public class RefreshTokenPostProcessor implements ResponseBodyAdvice<OAuth2AccessToken> { @Autowired private AlgamoneyApiProperty algamoneyApiProperty; @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { // Retorna o corpo da requição quando ela existir (Logo sera true somente nesse momento). return returnType.getMethod().getName().equals("postAccessToken"); } // Esse método só vai ser execuado quando o Método Supports(Acima) retornar true @Override public OAuth2AccessToken beforeBodyWrite(OAuth2AccessToken body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { // Converte a request para HttpServletRequest HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest(); // Converte response para HttpServletResponse HttpServletResponse resp = ((ServletServerHttpResponse) response).getServletResponse(); // Convertendo o body para disponibilizar os métodos do OAuth2 DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) body; // Pega o valor do refresh token gerado String refreshToken = body.getRefreshToken().getValue(); // Adicionando o Refresh token ao Cookie adicionarRefreshTokenNoCookie(refreshToken, req, resp); // Removendo o Refresh Token do body removerRefreshTokenDoBody(token); return body; } // Remove o RefreshToken da resposta private void removerRefreshTokenDoBody(DefaultOAuth2AccessToken token) { token.setRefreshToken(null); } // Adiciona O RefreshToken no Cookie private void adicionarRefreshTokenNoCookie(String refreshToken, HttpServletRequest req, HttpServletResponse resp) { // Criando o Cookie com o nome de "refreshToken" e salvando o refreshToken nele Cookie refreshTokenCookie = new Cookie("refreshToken", refreshToken); // Setando a disponibilidade do RefreshToken refreshTokenCookie.setHttpOnly(true); // Diz se o refreshToken é funcional em https refreshTokenCookie.setSecure(algamoneyApiProperty.getSeguranca().isEnableHttps()); // Caminho que o RefreshToken vai refreshTokenCookie.setPath(req.getContextPath() + "/oauth/token"); // Tempo de Expiração do Cookie refreshTokenCookie.setMaxAge(2592000); // 30 dias // Adicionando o refreshToken na resposta(Dentro do Cookie) resp.addCookie(refreshTokenCookie); } } <file_sep>/Front-End/AlgaWorksUI/src/app/shared/shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ToastModule } from 'primeng/toast'; import { MessageService } from 'primeng/components/common/messageservice'; import { ValidarFormularioService } from './services/validar-formulario.service'; @NgModule({ imports: [ CommonModule, ToastModule ], declarations: [], providers: [ValidarFormularioService, MessageService] }) export class SharedModule { }
04694f4d1d18a36f71daa9fade82d2b9182397b5
[ "Markdown", "Java", "TypeScript" ]
8
TypeScript
nychollas09/Curso-Alga-Works
c32045b759ead5feb002cce828085fac2e398939
da949efd49b91bab85441410868921b6ff4c84b3
refs/heads/master
<file_sep>package BusinessLogic; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import dbUtil.DbHelper; import dbUtil.IConnectionProvider; import dbUtil.JdbcProvider; import Entity.Order; public class OrderLogic { private IConnectionProvider connectionProvider = null; private String sourceName = "estore"; private DbHelper dbHelper; public OrderLogic(){ try { connectionProvider = new JdbcProvider( "com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/", "root","<PASSWORD>"); } catch (ClassNotFoundException e) { e.printStackTrace(); } dbHelper = new DbHelper(connectionProvider, sourceName); } //添加订单 public int add(int userId, String sku, int addressId, String oid) throws Exception{ String sql = "SELECT C_Number FROM cart WHERE U_Id=? AND SKU=?"; ResultSet rs = dbHelper.query(sql, userId, sku); int number = 0; String deliveryName = "", deliveryPhone="", deliveryAddress=""; String picstr = ""; double price=0; String name=""; if(rs.next()){ number = rs.getInt(1); } sql = "SELECT * FROM deliveryaddress WHERE D_No = ?"; rs = dbHelper.query(sql, addressId); if(rs.next()){ deliveryName = rs.getString(2); deliveryPhone = rs.getString(4); deliveryAddress = rs.getString(3); } sql = "SELECT * FROM products, productspic WHERE products.P_Id = productspic.P_Id AND products.SKU = ?"; rs = dbHelper.query(sql, sku); if(rs.next()){ picstr = rs.getString(15); if(rs.getDouble(8) >0) { price = rs.getDouble(8); } else{ price = rs.getDouble(7); } name = rs.getString(5); } sql = "INSERT INTO orders(O_Id, U_Id, SKU, O_Name, O_Price, O_Number, O_Date, O_Status, O_DeliveryName, O_DeliveryAddress, O_DeliveryPhone, O_Pic) values(?,?,?,?,?,?,?,?,?,?,?,?)"; int i = dbHelper.insertPrepareSQL(sql, oid, userId, sku, name, price, number, new Date(), 0, deliveryName, deliveryAddress, deliveryPhone, picstr); return i; } //find all oid public List<String> findAllOid() throws Exception{ String sql = "SELECT O_Id FROM orders ORDER BY O_Date DESC"; List<String> oids = new ArrayList<String>(); ResultSet rs = dbHelper.query(sql); while(rs.next()){ if(rs.getRow() == 1){ String[] oid = rs.getString(1).split("-"); oids.add(oid[0]); } else{ String aoids = rs.getString(1); String[] oid1 = aoids.split("-"); boolean ifexists = false; for(int i = 0; i<oids.size(); i++){ if(oid1[0].equals(oids.get(i))){ ifexists = true; } } if(!ifexists){ oids.add(oid1[0]); } } } return oids; } //find items in one order public List<Order> findAllItems(String oid) throws Exception{ String[] oids = oid.split("-"); String sql = "SELECT * FROM orders WHERE O_Id like '"+ oids[0] +"%'"; List<Order> items = new ArrayList<Order>(); ResultSet rs = dbHelper.query(sql); while(rs.next()){ Order item = new Order(); item.setOId(rs.getString(1)); item.setUId(rs.getInt(2)); item.setSKU(rs.getString(3)); item.setOName(rs.getString(4)); item.setOPrice(rs.getDouble(5)); item.setONumber(rs.getInt(6)); item.setODate(rs.getDate(7)); item.setOSentDate(rs.getDate(8)); item.setOConfirmDate(rs.getDate(9)); item.setOStatus(rs.getInt(10)); item.setODeliveryName(rs.getString(11)); item.setODeliveryAddress(rs.getString(12)); item.setODeliveryPhone(rs.getString(13)); item.setOLocation(rs.getString(14)); item.setOPic(rs.getString(15)); items.add(item); } return items; } //find all oid by userId public List<String> findOid(int userId) throws Exception{ String sql = "SELECT O_Id FROM orders WHERE U_Id=? ORDER BY O_Date DESC"; List<String> oids = new ArrayList<String>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ oids.add(rs.getString(1)); } return oids; } //find all oid to pay public List<String> findPayOid(int userId) throws Exception{ String sql = "SELECT O_Id FROM orders WHERE U_Id=? AND O_Status = 0 ORDER BY O_Date DESC"; List<String> oids = new ArrayList<String>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ oids.add(rs.getString(1)); } return oids; } //find all oid to remind public List<String> findRemindOid(int userId) throws Exception{ String sql = "SELECT O_Id FROM orders WHERE U_Id=? AND (O_Status = 1 OR O_Status = 2) ORDER BY O_Date DESC"; List<String> oids = new ArrayList<String>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ oids.add(rs.getString(1)); } return oids; } //find all oid to confirm public List<String> findConfirmOid(int userId) throws Exception{ String sql = "SELECT O_Id FROM orders WHERE U_Id=? AND O_Status = 3 ORDER BY O_Date DESC"; List<String> oids = new ArrayList<String>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ oids.add(rs.getString(1)); } return oids; } //find all oid to comment public List<String> findCommentOid(int userId) throws Exception{ String sql = "SELECT O_Id FROM orders WHERE U_Id=? AND O_Status = 4 ORDER BY O_Date DESC"; List<String> oids = new ArrayList<String>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ oids.add(rs.getString(1)); } return oids; } //find all items in an oid public List<Order> findItems(int userId, String oid) throws Exception{ String[] oids = oid.split("-"); String sql = "SELECT * FROM orders WHERE U_Id=? AND O_Id like '"+ oids[0] +"%'"; List<Order> items = new ArrayList<Order>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ Order item = new Order(); item.setOId(rs.getString(1)); item.setUId(rs.getInt(2)); item.setSKU(rs.getString(3)); item.setOName(rs.getString(4)); item.setOPrice(rs.getDouble(5)); item.setONumber(rs.getInt(6)); item.setODate(rs.getDate(7)); item.setOSentDate(rs.getDate(8)); item.setOConfirmDate(rs.getDate(9)); item.setOStatus(rs.getInt(10)); item.setODeliveryName(rs.getString(11)); item.setODeliveryAddress(rs.getString(12)); item.setODeliveryPhone(rs.getString(13)); item.setOLocation(rs.getString(14)); item.setOPic(rs.getString(15)); items.add(item); } return items; } //find all to pay public List<Order> findPayItems(int userId, String oid) throws Exception{ String[] oids = oid.split("-"); String sql = "SELECT * FROM orders WHERE U_Id=? AND O_Status=0 AND O_Id like '"+ oids[0] +"%'"; List<Order> items = new ArrayList<Order>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ Order item = new Order(); item.setOId(rs.getString(1)); item.setUId(rs.getInt(2)); item.setSKU(rs.getString(3)); item.setOName(rs.getString(4)); item.setOPrice(rs.getDouble(5)); item.setONumber(rs.getInt(6)); item.setODate(rs.getDate(7)); item.setOSentDate(rs.getDate(8)); item.setOConfirmDate(rs.getDate(9)); item.setOStatus(rs.getInt(10)); item.setODeliveryName(rs.getString(11)); item.setODeliveryAddress(rs.getString(12)); item.setODeliveryPhone(rs.getString(13)); item.setOLocation(rs.getString(14)); item.setOPic(rs.getString(15)); items.add(item); } return items; } //find all to remind public List<Order> findRemindItems(int userId, String oid) throws Exception{ String[] oids = oid.split("-"); String sql = "SELECT * FROM orders WHERE U_Id=? AND (O_Status=1 OR O_Status=2) AND O_Id like '"+ oids[0] +"%'"; List<Order> items = new ArrayList<Order>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ Order item = new Order(); item.setOId(rs.getString(1)); item.setUId(rs.getInt(2)); item.setSKU(rs.getString(3)); item.setOName(rs.getString(4)); item.setOPrice(rs.getDouble(5)); item.setONumber(rs.getInt(6)); item.setODate(rs.getDate(7)); item.setOSentDate(rs.getDate(8)); item.setOConfirmDate(rs.getDate(9)); item.setOStatus(rs.getInt(10)); item.setODeliveryName(rs.getString(11)); item.setODeliveryAddress(rs.getString(12)); item.setODeliveryPhone(rs.getString(13)); item.setOLocation(rs.getString(14)); item.setOPic(rs.getString(15)); items.add(item); } return items; } //find all to confirm public List<Order> findConfirmItems(int userId, String oid) throws Exception{ String[] oids = oid.split("-"); String sql = "SELECT * FROM orders WHERE U_Id=? AND O_Status=3 AND O_Id like '"+ oids[0] +"%'"; List<Order> items = new ArrayList<Order>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ Order item = new Order(); item.setOId(rs.getString(1)); item.setUId(rs.getInt(2)); item.setSKU(rs.getString(3)); item.setOName(rs.getString(4)); item.setOPrice(rs.getDouble(5)); item.setONumber(rs.getInt(6)); item.setODate(rs.getDate(7)); item.setOSentDate(rs.getDate(8)); item.setOConfirmDate(rs.getDate(9)); item.setOStatus(rs.getInt(10)); item.setODeliveryName(rs.getString(11)); item.setODeliveryAddress(rs.getString(12)); item.setODeliveryPhone(rs.getString(13)); item.setOLocation(rs.getString(14)); item.setOPic(rs.getString(15)); items.add(item); } return items; } //find all to comment public List<Order> findCommentItems(int userId, String oid) throws Exception{ String[] oids = oid.split("-"); String sql = "SELECT * FROM orders WHERE U_Id=? AND O_Status=4 AND O_Id like '"+ oids[0] +"%'"; List<Order> items = new ArrayList<Order>(); ResultSet rs = dbHelper.query(sql, userId); while(rs.next()){ Order item = new Order(); item.setOId(rs.getString(1)); item.setUId(rs.getInt(2)); item.setSKU(rs.getString(3)); item.setOName(rs.getString(4)); item.setOPrice(rs.getDouble(5)); item.setONumber(rs.getInt(6)); item.setODate(rs.getDate(7)); item.setOSentDate(rs.getDate(8)); item.setOConfirmDate(rs.getDate(9)); item.setOStatus(rs.getInt(10)); item.setODeliveryName(rs.getString(11)); item.setODeliveryAddress(rs.getString(12)); item.setODeliveryPhone(rs.getString(13)); item.setOLocation(rs.getString(14)); item.setOPic(rs.getString(15)); items.add(item); } return items; } //find an order public List<Order> findById(String oid) throws Exception{ String[] oids = oid.split("-"); String sql = "SELECT * FROM orders WHERE O_Id like '"+ oids[0]+"%'"; ResultSet rs = dbHelper.query(sql); List<Order> items = new ArrayList<Order>(); while(rs.next()){ Order item = new Order(); item.setOId(rs.getString(1)); item.setUId(rs.getInt(2)); item.setSKU(rs.getString(3)); item.setOName(rs.getString(4)); item.setOPrice(rs.getDouble(5)); item.setONumber(rs.getInt(6)); item.setODate(rs.getDate(7)); item.setOSentDate(rs.getDate(8)); item.setOConfirmDate(rs.getDate(9)); item.setOStatus(rs.getInt(10)); item.setODeliveryName(rs.getString(11)); item.setODeliveryAddress(rs.getString(12)); item.setODeliveryPhone(rs.getString(13)); item.setOLocation(rs.getString(14)); item.setOPic(rs.getString(15)); items.add(item); } return items; } //confirm order public int confirm(String oid) throws Exception{ String sql = "SELECT O_Id FROM orders WHERE O_Id like '"+oid+"%'"; ResultSet rs = dbHelper.query(sql); List<String> oids = new ArrayList<String>(); int update = 0; while(rs.next()){ oids.add(rs.getString(1)); } for(int i = 0; i<oids.size(); i++){ sql = "UPDATE orders SET O_ConfirmDate=?, O_Status=4 WHERE O_Id=?"; update = dbHelper.updatePrepareSQL(sql, new Date(), oids.get(i)); } return update; } //cancel order public int cancel(String oid) throws Exception{ String[] aoid = oid.split("-"); String sql = "SELECT O_Id FROM orders WHERE O_Id like '"+aoid[0]+"%'"; ResultSet rs = dbHelper.query(sql); List<String> oids = new ArrayList<String>(); int update = 0; while(rs.next()){ oids.add(rs.getString(1)); } for(int i = 0; i<oids.size(); i++){ sql = "UPDATE orders SET O_Status=5 WHERE O_Id=?"; update = dbHelper.updatePrepareSQL(sql, oids.get(i)); } return update; } //count public int count() throws Exception{ int count = 0; String sql = "SELECT COUNT(*) FROM orders"; ResultSet rs = dbHelper.query(sql); if(rs.next()){ count = rs.getInt(1); } return count; } //find all orders public List<Order> findAllOrders() throws Exception{ List<Order> orders = new ArrayList<Order>(); String sql = "SELECT * FROM orders"; ResultSet rs = dbHelper.query(sql); while(rs.next()){ Entity.Order aorder = new Entity.Order(); aorder.setOId(rs.getString(1)); aorder.setUId(rs.getInt(2)); aorder.setSKU(rs.getString(3)); aorder.setOName(rs.getString(4)); aorder.setOPrice(rs.getDouble(5)); aorder.setONumber(rs.getInt(6)); aorder.setODate(rs.getDate(7)); aorder.setOSentDate(rs.getDate(8)); aorder.setOConfirmDate(rs.getDate(9)); aorder.setOStatus(rs.getInt(10)); aorder.setODeliveryName(rs.getString(11)); aorder.setODeliveryAddress(rs.getString(12)); aorder.setODeliveryPhone(rs.getString(13)); aorder.setOLocation(rs.getString(14)); aorder.setOPic(rs.getString(15)); orders.add(aorder); } return orders; } //发货 public int send(String oid) throws Exception{ int updatecount = 0; String sql = "UPDATE orders SET O_Status=3 WHERE O_Id like '"+oid+"%'"; updatecount = dbHelper.updatePrepareSQL(sql); return updatecount; } //更新物流信息 public int updatelocation(String oid, String newlocation) throws Exception{ int updatecount = 0; String sql = "SELECT O_Location FROM orders WHERE O_Id like '"+oid+"%'"; ResultSet rs = dbHelper.query(sql); String location = ""; if(rs.next()){ location = rs.getString(1); } if(location == null){ location = newlocation; } else{ location = location + "/" + newlocation; } sql = "UPDATE orders SET O_Location=? WHERE O_Id like '"+oid+"%'"; updatecount = dbHelper.updatePrepareSQL(sql, location); return updatecount; } } <file_sep>package Entity; public class Kind { private int k_id; private int k_catalog1; private int k_catalog2; private String k_catalog3; public int getKId(){ return this.k_id; } public void setKId(int KId){ this.k_id = KId; } public int getKCatalog1(){ return this.k_catalog1; } public void setKCatalog1(int KCatalog1){ this.k_catalog1 = KCatalog1; } public int getKCatalog2(){ return this.k_catalog2; } public void setKCatalog2(int KCatalog2){ this.k_catalog2 = KCatalog2; } public String getKCatalog3(){ return this.k_catalog3; } public void setKCatalog3(String KCatalog3){ this.k_catalog3 = KCatalog3; } } <file_sep>package Servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.xml.internal.stream.Entity; import BusinessLogic.CommentLogic; import Entity.Comment; /** * Servlet implementation class CommentServlet */ @WebServlet("/Comment") public class CommentServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CommentServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf8"); response.setCharacterEncoding("utf8"); String action = request.getParameter("action"); CommentLogic cml = new CommentLogic(); int updatecount = 0; if(action != null && action.equals("add")){ int itemnumber = Integer.parseInt(request.getParameter("itemnumber")); String oldoid = request.getParameter("hiddenoid"); for(int i = 0; i<itemnumber; i++){ String radioname = "commentradio"+String.valueOf(i); String commentname = "comment" + String.valueOf(i); String idname = "orderid" + String.valueOf(i); String oid = request.getParameter(idname); String star = request.getParameter(radioname); String comment = request.getParameter(commentname); Comment acomment = new Comment(); acomment.setOId(oid); acomment.setCStar(Integer.parseInt(star)); acomment.setCComment(comment); acomment.setUName((String)request.getSession().getAttribute("USERNAME")); try { updatecount += cml.addComment(acomment); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(updatecount > 0){ request.getRequestDispatcher("myspace_index.jsp").forward(request, response); } else{ request.getRequestDispatcher("myspace_comment.jsp?oid="+oldoid).forward(request, response); } } } } <file_sep>package Servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import BusinessLogic.DeliveryAddressLogic; import Entity.DeliveryAddress; /** * Servlet implementation class DeliveryAddressServlet */ @WebServlet("/DeliveryAddress") public class DeliveryAddressServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DeliveryAddressServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf8"); response.setCharacterEncoding("utf8"); String action = request.getParameter("action"); if(action != null && action.equals("add")){ String name = request.getParameter("nametextbox"); String phone = request.getParameter("phone"); String address = request.getParameter("address"); String uid = request.getParameter("uid"); String product= request.getParameter("product"); DeliveryAddressLogic svc = new DeliveryAddressLogic(); Entity.DeliveryAddress aaddress = new DeliveryAddress(); aaddress.setUId(Integer.parseInt(uid)); aaddress.setDName(name); aaddress.setDPhone(phone); aaddress.setDAddress(address); try{ int i = svc.addAddress(aaddress); if(i>0){ request.getRequestDispatcher("order.jsp?userId="+uid+"&product="+product).forward(request, response); } else{ request.getRequestDispatcher("addNewAddress.jsp").forward(request, response); } }catch (Exception e){ e.printStackTrace(); } } } } <file_sep>package Entity; public class Brand { private int b_id; private String b_name; public int getBId(){ return this.b_id; } public void setBId(int BId){ this.b_id = BId; } public String getBName(){ return this.b_name; } public void setBName(String BName){ this.b_name = BName; } }
ade3aa098b144feaa75834537f9fcd0e54c837cb
[ "Java" ]
5
Java
JinfanYang/online-store
73f075b35589cf3eb3cb221d910a6277a781874a
7ac419f1ebc581c5ab22ee76e3d2f7eca5ddbccf
refs/heads/master
<file_sep>package au.edu.uq.itee.comp3506.assn2.entities; public class LinkedList<T> { private int size; //size of the linked list private Node<T> head; //head node of the linked list private Node<T> tail; //tail node of the linked list /** * constructor of the linked list * Runtime Complexity: O(1) * Space Usage Complexity: O(1) */ public LinkedList(){ size=0; head=null; tail=null; } /** * get method of the size of the linked list * Runtime Complexity: O(1) * Space Usage Complexity: O(1) * @return current size of the linked list */ public int getSize(){ return size; } /** * get method of the tail of the linked list * Runtime Complexity: O(1) * Space Usage Complexity: O(1) * @return current tail node of the linked list */ public Node getTail(){ return tail; } /** * get method of the tail of the linked list * Runtime Complexity: O(1) * Space Usage Complexity: O(1) * @return current head node of the linked list */ public Node getHead(){ return head; } /** * add a nextNode to the last of the linked list * Runtime Complexity: O(1) * Space Usage Complexity: O(1) */ public void addLast(Node newNode){ if(newNode==null){ return; }else{ if(size==0){ head=newNode; tail=head; size+=1; }else{ tail.setNext(newNode); tail=newNode; size+=1; } } } /** * remove the head node of the linked list * Runtime Complexity: O(1) * Space Usage Complexity: O(1) * @return previous head node of the linked list/ null if no head node is null */ public Node removeHead(){ Node temp; if(size==2){ temp=head; head=tail; size-=1; return temp; }else if(size==1){ temp=head; tail=null; head=null; size=0; return temp; }else if(size==0){ return null; }else if(size>2){ temp=head; head=head.getNext(); size-=1; return temp; } return null; } /** * remove the tail node of the linked list * Runtime Complexity: O(n) * Space Usage Complexity: O(1) * @return previous tail node of the linked list/ null if no tail node is null */ public Node removeTail(){ Node temp; if(size==2){ temp=tail; tail=head; head.setNext(null); size-=1; return temp; }else if(size==1){ size-=1; temp=tail; tail=null; head=null; return temp; }else if(size==0){ return null; }else if(size==3){ size-=1; temp=tail; tail=head.getNext(); tail.setNext(null); return temp; }else if(size>3){ temp=tail; Node nextNode=head.getNext(); for(int i=0;i<size-3;i++){ nextNode=nextNode.getNext(); } size-=1; tail=nextNode; tail.setNext(null); return temp; } return null; } /** * this method would move the first node to the last * Runtime Complexity: O(1) * Space Usage Complexity: O(1) * @return the original head node */ public Node<T> reverseHead(){ Node temp= head; head=head.getNext(); tail.setNext(temp); tail=temp; return temp; } /** * method that used to combining two linked list into one * Runtime Complexity: O(1) * Space Usage Complexity: O(1) * @param linkedList */ public void combineLinkList(LinkedList<T> linkedList){ //current linked list empty if(linkedList.getSize()==0){ return; }else{ if(size==0){ head=linkedList.getHead(); tail=linkedList.getTail(); size=linkedList.getSize(); }else{ this.tail.setNext(linkedList.getHead()); this.tail=linkedList.getTail(); size=size+linkedList.getSize(); } } } } <file_sep>package au.edu.uq.itee.comp3506.assn2.entities; /** * The class is mainly used for storing switch ID and its current connection count * * all of the variables/methods are primitive types or primitive operations * * The Runtime Complexity: O(1) * The SpaceUsage Complexity: O(1) */ public class SwitchElement { private int id; //switch identifier private int count; //switch connection count /** * constructor of the switch element * Runtime Complexity: O(1) * Space usage Complexity: O(1) */ public SwitchElement(){ this.id=0; this.count=0; } /** * constructor of the switch element * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param key */ public SwitchElement(Integer key){ this.id=key; this.count=0; } /** * get method of the connection count * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @return count */ public int getValue(){ return count; } /** * get method of the ID * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @return */ public int getKey(){ return id; } /** * method that add one count of the current Switch * Runtime Complexity: O(1) * Space usage Complexity: O(1) */ public void addCount(){ count+=1; } } <file_sep>package au.edu.uq.itee.comp3506.assn2.tests; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import au.edu.uq.itee.comp3506.assn2.api.TestAPI; import au.edu.uq.itee.comp3506.assn2.entities.CallRecord; import au.edu.uq.itee.comp3506.assn2.entities.DataReader; import au.edu.uq.itee.comp3506.assn2.entities.LinkedList; import au.edu.uq.itee.comp3506.assn2.entities.SwitchElement; import au.edu.uq.itee.comp3506.assn2.entities.SwitchList; import au.edu.uq.itee.comp3506.assn2.entities.CallPair; /** * Hook class used by automated testing tool. * The testing tool will instantiate an object of this class to test the functionality of your assignment. * You must implement the method and constructor stubs below so that they call the necessary code in your application. * * @author */ public final class AutoTester implements TestAPI { DataReader dataReader; //instance that would read the file LinkedList<CallPair> phoneNumberPairList; //linked list that contains all the call pair SwitchList switchesList; //List that contains all the switch ID public AutoTester() throws IOException{ dataReader=new DataReader(); dataReader.openFile(); dataReader.readSwitchesFile(); dataReader.readRecordFile(); dataReader.readShortRecordsFile(); dataReader.closeFile(); } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. getCaller() Runtime Complexity: O(1); * 6. getReceiver() Runtime Complexity: O(1); * * In the method, the for loop has been used which is linear runtime complexity. Meanwhile other methods' * runtime complexity is constant. Thus the whole runtime complexity of the method is O(n) * Runtime Complexity of the whole method:O(n) * * @param dialler The phone number that initiated the calls. * @return */ @Override public List<Long> called(long dialler) { List<Long> receivers=new ArrayList<Long>(); //phoneNumberPairList=dataReader.getphoneNumberLinkedList(); phoneNumberPairList=dataReader.getphoneNumberList2(); for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair element=(CallPair)phoneNumberPairList.reverseHead().getElement(); if(element.getCaller()==dialler){ receivers.add(element.getReceiver()); } } return receivers; } /** * * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. getCaller() Runtime Complexity: O(1); * 6. getReceiver() Runtime Complexity: O(1); * 7. isInTime() Runtime Complexity: O(1); * * In the method, the for loop has been used which is linear runtime complexity. Meanwhile other methods' * runtime complexity is constant. Thus the whole runtime complexity of the method is O(n) * Runtime Complexity of the whole method:O(n) * * @param dialler The phone number that initiated the calls. * @param startTime Start of time period. * @param endTime End of time period. * @return */ @Override public List<Long> called(long dialler, LocalDateTime startTime, LocalDateTime endTime) { List<Long> receivers=new ArrayList<Long>(); //phoneNumberPairList=dataReader.getphoneNumberLinkedList(); phoneNumberPairList=dataReader.getphoneNumberList2(); for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair element=phoneNumberPairList.reverseHead().getElement(); if(element.isIntime(startTime, endTime)){ if(element.getCaller()==dialler){ receivers.add(element.getReceiver()); } } } return receivers; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. getCaller() Runtime Complexity: O(1); * 6. getReceiver() Runtime Complexity: O(1); * * In the method, the for loop has been used which is linear runtime complexity. Meanwhile other methods' * runtime complexity is constant. Thus the whole runtime complexity of the method is O(n) * Runtime Complexity of the whole method:O(n) * * @param receiver The phone number that received the calls. * @return */ @Override public List<Long> callers(long receiver) { List<Long> caller=new ArrayList<Long>(); phoneNumberPairList=dataReader.getphoneNumberList2(); for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair element=phoneNumberPairList.reverseHead().getElement(); if(element.getReceiver()==receiver){ caller.add(element.getCaller()); } } return caller; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. getCaller() Runtime Complexity: O(1); * 6. getReceiver() Runtime Complexity: O(1); * 7. isInTime() Runtime Complexity: O(1); * * In the method, the for loop has been used which is linear runtime complexity. Meanwhile other methods' * runtime complexity is constant. Thus the whole runtime complexity of the method is O(n) * Runtime Complexity of the whole method:O(n) */ @Override public List<Long> callers(long receiver, LocalDateTime startTime, LocalDateTime endTime) { List<Long> callers=new ArrayList<Long>(); phoneNumberPairList=dataReader.getphoneNumberList2(); for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair element=phoneNumberPairList.reverseHead().getElement(); if(element.isIntime(startTime, endTime)){ if(element.getReceiver()==receiver){ callers.add(element.getCaller()); } } } return callers; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. getCaller() Runtime Complexity: O(1); * 6. getfaultSwitchID() Runtime Complexity: O(1); * 7. add() Runtime Complexity: O(1); * * For this method only one for loop has been used to loop through phoneNumberList which will be iterated for * n(phoneNumberList size) times. Other operation would be either took constant time or is primitive operations. * Runtime complexity is: O(n) * @param dialler The phone number that initiated the calls. * @return List of switch ID that is faulty */ @Override public List<Integer> findConnectionFault(long dialler) { int j=0; phoneNumberPairList=dataReader.getphoneNumberList2(); List<Integer> faultSwitches=new ArrayList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair callpair=phoneNumberPairList.reverseHead().getElement(); if(callpair.getCaller()==dialler){ if(getfaultSwitchID(callpair)!=0){ faultSwitches.add(getfaultSwitchID(callpair)); } } } return faultSwitches; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. isIntime() Runtime Complexity: O(1); * 6. getCaller() Runtime Complexity: O(1); * 7. getfaultSwitchID() Runtime Complexity: O(1); * 8. add() Runtime Complexity: O(1); * * For this method only one for loop has been used to loop through phoneNumberList which will be iterated for * n(phoneNumberList size) times. Other operations/methods would be either took constant time or is primitive operations. * Runtime complexity is: O(n) * @param dialler The phone number that initiated the calls. * @param startTime Start of time period. * @param endTime End of time period. * @return List of switch ID that is faulty */ @Override public List<Integer> findConnectionFault(long dialler, LocalDateTime startTime, LocalDateTime endTime) { phoneNumberPairList=dataReader.getphoneNumberList2(); List<Integer> faultSwitches=new ArrayList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair callpair=phoneNumberPairList.reverseHead().getElement(); //is call record within time if(callpair.isIntime(startTime, endTime)){ //is the assigned caller if(callpair.getCaller()==dialler){ //does any switch wrong if(getfaultSwitchID(callpair)!=0){ faultSwitches.add(getfaultSwitchID(callpair)); } } } } return faultSwitches; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. getReceiver() Runtime Complexity: O(1); * 6. getfaultSwitchID() Runtime Complexity: O(1); * 7. add() Runtime Complexity: O(1); * * For this method only one for loop has been used to loop through phoneNumberList which will be iterated for * n(phoneNumberList size) times. Other operations/methods would be either took constant time or is primitive operations. * Runtime complexity is: O(n) * @param reciever The phone number that should have received the calls. * @return */ @Override public List<Integer> findReceivingFault(long reciever) { phoneNumberPairList=dataReader.getphoneNumberList2(); List<Integer> faultSwitches=new ArrayList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair callpair=phoneNumberPairList.reverseHead().getElement(); if(callpair.getReceiver()==reciever){ if(getfaultSwitchID(callpair)!=0){ faultSwitches.add(getfaultSwitchID(callpair)); } } } return faultSwitches; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. isIntime() Runtime Complexity: O(1); * 6. getReceiver() Runtime Complexity: O(1); * 7. getfaultSwitchID() Runtime Complexity: O(1); * 8. add() Runtime Complexity: O(1); * * For this method only one for loop has been used to loop through phoneNumberList which will be iterated for * n(phoneNumberList size) times. Other operations/methods would be either took constant time or is primitive operations. * Runtime complexity is: O(n) * @param reciever The phone number that should have received the calls. * @return */ @Override public List<Integer> findReceivingFault(long reciever, LocalDateTime startTime, LocalDateTime endTime) { phoneNumberPairList=dataReader.getphoneNumberList2(); List<Integer> faultSwitches=new ArrayList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair callpair=phoneNumberPairList.reverseHead().getElement(); if(callpair.isIntime(startTime, endTime)){ if(callpair.getReceiver()==reciever){ if(getfaultSwitchID(callpair)!=0){ faultSwitches.add(getfaultSwitchID(callpair)); } } } } return faultSwitches; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. combineLinkList() Runtime Complexity: O(1); * 6. getCapacity() Runtime Complexity: O(1); * 7. addCount() Runtime Complexity: O(1); * * Initially, it will loop through the call record linked list and the methods inside the loop would execute * n(LinkedList<CallPair> size) times. During each iteration, it would connection the current * linkedList(connectionPath) behind the previous linkedList. As a result, all the connectionPath would be integrate * into one big linkedList. Then, another for loop which size is m(LinkedList<Integer> size) would be called to loop * through the big connectionPath linkedList and according to its switchID, find itself inside the switchList which * will need a for loop through the switch list which size is 1000 and add one connection count. * At last, return the maximum count Switch * The runtime complexity of the method would be: O(n+m*1000*constant) => O(n) * * @return maxConnection count's switch ID */ @Override public int maxConnections() { phoneNumberPairList=dataReader.getphoneNumberList2(); switchesList=dataReader.getSwitchList(); LinkedList<Integer> allConnectionPath=new LinkedList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ allConnectionPath.combineLinkList(phoneNumberPairList.reverseHead().getElement().getConnectionPath()); } int maxCount=0; int maxCountSwitch=0; for(int i=0;i<allConnectionPath.getSize();i++){ int switchID=allConnectionPath.reverseHead().getElement(); for(int j=0;j<switchesList.getCapacity();j++){ SwitchElement currentSwitch=switchesList.getElement(j); if(currentSwitch.getKey()==switchID){ currentSwitch.addCount(); if(maxCount<currentSwitch.getValue()){ maxCount=currentSwitch.getValue(); maxCountSwitch=currentSwitch.getKey(); }else if(maxCount==currentSwitch.getValue()&& maxCountSwitch>currentSwitch.getKey()){ maxCountSwitch=currentSwitch.getKey(); } } } } return maxCountSwitch; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. isInTime() Runtime Complexity: O(1); * 6. combineLinkList() Runtime Complexity: O(1); * 7. getCapacity() Runtime Complexity: O(1); * 8. addCount() Runtime Complexity: O(1); * * Initially, it will loop through the call record linked list and the methods inside the loop would execute * n(LinkedList<CallPair> size) times. During each iteration, it would connection the current * linkedList(connectionPath) behind the previous linkedList. As a result, all the connectionPath would be integrate * into one big linkedList. Then, another for loop which size is m(LinkedList<Integer> size) would be called to loop * through the big connectionPath linkedList and according to its switchID, find itself inside the switchList which * will need a for loop through the switch list which size is 1000 and add one connection count. * At last, return the maximum count Switch * The runtime complexity of the method would be: O(n+m*1000*constant) => O(n) * * @param startTime Start of time period. * @param endTime End of time period. * @return maxConnection count's switch ID */ @Override public int maxConnections(LocalDateTime startTime, LocalDateTime endTime) { phoneNumberPairList=dataReader.getphoneNumberList2(); switchesList=dataReader.getSwitchList(); LinkedList<Integer> allConnectionPath=new LinkedList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair element=phoneNumberPairList.reverseHead().getElement(); if(element.isIntime(startTime, endTime)){ allConnectionPath.combineLinkList(element.getConnectionPath()); } } int maxCount=0; int maxCountSwitch=0; for(int i=0;i<allConnectionPath.getSize();i++){ int switchID=allConnectionPath.reverseHead().getElement(); for(int j=0;j<switchesList.getCapacity();j++){ SwitchElement currentSwitch=switchesList.getElement(j); if(currentSwitch.getKey()==switchID){ currentSwitch.addCount(); if(maxCount<currentSwitch.getValue()){ maxCount=currentSwitch.getValue(); maxCountSwitch=currentSwitch.getKey(); }else if(maxCount==currentSwitch.getValue()&& maxCountSwitch>currentSwitch.getKey()){ maxCountSwitch=currentSwitch.getKey(); } } } } return maxCountSwitch; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. combineLinkList() Runtime Complexity: O(1); * 6. getCapacity() Runtime Complexity: O(1); * 7. addCount() Runtime Complexity: O(1); * * Initially, it will loop through the call record linked list and the methods inside the loop would execute * n(LinkedList<CallPair> size) times. During each iteration, it would connection the current * linkedList(connectionPath) behind the previous linkedList. As a result, all the connectionPath would be integrate * into one big linkedList. Then, another for loop which size is m(LinkedList<Integer> size) would be called to loop * through the big connectionPath linkedList and according to its switchID, find itself inside the switchList which * will need a for loop through the switch list which size is 1000 and add one connection count. * At last, return the minimum count Switch * The runtime complexity of the method would be: O(n+m*1000*constant+1000*constant) => O(n) * * @return minConnection count's switch ID */ @Override public int minConnections() { phoneNumberPairList=dataReader.getphoneNumberList2(); switchesList=dataReader.getSwitchList(); LinkedList<Integer> allConnectionPath=new LinkedList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ allConnectionPath.combineLinkList(phoneNumberPairList.reverseHead().getElement().getConnectionPath()); } for(int i=0;i<allConnectionPath.getSize();i++){ int switchID=allConnectionPath.reverseHead().getElement(); for(int j=0;j<switchesList.getCapacity();j++){ SwitchElement currentSwitch=switchesList.getElement(j); if(currentSwitch.getKey()==switchID){ currentSwitch.addCount(); } } } int minID=100000; int minCount=allConnectionPath.getSize(); for(int j=0;j<switchesList.getCapacity();j++){ SwitchElement currentSwitch=switchesList.getElement(j); int currentCount=currentSwitch.getValue(); int currentID=currentSwitch.getKey(); if(minCount>currentCount){ minCount=currentCount; minID=currentID; }else if(minCount==currentCount&& minID>currentID){ minID=currentID; } } return minID; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. isInTime() Runtime Complexity: O(1); * 6. combineLinkList() Runtime Complexity: O(1); * 7. getCapacity() Runtime Complexity: O(1); * 8. addCount() Runtime Complexity: O(1); * * Initially, it will loop through the call record linked list and the methods inside the loop would execute * n(LinkedList<CallPair> size) times. During each iteration, it would connection the current * linkedList(connectionPath) behind the previous linkedList. As a result, all the connectionPath would be integrate * into one big linkedList. Then, another for loop which size is m(LinkedList<Integer> size) would be called to loop * through the big connectionPath linkedList and according to its switchID, find itself inside the switchList which * will need a for loop through the switch list which size is 1000 and add one connection count. * At last, return the minimum count Switch * The runtime complexity of the method would be: O(n+m*1000*constant+1000*constant) => O(n) * * @param startTime Start of time period. * @param endTime End of time period. * @return minConnection count's switch ID */ @Override public int minConnections(LocalDateTime startTime, LocalDateTime endTime) { phoneNumberPairList=dataReader.getphoneNumberList2(); LinkedList<Integer> allConnectionPath=new LinkedList<>(); //combine all the connectionPath into one linkList for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair element=phoneNumberPairList.reverseHead().getElement(); if(element.isIntime(startTime, endTime)){ allConnectionPath.combineLinkList(element.getConnectionPath()); } } for(int i=0;i<allConnectionPath.getSize();i++){ int switchID=allConnectionPath.reverseHead().getElement(); for(int j=0;j<switchesList.getCapacity();j++){ SwitchElement currentSwitch=switchesList.getElement(j); if(currentSwitch.getKey()==switchID){ currentSwitch.addCount(); } } } int minID=100000; int minCount=allConnectionPath.getSize(); for(int j=0;j<switchesList.getCapacity();j++){ SwitchElement currentSwitch=switchesList.getElement(j); int currentCount=currentSwitch.getValue(); int currentID=currentSwitch.getKey(); if(minCount>currentCount){ minCount=currentCount; minID=currentID; }else if(minCount==currentCount&& minID>currentID){ minID=currentID; } } return minID; } /** * Runtime Complexity of used method: * 1. getphoneNumberLinkedList() Runtime Complexity: O(1); * 2. getSize() Runtime Complexity: O(1); * 3. reverseHead() Runtime Complexity: O(1); * 4. getElement() Runtime Complexity: O(1); * 5. isIntime() Runtime Complexity: O(1); * 6. getConnectionPath() Runtime Complexity: O(1); * * In the first for loop, all the method inside of the list would be executed n(linkedlist<CallRecord> size) times. * Additionally, inside the first for loop, another for loop has been used to loop through the connection Path * and the method inside would executed for m(linkedList<Integer> size) times. * Thus, the runtime complexity of the method is :O(m*n) => O(n^2) * * @param startTime Start of time period. * @param endTime End of time period. * @return List<CallRecord> */ @Override public List<CallRecord> callsMade(LocalDateTime startTime, LocalDateTime endTime) { List<CallRecord> callRecords=new ArrayList<>(); phoneNumberPairList=dataReader.getphoneNumberList2(); for(int i=0;i<phoneNumberPairList.getSize();i++){ CallPair callpair=phoneNumberPairList.reverseHead().getElement(); List<Integer> connectionPath=new ArrayList<Integer>(); if(callpair.isIntime(startTime, endTime)){ for(int j=0;j<callpair.getConnectionPath().getSize();j++){ if(callpair.getConnectionPath().getSize()!=0){ connectionPath.add((callpair.getConnectionPath().reverseHead().getElement())); } } } callRecords.add(new CallRecord(callpair.getCaller(), callpair.getReceiver(), callpair.getCallerSwitch(), callpair.getReceiverSwitch(), connectionPath, callpair.getTimeStamp())); } return callRecords; } public static void main(String[] args) throws IOException { AutoTester test = new AutoTester(); } /** * method that used to determine whether given callpair is fault or not * * Created a new instance of Arraylist. Thus the space usage complexity is O(n) * * Runtime Complexity: O(1) * Space usage Complexity: O(n) * @param callpair * @return */ public int getfaultSwitchID(CallPair callpair){ LinkedList<Integer> connectionPath=callpair.getConnectionPath(); // connection Path is null then the callerSwitch is fault if(connectionPath.getSize()==0){ return callpair.getCallerSwitch(); } //the connectionpath's size is one and the fault is at the CallerSwitch else if(connectionPath.getSize()==1){ if((int)connectionPath.getHead().getElement()!=callpair.getReceiverSwitch()){ return (int)connectionPath.getHead().getElement(); } } if(connectionPath.getSize()>=2){ //the final switch in the connection path is not the same as receiver's switch if((int)connectionPath.getTail().getElement()!=callpair.getReceiverSwitch()){ return (int)connectionPath.getTail().getElement(); } } return 0; } }<file_sep>package au.edu.uq.itee.comp3506.assn2.entities; /** * the class is mainly created as the list that contains all of the switch element * * all of the variables/methods are primitive types or primitive operations * * The Runtime Complexity: O(1) * The SpaceUsage Complexity: O(n) */ public class SwitchList { private SwitchElement[] elements; //List that contains all the switch element private int capacity; //list capacity /** * constructor of the switchList * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param capacity */ public SwitchList(int capacity){ this.capacity=capacity; elements=new SwitchElement[capacity]; } /** * set method of the linked list element value according to given index * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param index * @param se */ public void setValue(int index,SwitchElement se){ this.elements[index]=se; } /** * get method of the element of the linked list according to the given index * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param index * @return */ public SwitchElement getElement(int index){ return this.elements[index]; } /** * get method of the capacity * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @return */ public int getCapacity(){ return capacity; } } <file_sep>package au.edu.uq.itee.comp3506.assn2.entities; /** * this class is the linked list node that contains element info and pointer to the next node * * the runtime Complexity: O(1) * the SpaceUsage Complexity: O(1) * @param <T> */ public class Node<T> { private T element; //Element that the node carried private Node nextNode; //Info of NextNode /** * constructor of the Node class * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param object */ public Node(T object){ this.element=object; nextNode=null; } /** * constructor of the Node class * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param object * @param node */ public Node(T object,Node node){ this.element=object; this.nextNode=node; } /** * get method of the next node * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @return nextNode */ public Node getNext(){ return nextNode; } /** * set method of the nextNode * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param node */ public void setNext(Node node){ this.nextNode=node; } /** * get method of the current element * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @return */ public T getElement(){ return this.element; } /** * set method of the current element * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @param object */ public void setElement(T object){ this.element=object; } /** * method used to check whether current node has next node info * Runtime Complexity: O(1) * Space usage Complexity: O(1) * @return */ public boolean hasNext(){ if(nextNode==null){ return false; }else{ return true; } } } <file_sep>package au.edu.uq.itee.comp3506.assn2.entities; import javax.swing.text.DateFormatter; import java.io.File; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Scanner; /** * the main purpose of this class is to read the data from the file and store data using constructed data structure * * the class initiated two linked list as length of n,m which will take up to O(n*m) => O(n^2) space. * While the runtime complexity of the class would be O(n^2) as there are two method used to reading and storing the * file data from the given txt file * * The runtime Complexity: O(n^2) * The space usage Complexity: O(n^2) * */ public class DataReader { //scanners for switches, callRecordFile, callRecordShortFile private Scanner switches; private Scanner callRecords; private Scanner callRecordsShort; //scanners for each line private Scanner lineScanner; //LinkedList that contains all the call Record private LinkedList<CallPair> phoneNumberList; private LinkedList<CallPair> phoneNumberList2; //linkedList that contains all the switchID private SwitchList switchList; /** * method that open file * Space usage Complexity: O(1) * Runtime Complexity: O(1) * @throws IOException */ public void openFile() throws IOException { phoneNumberList = new LinkedList<>(); phoneNumberList2 = new LinkedList<>(); try { switches = new Scanner(new File("COMP3506-Assign2/data/switches.txt")); callRecords = new Scanner(new File("COMP3506-Assign2/data/call-records.txt")); callRecordsShort = new Scanner(new File("COMP3506-Assign2/data/call-records-short.txt")); } catch (Exception e) { throw new IOException("File does not found!"); } } /** * the class initiated the new linked list which length is 1000 which take constant space. * and a while loop has been used to store data into the linked list which will run 1000 times * Space usage Complexity: O(1) * Runtime Complexity: O(1) */ public void readSwitchesFile(){ int number=0; if(switches.hasNextInt()){ if(switches.nextInt()==1000){ switchList=new SwitchList(1000); while(switches.hasNextInt()){ this.switchList.setValue(number, new SwitchElement(switches.nextInt())); number+=1; } } } } /** * Space Complexity: * 1. hasNextLine() O(1) * 2. nextLine() O(1) * 3. hasNextLong() O(1) * 4. intValue() O(1) * 5. addLast() O(1) * 6. setCaller() O(1) * 7. getCaller() O(1) * 8. setReceiver() O(1) * 9. setCallerSwitch() O(1) * 10. setReceiverSwitch() O(1) * 11. setConnectionPath() O(1) * 12. isValid() O(1) * 13. removeTail() O(1) * 14. removeHead() O(1) * * Runtime Complexity: * 1. hasNextLine() O(1) * 2. nextLine() O(1) * 3. hasNextLong() O(1) * 4. intValue() O(1) * 5. addLast() O(1) * 6. setCaller() O(1) * 7. getCaller() O(1) * 8. setReceiver() O(1) * 9. setCallerSwitch() O(1) * 10. setReceiverSwitch() O(1) * 11. setConnectionPath() O(1) * 12. isValid() O(1) * 13. removeTail() O(n) * 14. removeHead() O(1) * * two while loop has been used to read all the data from the file which will iterate n(file lines count) times and * m(line tokens count) times. RemoveTail() method's runtime complexity is O(b) (b is the size of the linkedlist) * in worst case * Space usage Complexity: O(m*n) => O(n^2) * Runtime Complexity: O(n*m+b) => O(n^2) */ public void readRecordFile(){ int lineNumber=0; //loop through every line while(callRecords.hasNextLine()){ lineNumber+=1; int tokenNumber=0; String record=callRecords.nextLine(); lineScanner=new Scanner(record); //initialise a connectionPath that contains CallerSwitch& ReceiverSwitch LinkedList<Integer> connectionPath=new LinkedList<Integer>(); //initialise a callPair with its lineNumber CallPair callPair=new CallPair(lineNumber); //info before time stamp while(lineScanner.hasNextLong()){ tokenNumber+=1; Long nextLong=lineScanner.nextLong(); //whether the number is SwitchID or PhoneNumber if(nextLong<=100000&&nextLong>=10000){ int nextInt=nextLong.intValue(); connectionPath.addLast(new Node<Integer> (nextInt)); }else if(nextLong>=1000000000){ //store phoneNumber as caller and receiver according to accessing order if(callPair.getCaller()==0){ callPair.setCaller(nextLong); }else{ callPair.setReceiver(nextLong); } } } //info of time stamp while(lineScanner.hasNext()){ String timeStamp=lineScanner.next(); try{ LocalDateTime time = LocalDateTime.parse(timeStamp); if(time.getYear()==2017){ if(time.getMonth().toString().equals("SEPTEMBER")){ if(time.getDayOfMonth()>=1&&time.getDayOfMonth()<=21){ callPair.setTimeStamp(time); } } }else{ break; } }catch (DateTimeParseException e){ e.printStackTrace(); break; } } //token sum of CallerSwitch, ReceiverSwitch and connectionPath should be bigger than 3 if(tokenNumber<=3){ continue; }else{ /*Remove the CallerSwitch and ReceiveSwitch from connectionPath *and store the data into callPair */ callPair.setCallerSwitch((Integer)connectionPath.removeHead().getElement()); callPair.setReceiverSwitch((Integer)connectionPath.removeTail().getElement()); callPair.setConnectionPath(connectionPath); if(isValid(callPair)){ phoneNumberList2.addLast(new Node(callPair)); } } } } /** * Space Complexity: * 1. hasNextLine() O(1) * 2. nextLine() O(1) * 3. hasNextLong() O(1) * 4. intValue() O(1) * 5. addLast() O(1) * 6. setCaller() O(1) * 7. getCaller() O(1) * 8. setReceiver() O(1) * 9. setCallerSwitch() O(1) * 10. setReceiverSwitch() O(1) * 11. setConnectionPath() O(1) * 12. isValid() O(1) * * Runtime Complexity: * 1. hasNextLine() O(1) * 2. nextLine() O(1) * 3. hasNextLong() O(1) * 4. intValue() O(1) * 5. addLast() O(1) * 6. setCaller() O(1) * 7. getCaller() O(1) * 8. setReceiver() O(1) * 9. setCallerSwitch() O(1) * 10. setReceiverSwitch() O(1) * 11. setConnectionPath() O(1) * 12. isValid() O(1) * * two while loop has been used to read all the data from the file which will iterate n(file lines count) times and * m(line tokens count) times. * Space usage Complexity: O(m*n) => O(n^2) * Runtime Complexity: O(n*m) => O(n^2) */ public void readShortRecordsFile(){ int lineNumber=0; //loop through every line while(callRecordsShort.hasNextLine()){ lineNumber+=1; int tokenNumber=0; String record=callRecordsShort.nextLine(); lineScanner=new Scanner(record); //initialise a connectionPath that contains CallerSwitch& ReceiverSwitch LinkedList<Integer> connectionPath=new LinkedList<Integer>(); //initialise a callPair with its lineNumber CallPair callPair=new CallPair(lineNumber); //info before time stamp while(lineScanner.hasNextLong()){ tokenNumber+=1; Long nextLong=lineScanner.nextLong(); //whether the number is SwitchID or PhoneNumber if(nextLong<=100000&&nextLong>=10000){ int nextInt=nextLong.intValue(); connectionPath.addLast(new Node<Integer> (nextInt)); }else if(nextLong>=1000000000){ //store phoneNumber as caller and receiver according to accessing order if(callPair.getCaller()==0){ callPair.setCaller(nextLong); }else{ callPair.setReceiver(nextLong); } } } //info of time stamp while(lineScanner.hasNext()){ String timeStamp=lineScanner.next(); LocalDateTime time = LocalDateTime.parse(timeStamp); callPair.setTimeStamp(time); } //token sum of CallerSwitch, ReceiverSwitch and connectionPath should be bigger than 3 if(tokenNumber>3){ /*Remove the CallerSwitch and ReceiveSwitch from connectionPath *and store the data into callPair */ callPair.setCallerSwitch((Integer)connectionPath.removeHead().getElement()); callPair.setReceiverSwitch((Integer)connectionPath.removeTail().getElement()); callPair.setConnectionPath(connectionPath); if(isValid(callPair)){ phoneNumberList.addLast(new Node(callPair)); } } } } /** * method used to close all file * Space usage Complexity: O(1) * Runtime Complexity: O(1) * @return the data read from call-records-short */ public void closeFile(){ switches.close(); callRecords.close(); callRecordsShort.close(); } /** * get method of phoneNumberLinkedList * Space usage Complexity: O(1) * Runtime Complexity: O(1) * @return the data read from call-records-short */ public LinkedList<CallPair> getphoneNumberLinkedList(){ return phoneNumberList; } /** * get method of phoneNumberLinkedList2 * Space usage Complexity: O(1) * Runtime Complexity: O(1) * @return the data read from call-records */ public LinkedList<CallPair> getphoneNumberList2() { return phoneNumberList2; } /** * get method of the switchList * Space usage Complexity: O(1) * Runtime Complexity: O(1) * @return switchList */ public SwitchList getSwitchList() { return switchList; } /** * method that used to check whether the callpair is faulty * Space usage Complexity: O(n) * Runtime Complexity: O(1) * @param callpair * @return */ public boolean isValid(CallPair callpair){ LinkedList<Integer> connectionPath=callpair.getConnectionPath(); int callerSwitch=callpair.getCallerSwitch(); if(connectionPath.getSize()>0){ //First node in connection path is not the same with callerSwitchID if(callerSwitch!=(int)connectionPath.getHead().getElement()||callpair.getTimeStamp()==null){ return false; } } return true; } }
fd60506aea5c5dbc0edf4c51de146c318834019b
[ "Java" ]
6
Java
yifan0707/Call-Record
a26ec1f2183113cdb66843f0bd8657b265484889
6b117d4c0836b1ba2f0589d0a8a2ab67e6c9f61e
refs/heads/master
<repo_name>noel3740/clicky-game<file_sep>/src/services/GiphyAPIService.js import axios from "axios"; const giphyHost = "https://api.giphy.com/v1/gifs"; const apiKey = "<KEY>"; export default { //Get a random gif from the giphy service getRandomPicture: function (searchTerm) { return axios.get(`${giphyHost}/random?api_key=${apiKey}&tag=${searchTerm}`); } }; <file_sep>/README.md # Video Game Memory This is a single page video game themed memory game built using React, Node, Axios, Materialize, JQuery, and JQuery UI. The point of the game is to click on as many unique images as possible. Each time an image is selected the image cards will randomly shuffle. To win the user will need to guess all unique images without selecting an image they have previously selected. If an image was previously selected then the game will start over resetting the user's score back to 0 and updating the Top Score where appropriate. The project is deployed [here](https://noel3740.github.io/clicky-game/). # Steps to Play 1. To start playing simply selecting an image. ![](screenshots/mainScreen.jpg "Screenshot of Main Screen") 2. Continue selecting images being careful to only select those that have not previously been selected. Toast messages will appear as you select images letting you know if you have correctly guessed a unique image or not. The users score will also increate if they have guessed correctly. ![](screenshots/correctCard.gif "Gif of selecting correct cards") 3. After selecting an incorrect image then the top score will update if the user's score was their best score in their current session. ![](screenshots/incorrectCard.gif "Gif of selecting incorrect cards") 4. If all unique images have been selected then a toast will appear notifying the user that they have won as well as a modal will pop up with a random gif. ![](screenshots/win.gif "Gif of a user winning") # Create React App Setup This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.<br> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.<br> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting ### Analyzing the Bundle Size This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size ### Making a Progressive Web App This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app ### Advanced Configuration This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration ### Deployment This section has moved here: https://facebook.github.io/create-react-app/docs/deployment ### `npm run build` fails to minify This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify <file_sep>/src/App.js import React, { Component } from 'react'; import MainHeader from './components/MainHeader' import Card from './components/Card' import Nav from './components/Nav' import Modal from './components/Modal' import './App.css'; import GiphyAPIService from './services/GiphyAPIService' class App extends Component { state = { score: 0, topScore: 0, winGif: "", winGifText: "" }; imagesSelected = []; winModal; //Function that will require all the images into the code requireAll = requireContext => { return requireContext.keys().map(requireContext); }; //Get all images that are in the cardImages folder images = this.requireAll(require.context('./cardImages', false, /\.(png|jpe?g|svg)$/)); //Function that will set the modal gif info setModalGif = () => { GiphyAPIService.getRandomPicture("winning") .then(res => { this.setState({ winGif: res.data.data.image_url, winGifText: res.data.data.title }); }); }; componentDidMount = () => { //Get a modal gif to display initially this.setModalGif(); }; //Function that will handle the on click when a user clicks on a card handleOnCardClick = imageUrl => { let message = ""; //User has guessed correctly if (!this.imagesSelected.includes(imageUrl)) { this.imagesSelected.push(imageUrl); //User has won if (this.imagesSelected.length === this.images.length) { this.imagesSelected = []; message = "You won!"; //Set the state variables this.setState({ topScore: this.images.length, score: 0 }); //Open the win modal this.winModal.displayModal(); } //User has not won but has guessed correctly else { message = "You guessed correctly!"; //Set the state this.setState(state => ({ score: state.score + 1 })); } } //User has guessed incorrectly else { this.imagesSelected = []; message = "You guessed incorrectly!"; //Set the state this.setState(state => ({ topScore: state.score > state.topScore ? state.score : state.topScore, score: 0 })); window.$("#cardContainer").effect("shake") } //Display a toast on screen with the message of if they guessed correctly, incorrectly, or if they won const toastClass = message.includes("incorrectly") ? "incorrectToast" : (message.includes("won") ? "wonToast" : "correctToast"); window.M.toast({ html: message, classes: toastClass }); //Randomize the images this.images = this.randomizeArray(this.images); //this.images.sort(() => Math.random() - 0.5); }; randomizeArray = originalArray => { const newArray = []; const tempArray = [...originalArray]; originalArray.forEach(() => { const randomIndex = Math.floor(Math.random() * tempArray.length); newArray.push(tempArray.splice(randomIndex, 1)[0]); }); return newArray; }; render() { return ( <div className="App"> <Nav score={this.state.score} topScore={this.state.topScore} /> <MainHeader mainText="Video Game Memory" detailText="Click on a video game image to earn points, but don't click on any more than once!" /> <div id="cardContainer" className="container"> <div className="row"> {this.images.map(image => <Card key={image} imageUrl={image} imageText="test" onClickMethod={this.handleOnCardClick} /> )} </div> </div> <Modal id="winModal" header="You Won!" imageUrl={this.state.winGif} imageText={this.state.winGifText} ref={ref => { this.winModal = ref }} onCloseEnd={ this.setModalGif } /> </div> ); } } export default App; <file_sep>/src/components/Modal/index.js import React from 'react'; import './style.css'; class Modal extends React.Component { modalInstance; componentDidMount() { //Initialize the materialize modal so it can be used later var modalElement = document.getElementById(this.props.id); window.M.Modal.init(modalElement, {endingTop: 20, onCloseEnd: this.props.onCloseEnd}); this.modalInstance = window.M.Modal.getInstance(modalElement); }; displayModal() { //Open the modal window this.modalInstance.open(); }; render() { return ( <div id={this.props.id} className="reactModal modal"> <div className="modal-content"> <h4>{this.props.header}</h4> <img src={this.props.imageUrl} alt={this.props.imageAlt} /> </div> </div> ); } } export default Modal; <file_sep>/src/components/Nav/index.js import React from 'react'; import './style.css'; import logo from './logo.png' const Nav = props => { return ( <div className="navbar-fixed"> <nav> <div className="nav-wrapper black"> <div className="row"> <div className="col s12 m6 left-align myNavItem"> <img className="vgmNavLogo" src={logo} alt="logo"></img> VGM </div> <div className="col s12 m6 right-align myNavItem"> <span>Score: {props.score}, </span> <span>Top Score: {props.topScore}</span> </div> </div> </div> </nav> </div> ); } export default Nav;
145a41cae5d9114c223b1540a1c2d82b3ed426d9
[ "JavaScript", "Markdown" ]
5
JavaScript
noel3740/clicky-game
a18a38d8b2731cab69e65ca5b4c9f82cf0d35f32
a69a6b1a910ede3ba997b01b972106773e19394d
refs/heads/master
<file_sep>import asyncio import aiohttp from fpl import FPL class FplSession: def __init__(self, email, password): self.email = email self.password = <PASSWORD> self.session = aiohttp.ClientSession() self.fpl = FPL(self.session) async def login(self): await self.fpl.login(self.email, self.password) async def close(self): await self.session.close() def open(self): self.session = aiohttp.ClientSession() def session_is_open(self): if self.session.closed: return False else: return True <file_sep>class User: def __init__(self, id, team_name, user_name, game_weeks): self.id = id self.team_name = team_name self.user_name = user_name self.game_weeks = game_weeks def set_game_weeks(self, game_weeks): self.game_weeks = game_weeks def get_game_weeks(self): return self.game_weeks<file_sep>import './App.css'; import { useEffect, useState } from "react"; import LineChart from './components/LineChart'; function App() { const [gameweeks, setGameweeks] = useState(null); useEffect(() => { console.log('gameweeks = ', gameweeks); }, [gameweeks]) const readJsonFile = (event) => { const file = event.target.files[0]; if (file) { const fileReader = new FileReader(); fileReader.onload = ((e) => { const data = fileReader.result; const json = JSON.parse(data); if (json) { setGameweeks(json); } }); fileReader.readAsText(file); } }; const getRandomColor = () => { const min = 0; const max = 255; const randomBetween = (min, max) => min + Math.floor(Math.random() * (max - min + 1)); return `rgb(${randomBetween(min, max)}, ${randomBetween(min, max)}, ${randomBetween(min, max)})`; } const getUserDataset = (user, data) => ({ label: user.name, data: data, borderColor: user.lineColor, backgroundColor: user.lineColor }) let users; const userGameweekPointsDictionary = {}; // user_id = key, value = array of gameweek_data. if (gameweeks) { // get list of users from final gameweek, as initial gameweeks may have fewer users. users = gameweeks[37].gameweek_data.map(g => ({ id: g.user_id, name: g.user, teamName: g.team_name, lineColor: getRandomColor() })); for (const gameweek of gameweeks) { for (const gameweekDataItem of gameweek.gameweek_data) { if (userGameweekPointsDictionary[gameweekDataItem.user_id]) { userGameweekPointsDictionary[gameweekDataItem.user_id].push({ points: gameweekDataItem.total_points, position: gameweekDataItem.rank }); } else { userGameweekPointsDictionary[gameweekDataItem.user_id] = [{ points: gameweekDataItem.total_points, position: gameweekDataItem.rank }]; } } } } let pointsLineChart; let positionsLineChart; let individualLineCharts; if (users) { pointsLineChart = ( <LineChart chartTitle="TMSUK PREMIERSHIP 2021-22 Overall Points" datasets={users.map(u => getUserDataset(u, userGameweekPointsDictionary[u.id].map(x => x.points)))} /> ); positionsLineChart = ( <LineChart chartTitle="TMSUK PREMIERSHIP 2021-22 Position changes" datasets={users.map(u => getUserDataset(u, userGameweekPointsDictionary[u.id].map(x => x.position)))} yAxis={{ ticks: { min: 1, max: users.length, stepSize: 1, reverse: true } }} /> ); individualLineCharts = users.map(u => { return ( <div> <LineChart chartTitle={`TMSUK PREMIERSHIP 2021-22 ${u.name} Points`} datasets={[getUserDataset(u, userGameweekPointsDictionary[u.id].map(x => x.points))]} /> <LineChart chartTitle={`TMSUK PREMIERSHIP 2021-22 ${u.name} Position changes`} datasets={[getUserDataset(u, userGameweekPointsDictionary[u.id].map(x => x.position))]} yAxis={{ ticks: { min: 1, max: users.length, stepSize: 1, reverse: true } }} /> </div> ); }); } return ( <div className="App"> <div> <label htmlFor="file">Load Json gameweeks file</label> <input type="file" accept="application/json" id="file" onChange={readJsonFile} /> </div> {pointsLineChart} {positionsLineChart} {individualLineCharts} </div> ); } export default App; <file_sep># FPL Mini League Gameweek-to-Gameweek standings script ## Description This script will generate a JSON file containing the standings of a mini league for each gameweek across the season. **Only the first page of users in a mini league are supported, if you have a mini league with more than one pages' worth of users (I believe the limit per page is 25?) then this script will only get the first page of users stats for each gameweek. PR's are welcome to support multiple pages of users!** This project makes use of the FPL python library to get the data from the Fantasy Premier League API. The library can be found here: https://github.com/amosbastian/fpl ## Running the script Requires the following dependencies, install via pip: + fpl + aiohttp + jsonpickle - Enter your email address and password for FPL in the secrets.cfg file - Open a terminal and run 'python3 main.py' to start the script. (main.py is located within the /script folder) - Enter the mini league id - Viola! the gameweeks.json file can be found in the data directory. ## Fancy charts I'm currently working on a small javascript project to take the gameweeks.json and show the data in pretty charts/tables. More details to follow shortly... <file_sep>class Standings: def __init__(self, has_next, number, results): self.has_next = has_next self.number = number self.results = results <file_sep>class Gameweek: def __init__(self, week, user_id, gameweek_points, total_points, rank): self.week = week self.user_id = user_id self.gameweek_points = gameweek_points self.total_points = total_points self.rank = rank<file_sep>import { Line, Chart } from 'react-chartjs-2'; import { Chart as ChartJS, registerables } from 'chart.js'; ChartJS.register(...registerables); export default function LineChart({chartTitle, datasets, yAxis}) { const options = { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: chartTitle, }, }, scales: { y: yAxis ? {reverse: true, ...yAxis } : {} } }; const labels = []; for (let i = 0; i < 38; i++) { labels.push(i + 1); } const data = { labels, datasets: datasets }; return ( <Line options={options} data={data} /> ); }
251c0c830ff800f981b0921762348f80c984c7f8
[ "JavaScript", "Python", "Markdown" ]
7
Python
mikesjp/fpl-mini
0ae62588d93fe405d8382fad6dfaa9d2021313f7
95a48767fbd8e636d6f72b36b788b6051ca7cb67
refs/heads/master
<file_sep>narrow<- read.csv("/Users/annazhu/PayWhatYouWant/Spring2016/AI_Thomascombined/mturkclose_multiplelines.csv", stringsAsFactors = FALSE)%>% select(-X) prepare <- wide %>% select(Group) %>% mutate(Q1 = "", A1a = "", A1b = "", Q2 = "", A2a ="", A2b ="", Q3 ="", A3a ="", A3b ="", Q4 ="", A4a ="", A4b ="", Q5 ="", A5a ="", A5b ="", Q6 ="", A6a ="", A6b ="", Q7 ="", A7a ="", A7b ="", Q8 ="", A8a ="", A8b ="", Q9 ="", A9a ="", A9b ="", Q10 ="", A10a ="", A10b ="", Q11 ="", A11a ="", A11b ="", Q12 ="", A12a ="", A12b ="", Q13 ="", A13a ="", A13b ="", Q14 ="", A14a ="", A14b ="", Q15 ="", A15a ="", A15b = "") %>% mutate(`Talker1ID` = wide$Talker1.ID) r = 1 i = 0 q0 = FALSE q1 = FALSE q2 = FALSE q3 = FALSE q4 = FALSE q5 = FALSE q6 = FALSE q7 = FALSE q8 = FALSE q9 = FALSE q10 = FALSE q11 = FALSE q12 = FALSE q13 = FALSE q14 = FALSE currgroup = "group 14" Talker1 = "User 1" for (count in 1:nrow(narrow)) { if (narrow$Group[count] != currgroup) { r = r + 1 i = 0 q0 = FALSE q1 = FALSE q2 = FALSE q3 = FALSE q4 = FALSE q5 = FALSE q6 = FALSE q7 = FALSE q8 = FALSE q9 = FALSE q10 = FALSE q11 = FALSE q12 = FALSE q13 = FALSE q14 = FALSE Talker1 = narrow$User[count] currgroup = narrow$Group[count] } if ( (!q0) & grepl("anyone.*in.*the.*world.*dinner.*guest",narrow$Message[count], ignore.case = TRUE)) { i = 0 prepare[r, i*3+2] = narrow$Message[count] i = 1 q0 = TRUE } else if ((!q1) & grepl("constitute.*a.*perfect.*day",narrow$Message[count], ignore.case = TRUE)) { i = 1 prepare[r,i * 3 + 2] = narrow$Message[count] i = 2 q1 = TRUE } else if ((!q2) & grepl("the.*age.*of.*90.*retain.*either.*the.*mind.*or.*body",narrow$Message[count], ignore.case = TRUE)) { i = 2 prepare[r,i * 3 + 2] = narrow$Message[count] i = 3 q2 = TRUE } else if ((!q3) & grepl("change.*anything.*about.*you.*raised,",narrow$Message[count], ignore.case = TRUE)) { i = 3 prepare[r,i * 3 + 2] = narrow$Message[count] i = 4 q3 = TRUE } else if ((!q4) & grepl("wake.*up.*tomorrow.*gain.*quality.*or.*ability,",narrow$Message[count], ignore.case = TRUE)) { i = 4 prepare[r,i * 3 + 2] = narrow$Message[count] i = 5 q4 = TRUE } else if ((!q5) & grepl("crystal.*ball.*tell.*you.*truth.*about.*life.*future.*anything.*else",narrow$Message[count], ignore.case = TRUE)) { i = 5 prepare[r,i * 3 + 2] =narrow$Message[count] i = 6 q5 = TRUE } else if ((!q6) & grepl("greatest.*accomplishment.*of.*your.*life",narrow$Message[count], ignore.case = TRUE)) { i = 6 prepare[r,i * 3 + 2] = narrow$Message[count] i = 7 q6 = TRUE } else if ((!q7) & grepl("most.*treasured.*memory",narrow$Message[count], ignore.case = TRUE)) { i = 7 prepare[r,i * 3 + 2] = narrow$Message[count] i = 8 q7 = TRUE } else if ((!q8) & grepl("die.*suddenly.*change.*anything.*about.*the.*way",narrow$Message[count], ignore.case = TRUE)) { i = 8 prepare[r,i * 3 + 2] = narrow$Message[count] i = 9 q8 = TRUE } else if ((!q9) & grepl("relationship.*with.*your.*mother",narrow$Message[count], ignore.case = TRUE)) { i = 9 prepare[r,i * 3 + 2] = narrow$Message[count] i = 10 q9 = TRUE } else if ((!q10) & grepl("an.*embarrassing.*moment.*in.*your.*life",narrow$Message[count], ignore.case = TRUE)) { i = 10 prepare[r,i * 3 + 2] = narrow$Message[count] i = 11 q10 = TRUE } else if ((!q11) & grepl("last.*cry.*in.*front.*of.*another.*person",narrow$Message[count], ignore.case = TRUE)) { i = 11 prepare[r,i * 3 + 2] = narrow$Message[count] i = 12 q11 = TRUE } else if ((!q12) & grepl("opportunity.*to.*communicate.*with.*anyone.*regret",narrow$Message[count], ignore.case = TRUE)) { i = 12 prepare[r,i * 3 + 2] = narrow$Message[count] i = 13 q12 = TRUE } else if ((!q13) & grepl("catch.*fire.*a.*final.*dash.*to.*save.*any.*one.*item",narrow$Message[count], ignore.case = TRUE)) { i = 13 prepare[r,i * 3 + 2] = narrow$Message[count] i = 14 q13 = TRUE } else if ((!q14) & grepl("family.*whose.*death.*most.*disturbing",narrow$Message[count], ignore.case = TRUE)) { i = 14 prepare[r,i * 3 + 2] = narrow$Message[count] i = 15 q14 = TRUE } else { if (i == 0) { if (narrow$User[count]== Talker1) { prepare[r,i * 3 + 3] = paste(prepare[r,i * 3 + 3], narrow$Message[count], sep = " ") } else { prepare[r,i * 3 + 4] = paste(prepare[r,i * 3 + 4], narrow$Message[count], sep = " ") } }else{ if (narrow$User[count] == Talker1) { prepare[r,(i-1) * 3 + 3] = paste(prepare[r,(i-1) * 3 + 3], narrow$Message[count], sep = " ") } else { prepare[r,(i-1) * 3 + 4] = paste(prepare[r,(i-1) * 3 + 4], narrow$Message[count], sep = " ") } } } } write.csv(prepare, "/Users/annazhu/PayWhatYouWant/Spring2016/AI_Thomascombined/mturk_close_XiaoPrepare2.csv") <file_sep>narrow<- read.csv("/Users/annazhu/PayWhatYouWant/Spring2016/AI_Thomascombined/mturksmall_multiplelines.csv", stringsAsFactors = FALSE)%>% select(-X) prepare <- wide %>% select(Group) %>% mutate(Q1 = "", A1a = "", A1b = "", Q2 = "", A2a ="", A2b ="", Q3 ="", A3a ="", A3b ="", Q4 ="", A4a ="", A4b ="", Q5 ="", A5a ="", A5b ="", Q6 ="", A6a ="", A6b ="", Q7 ="", A7a ="", A7b ="", Q8 ="", A8a ="", A8b ="", Q9 ="", A9a ="", A9b ="", Q10 ="", A10a ="", A10b ="", Q11 ="", A11a ="", A11b ="", Q12 ="", A12a ="", A12b ="", Q13 ="", A13a ="", A13b ="", Q14 ="", A14a ="", A14b ="", Q15 ="", A15a ="", A15b = "") %>% mutate(`Talker1ID` = wide$Talker1.ID) r = 1 i = 0 q0 = FALSE q1 = FALSE q2 = FALSE q3 = FALSE q4 = FALSE q5 = FALSE q6 = FALSE q7 = FALSE q8 = FALSE q9 = FALSE q10 = FALSE q11 = FALSE q12 = FALSE q13 = FALSE q14 = FALSE currgroup = "group 3" Talker1 = "User 2" for (count in 1:nrow(narrow)) { if (narrow$Group[count] != currgroup) { r = r + 1 i = 0 q0 = FALSE q1 = FALSE q2 = FALSE q3 = FALSE q4 = FALSE q5 = FALSE q6 = FALSE q7 = FALSE q8 = FALSE q9 = FALSE q10 = FALSE q11 = FALSE q12 = FALSE q13 = FALSE q14 = FALSE Talker1 = narrow$User[count] currgroup = narrow$Group[count] } if ( (!q0) & grepl("walk.*for.*more.*than.*an.*hour",narrow$Message[count], ignore.case = TRUE)) { i = 0 prepare[r, i*3+2] = narrow$Message[count] i = 1 q0 = TRUE } else if ((!q1) & grepl("how.*celebrate.*last.*halloween",narrow$Message[count], ignore.case = TRUE)) { i = 1 prepare[r,i * 3 + 2] = narrow$Message[count] i = 2 q1 = TRUE } else if ((!q2) & grepl("a.*new.*flavor.*of.*ice.*cream",narrow$Message[count], ignore.case = TRUE)) { i = 2 prepare[r,i * 3 + 2] = narrow$Message[count] i = 3 q2 = TRUE } else if ((!q3) & grepl("best.*gift.*you.*ever.*received,)|(what.*is.*your.*favorite.*holiday)",narrow$Message[count], ignore.case = TRUE)) { i = 3 prepare[r,i * 3 + 2] = narrow$Message[count] i = 4 q3 = TRUE } else if ((!q4) & grepl("gift.*receive.*last.*birthday",narrow$Message[count], ignore.case = TRUE)) { i = 4 prepare[r,i * 3 + 2] = narrow$Message[count] i = 5 q4 = TRUE } else if ((!q5) & grepl("last.*time.*went.*to.*the.*zoo",narrow$Message[count], ignore.case = TRUE)) { i = 5 prepare[r,i * 3 + 2] =narrow$Message[count] i = 6 q5 = TRUE } else if ((!q6) & grepl("get.*up.*early.*stay.*up.*late",narrow$Message[count], ignore.case = TRUE)) { i = 6 prepare[r,i * 3 + 2] = narrow$Message[count] i = 7 q6 = TRUE } else if ((!q7) & grepl("what.*did.*you.*do.*this.*summer",narrow$Message[count], ignore.case = TRUE)) { i = 7 prepare[r,i * 3 + 2] = narrow$Message[count] i = 8 q7 = TRUE } else if ((!q8) & grepl("favorite.*actor.*of.*your.*gender",narrow$Message[count], ignore.case = TRUE)) { i = 8 prepare[r,i * 3 + 2] = narrow$Message[count] i = 9 q8 = TRUE } else if ((!q9) & grepl("what.*is.*your.*favorite.*holiday",narrow$Message[count], ignore.case = TRUE)) { i = 9 prepare[r,i * 3 + 2] = narrow$Message[count] i = 10 q9 = TRUE } else if ((!q10) & grepl("foreign.*country.*most.*like.*to.*visit",narrow$Message[count], ignore.case = TRUE)) { i = 10 prepare[r,i * 3 + 2] = narrow$Message[count] i = 11 q10 = TRUE } else if ((!q11) & grepl("Do.*you.*prefer.*digital.*watches.*and.*clocks.*or.*the.*kind.*with.*hands",narrow$Message[count], ignore.case = TRUE)) { i = 11 prepare[r,i * 3 + 2] = narrow$Message[count] i = 12 q11 = TRUE } else if ((!q12) & grepl("your.*mother.*best.*friend",narrow$Message[count], ignore.case = TRUE)) { i = 12 prepare[r,i * 3 + 2] = narrow$Message[count] i = 13 q12 = TRUE } else if ((!q13) & grepl("how.*often.*get.*your.*hair.*cut",narrow$Message[count], ignore.case = TRUE)) { i = 13 prepare[r,i * 3 + 2] = narrow$Message[count] i = 14 q13 = TRUE } else if ((!q14) & grepl("what.*is.*the.*last.*concert.*you.*saw",narrow$Message[count], ignore.case = TRUE)) { i = 14 prepare[r,i * 3 + 2] = narrow$Message[count] i = 15 q14 = TRUE } else { if (i == 0) { if (narrow$User[count]== Talker1) { prepare[r,i * 3 + 3] = paste(prepare[r,i * 3 + 3], narrow$Message[count], sep = " ") } else { prepare[r,i * 3 + 4] = paste(prepare[r,i * 3 + 4], narrow$Message[count], sep = " ") } }else{ if (narrow$User[count] == Talker1) { prepare[r,(i-1) * 3 + 3] = paste(prepare[r,(i-1) * 3 + 3], narrow$Message[count], sep = " ") } else { prepare[r,(i-1) * 3 + 4] = paste(prepare[r,(i-1) * 3 + 4], narrow$Message[count], sep = " ") } } } } write.csv(prepare, "/Users/annazhu/PayWhatYouWant/Spring2016/AI_Thomascombined/mturk_small_XiaoPrepare2.csv")
6424501aa0eae92b1becf20a5dfd2221f59b6641
[ "R" ]
2
R
thomasysun/GivingAndAppreciatingLab
42a4b670f3c41635975d88c0f3350ba5a91d5277
e512e500a32a6383404b781cf4378bee1fc3af2e
refs/heads/master
<file_sep># Mutsuki test <file_sep>/* * ゲームに不要な余計な処理を隠蔽する。 * 2011 / 07 / 28 * jskny */ // コマンドラインを消す。 #pragma comment(linker, "/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup") #include <DxLib.h> #include <assert.h> #include "GameWindow.h" //--------------------------------------------------------- int main(int argc, char* argv[]) { if (!WindowCreate()) { return (1); } while (WindowLoop()) { // なにもしない。 } WindowClose(); return (0); } //--------------------------------------------------------- static bool s_flagLoopEnd = false; // これが true なら終了。 static long long int s_windowLoopCounter = 0; // ウインドウループの間インクリメントされ続ける変数。 static long int s_windowLoopWaitCounter = 0; static BaseSequence* s_sequenceCurrent = NULL; BaseSequence::~BaseSequence() { } BaseSequence* BaseSequence::update(void) { return (this); } void BaseSequence::init(void) { } void BaseSequence::destroy(void) { } // 指定したフレーム分 // Update を呼ぶのをスキップする。 void WindowWait(int count) { if (count <= 0) { return; } if (s_windowLoopWaitCounter > 0) { assert("why ? crash of library memory."); } s_windowLoopWaitCounter = count; } // フレームカウントの取得 long long int WindowLoopCounter(void) { return (s_windowLoopCounter); } void GameSystemSetStartupSequence(BaseSequence* s) { if (s == NULL) { assert("StartupSequence is incorrect."); return; } s_sequenceCurrent = s; s_sequenceCurrent->init(); } bool WindowCreate(void) { // window モードの設定 TRUE 通常、 FALSE フルスクリーン ChangeWindowMode(TRUE); SetMainWindowText("GameLib"); if (SetGraphMode(WINDOW_W, WINDOW_H, 16) != DX_CHANGESCREEN_OK) { // ウインドウサイズの変更に失敗した return (false); } // ウインドウアイコン SetWindowIconID(1012); // ウインドウサイズを変更可能にするか否か 変更可能 TRUE 不可能 FALSE SetWindowSizeChangeEnableFlag(FALSE); // プログラムの二重起動を許可するか否か 許可 TRUE 非許可 FALSE SetDoubleStartValidFlag(FALSE); // 非アクティブ時に処理を続けるか否か (続ける TRUE) SetAlwaysRunFlag(FALSE); // 垂直同期信号を待つか待たないか (待つ TRUE) SetWaitVSyncFlag(FALSE); // wait_fps の邪魔をするので無視する。 // ログを表示するか否か 表示 TRUE 非表示 FALSE SetOutApplicationLogValidFlag(TRUE); // DxLib を再起動可能にする。 SetDxLibEndPostQuitMessageFlag(FALSE); // DirectDrawをマルチスレッド化するか // TRUE マルチ SetMultiThreadFlag(TRUE); // ウインドウのスタイル // 0 通常 // 1 タイトルバー無 枠あり // 2 タイトルバー無 枠なし SetWindowStyleMode(0); // 描画対象の指定 SetDrawScreen(DX_SCREEN_BACK); // 光度を設定 SetDrawBright(255, 255, 255); // 透過色を設定 SetTransColor(0, 0, 0); // Z バッファを有効化 SetUseZBuffer3D(TRUE); // Z バッファにデータを書き込む。 SetWriteZBuffer3D(TRUE); if (DxLib_Init() == -1) { return (false); } s_flagLoopEnd = false; s_windowLoopCounter = 0; GameSystemStartup(); return (true); } void WindowClose(void) { if (s_sequenceCurrent != NULL) { s_sequenceCurrent->destroy(); delete (s_sequenceCurrent); s_sequenceCurrent = NULL; } GameSystemDestroy(); DxLib_End(); } void WindowLoopBreak(void) { s_flagLoopEnd = true; } bool WindowLoop(void) { if ( ProcessMessage() == 0 && CheckHitKey(KEY_INPUT_ESCAPE) == 0 && !s_flagLoopEnd) { if (s_windowLoopWaitCounter == 0) { ClsDrawScreen(); auto next = s_sequenceCurrent->update(); if (next != s_sequenceCurrent) { if (next == NULL) { return (false); } // 画面遷移が発生 // 昔の画面を解放し新しい画面へ移る。 s_sequenceCurrent->destroy(); delete (s_sequenceCurrent); s_sequenceCurrent = next; s_sequenceCurrent->init(); } ScreenFlip(); Sleep(10); } else { Sleep(17); } // なぜ、このコードが書かれているのか、 // それは、 // もし、カウンター関連のバグがあったとして、 // そのエラーが発生するのは、 // unsigned long int の最大値、 // 約四億フレーム後。 // とゆーことがないようにするため。 if (s_windowLoopCounter > 100) { s_windowLoopCounter = 0; } s_windowLoopCounter++; if (s_windowLoopWaitCounter > 0) { s_windowLoopWaitCounter--; } } else { return (false); } return (true); } <file_sep>/* * ゲームに不要な余計な処理を隠蔽する。 * 2011 / 07 / 28 * jskny */ // 追記 // 2018/03/18 // 画面遷移システムを追加した。 #pragma once const unsigned int WINDOW_W = 800; const unsigned int WINDOW_H = 600; class BaseSequence; //------------------------------------- // user //------------------------------------- // システム起動時に一度だけ呼び出されます。 // この関数内で、最初の画面を設定したりします。 extern void GameSystemStartup(); extern void GameSystemDestroy(); extern void GameSystemSetStartupSequence(BaseSequence* s); //------------------------------------- // DxLib を直接制御する時に使う。 //------------------------------------- // library extern bool WindowCreate(void); extern void WindowClose(void); extern bool WindowLoop(void); // ウィンドウループから抜ける。 extern void WindowLoopBreak(void); // 指定したフレーム分 // Update を呼ぶのをスキップする。 extern void WindowWait(int count); // フレームカウントの取得 extern long long int WindowLoopCounter(void); //------------------------------------- // 画面遷移管理 //------------------------------------- // 基本となる画面 // これを継承して各種画面を作成する。 class BaseSequence { public: virtual ~BaseSequence() = 0; virtual BaseSequence* update(void) = 0; virtual void init(void) = 0; // シーケンス起動時に呼ばれる。 virtual void destroy(void) = 0; }; <file_sep>/* * <NAME> * 久しぶりにゲームでも作る? * 2018/03/18 * jskny */ #include <DxLib.h> #include "GameWindow.h" class GTitle : public BaseSequence { public: void init(); void destroy(void); BaseSequence* update(); private: int m_handleFontTitle; }; void GTitle::init() { this->m_handleFontTitle = CreateFontToHandle("メイリオ", 24, 2, DX_FONTTYPE_NORMAL); } void GTitle::destroy(void) { DeleteFontToHandle(this->m_handleFontTitle); } BaseSequence* GTitle::update() { auto ret = this; DrawStringToHandle(0, 0, "Hello World !", GetColor(0xFF, 0, 0), this->m_handleFontTitle); return (ret); } void GameSystemStartup() { auto p = new GTitle(); // メモリ解放処理は、ライブラリが行う。 GameSystemSetStartupSequence(p); return; } void GameSystemDestroy() { }
f1a6b8f39488479e26eb0a6e38cae754b444b9da
[ "Markdown", "C++" ]
4
Markdown
jskny/Mutsuki
f97db05ad49046e61d460729fe462bc5086c08b8
29112952958c4abcc85c4220024745482695298b
refs/heads/master
<repo_name>wayne2k/Quill18creates_DragDropUI<file_sep>/Assets/DropZone.cs using UnityEngine; using UnityEngine.EventSystems; using System.Collections; public class DropZone : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler { public Draggable.ItemTypes dropType = Draggable.ItemTypes.INVENTORY; public void OnDrop (PointerEventData eventData) { Debug.Log (eventData.pointerDrag.name + " Was dropped on " + gameObject.name); Draggable droppedItem = eventData.pointerDrag.GetComponent<Draggable> (); if (droppedItem != null) { if (dropType == Draggable.ItemTypes.INVENTORY || droppedItem.itemType == dropType) { droppedItem.parentToReturnTo = transform; } } } public void OnPointerEnter (PointerEventData eventData) { if (eventData.pointerDrag == null) return; Draggable droppedItem = eventData.pointerDrag.GetComponent<Draggable> (); if (droppedItem != null) { if (dropType == Draggable.ItemTypes.INVENTORY || droppedItem.itemType == dropType) { droppedItem.placeholderParent = transform; } } } public void OnPointerExit (PointerEventData eventData) { if (eventData.pointerDrag == null) return; Draggable droppedItem = eventData.pointerDrag.GetComponent<Draggable> (); if (droppedItem != null && droppedItem.placeholderParent == transform) { if (dropType == Draggable.ItemTypes.INVENTORY || droppedItem.itemType == dropType) { droppedItem.placeholderParent = droppedItem.parentToReturnTo; } } } } <file_sep>/README.md # Quill18creates_DragDropUI Unity3d Tutorial - quill18creates Drag and Drop <file_sep>/Assets/Draggable.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public enum ItemTypes { WEAPON, HEAD, CHEST, LEGS, FEET, INVENTORY } public ItemTypes itemType = ItemTypes.WEAPON; [HideInInspector] public Transform parentToReturnTo; [HideInInspector] public Transform placeholderParent; Vector3 dragOffset; GameObject placeholder = null; public void OnBeginDrag (PointerEventData eventData) { Debug.Log ("Begin Drag"); placeholder = new GameObject ("PlaceHolder"); placeholder.transform.SetParent (transform.parent); LayoutElement layoutElement = placeholder.AddComponent <LayoutElement> (); layoutElement.preferredWidth = GetComponent<LayoutElement> ().preferredWidth; layoutElement.preferredHeight = GetComponent<LayoutElement> ().preferredHeight; layoutElement.flexibleWidth = 0f; layoutElement.flexibleHeight = 0f; placeholder.transform.SetSiblingIndex (transform.GetSiblingIndex ()); dragOffset = transform.position - (Vector3) eventData.position; parentToReturnTo = transform.parent; placeholderParent = parentToReturnTo; transform.SetParent (transform.parent.parent); GetComponent<CanvasGroup> ().blocksRaycasts = false; } public void OnDrag (PointerEventData eventData) { // Debug.Log ("Draggign"); transform.position = (Vector3) eventData.position + dragOffset; if (placeholder.transform.parent != placeholderParent) { placeholder.transform.SetParent (placeholderParent); } int newSiblingIndex = placeholderParent.childCount; for (int i = 0; i < placeholderParent.childCount; i++) { if (transform.position.x < placeholderParent.GetChild (i).transform.position.x) { newSiblingIndex = i; if (placeholder.transform.GetSiblingIndex () < newSiblingIndex) { newSiblingIndex --; } break; } } placeholder.transform.SetSiblingIndex (newSiblingIndex); } public void OnEndDrag (PointerEventData eventData) { Debug.Log ("End Drag"); dragOffset = Vector3.zero; transform.SetParent (parentToReturnTo); transform.SetSiblingIndex (placeholder.transform.GetSiblingIndex ()); GetComponent<CanvasGroup> ().blocksRaycasts = true; Destroy (placeholder); } }
0f85662eecf63b87bf8c77d9d5d38bab90bc9fac
[ "Markdown", "C#" ]
3
C#
wayne2k/Quill18creates_DragDropUI
4d2d78a151013520a10b74ad8cffac1cd950e1e2
9172afdd58cb9cb51a8b68bc9dcfd892f082dc67
refs/heads/master
<file_sep>library(data.table) library(ggplot2) library(lubridate) library(dplyr) library(tidyr) library(rebus) zt <- function(v,na.rm=TRUE) { return((v - mean(v,na.rm=na.rm))/sd(v,na.rm=na.rm)) } gt <- fread("./data/GlobalTemperatures.csv") %>% mutate( dt=ymd(dt), year=year(dt), LandAverageTemperature_zt = zt(LandAverageTemperature), LandAndOceanAverageTemperature_zt = zt(LandAndOceanAverageTemperature) ) p <- ggplot(gt,aes(x=dt,y=LandAverageTemperature_zt))+geom_smooth(method='loess') print(p) co2 <- fread("./data/API_EN.ATM.CO2E.KT_DS2_en_csv_v2.csv") %>% filter(`Country Name`=='World') %>% select(matches("[0-9][0-9][0-9][0-9]")) %>% gather("year","kt_co2") %>% mutate( year=as.numeric(year), kt_co2=as.numeric(kt_co2), kt_co2_zt=zt(kt_co2) ) p2 <- ggplot(co2,aes(x=year,y=kt_co2_zt))+geom_smooth(method='loess') print(p2) co2ppm <- fread("./data/archive.csv") %>% mutate( co2ppm_zt = zt(`Carbon Dioxide (ppm)`), year=Year ) %>% select(year,co2ppm_zt) %>% gather("year",co2ppm_zt) %>% group_by(year) %>% summarise(co2ppm_zt_ya = mean(co2ppm_zt)) %>% filter(!is.na(co2ppm_zt_ya)) %>% select(year,co2ppm_zt_ya) co2small <- co2 %>% select(year,kt_co2_zt) %>% filter(!is.na(kt_co2_zt)) gtsmall <- gt %>% select( year, LandAverageTemperature_zt, LandAndOceanAverageTemperature_zt ) %>% group_by(year) %>% summarise( LandAverageTemperature_zt_ya = mean(LandAverageTemperature_zt), LandAndOceanAverageTemperature_zt_ya = mean(LandAndOceanAverageTemperature_zt) ) %>% filter( !is.na(LandAverageTemperature_zt_ya) & !is.na(LandAndOceanAverageTemperature_zt_ya) ) wt_co2 <- co2small %>% left_join(gtsmall,by="year") %>% left_join(co2ppm,by="year") %>% gather("key","value",2:5) p3 <- ggplot(wt_co2,aes(x=year,y=value,color=key)) +geom_line() +geom_smooth(method='loess') print(p3) wt_co2_corr <- co2small %>% left_join(gtsmall,by="year") cor(wt_co2_corr$LandAverageTemperature_zt_ya,wt_co2_corr$kt_co2_zt) cor(wt_co2_corr$LandAndOceanAverageTemperature_zt_ya,wt_co2_corr$kt_co2_zt) <file_sep># ds_warming AN investigation in global warming data sets and co2 emissions
c5fdab77e4b896c888c642e67206d1644c0dd74d
[ "Markdown", "R" ]
2
R
johanjordaan/ds_warming
5d5e6ccf00589dd6388258c6b539f954ce398f18
0a42efe721ab0d9d204bb43e27f73f36a76e4e96
refs/heads/master
<file_sep> // Part of https://todbot.github.io/blink1-webhid/ let canvas = document.getElementById('canvas_picker').getContext('2d'); let rgbinput = document.getElementById('rgb'); let hexinput = document.getElementById('hex'); let status = document.getElementById('status'); let canvas_picker = document.getElementById('canvas_picker'); canvas_picker.addEventListener('click', handleClick); canvas_picker.addEventListener('mousemove', handleClick); document.getElementById('connect-button').addEventListener('click', handleConnect); // create an image object and set its source let img = new Image(); img.src = 'HTML-Color-Code-300x255.gif'; var isConnected = false; // copy the image to the canvas img.addEventListener('load', function() { canvas.drawImage(img,0,0); }); async function handleConnect() { const device = await openDevice(); if( !device ) { console.log("*** no device!"); } await fadeToColor(device, [100,100,100], 100, 0 ); isConnected = true; status.innerHTML = "connected"; } // http://www.javascripter.net/faq/rgbtohex.htm function rgbToHex(R,G,B) { return toHex(R)+toHex(G)+toHex(B); } function toHex(n) { n = parseInt(n,10); if (isNaN(n)) return "00"; n = Math.max(0,Math.min(n,255)); return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16); } async function handleClick(event) { // get click coordinates in image space const x = event.offsetX; const y = event.offsetY; // get image data and RGB values const img_data = canvas.getImageData(x, y, 1, 1).data; const r = img_data[0]; const g = img_data[1]; const b = img_data[2]; const rgbstr = r + ',' + g + ',' + b; const hexstr = rgbToHex(r,g,b); rgbinput.value = rgbstr; hexinput.value = '#' + hexstr; console.log("hex:",hexstr); if( isConnected ) { const device = await openDevice(); await fadeToColor(device, [r,g,b], 100, 0 ); } } async function openDevice() { const vendorId = 0x27b8; // blink1 vid const productId = 0x01ed; // blink1 pid const devices = await navigator.hid.getDevices(); let device = devices.find(d => d.vendorId === vendorId && d.productId === productId); if (!device) { device = await navigator.hid.requestDevice({ filters: [{ vendorId, productId }], }); } if (!device.opened) { await device.open(); } return device; } async function fadeToColor(device, [r, g, b], fadeMillis, ledn ) { const reportId = 1; const dmsh = (fadeMillis/10) >> 8; const dmsl = (fadeMillis/10) % 0xff; // NOTE: do not put reportId in data array (at least on MacOS), // and array must be exactly REPORT_COUNT big (8 bytes in this case) const data = Uint8Array.from([0x63, r, g, b, dmsh, dmsl, ledn, 0x00]); try { await device.sendFeatureReport(reportId, data); } catch (error) { console.error('fadeToColor: failed:', error); } }
b898c87dbea62b00e630b9bdd5c7093dd4e70c23
[ "JavaScript" ]
1
JavaScript
itnachos/blink1-webhid
8600891ad594530215b7fabaaeebaaf17fa71e32
5937038258b9b83099978333986fcdb2a74a287e
refs/heads/dev
<file_sep>var express = require('express'); var passport = require('passport') var BearerStrategy = require('passport-azure-ad').BearerStrategy let tenantID= `${process.env.tenantID}` let clientID= `${process.env.clientID}` let audience= `${process.env.audience}` let options = { identityMetadata: `https://login.microsoftonline.com/${process.env.tenantID}/v2.0/well-known/openid-configuration'`, // Required, the client ID of your app in AAD clientID: `${process.env.clientID}`, // Required if you want to provide the issuer(s) you want to validate instead of using the issuer from metadata // issuer could be a string or an array of strings of the following form: 'https://sts.windows.net/<tenant_guid>/v2.0' issuer: `https://sts.windows.net/${process.env.tenantID}/`, // The additional scopes we want besides 'openid'. scope: ['user_impersonation'], // Optional, 'error', 'warn' or 'info' loggingLevel: 'info', passReqToCallback: false } let bearerStrategy = new BearerStrategy(options, (token, done) => { done(null, {}, token) }) var app = express(); app.use(require('morgan')('combined')); app.use(passport.initialize()); passport.use(bearerStrategy); app.use((req, res, next) => { res.header('Access-Control-Allow-origin', '*'); res.header( 'Acess-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Accept' ); next(); }) app.all( '/', passport.authenticate('oauth-bearer', { session: false}), (req, res) => { let claims = req.authinfo; console.log('User info: ', req.user); console.log('Validated claims: ', claims); res.status(200).json({ name: claims['name']}); } ); let port = process.env.port || 4000; app.listen(port, () => { console.log(`listening on port ${port}` ) });
57dcef18e7373c153e20612af6f422b08ea46737
[ "JavaScript" ]
1
JavaScript
chinazor-allen/az-api-example
b738c63135bc565df2788ac2af93b12b82906dbb
9eca2e88c0581ab168401ae16d22cc1f682d6723
refs/heads/master
<repo_name>adamgreig/phabd<file_sep>/sandbox/snr.py import numpy as np import matplotlib.pyplot as plt def add_noise(tx, snr): """ Add AGWN to *tx* so it has SNR=*snr*. Returns tx+noise. """ tx_pwr = np.sum(np.abs(tx)**2)/tx.size noise = np.random.randn(tx.size) noise_pwr = np.sum(np.abs(noise)**2)/noise.size return tx + noise * np.sqrt((tx_pwr / noise_pwr) * (10.0 ** (-snr / 10.0))) if __name__ == "__main__": N = 128 t = np.arange(N) tx = np.sqrt(2.0) * np.sin(2.0*np.pi*t*(5.0/N)) rx = add_noise(tx, 0.0) plt.plot(tx, color='g') plt.plot(rx, color='r') plt.show() <file_sep>/phabd.py import multiprocessing import numpy as np import matplotlib.pyplot as plt NBITS = 2056 BD = 50.0 SR = 44100.0 F0 = 850.0 F1 = 1150.0 def generate_bitstream(n=NBITS): np.random.seed() return np.random.random_integers(0, 1, n) def generate_pure_tones(n, phi=0, f0=F0, f1=F1, sr=SR, bd=BD): """ Generate sinusoids at *f0* and *f1* with phase *phi*, *n* samples at *sr*. """ t = np.linspace(0, 1.0/bd, n).reshape(-1, 1) s0 = np.sqrt(2.0) * np.sin(2.0 * np.pi * f0 * t + phi) s1 = np.sqrt(2.0) * np.sin(2.0 * np.pi * f1 * t + phi) return (s0, s1) def fsk_samples(bits, phi=0, f0=F0, f1=F1, sr=SR, bd=BD): """ FSK modulate *bits* with parameters. Returns sample vector. Currently starts each new bit at zero phase, which is not the same as selecting from two clock sources. """ N = sr/bd s0, s1 = generate_pure_tones(N, phi, f0, f1, sr, bd) output = np.empty(bits.size * N).reshape(-1, 1) for idx, bit in enumerate(bits): output[idx*N:(idx+1)*N] = s1 if bit else s0 return output def add_noise(tx, snr): """ Add AGWN to *tx* so it has SNR=*snr*. Returns tx+noise. """ tx_pwr = np.sum(np.power(2, np.abs(tx)))/tx.size noise = np.random.randn(tx.size).reshape(-1, 1) noise_pwr = np.sum(np.power(2, np.abs(noise)))/noise.size return tx + noise * np.sqrt((tx_pwr / noise_pwr) * np.power(10, -snr/10.0)) def bit_log_likelihood(rx, snr, phi=0, f0=F0, f1=F1, sr=SR, bd=BD): """ Compute the log likelihood of the received baseband signal being 0 or 1, assuming that *rx* has *phi* phase and *snr* is the correct noise power. """ # overconstrained on SR and BD, given rx.size. # choose to ignore BD. N = rx.size if abs(bd - sr/N) > (bd/20.0): print("W bit_log_likelihood: rx.size {0} not ok".format(rx.size)) bd = sr/N ss = np.power(10.0, -snr / 10.0) k = -N/2.0 * np.log(2 * ss * np.pi) s0, s1 = generate_pure_tones(rx.size, phi, f0, f1, sr, bd) ll0 = k - 1.0/(2*ss) * np.sum(np.power(2, rx-s0)) ll1 = k - 1.0/(2*ss) * np.sum(np.power(2, rx-s1)) return (ll0, ll1) def ll_to_bits(ll0, ll1): """Convert log likelihoods to a bitstream.""" return (ll1 > ll0).astype(np.uint8) def bits_to_rx(bits, snr, phi=0, f0=F0, f1=F1, sr=SR, bd=BD): """Modulate a bitstream to a received bytestream.""" tx = fsk_samples(bits, np.pi/8, f0, f1, sr, bd) return add_noise(tx, snr) def rx_to_bits(rx, snr, f0=F0, f1=F1, sr=SR, bd=BD): """Decode a sample stream to a bitstream.""" N = SR/BD nbits = int(rx.size / N) ll0 = np.empty(nbits) ll1 = np.empty(nbits) for i in range(nbits): ll0[i], ll1[i] = bit_log_likelihood(rx[i*N:(i+1)*N], snr) return ll_to_bits(ll0, ll1) def ber_for_snr(snr): """Find the BER at SNR=*snr*. Returns BER.""" nbits = 0 errs = 0 while errs < 2 and nbits < 1024*1024: print(" snr={0:+0.02f} nbits={1}".format(snr, nbits)) tx_bits = generate_bitstream(1024) rx = bits_to_rx(tx_bits, snr) rx_bits = rx_to_bits(rx, snr) errs += np.sum(np.abs(tx_bits - rx_bits)) nbits += 1024 ber = float(errs) / nbits print("*** snr={0:0.02f} ber={1:.2e}".format(snr, ber)) return ber if __name__ == "__main__": snrs = np.linspace(-15, -5, 11) pool = multiprocessing.Pool(processes=8) bers = pool.map(ber_for_snr, snrs) plt.plot(snrs, bers) plt.yscale('log') plt.xlabel("SNR (dB)") plt.ylabel("BER") plt.grid() plt.show()
10a5f6598cd8895702a2e232d863e829baac4fd7
[ "Python" ]
2
Python
adamgreig/phabd
7dcbde0838f3a958d21fefb34e0c1459b07af21c
8c829e9e3fac4af5c86c83dd43fa3fd31c83e740
refs/heads/master
<repo_name>mbarkhau/omnibust<file_sep>/requirements.txt pytest==2.3.5<file_sep>/test_omnibust.py from __future__ import print_function import os import sys import time import codecs import tempfile import omnibust as ob try: from cStringIO import StringIO except ImportError: from io import StringIO PY2 = sys.version_info[0] == 2 if PY2: from itertools import imap as map range = xrange else: unicode = str def _write_tmp_file(content, path=None): if path is None: _, path = tempfile.mkstemp() with codecs.open(path, 'wb', encoding="utf-8") as f: f.write(content) return path def touch(path): if os.path.exists(path): with open(path, 'r') as f: content = f.read() else: content = "" with open(path, 'w') as f: f.write(content) def _mk_test_project(): root = tempfile.mkdtemp() subdir_a = os.path.join(root, "subdir_a") subdir_b = os.path.join(root, "subdir_b") touch(os.path.join(root, "foo.js")) touch(os.path.join(root, "bar.js")) touch(os.path.join(root, "buzz.py")) touch(os.path.join(root, "baz.jpg")) os.makedirs(subdir_a) touch(os.path.join(subdir_a, "a.py")) touch(os.path.join(subdir_a, "a.pyc")) touch(os.path.join(subdir_a, "b.py")) touch(os.path.join(subdir_a, "b.pyc")) os.makedirs(subdir_b) touch(os.path.join(subdir_b, "a.js")) touch(os.path.join(subdir_b, "b.js")) return root expansions = { "${foo}": ["exp_a", "exp_b"], "{{bar}}": ["exp_c", "exp_d", "exp_e"] } p_ref = ob.Ref("foo/static", "test.html", 123, "url('/static/app.js')", "/static/app.js", "", ob.PLAIN_REF) qs_ref = ob.Ref("bar/static", "test.html", 123, "url('/static/app.js?_cb_=123456&a=b')", "/static/app.js", "123456", ob.QS_REF) fn_ref = ob.Ref("assets/baz", "test.html", 123, "url('/static/app_cb_123456.js?foo=12&bar=34')", "/static/app.js", "123456", ob.FN_REF) def test_flatten(): assert ob.flatten([(1, 2, 3), (4, 5, 6)]) == [1, 2, 3, 4, 5, 6] assert ob.flatten(((1, 2, 3), (4, 5, 6))) == [1, 2, 3, 4, 5, 6] def test_ext(): assert ob.ext("foo.bar") == ".bar" assert ob.ext("foo/bar.baz") == ".baz" assert ob.ext("foo/bar.tar.gz") == ".gz" def test_extension_globs(): extensions = ob.extension_globs([ "test.foo", "test.bar", "test.baz", "testb.foo" ]) assert sorted(extensions) == ["*.bar", "*.baz", "*.foo"] def test_b32enc(): assert len(ob.b32enc(1)) == 13 assert len(ob.b32enc(1.1)) == 13 assert len(ob.b32enc(123456)) == 13 assert ob.b32enc(123456) == "idracaaaaaaaa" assert isinstance(ob.b32enc(b"test"), unicode) assert ob.b32enc("test") == "orsxg5a" def test_filestat(): fp, path = tempfile.mkstemp() time.sleep(0.02) touch(path) assert ob.filestat(path) == ob.filestat(path) stat = ob.filestat(path) time.sleep(0.02) touch(path) assert stat != ob.filestat(path) assert ob.filestat(path) == ob.filestat(path) def test_digest_data(): digest = ob.digest_data assert isinstance(digest("test"), unicode) assert digest("test") == digest("test") assert digest("foo") != digest("bar") assert digest("test", 'sha1') == digest("test", 'sha1') assert digest("foo", 'sha1') != digest("bar", 'sha1') assert digest("test", 'sha1') != digest("test", 'md5') def test_buster(): path_a = _write_tmp_file("test") time.sleep(0.02) path_b = _write_tmp_file("test") crc_buster = ob.mk_buster('crc32', 4, 4) assert crc_buster([path_a])[:4] == crc_buster([path_b])[:4] assert crc_buster([path_a])[4:] != crc_buster([path_b])[4:] path_a = _write_tmp_file("foo") path_b = _write_tmp_file("bar") assert crc_buster([path_a]) != crc_buster([path_b]) def test_bust_paths(): buster = ob.mk_buster('sha1') path_a = _write_tmp_file("foo") path_b = _write_tmp_file("bar") bustcode_1 = buster([path_a, path_b]) bustcode_2 = buster([path_a, path_b]) assert bustcode_1 == bustcode_2 time.sleep(0.02) touch(path_a) bustcode_3 = buster([path_a, path_b]) assert bustcode_1 != bustcode_3 time.sleep(0.02) open(path_a, 'w').write("baz") bustcode_4 = buster([path_a, path_b]) assert bustcode_3 != bustcode_4 bustcode_5 = buster([path_a]) bustcode_6 = buster([path_a]) assert bustcode_5 == bustcode_6 def test_glob_matcher(): js_matcher = ob.glob_matcher("*.js") assert js_matcher("foo.js") assert js_matcher("foo/bar.js") assert not js_matcher("foo/bar.py") jpg_matcher = ob.glob_matcher(("*.jpg", "*.jpeg")) assert jpg_matcher("foo.jpg") assert jpg_matcher("foo.jpg") assert jpg_matcher("foo/bar.jpeg") assert jpg_matcher("foo/bar.jpeg") assert not jpg_matcher("foo/bar.py") assert not jpg_matcher("foo/bar.py") def test_filter_longest(): elems = ["abcdefghij", "aabbccddeeffgghhii", "aabbccddeeeef"] match = lambda i, e: ord(e[i]) <= ord("e") length, longest = ob.filter_longest(match, elems) assert longest[:length] == "aabbccddeeee" match = lambda i, e: i < 9 and e[i] == "abcdefghi"[i] length, longest = ob.filter_longest(match, elems) assert longest[:length] == "abcdefghi" def test_mk_fn_dir_map(): paths = [ "test/test.js", "foo/bar.js", "foo/baz.js", "bar/bar.js", ] fn_dir_map = ob.mk_fn_dir_map(paths) assert len(fn_dir_map) == 3 assert len(fn_dir_map['test.js']) == 1 assert len(fn_dir_map['bar.js']) == 2 def test_closest_matching_path(): dirpaths = set(["foo/static"]) path = ob.closest_matching_path("bar/abc.js", "/test", dirpaths) assert path == "foo/static" dirpaths = ["foo/static", "foo/assets", "bar/static"] path = ob.closest_matching_path("foo/abc.js", "/static", dirpaths) assert path == "foo/static" path = ob.closest_matching_path("bar/static", "", dirpaths) assert path == "bar/static" def test_find_static_filepath(): static_fn_dirs = ob.mk_fn_dir_map([ "foo/assets/app.js", "bar/static/js/app.js", "bar/static/lib/app.js", ]) assert "bar/static/js/app.js" == ob.find_static_filepath( "bar", "/static/js/app.js", static_fn_dirs) assert "bar/static/js/app.js" == ob.find_static_filepath( "foo", "/static/js/app.js", static_fn_dirs) assert "bar/static/lib/app.js" == ob.find_static_filepath( "foo", "/lib/app.js", static_fn_dirs) assert "foo/assets/app.js" == ob.find_static_filepath( "foo", "/app.js", static_fn_dirs) def test_find_static_filepaths(): static_fn_dirs = ob.mk_fn_dir_map([ "foo/static/img/logo_a.png", "foo/static/img/logo_b.png", "foo/static/img/logo_c.png", ]) ref_paths = [ "logo_a.png", "logo_b.png", "logo_c.png", "logo_d.png" ] static_paths = set(ob.find_static_filepaths("foo", ref_paths, static_fn_dirs)) assert len(static_paths) == 3 assert "foo/static/img/logo_a.png" in static_paths assert "foo/static/img/logo_b.png" in static_paths assert "foo/static/img/logo_c.png" in static_paths def test_expand_path(): paths = ob.expand_path("/static/foo_${foo}.png", expansions) assert len(paths) == 3 assert "/static/foo_${foo}.png" in paths assert "/static/foo_exp_a.png" in paths assert "/static/foo_exp_b.png" in paths paths = ob.expand_path("/static/bar_{{bar}}.js", expansions) assert len(paths) == 4 assert "/static/bar_{{bar}}.js" in paths assert "/static/bar_exp_c.js" in paths assert "/static/bar_exp_d.js" in paths assert "/static/bar_exp_e.js" in paths def test_ref_paths(): ref = ob.Ref("foo/static", "test.html", 123, "url('/static/app_${foo}.js')", "/static/app_${foo}.js", "", ob.PLAIN_REF) static_paths = list(ob.ref_paths(ref, expansions)) assert len(static_paths) == 3 assert "/static/app_${foo}.js" in static_paths assert "/static/app_exp_a.js" in static_paths assert "/static/app_exp_b.js" in static_paths def test_mk_plainref(): assert ob.mk_plainref(p_ref) == "url('/static/app.js')" assert ob.mk_plainref(fn_ref) == "url('/static/app.js?foo=12&bar=34')" assert ob.mk_plainref(qs_ref) == "url('/static/app.js?a=b')" def test_set_fn_bustcode(): busted = ob.set_fn_bustcode(p_ref, "abcdef") assert busted == "url('/static/app_cb_abcdef.js')" busted = ob.set_fn_bustcode(fn_ref, "abcdef") assert busted == "url('/static/app_cb_abcdef.js?foo=12&bar=34')" busted = ob.set_fn_bustcode(qs_ref, "abcdef") assert busted == "url('/static/app_cb_abcdef.js?a=b')" def test_set_qs_bustcode(): busted = ob.set_qs_bustcode(p_ref, "abcdef") assert busted == "url('/static/app.js?_cb_=abcdef')" busted = ob.set_qs_bustcode(fn_ref, "abcdef") assert busted == "url('/static/app.js?_cb_=abcdef&foo=12&bar=34')" busted = ob.set_qs_bustcode(qs_ref, "abcdef") assert busted == "url('/static/app.js?_cb_=abcdef&a=b')" def test_replace_bustcode(): busted = ob.replace_bustcode(fn_ref, "abcdef") assert busted == "url('/static/app_cb_abcdef.js?foo=12&bar=34')" busted = ob.replace_bustcode(qs_ref, "abcdef") assert busted == "url('/static/app.js?_cb_=abcdef&a=b')" def test_updated_fullref(): # "codepath, lineno, reftype, fullref, refpath, bustcode" rewritten = ob.updated_fullref(p_ref, "abcdef", ob.QS_REF) assert rewritten == "url('/static/app.js?_cb_=abcdef')" rewritten = ob.updated_fullref(qs_ref, "abcdef", ob.QS_REF) assert rewritten == "url('/static/app.js?_cb_=abcdef&a=b')" rewritten = ob.updated_fullref(fn_ref, "abcdef", ob.FN_REF) assert rewritten == "url('/static/app_cb_abcdef.js?foo=12&bar=34')" nodir_ref = ob.Ref("static", "test.html", 123, "url('logo.png?_cb_=123456&a=b')", "logo.png", "123456", ob.QS_REF) rewritten = ob.updated_fullref(nodir_ref, "abcdef") assert rewritten == "url('logo.png?_cb_=abcdef&a=b')" rewritten = ob.updated_fullref(nodir_ref, "abcdef", ob.FN_REF) assert rewritten == "url('logo_cb_abcdef.png?a=b')" def test_plainref_line_parser(): line = '<img src="/static/img/logo.png"/>' _, ref_path, bust, ref_type = next(ob.plainref_line_parser(line)) assert not bust assert ref_path == "/static/img/logo.png" assert ref_type == ob.PLAIN_REF line = '<img src="/static/img/logo_cb_1234.png"/>' try: next(ob.plainref_line_parser(line)) assert False, "should have failed with StopIteration" except StopIteration: pass line = '<img src="/static/img/logo.png?_cb_=1234"/>' try: next(ob.plainref_line_parser(line)) assert False, "should have failed with StopIteration" except StopIteration: pass def test_markedref_line_parser(): line = '<img src="/static/img/logo.png"/>' try: next(ob.markedref_line_parser(line)) assert False, "should have failed with StopIteration" except StopIteration: pass line = '<img src="/static/img/logo_cb_1234.png"/>' _, ref_path, bust, ref_type = next(ob.markedref_line_parser(line)) assert bust == "1234" assert ref_path == "/static/img/logo.png" assert ref_type == ob.FN_REF line = '<img src="/static/img/logo.png?_cb_=1234"/>' _, ref_path, bust, ref_type = next(ob.markedref_line_parser(line)) assert bust == "1234" assert ref_path == "/static/img/logo.png" assert ref_type == ob.QS_REF def test_parse_content_refs(): assert len(ob.parse_content_refs("")) == 0 refs = ob.parse_content_refs(""" <img src="data:image/png;base64,iV=="> <script src="/static/js/lib.js"></script> <script src="/static/js/app.js?_cb_=123"></script> <script src="/static/js/app.js?foo=bar&_cb_=abc"></script> <link href="/static/css/style_cb_xyz.css"> "/assets/img/logo_cb_lmn.png" """) assert len(refs) == 5 assert refs[0].type == ob.PLAIN_REF assert refs[1].type == ob.QS_REF assert refs[2].type == ob.QS_REF assert refs[3].type == ob.FN_REF assert refs[4].type == ob.FN_REF paths = set((r.path for r in refs)) assert "/static/js/lib.js" in paths assert "/static/js/app.js" in paths assert "/static/css/style.css" in paths busts = set((r.bustcode for r in refs)) assert "123" in busts assert "abc" in busts assert "lmn" in busts assert "xyz" in busts def test_iter_refs(): pass # TODO def test_iter_filepaths(): root = _mk_test_project() iterfp = lambda *a, **k: list(ob.iter_filepaths(*a, **k)) assert len(iterfp(root)) == 10 assert len(iterfp(root, "*.js")) == 4 assert iterfp(root, "*.jpg")[0].endswith("baz.jpg") assert len(iterfp(root, file_exclude="*.js")) == 6 assert len(iterfp(root, dir_filter="*subdir_a")) == 4 assert len(iterfp(root, dir_filter="*subdir_a", file_filter="*.py")) == 2 def test_multi_iter_filepaths(): root = _mk_test_project() dirs = [os.path.join(root, "subdir_a"), os.path.join(root, "subdir_b")] assert len(list(ob.multi_iter_filepaths(dirs))) == 6 def test_init_project_paths(): pass # TODO def test_cfg_project_paths(): pass # TODO def test_ref_print_wrapper(): refs = [ (ob.Ref("foo/static", "test.html", 123, "url('/static/app.js')", "/static/app.js", "", ob.PLAIN_REF), ("foo/static/app.js",), "url('/static/app.js?_cb_=test')", ) ] orig_out = sys.stdout tmp_out = sys.stdout = StringIO() assert list(ob.ref_print_wrapper(refs)) == refs sys.stdout = orig_out lines = tmp_out.getvalue().splitlines() assert len(lines) == 3 assert lines[0] == "foo/static/test.html" assert lines[1].endswith("url('/static/app.js')") assert "_cb_=test" not in lines[1] assert "_cb_=test" in lines[2] def test_rewrite_content(): pass # TODO def test_scan_project(): pass # TODO def test_read_cfg(): cfg = ob.read_cfg(['--no-init']) assert isinstance(cfg['static_dirs'], list) assert isinstance(cfg['code_dirs'], list) assert isinstance(cfg['static_fileglobs'], list) assert isinstance(cfg['code_fileglobs'], list) assert isinstance(cfg['bust_length'], int) assert isinstance(cfg['stat_length'], int) assert isinstance(cfg['digest_length'], int) def test_dumplist(): assert ob.dumpslist(["foo", "bar", "baz"]) == """[ "foo", "bar", "baz" ]""" def test_strip_comments(): stripped = ob.strip_comments(""" http://foo.com/bar // a comment """).strip() assert stripped == "http://foo.com/bar" stripped = ob.strip_comments(""" foo bar baz // a comment """).strip() assert stripped == "foo bar baz" def test_get_flag(): args = ["--foo", "--bar", "--baz"] assert ob.get_flag(args, '--foo') assert not ob.get_flag(args, '--test') assert not ob.get_flag([], '--foo') def test_get_command(): assert ob.get_command(["init"]) == "init" try: ob.get_command([]) assert False, "expected BaseError because of missing command" except ob.BaseError: pass try: ob.get_command(["foo"]) assert False, "expected BaseError because of invalid command" except ob.BaseError: pass def test_get_target_reftype(): assert ob.get_target_reftype(["update", "--filename"]) == ob.FN_REF assert ob.get_target_reftype(["update", "--querystring"]) == ob.QS_REF assert ob.get_target_reftype(["update"]) is None def test_get_opt(): assert ob.get_opt(["--baz", "--foo=bar"], '--foo') == "bar" assert ob.get_opt(["--baz", "--foo", "bar"], '--foo') == "bar" assert ob.get_opt(["baz", "--foo", "bar"], '--foo') == "bar" try: ob.get_opt(["--baz", "--foo=bar"], '--baz') assert False, "expected KeyError" except KeyError: pass if __name__ == '__main__': # quick and dirty test harness, mainly for python3 and win compat testing fail = [] for k, v in list(locals().items()): if k.startswith('test_'): try: v() print(".", end="") except Exception as ex: fail.append("Failed: %s\nReason: %s %s\n" % (k, type(ex), ex)) print("F", end="") sys.stdout.flush() print("") for f in fail: print(f) <file_sep>/omnibust/__init__.py #!/usr/bin/env python """Omnibust v0.1.2 - A universal cachebusting script Omnibust will scan the files of your web project for static resources (js, css, png) and also for urls in your sourcecode (html, js, css, py, rb, etc.) which reference these resources. It will add or update a cachebust parameter on any such urls based on the static resources they reference. First steps: omnibust init # scan and write omnibust.cfg omnibust status # view updated urls omnibust rewrite # add or update cachebust params Usage: omnibust (--help|--version) omnibust init (--filename | --querystring) omnibust status [--no-init] [--filename | --querystring] omnibust rewrite [--no-init] [--filename | --querystring] Options: -h --help Display this message -v --verbose Verbose output -q --quiet No output --version Display version number -n --no-init Use default configuration to scan for and update existing '_cb_' cachebust parameters. --querystring Rewrites all references so the querystring contains a cachebust parameter. --filename Rewrites all references so the filename contains a cachebust parameter. """ from __future__ import print_function import time import base64 import codecs import collections import fnmatch import hashlib import json import os import re import struct import sys import zlib PY2 = sys.version_info[0] == 2 if PY2: from itertools import imap as map range = xrange else: unicode = str class BaseError(Exception): pass class PathError(BaseError): def __init__(self, message, path): self.path = path self.message = message Ref = collections.namedtuple('Ref', ( "code_dir", "code_fn", "lineno", "full_ref", "path", "bustcode", "type" )) # util functions def get_version(): return tuple(map(int, __doc__[10:16].split("."))) __version__ = ".".join(map(unicode, get_version())) def ref_codepath(ref): return os.path.join(ref.code_dir, ref.code_fn) def ext(path): return os.path.splitext(path)[1] def extension_globs(filenames): return list(set("*" + os.path.splitext(fn)[1] for fn in filenames)) def flatten(lists): res = [] for sublist in lists: res.extend(sublist) return res def b32enc(val): if isinstance(val, float): val = struct.pack("<d", val) if isinstance(val, int): val = struct.pack("<q", val) if isinstance(val, unicode): val = val.encode('utf-8') b32val = base64.b32encode(val) return b32val.decode('ascii').replace("=", "").lower() def digest_data(data, digester_name='sha1'): if isinstance(data, unicode): data = data.encode('utf-8') if hasattr(hashlib, digester_name): hashval = hashlib.new(digester_name, data).digest() else: hashval = zlib.crc32(data) return b32enc(hashval) def filestat(filepath): # digesting ensures any change in the file modification # time is reflected in all/most of the returned bytes return digest_data(unicode(os.path.getmtime(filepath))) def mk_buster(digest_func, digest_len=3, stat_len=3): _cache = {} def _buster(filepath): if stat_len == 0: stat = "" else: stat = filestat(filepath) stat = stat[:stat_len] old_bust = _cache.get(filepath, "") if stat and old_bust.endswith(stat): return old_bust if digest_len == 0: digest = "" else: with open(filepath, 'rb') as f: digest = digest_data(f.read(), digest_func) digest = digest[:digest_len] bust = digest + stat _cache[filepath] = bust return bust def _bust_paths(paths): busts = (_buster(p) for p in paths) full_bust = "" for bust in busts: full_bust += bust if len(paths) == 1: return full_bust bust_len = len(full_bust) // len(paths) return digest_data(full_bust)[:bust_len] return _bust_paths def digest_paths(filepaths, digest_func): digests = (digest_func(path) for path in filepaths) return digest_data(b"".join(digests)) # file system/path traversal and filtering def glob_matcher(arg): if hasattr(arg, '__call__'): return arg def _matcher(glob): return lambda p: fnmatch.fnmatch(p, glob) # arg is a sequence of glob strings if isinstance(arg, (tuple, list)): matchers = list(map(_matcher, arg)) return lambda p: any((m(p) for m in matchers)) # arg is a single glob string if isinstance(arg, (unicode, bytes)): return _matcher(arg) return arg # ref -> path matching def filter_longest(_filter, iterator): length = 0 longest = tuple() for elem in iterator: for i in range(len(elem)): if not _filter(i, elem): i -= 1 break if i + 1 > length: length = i + 1 longest = elem return length, longest def mk_fn_dir_map(filepaths): res = collections.defaultdict(set) for p in filepaths: dirname, filename = os.path.split(p) res[filename].add(dirname) return res def closest_matching_path(code_dirpath, refdir, dirpaths): """Find the closest static directory associated with a reference""" if len(dirpaths) == 1: return next(iter(dirpaths)) if refdir.endswith("/"): refdir = refdir[:-1] refdir = tuple(filter(bool, refdir.split(os.sep))) code_dirpath = code_dirpath.split(os.sep) split_dirpaths = [p.split(os.sep) for p in dirpaths] def suffix_matcher(i, elem): return i < len(refdir) and refdir[-1 - i] == elem[-1 - i] def prefix_matcher(i, elem): return i < len(code_dirpath) and code_dirpath[i] == elem[i] length, longest = filter_longest(suffix_matcher, split_dirpaths) suffix = longest[-length:] if len(suffix) == 0: suffix_paths = split_dirpaths else: suffix_paths = [p for p in split_dirpaths if p[-len(suffix):] == suffix] if len(suffix_paths) > 1: length, longest = filter_longest(prefix_matcher, suffix_paths) else: longest = suffix_paths[0] return os.sep.join(longest) def find_static_filepath(base_dir, ref_path, static_fn_dirs): dirname, filename = os.path.split(ref_path) if filename not in static_fn_dirs: # at least the filename must match return static_dir = closest_matching_path(base_dir, dirname, static_fn_dirs[filename]) return os.path.join(static_dir, filename) def find_static_filepaths(base_dir, ref_paths, static_fn_dirs): for path in ref_paths: static_filepath = find_static_filepath(base_dir, path, static_fn_dirs) if static_filepath: yield static_filepath def expand_path(path, multibust): allpaths = set([path]) for search, replacements in multibust.items(): if search in path: allpaths.update((path.replace(search, r) for r in replacements)) return allpaths def ref_paths(ref, multibust): if not multibust: yield ref.path return for expanded_path in expand_path(ref.path, multibust): yield expanded_path # url/src/href reference parsing and rewriting PLAIN_REF = 1 PLAIN_REF_RE = re.compile( r"(url\([\"\']?|href=[\"\']|src=[\"\'])" "(?P<path>" "(?P<dir>[^\"\'\)\s\?]+\/)?" "[^\/\"\'\)\s\?]+)" "[\?=&\w]*[\"\'\)]*" ) FN_REF = 2 FN_REF_RE = re.compile( r"(url\([\"\']?|href=[\"\']?|src=[\"\']?)?" "(?P<prefix>[^\"\']+?)" "_cb_(?P<bust>[a-zA-Z0-9]{0,16})" "(?P<ext>\.\w+)" "[\?=&\w]*[\"\'\)]*" ) QS_REF = 3 QS_REF_RE = re.compile( r"(url\([\"\']?|href=[\"\']?|src=[\"\']?)?" "(?P<ref>[^\"\']+?)" "\?(.+?&)?_cb_" "(=(?P<bust>[a-zA-Z0-9]{0,16}))?" "[\?=&\w]*[\"\'\)]*" ) def mk_plainref(ref): assert ref.type in (PLAIN_REF, FN_REF, QS_REF) if ref.type == PLAIN_REF: return ref.full_ref if ref.type == FN_REF: return ref.full_ref.replace("_cb_" + ref.bustcode, "") if ref.type == QS_REF: return (ref.full_ref.replace("?_cb_=" + ref.bustcode, "?") .replace("&_cb_=" + ref.bustcode, "") .replace("?&", "?") .replace("?)", ")") .replace("?')", "')") .replace('?")', '")') .replace('?"', '"') .replace("?'", "'")) def set_fn_bustcode(ref, new_bustcode): _, ext = os.path.splitext(ref.path) basename = ref.path[:-len(ext)] fnref = basename + "_cb_" + new_bustcode + ext return mk_plainref(ref).replace(ref.path, fnref) def set_qs_bustcode(ref, new_bustcode): new_refpath = ref.path + "?_cb_=" + new_bustcode new_ref = mk_plainref(ref).replace(ref.path, new_refpath) if new_refpath + "?" in new_ref: new_ref = new_ref.replace(new_refpath + "?", new_refpath + "&") return new_ref def replace_bustcode(ref, new_bustcode): if ref.type == FN_REF: prefix = "_cb_" if ref.type == QS_REF: prefix = "_cb_=" return ref.full_ref.replace(prefix + ref.bustcode, prefix + new_bustcode) def updated_fullref(ref, new_bustcode, target_reftype=None): if target_reftype is None: target_reftype = ref.type assert target_reftype in (PLAIN_REF, FN_REF, QS_REF) if ref.bustcode == new_bustcode and ref.type == target_reftype: return ref.full_ref if ref.type == target_reftype: return replace_bustcode(ref, new_bustcode) if target_reftype == PLAIN_REF: return ref.fullref if target_reftype == FN_REF: return set_fn_bustcode(ref, new_bustcode) if target_reftype == QS_REF: return set_qs_bustcode(ref, new_bustcode) # codefile parsing def plainref_line_parser(line): for match in PLAIN_REF_RE.finditer(line): full_ref = match.group() if "_cb_" in full_ref: continue ref_path = match.group('path') yield full_ref, ref_path, "", PLAIN_REF def markedref_line_parser(line): if "_cb_" not in line: return for match in FN_REF_RE.finditer(line): full_ref = match.group() ref_path = match.group('prefix') + match.group('ext') bust = match.group('bust') yield full_ref, ref_path, bust, FN_REF for match in QS_REF_RE.finditer(line): full_ref = match.group() ref_path = match.group('ref') bust = match.group('bust') yield full_ref, ref_path, bust, QS_REF def parse_refs(line_parser, content): for lineno, line in enumerate(content.splitlines()): for match in line_parser(line): fullref = match[0] if "data:image/" in fullref: continue yield Ref("", "", lineno + 1, *match) def parse_content_refs(content, parse_plain=True): all_refs = [] if parse_plain: all_refs.extend(parse_refs(plainref_line_parser, content)) if "_cb_" in content: all_refs.extend(parse_refs(markedref_line_parser, content)) seen = {} for ref in all_refs: key = (ref.lineno, ref.full_ref) if key not in seen or seen[key].type < ref.type: seen[key] = ref return sorted(seen.values(), key=lambda r: r.lineno) def iter_refs(codefile_paths, parse_plain=True, encoding='utf-8'): for codefile_path in codefile_paths: code_dir, code_fn = os.path.split(codefile_path) try: with codecs.open(codefile_path, 'r', encoding) as fp: content = fp.read() except Exception as e: print("omnibust: error reading '{0}' ('{1}')".format(codefile_path, e)) continue for ref in parse_content_refs(content, parse_plain): yield ref._replace(code_dir=code_dir, code_fn=code_fn) # project dir scanning def iter_filepaths(rootdir, file_filter=None, file_exclude=None, dir_filter=None, dir_exclude=None): file_filter = glob_matcher(file_filter) file_exclude = glob_matcher(file_exclude) dir_filter = glob_matcher(dir_filter) dir_exclude = glob_matcher(dir_exclude) for root, _, files in os.walk(rootdir): if dir_exclude and dir_exclude(root): continue if dir_filter and not dir_filter(root): continue for filename in files: path = os.path.join(root, filename) if file_exclude and file_exclude(path): continue if not file_filter or file_filter(path): yield path def multi_iter_filepaths(rootdirs, *args, **kwargs): for basedir in rootdirs: for path in iter_filepaths(basedir, *args, **kwargs): yield path def init_project_paths(): # scan project for files we're interested in filepaths = list(iter_filepaths(".", dir_exclude=INIT_EXCLUDE_GLOBS)) static_filepaths = [p for p in filepaths if ext(p) in STATIC_FILETYPES] codefile_paths = [p for p in filepaths if ext(p) in CODE_FILETYPES] return codefile_paths, static_filepaths def cfg_project_paths(cfg): code_filepaths = multi_iter_filepaths(cfg['code_dirs'], cfg['code_fileglobs'], cfg['ignore_dirglobs']) static_filepaths = multi_iter_filepaths(cfg['static_dirs'], cfg['static_fileglobs'], cfg['ignore_dirglobs']) return code_filepaths, static_filepaths def ref_print_wrapper(refs): prev_codepath = None for ref, paths, new_full_ref in refs: codepath = os.path.join(ref.code_dir, ref.code_fn) if codepath != prev_codepath: print(codepath) prev_codepath = codepath lineno = "% 5d" % ref.lineno print(" %s %s" % (lineno, ref.full_ref)) print(" ->", new_full_ref) yield ref, paths, new_full_ref def busted_refs(ref_map, cfg, target_reftype): buster = mk_buster(cfg['hash_function'], cfg['digest_length'], cfg['stat_length']) for ref, paths in ref_map.items(): new_bustcode = buster(paths) if ref.bustcode == new_bustcode and (target_reftype is None or ref.type == target_reftype): continue yield ref, paths, updated_fullref(ref, new_bustcode, target_reftype) def rewrite_content(ref, new_full_ref): # TODO: better handling of file encoding with codecs.open(ref_codepath(ref), 'r', encoding='utf-8') as f: content = f.read() with codecs.open(ref_codepath(ref), 'w', encoding='utf-8') as f: f.write(content.replace(ref.full_ref, new_full_ref)) def _scan_project(codefile_paths, static_filepaths, multibust=None, parse_plain=True, encoding='utf-8'): refs = collections.OrderedDict() # init mapping to check if a ref has a static file static_fn_dirs = mk_fn_dir_map(static_filepaths) for ref in iter_refs(codefile_paths, parse_plain, encoding=encoding): paths = ref_paths(ref, multibust) if multibust else [ref.path] reffed_filepaths = list(find_static_filepaths(ref.code_dir, paths, static_fn_dirs)) if reffed_filepaths: refs[ref] = reffed_filepaths return refs def scan_project(args, cfg): target_reftype = get_target_reftype(args) return _scan_project(*cfg_project_paths(cfg), multibust=cfg['multibust'], parse_plain=target_reftype is not None, encoding=cfg['file_encoding']) # configuration def read_cfg(args): cfg = json.loads(strip_comments(DEFAULT_CFG)) if not get_flag(args, '--no-init') and not os.path.exists(".omnibust"): raise PathError("try 'omnibust init'", ".omnibust") return None if not get_flag(args, '--no-init'): try: with codecs.open(".omnibust", 'r', encoding='utf-8') as f: cfg.update(json.loads(strip_comments(f.read()))) except (ValueError, IOError) as e: raise BaseError("Error parsing '%s', %s" % (".omnibust", e)) if 'stat_length' not in cfg: cfg['stat_length'] = cfg['bust_length'] // 2 if 'digest_length' not in cfg: cfg['digest_length'] = cfg['bust_length'] - cfg['stat_length'] return cfg def dumpslist(l): return json.dumps(l, indent=8).replace("]", " ]") def strip_comments(data): return re.sub("(^|\s)//.*", "", data) STATIC_FILETYPES = ( ".png", ".gif", ".jpg", ".jpeg", ".ico", ".webp", ".svg", ".js", ".css", ".swf", ".mov", ".avi", ".mp4", ".webm", ".ogg", ".wav", ".mp3", "ogv", "opus" ) CODE_FILETYPES = ( ".htm", ".html", ".jade", ".erb", ".haml", ".txt", ".md", ".css", ".sass", ".less", ".scss", ".xml", ".json", ".yaml", ".cfg", ".ini", ".js", ".coffee", ".dart", ".ts", ".py", ".rb", ".php", ".java", ".pl", ".cs", ".lua" ) INIT_EXCLUDE_GLOBS = ( "*lib/*", "*lib64/*", ".git/*", ".hg/*", ".svn/*", ) DEFAULT_CFG = r""" { "static_dirs": ["."], "static_fileglobs": %s, "code_dirs": ["."], "code_fileglobs": %s, "ignore_dirglobs": ["*.git/*", "*.hg/*", "*.svn/*", "*lib/*", "*lib64/*"], "multibust": {}, // TODO: use file encoding parameter "file_encoding": "utf-8", "hash_function": "sha1", "bust_length": 6 } """ % ( dumpslist(["*" + ft for ft in STATIC_FILETYPES]), dumpslist(["*" + ft for ft in CODE_FILETYPES]) ) INIT_CFG = r"""{ // paths are relative to the project directory "static_dirs": %s, "static_fileglobs": %s, "code_dirs": %s, "code_fileglobs": %s, "ignore_dirglobs": ["*.git/*", "*.hg/*", "*.svn/*", "*lib/*", "*lib64/*"] // "file_encoding": "utf-8", // for reading codefiles // "hash_function": "sha1", // sha1, sha256, sha512, crc32 // "bust_length": 6 // Cachebust references which contain a multibust marker are // expanded using each of the replacements. The cachebust hash will // be unique for the combination of all static resources. Example: // // <img src="/static/i18n_img_{{ lang }}.png?_cb_=1234567"> // // If either of /static/i18n_img_en.png or /static/i18n_img_de.png // are changed, then the cachebust varible will be refreshed. // "multibust": { // "{{ lang }}": ["en", "de"] // marker: replacements // }, } """ # option parsing VALID_ARGS = set([ "-h", "--help", "-q", "--quiet", "--version", "--no-init", "--filename", "--querystring", ]) def validate_args(args): if len(args) == 0: return False if '--filename' in args and '--querystring' in args: raise BaseError("Invalid invocation, only one of " "'--filename' and '--querystring' is permitted") args = iter(args) cmd = next(args) if cmd not in ("init", "status", "rewrite"): raise BaseError("Invalid command '%s' " % cmd) for arg in args: if arg in VALID_ARGS: continue raise BaseError("Invalid argument '%s' " % arg) def get_flag(args, flag): return flag in args or flag[1:3] in args def get_command(args): if len(args) == 0: raise BaseError("Expected command (init|status|rewrite)") cmd = args[0] if cmd not in ("init", "status", "rewrite"): raise BaseError("Expected command (init|status|rewrite)") return cmd def get_target_reftype(args): if get_flag(args, '--filename'): return FN_REF if get_flag(args, '--querystring'): return QS_REF return None def get_opt(args, opt, default='__sentinel__'): for i, arg in enumerate(args): if not arg.startswith(opt): continue if "=" in arg: return arg.split("=")[1] if i + 1 < len(args): arg = args[i + 1] if not arg.startswith("--"): return args[i + 1] raise KeyError(opt) if default is not '__sentinel__': return default raise KeyError(opt) # top level program def init_project(args): if os.path.exists(".omnibust"): raise PathError("Config already exists", ".omnibust") ref_map = _scan_project(*init_project_paths()) static_dirs = set(os.path.split(p)[0] for p in flatten(ref_map.values())) code_dirs = set(r.code_dir for r in ref_map) static_extensions = extension_globs(flatten(ref_map.values())) code_extensions = extension_globs((r.code_fn for r in ref_map)) with codecs.open(".omnibust", 'w', 'utf-8') as f: f.write(INIT_CFG % ( dumpslist(list(static_dirs)), dumpslist(static_extensions), dumpslist(list(code_dirs)), dumpslist(code_extensions) )) print("omnibust: wrote {0}".format(".omnibust")) def status(args, cfg): target_reftype = get_target_reftype(args) ref_map = scan_project(args, cfg) refs = list(ref_print_wrapper(busted_refs(ref_map, cfg, target_reftype))) if not refs: print("omnibust: nothing to cachebust") def rewrite(args, cfg): target_reftype = get_target_reftype(args) # the loop is to deal with cascades # it continues until all paths have been busted at least once updated_paths = set() while True: ref_map = scan_project(args, cfg) time.sleep(0.02) # wait just a bit so that any rewrite will result # in a different timestamp on the next iteration cur_paths = set() refs = ref_print_wrapper(busted_refs(ref_map, cfg, target_reftype)) for ref, paths, new_full_ref in refs: rewrite_content(ref, new_full_ref) cur_paths.update(paths) if len(cur_paths - updated_paths) == 0: break updated_paths.update(cur_paths) if not updated_paths: print("omnibust: nothing to cachebust") def dispatch(args): cmd = get_command(args) if cmd == 'init': return init_project(args) if cmd == 'status': return status(args, read_cfg(args)) if cmd == 'rewrite': return rewrite(args, read_cfg(args)) def main(args=sys.argv[1:]): """Print help/version info if requested, otherwise do the do run run. """ if len(args) == 0: usage = __doc__.split("Options:")[0].strip().split("Usage:")[1] print("\nUsage:" + usage) return if "--version" in args: print(__doc__.split(" -")[0]) return if get_flag(args, "--help"): print(__doc__) return try: validate_args(args) return dispatch(args) except PathError as e: print("omnibust: path error '%s': %s" % (e.path, e.message)) return 1 except BaseError as e: print("omnibust: " + e.message) return 1 except Exception as e: print("omnibust: " + unicode(e)) raise if __name__ == '__main__': sys.exit(main()) <file_sep>/README.md ## Omnibust - A universal cachebusting script A language and framework agnostic cachbusting script. Omnibust will scan the files of your web project for static resources (js, css, png) and also for urls in your source code (html, js, css, py, rb, etc.) which reference these resources. It will add or update a cachebust parameter on any such urls based on the static resources they reference. Requires python >= 2.6 or python >= 3.2. [![Build Status](https://travis-ci.org/mbarkhau/omnibust.png)](https://travis-ci.org/mbarkhau/omnibust) ### Installation $ pip install omnibust Or $ wget https://raw.github.com/mbarkhau/omnibust/master/omnibust.py $ chmod +x omnibust.py $ cp omnibust.py /usr/local/bin/omnibust Check that it worked $ omnibust --help ### Usage Project setup: $ cd your/project/directory $ omninust init This will write the `.omnibust` file, which you can take a look at and update if some of your urls are not being found or scanning your project files is taking too long. If this doesn't find all references to static files, or doesn't find the static files themselves, you will have to adjust `static_dirs` and `code_dirs` in your `.omnibust` file (see below). Please also consider opening a ticket on [https://bitbucket.org/mbarkhau/omnibust], as omnibust should work out of the box for as many projects as reasonably possible. The `rewrite` option will add a `_cb_` to every static url it can find and associate with a static file in the project directory. CAUTION: Since `rewrite` will modify your source files, you should commit or backup your files and run `omnibust status` first to make certain it won't modify anything it shouldn't. $ omnibust status --querystring $ omnibust rewrite --querystring From now on you simply run omnibust rewrite on your project directory and it will only update urls with an existing `_cb_` parameter. $ omnibust rewrite ### Options and Configuration Explicitly specify files TODO: parameter configuration ### Dynamic URLs and Multibust Some URLs may not be found with `omnibust init`, esp. if they are not preceded by something like `src=` or `url(`, and of course URLs which are dynamically created during runtime cannot automatically be found at all. You can help omnibust find these by manually marking them with `_cb_`. After this, you can run `omnibust update` will expand the marker to a full cachbust parameter. The `multibust` configuration option allows for a limited form of dynamic URLs. Omnibust will expand any URL using the configured `multibust` mapping. If a multibust key (typically a template variable) is found in an URL, it is expanded using the corresponding associated multibust values. The search for static resources is then based on the expanded URLs. Given the configuration "multibust": {"{{ language }}": ["en", "de", "fr", "jp", "es"]} And the following URL <img src="i18n_image_{{ language }}_cb_0123abcd.png" /> The following static resources may be matched for this URL /static/i18n_image_en.png /static/i18n_image_de.png ... If any of these files is modified, the cachebust parameter will be updated. This method is safe (in that any change to the static resource results in cache invalidation) and convenient (in that one url can be used to reference semantically similar files), but it does mean that some cached files will be invalidated that were still valid. If this is a problem for you, all static files will have to be referenced explicitly. You could for example create a mapping of the form i18n_images = { 'en': "/static/i18n_image_en_cb_0123abcd.png", 'de': "/static/i18n_image_de_cb_0123abcd.png", ... } And reference it for example from a jinja2 template like this <img src="{{ i18n_image[language] }}" /> ### Webserver Setup In order for browsers to cache and reuse your static resources, your webserver must set appropriate cache headers. Here are some example configuration directives for common webservers. ### Filename Based Cachbusting Omnibust defaults to query parameter `app.js?_cb_=0123abcd` based cachbusting, but it can also rewrite the filenames in urls to the form `app_cb_0123abcd.js`. This is useful since URLs with query parameters are not cached by all browsers in all situations, even if all caching headers are provided correctly [needs reference]. TODO: check if there are browsers where a cached resource will be used even if the query string changes. Putting a cachebust parameter in the filename of a URL will guarantee that your static resource is loaded when it has changed and it will be cached in more situations. The downside is, that your urls now have filenames which reference files that don't actually exist! (Assuming you don't create them, which would be quite laborious and error prone.) The sollution is to have your webserver rewrite the urls of requests it recieves, by stripping out the cachebust parameter, and serving the correct static resource. Here are some configuration directives for common webservers. # Nginx location ~* ^/static/(.+?)_cb_\w+(\.\w+)$ { alias /srv/www/static/$1$2; add_header Vary Accept-Encoding; expires max; } # Apache RewriteRule ^/static/(.+?)_cb_\w+(\.\w+)$ /static/$1$2
d4b0327b3d3d59462cd6636fc300b2dba143e71f
[ "Markdown", "Python", "Text" ]
4
Text
mbarkhau/omnibust
b18ef963e20efe067cd345021169f924d5911625
3dbbe48b4d15e956ecbce3748c4a277ce23e471c
refs/heads/master
<file_sep>/** * Created by XH on 2017/3/17. */ <file_sep>/** * Created by XH on 2017/3/17. */ var a = 1;
b79e6d55e6327f23dba61db01aed5a9f0c987c6f
[ "JavaScript" ]
2
JavaScript
HAX1314/drag
ea606d8e5271cfce3afd05404b7174e508d2dfd9
5120cc3ee70d1246ef09ab92d789f21658aa7701
refs/heads/master
<file_sep>// PLEASE DON'T change function name module.exports = function makeExchange(currency) { // Your code goes here! const coins={H:50, Q: 25, D: 10, N: 5, P: 1}; const res={}; if (currency>10000) { return {error: "You are rich, my friend! We don't have so much coins for exchange"}; } for (let coinTitle in coins) { const count = Math.floor(currency / coins[coinTitle]); if (count > 0) { res[coinTitle] = count; currency -= coins[coinTitle] * count; } } return res; // Return an object containing the minimum number of coins needed to make change }
c0030a97f4a87b4f8d9b85039006fdfb1eabd0fe
[ "JavaScript" ]
1
JavaScript
Pozharitskiy/Money-Exchange
2c38e7936b8ea54651a3bc1d7d345c9c67b7ffa3
24d73c3c28da585e359cd76eed3a5ea6964e1725
refs/heads/master
<repo_name>josemiguelhdez/Djikstra3<file_sep>/src/ldh/Test_Djikstra.java package ldh; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; public class Test_Djikstra extends TestCase{ Vertex v0 = new Vertex("La Laguna"); Vertex v1 = new Vertex("S/C de tenerife"); Vertex v2 = new Vertex("La Orotava"); Vertex v3 = new Vertex("Icod de los Vinos"); Vertex v4 = new Vertex("Puerto de la Cruz"); Vertex[] vertices = { v0, v1, v2, v3, v4 }; public void setUp(){ v0.adjacencies = new Edge[]{ new Edge(v1, 5), new Edge(v2, 10),new Edge(v3, 8) }; v1.adjacencies = new Edge[]{ new Edge(v0, 5), new Edge(v2, 3), new Edge(v4, 7) }; v2.adjacencies = new Edge[]{ new Edge(v0, 10), new Edge(v1, 3) }; v3.adjacencies = new Edge[]{ new Edge(v0, 8), new Edge(v4, 2) }; v4.adjacencies = new Edge[]{ new Edge(v1, 7), new Edge(v3, 2) }; } @Test public void test() { Dijkstra.computePaths(v0); //Soluciones por iteracion ArrayList<Vertex> x1 = new ArrayList<Vertex>(){{add(v0);}}; ArrayList<Vertex> x2 = new ArrayList<Vertex>(){{add(v0);add(v1);}}; ArrayList<Vertex> x3 = new ArrayList<Vertex>(){{add(v0);add(v1);add(v2);}}; ArrayList<Vertex> x4 = new ArrayList<Vertex>(){{add(v0);add(v3);}}; ArrayList<Vertex> x5 = new ArrayList<Vertex>(){{add(v0);add(v3);add(v4);}}; ArrayList<ArrayList<Vertex>> pruebas = new ArrayList<ArrayList<Vertex>>(); pruebas.add(x1); pruebas.add(x2); pruebas.add(x3); pruebas.add(x4); pruebas.add(x5); List<Vertex> path = null; for (int i = 0; i < vertices.length; i++){ path = Dijkstra.getShortestPathTo(vertices[i]); Assert.assertEquals(pruebas.get(i), path); } } }
cf75b5beb85476c2ccaa19318b04d4e9298236e5
[ "Java" ]
1
Java
josemiguelhdez/Djikstra3
c823a8ad62073849982aade6ba17aaee211b091e
403b2441279b8b3384a69b77c494d5c902acab5a
refs/heads/main
<repo_name>mariliabreis/afunctiontorulethemall<file_sep>/afunctiontorulethemall/lib.py def try_me(): return 42
d91370bd150ee78180d0be295cc9299eecb9a46d
[ "Python" ]
1
Python
mariliabreis/afunctiontorulethemall
cc7b2cbb281e482329823414cea8b5441e0ca71e
62050ad0b53c08e5bf44401e594abfbef583208b
refs/heads/master
<repo_name>proofguru/simple-calculator<file_sep>/src/test/java/org/proofguru/com/Tester.java package org.proofguru.com; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class Tester extends TestCase { /** * Create the test case * * @param testName name of the test case */ public Tester( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( Tester.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } public void testAddition1() { Calculator calculator = new Calculator(); assertEquals(2, calculator.add(1, 1)); } public void testAddition2() { Calculator calculator = new Calculator(); assertEquals(7, calculator.add(3, 4)); } public void testAddition3() { Calculator calculator = new Calculator(); assertEquals(10, calculator.add(5, 5)); } public void testSubtraction1() { Calculator calculator = new Calculator(); assertEquals(2, calculator.subtract(5,3)); } public void testSubtraction2() { Calculator calculator = new Calculator(); assertEquals(4, calculator.subtract(12,8)); } public void testMultiplication() { Calculator calculator = new Calculator(); assertEquals(12, calculator.multiply(3,4)); } } <file_sep>/README.md # simple-calculator Simple calculator that can add and subtract
96d225de2763c7e7b9b396e33da4a23087e128db
[ "Markdown", "Java" ]
2
Java
proofguru/simple-calculator
b6410229d6c6cd9135fad6e72d6e6b37fd5b6289
f106728ea26d1a411e8ed86c962c692dafa9a2e9
refs/heads/master
<repo_name>nare06/hackerrank<file_sep>/service-lane.rb input = gets.to_s.split(" ") sum = 0 (1..(input.first.to_i)).each do |i| if (i.to_s) == (i.to_s.reverse) && (i.to_s(input.last.to_i))== (i.to_s(input.last.to_i).reverse) sum+=i end end puts sum <file_sep>/gem_elements.rb gem_elements = [] no_of_rocks = gets.to_i (1..no_of_rocks).each do |i| a = gets.to_s puts a.chars.to_a gem_elements = gem_elements & (a.chars.to_a) puts gem_elements end puts gem_elements.to_a.uniq.count <file_sep>/palidrome.rb string = gets.chomp s1 = string.chars total_even_count = 0 total_odd_count = 0 str = s1.to_a.uniq list = str.collect{|id| s1.select{|id2| id2 == id}.size} list.each do |u| if (u % 2) == 0 total_even_count += 1 else total_odd_count += 1 end end if total_odd_count == 1 puts "YES" elsif total_even_count > 0 and total_odd_count <= 1 puts "YES" else puts "NO" end<file_sep>/new.rb require 'debugger' def factorial(n) if n == 0 1 else n*factorial(n-1) end end x = 1000 count = 0 for u in 10..(x.to_i) do a = u.to_s.chars.map(&:to_i) sum = 0 a.each do |value| # debugger sum = sum + factorial(value) end count += u if (sum % u.to_i) == 0 end puts count <file_sep>/permute.rb class New @@count = 0 def permute(prefix,str) if str.length == 0 puts prefix @@count += 1 else #puts new_str en = str.length-1 range = (0..en) range.each do |i| permute(prefix + str[i],str[0,i]+str[i+1,en]) #str[i] + permute((str*2)[i,en]) #str[i] + permute((str*2)[(i+1)..(en+i)]) end return @@count end end end str = gets.chomp a = New.new puts a.permute("",str)<file_sep>/code.rb def feb(n) if n==2 1 elsif n==1 1 else feb(n-2)+feb(n-1) end end puts feb(9) def factorial(n) if n == 0 1 else n*factorial(n-1) end end puts factorial(10) puts factorial(4) def maxstars str = "###*****##*************####***************##" max_star_count = 0 max_hash_count = 0 hash_count = 0 star_count = 0 str.each do |u|{ if u == "#" star_count = 0 hash_count++ max_hash_count = hash_count if max_hash_count < hash_count else hash_count = 0 max_star_count = star_count if max_star_count < star_count star_count++ end } end max_star_count end puts maxstarts <file_sep>/nth_max.rb def nthmax(arr,n) pivot = arr[n-1] #puts pivot i = j = 0 new_arr = [pivot] #puts arr arr.each do |element| if element > pivot new_arr = new_arr << element j += 1 elsif element < pivot new_arr = new_arr.unshift(element) i += 1 end end if n < i+1 #(i+1) is new pivot position return nthmax(new_arr[0,i],n) elsif n > i+1 #debugger return nthmax(new_arr[i+1,new_arr.length],n-i-1) else return arr[i] end end arr = [8,9,2,1,0,-4,-9,25,45,-100,-90,100,100,100,56,56,90,-1000,56,78,89,90,56,56,89,90,1,908,200000,34556].shuffle #arr = [908, 56, 90, -1000, 56, -90, 100, 56, 8, 90, -100, 89, 56, 45, 25, 90, 1, 100, 1, -9, 78, 100, 0, 56, -4, 9, 89, 2] #There is an error with this input before. For the solution I thought about I want to use an hash #print arr a = Hash.new arr.each do |u| i = 1 if a[u].nil? a[u] = i else a[u] = a[u] + i end end puts nthmax(a.keys,11) puts arr.uniq.sort[10]
09aeae5172e095c574fb3e280592535ea5a579e5
[ "Ruby" ]
7
Ruby
nare06/hackerrank
e1a042e63f6fe59360d22960ca0aecddc7fb0f2d
b10260aeb90322abcf9e0ced4983390f56bb9b98
refs/heads/master
<repo_name>erisrp/Introduction-to-Programming---LAB<file_sep>/Assignment 05 - Pygame/app.py # import pygame with all the special sub-modules from pygame import * # import menu.py import menu # import 'random' api to create random asteroid import random # import classes.py with all the class from classes import * def run_game(): # create screen resolution screen = pygame.display.set_mode((800, 600)) # create program name display.set_caption("Dank Mission") # initialize score scores = 0 # initialize all imported pygame modules pygame.init() # create jet object group jet1 = Jet(screen) Jet_sprites = Group(jet1) # create asteroid object group asteroid_group = Group() # create bullets object Group bullets = Group() # create how fast the game phase theClock = pygame.time.Clock() Fps = 40 asteroid_timer = pygame.time.get_ticks() while True: theClock.tick(Fps) Fps += 0.01 # game phase goes faster after every frame # create score board font=pygame.font.Font("Minecraft.ttf",36) # create font score_board=font.render("score:"+str(scores),True,(255,255,255)) # update referred to the word's method screen.blit(score_board,(10,550)) # load bg image for game screen.fill(pygame.Color(15, 77, 143)) # create jet Jet_sprites.draw(screen) # create bullets bullets.draw(screen) # create asteroid asteroid_group.draw(screen) # update current frame with all the above changes display.update() # get events from the queue pygame.event.get() """moving the jet according to key pressed""" key = pygame.key.get_pressed() # LEFT if key[K_LEFT] and jet1.rect.x>0: jet1.moveleft() # RIGHT if key[K_RIGHT] and jet1.rect.x<=700: jet1.moveright() # DOWN if key[K_DOWN] and jet1.rect.y<=500: jet1.movedown() # UP if key[K_UP] and jet1.rect.y>0: jet1.moveup() # SPACE if key[K_SPACE] and len(bullets) <= jet1.firerates+(scores/4000): bullet = Bullet(screen, jet1.rect.x+50, jet1.rect.y+42) bullets.add(bullet) pygame.mixer.music.load("LaserBlast.wav") pygame.mixer.music.play() # ESC if key[K_ESCAPE]: menu.pause_menu(Button,run_game) # P if key[K_p]: menu.pause_menu(Button,run_game) """generate asteroid randomly""" if pygame.time.get_ticks() - asteroid_timer >= 200: asteroid = Asteroid(screen, 50, 50, random.randint(1,4)*6, 800, (random.randint(1,28) * 20)) asteroid_group.add(asteroid) asteroid_timer = pygame.time.get_ticks() """update the movement of asteroid""" for asteroid in asteroid_group: asteroid.movement() if asteroid.rect.right <= 0: asteroid_group.remove(asteroid) #remove after screen if groupcollide(Jet_sprites,asteroid_group,dokilla=True,dokillb=True):#collition check menu.lose_menu(Button,run_game,scores) """update bullet movement on screen""" for bullet in bullets: bullet.movement() if bullet.rect.left > 800: bullets.remove(bullet) if groupcollide(bullets,asteroid_group,dokilla=True,dokillb=True): scores += 100 pygame.mixer.music.load('oof.mp3') pygame.mixer.music.play(0) # run game menu.menu_screen(Button,run_game) <file_sep>/Assignment 04 - Class Toll/v2.py class TollGate: def __init__(self): self.car_price = 6000 self.bus_price = 8000 self.truck_price = 10000 self.car_total = [0] self.bus_total = [0] self.truck_total = [0] self.car_revenue_total = [0] self.bus_revenue_total = [0] self.truck_revenue_total = [0] def get_car_total(self): return self.car_total[0] def get_bus_total(self): return self.bus_total[0] def get_truck_total(self): return self.truck_total[0] def get_car_revenue_total(self): return self.car_revenue_total[0] def get_bus_revenue_total(self): return self.bus_revenue_total[0] def get_truck_revenue_total(self): return self.truck_revenue_total[0] class Vehicle(TollGate): def car(self): self.car_total[0] += 1 self.car_revenue_total[0] += self.car_price def bus(self): self.bus_total[0] += 1 self.bus_revenue_total[0] += self.bus_price def truck(self): self.truck_total[0] += 1 self.truck_revenue_total[0] += self.truck_price v = Vehicle() print('================================================================================\n Toll Payment Systems\n PT Jasa Marga, Tbk.\n================================================================================') while True: usr=input('\nMenu:\n1. Charge the vehicles.\n2. Count the total number of vehicles.\n3. Count the total revenue of the day.\n> ') if usr == '1': ask=input('\nCategory of vehicle:\n1. Car (RP 6000)\n2. Bus (RP 8000)\n3. Truck (RP 10000)\n> ') if ask == '1': v.car() print('\nSuccess!\n') if ask == '2': v.bus() print('\nSuccess!\n') if ask == '3': v.truck() print('\nSuccess!\n') if usr == '2': print('\n-------------------\nCar Bus Truck\n-------------------\n',v.get_car_total(),'\t ',v.get_bus_total(),'\t ',v.get_truck_total(),'\n-------------------\n') print('Total number of vehicles:',v.get_car_total()+v.get_bus_total()+v.get_truck_total(),'\n') if usr == '3': print('\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_car_revenue_total(),'\t ',v.get_bus_revenue_total(),'\t',v.get_truck_revenue_total(),'\n--------------------------\n') print('Total revenue: Rp.',v.get_car_revenue_total()+v.get_bus_revenue_total()+v.get_truck_revenue_total(),'\n') <file_sep>/Extra Assignment - Lambda Calculator.py # <NAME> # 2201797052 #### LAMBDA CALCULATOR #### # For this method, You must input the number like this: 1+1 *ENTER* (!!! NO SPACES !!!) # You can't input like this: 1 *ENTER* + *ENTER* 1 *ENTER* # After getting the result, you can continue input again like this: +1 *ENTER* # Please be gentle and don't input something like this: 1+2002-3840*100080/4000000402020020 # This calculator only support one operator at a time. ^^ stack=[] # Create List. x=True while x is True: # Create infinite loop. num=input() # Input. stack.extend(num) # Slice string that you input into stack as individual strings. ex: '1+1' -> '1','+','1' if num=='q': # Enter q to stop. break a=int(stack.pop()) # Create variable 'a' : Take the string from the stack that you input as integer (In this case number) op=stack.pop() # Create variable 'op' : Take another one as string (In this case operator) b=int(stack.pop()) # Create variable 'b' : And another as integer (In this case number) plus = lambda a,b: a+b # Plus lambda minus = lambda a,b: b-a # Minus lambda kali = lambda a,b: a*b # Times lambda bagi = lambda a,b: b/a # Obelus lambda if op=='+': # If 'op' is '+' then print '=' and Plus lambda with parameter of 'a' and 'b' print('=',plus(a,b)) stack.append(plus(a,b)) if op=='-': # If 'op' is '-' then print '=' and Minus lambda with parameter of 'a' and 'b' print('=',minus(a,b)) stack.append(minus(a,b)) if op=='*': # If 'op' is '*' then print '=' and Times lambda with parameter of 'a' and 'b' print('=',kali(a,b)) stack.append(kali(a,b)) if op=='/': # If 'op' is '/' then print '=' and Obelus lambda with parameter of 'a' and 'b' print('=',bagi(a,b)) stack.append(bagi(a,b)) <file_sep>/Assignment 04 - Class Toll/v3.py class TollGate: def __init__(self): super(TollGate,self).__init__() self.car_price = 6000 self.bus_price = 8000 self.truck_price = 10000 self.car_total = [0] self.bus_total = [0] self.truck_total = [0] self.car_revenue_total = [0] self.bus_revenue_total = [0] self.truck_revenue_total = [0] def get_car_total(self): return self.car_total[0] def get_bus_total(self): return self.bus_total[0] def get_truck_total(self): return self.truck_total[0] def get_car_revenue_total(self): return self.car_revenue_total[0] def get_bus_revenue_total(self): return self.bus_revenue_total[0] def get_truck_revenue_total(self): return self.truck_revenue_total[0] class TollGate2: def __init__(self): super(TollGate2,self).__init__() self.car_price2 = 18000 self.bus_price2 = 20000 self.truck_price2 = 25000 self.car_total2 = [0] self.bus_total2 = [0] self.truck_total2 = [0] self.car_revenue_total2 = [0] self.bus_revenue_total2 = [0] self.truck_revenue_total2 = [0] def get_car_total2(self): return self.car_total2[0] def get_bus_total2(self): return self.bus_total2[0] def get_truck_total2(self): return self.truck_total2[0] def get_car_revenue_total2(self): return self.car_revenue_total2[0] def get_bus_revenue_total2(self): return self.bus_revenue_total2[0] def get_truck_revenue_total2(self): return self.truck_revenue_total2[0] class Vehicle(TollGate,TollGate2): def __init__(self): super(Vehicle,self).__init__() def car(self): self.car_total[0] += 1 self.car_revenue_total[0] += self.car_price def bus(self): self.bus_total[0] += 1 self.bus_revenue_total[0] += self.bus_price def truck(self): self.truck_total[0] += 1 self.truck_revenue_total[0] += self.truck_price def car2(self): self.car_total2[0] += 1 self.car_revenue_total2[0] += self.car_price2 def bus2(self): self.bus_total2[0] += 1 self.bus_revenue_total2[0] += self.bus_price2 def truck2(self): self.truck_total2[0] += 1 self.truck_revenue_total2[0] += self.truck_price2 v = Vehicle() print('================================================================================\n Toll Payment Systems\n PT Jasa Marga, Tbk.\n================================================================================') while True: ask = input('\nSelect location of Toll gate:\n1. Meruya\n2. Pondok Aren\nPress 3 for the whole number of vehicles passing the toll gates and total revenue of the day on both gates.\n> ') if ask == '1': while True: usr=input('\nLocation of Toll gate: Meruya\nMenu:\n1. Charge the vehicles.\n2. Count the total number of vehicles.\n3. Count the total revenue of the day.\n4. Change Toll Gate\n> ') if usr == '1': ask=input('\nCategory of vehicle:\n1. Car (RP 6000)\n2. Bus (RP 8000)\n3. Truck (RP 10000)\n> ') if ask == '1': v.car() print('\nSuccess!\n') if ask == '2': v.bus() print('\nSuccess!\n') if ask == '3': v.truck() print('\nSuccess!\n') if usr == '2': print('\n-------------------\nCar Bus Truck\n-------------------\n',v.get_car_total(),'\t ',v.get_bus_total(),'\t ',v.get_truck_total(),'\n-------------------\n') print('Total number of vehicles:',v.get_car_total()+v.get_bus_total()+v.get_truck_total(),'\n') if usr == '3': print('\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_car_revenue_total(),'\t ',v.get_bus_revenue_total(),'\t',v.get_truck_revenue_total(),'\n--------------------------\n') print('Total revenue: Rp.',v.get_car_revenue_total()+v.get_bus_revenue_total()+v.get_truck_revenue_total(),'\n') if usr == '4': break elif ask == '2': while True: usr=input('\nLocation of Toll gate: Pondok Aren\nMenu:\n1. Charge the vehicles.\n2. Count the total number of vehicles.\n3. Count the total revenue of the day.\n4. Change Toll Gate\n> ') if usr == '1': ask=input('\nCategory of vehicle:\n1. Car (RP 18000)\n2. Bus (RP 20000)\n3. Truck (RP 25000)\n> ') if ask == '1': v.car2() print('\nSuccess!\n') if ask == '2': v.bus2() print('\nSuccess!\n') if ask == '3': v.truck2() print('\nSuccess!\n') if usr == '2': print('\n-------------------\nCar Bus Truck\n-------------------\n',v.get_car_total2(),'\t ',v.get_bus_total2(),'\t ',v.get_truck_total2(),'\n-------------------') print('Total number of vehicles:',v.get_car_total2()+v.get_bus_total2()+v.get_truck_total2(),'\n') if usr == '3': print('\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_car_revenue_total2(),'\t ',v.get_bus_revenue_total2(),'\t',v.get_truck_revenue_total2(),'\n--------------------------') print('Total revenue: Rp.',v.get_car_revenue_total2()+v.get_bus_revenue_total2()+v.get_truck_revenue_total2(),'\n') if usr == '4': break elif ask == '3': print('\nVehicles\n-------------------\nCar Bus Truck\n-------------------\n',v.get_car_total()+v.get_car_total2(),'\t ',v.get_bus_total()+v.get_bus_total2(),'\t ',v.get_truck_total()+v.get_truck_total2(),'\n-------------------') print('Total number of vehicles:',v.get_car_total()+v.get_bus_total()+v.get_truck_total()+v.get_car_total2()+v.get_bus_total2()+v.get_truck_total2(),'\n\n') print('Revenues\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_car_revenue_total()+v.get_car_revenue_total2(),'\t ',v.get_bus_revenue_total()+v.get_bus_revenue_total2(),'\t',v.get_truck_revenue_total()+v.get_truck_revenue_total2(),'\n--------------------------') print('Total revenue: Rp.',v.get_car_revenue_total()+v.get_bus_revenue_total()+v.get_truck_revenue_total()+v.get_car_revenue_total2()+v.get_bus_revenue_total2()+v.get_truck_revenue_total2(),'\n') <file_sep>/Assignment 06 - Projectile.py import numpy as np import matplotlib.pylab as plot import math as m import sys num = int(input('How many projectile you want to create? >> '))+1 # Create how many graph for i in range(1,num): v = int(input('Enter the no {} initial velocity (m/s) >> '.format(i))) # Input vector g = 9.8 angle = m.radians(int(input('Enter the no {} angle of projection (degrees) >> '.format(i)))) # Input degree t = ((2*v)*np.sin(angle))/g # Formula to find time ts = t*np.linspace(0,1) # Time vector x = (v*ts)*np.cos(angle) # Formula to find the x position y = (v*ts)*np.sin(angle) - (g/2)*(ts**2) # Formula to find y position plot.plot(x,y,label='Projectile no {}'.format(i)) # Create line graph with label plot.title('Projection motion of a ball') # Graph title plot.xlabel('x-coordinate') # Graph x label title plot.ylabel('y-coordinate') # Graph y label title plot.legend() # Print legend ask = input('Do you want to save your graph? [Y/N] >> ').upper() if ask == 'Y': plot.savefig('graph.png', bbox_inches='tight') # Save graph print('done.') elif ask == 'N': m.pi plot.show() # Print graph sys.exit() ##### References ##### # https://newcontent.binus.ac.id/data_content/lecturer_shared_materials/main_material/IS1/201810150749390860002405_Data%20Visualization.pdf # projectile motion formula # and also pasha for finding the formula <file_sep>/Assignment 03 - Class ATM.py # <NAME> # 2201797052 #### CLASS ATM #### # a Bank with class. B-) # Class for bank class Bank: # Ask customer name here def register(self): a = input('First Name: ') b = input('Last Name: ') global customer # Declare variable 'customer' as global customer = Customer(a,b) # Object for Customer class with 'a' and 'b' as parameter customer.data() # Execute 'data' module inside Costumer class # Class for customer class Customer: # Initialize parameter 'a' and 'b' def __init__(self,a,b): self.firstName = a self.lastName = b # Store new customer name here, and also give them 0 money def data(self): namebase.append(self.firstName+' '+self.lastName) moneybase.append(0) print('\nAccount successfully registered!\n') # If you get bored and want to get fired, delete some registered customer here! def delete(self): for x in range (len(namebase)): print('\nNo.',x,'\nCustomer:',namebase[x],'\nAccount: $',moneybase[x],'\n') ask = int(input('Select account to delete: ')) del namebase[ask] del moneybase[ask] # Class for account class Account: # Show list of registered customer def getBalance(self): for x in range (len(namebase)): print('\nNo.',x,'\nCustomer:',namebase[x],'\nAccount: $',moneybase[x],'\n') # Deposit dem money here def deposit(self): for x in range (len(namebase)): print('\nNo.',x,'\nCustomer:',namebase[x],'\nAccount: $',moneybase[x],'\n') ask=int(input('Who? ')) amount = int(input('How much? ')) moneybase[ask] += amount # Withdraw customer money here def withdraw(self): ask=int(input('Who? ')) amount = int(input('How much? ')) moneybase[ask] -= amount # Be nice and give some to charity will ya? def transfer(self): for x in range (len(namebase)): print('\nNo.',x,'\nCustomer:',namebase[x],'\nAccount: $',moneybase[x],'\n') ask=int(input('Transfer from: ')) ask2=int(input('Transfer to: ')) ask3=int(input('Amount of money to transfer: ')) moneybase[ask] -= ask3 moneybase[ask2] += ask3 namebase = [] # Store customer name here moneybase = [] # Store customer money here bankName = 'Cool' # Insert the bank name here bank = Bank() # Object for Bank Class account = Account() # Object for Account Class #Create a loop while True: # Create a menu for input usr=input('Welcome to '+bankName+'bank!\nMenu:\n1. Register\n2. View Account\n3. Deposit\n4. Withdraw\n5. Transfer\n6. Delete Account\n7. Quit\n> ') if usr=='1': bank.register() if usr=='2': account.getBalance() if usr=='3': account.deposit() if usr=='4': account.withdraw() if usr=='5': account.transfer() if usr=='6': customer.delete() if usr=='7': print('Please come back again!\n') break <file_sep>/Assignment 02 - Class Calculator.py # <NAME> # 2201797052 #### CLASS CALCULATOR #### # For this method, You must input the number like this: 1+1 *ENTER* (!!! NO SPACES !!!) (Let me know if you want the input with spaces version.) # You can't input like this: 1 *ENTER* + *ENTER* 1 *ENTER* # After getting the result, you can continue input again like this: +1 *ENTER* # Please be gentle and don't input something like this: 1+2002-3840*100080/4000000402020020 # This calculator only support one operator at a time. ^^ stack=[] # Create List. x=True while x is True: # Create infinite loop. num=input() # Input. stack.extend(num) # Slice string that you input into stack as individual strings. ex: '1+1' -> '1','+','1' if num=='q': # Enter q to stop. break a=int(stack.pop()) # Create variable 'a' : Take the string you input as integer (In this case number) op=stack.pop() # Create variable 'op' : Take another one as string (In this case operator) b=int(stack.pop()) # Create variable 'b' : And another as integer (In this case number) class Calculator: # Create Class. def __init__(self,one,two): # Initialize parameter self.number = one self.number0 = two def plus(self): # Module for plus print('=',self.number + self.number0) stack.append(self.number + self.number0) def minus(self): # Module for minus print('=',self.number0 - self.number) stack.append(self.number0 - self.number) def kali(self): # Module for times print('=',self.number * self.number0) stack.append(self.number * self.number0) def bagi(self): # Module for obelus print('=',self.number0 / self.number) stack.append(self.number0 / self.number) calculator = Calculator(a,b) # assign class as 'calculator' and also 'a' & 'b' as the parameter if op=='+': # if 'op' is '+', do dis module from inside the Calculator class. calculator.plus() if op=='-': # self explainatory, just like above calculator.minus() if op=='*': # are you even still asking what's this? calculator.kali() if op=='/': # bruh calculator.bagi() <file_sep>/Quiz 02 - Hotel/Hotel.py import sys class Hotel: def __init__(self): # initialize room self.room = [] # set room category prices self.room_price1 = 500000 self.room_price2 = 1000000 # initialize revenue self.revenue = 0 # check occupied rooms def check_room(self): # show total of occupied room print('\nCurrent room:\n',len(self.room),'Room occupied\n') print('Occupied room numbers:') # show every occupied rooms for bed in self.room: print(bed) print('\n') # check revenue def check_revenue(self): print('\nRevenue: Rp.',self.revenue,'\n') # menu def menu(self): while True: usr = input('Welcome to Ritz-Carlton Hotel!\nWhat do you want to do?:\n1. Check In\n2. Check Out\n3. Check Room\n4. Check Revenue\n5. Exit\n> ') if usr == '1': c.check_in() elif usr == '2': c.check_out() elif usr == '3': c.check_room() elif usr == '4': c.check_revenue() elif usr == '5': sys.exit() # customer class inheritance with hotel class class Customer(Hotel): # check in def check_in(self): # choose room category print('\nChoose room category:\n1. Cheap\n2. Expensive') usr2 = input('> ') # cheap if usr2 == '1': # enter room number, you are the operator, you know all the room numbers, you have to, you don't need a list of room numbers room = int(input('\nEnter room number: ')) # if you enter the room number that's already occupied if room in self.room: print('\nSorry, room number',room,'is already occupied.\n') # if not then add it else: self.room.append(room) self.revenue += self.room_price1 print('\nYou payed Rp. 500.000\nEnjoy your stay!\n') # expensive elif usr2 == '2': # enter room number, you are the operator, you know all the room numbers, you have to, you don't need a list of room numbers room = int(input('\nEnter room number: ')) # if you enter the room number that's already occupied if room in self.room: print('\nSorry, room number',room,'is already occupied.\n') # if not then add it else: self.room.append(room) self.revenue += self.room_price2 print('\nYou payed Rp. 1.000.000\nEnjoy your stay!\n') # check out def check_out(self): # show every occupied rooms print('\nChoose room number:') for bed in self.room: print(bed) # choose room to check out room = int(input('> ')) # if room is occupied if room in self.room: self.room.remove(room) print('\nThank you for staying in Ritz-Carlton Hotel!\n') # if not else: print('\nSorry, can\'t check out room number',room,', it is empty right now.\n') c = Customer() c.menu() <file_sep>/Assignment 05 - Pygame/menu.py from pygame import * import sys import pygame def menu_screen(Button,run_game): """make the screen for menu""" display.set_caption("Jet Mission") screen = pygame.display.set_mode((800, 600)) # load button image for quit and start start_button = Button("start.png") quit_button = Button("exit.png") # load image for the menu's background bg_image=pygame.image.load("star.gif") # resize image bg_image=pygame.transform.scale(bg_image, (800, 600)) # initialize all imported pygame modules pygame.init() while True: # create start button hit box rect_start= draw.rect(screen, (0, 0, 0), (250, 200, 300, 125)) # create quit button hit box rect_quit = draw.rect(screen, (0, 0, 0), (250, 300, 300, 125)) # print bg screen.blit(bg_image,(0,0)) # print start button screen.blit(start_button.button,(250,200)) # print quit button screen.blit(quit_button.button,(250,300)) # wait for a key to be pressed ev=event.wait() # create a click able button for mouse if ev.type == MOUSEBUTTONDOWN: if rect_start.collidepoint(mouse.get_pos()): run_game() if rect_quit.collidepoint(mouse.get_pos()): sys.exit() # if user want to quit if ev.type == QUIT: pygame.quit() sys.exit() # render new frame display.update() def pause_menu(Button,run_game): """pause_menu""" # make the screen display display.set_caption("Dank Mission") screen = pygame.display.set_mode((800, 600)) pygame.init() paused = True while paused: # print bg screen.fill(pygame.Color(15, 77, 143)) # create font font=pygame.font.Font("Minecraft.ttf",50) # print font text=font.render("Paused",True,(255,255,255)) screen.blit(text,(320,280)) # wait for a key to be pressed ev = event.wait() # press esc to resume if ev.type == K_ESCAPE: paused = False if ev.type == K_p: paused = False # if user want to quit if ev.type == QUIT: sys.exit() # render new frame display.update() def lose_menu(Button,run_game,score): """make the screen for menu""" display.set_caption("Dank Mission") screen = pygame.display.set_mode((800, 600)) # create font font=pygame.font.Font("Minecraft.ttf",50) # print font text=font.render("Haha you suck",True,(255,255,255)) # print score score_text=font.render("Score: "+str(score),True,(255,255,255)) # object button for quit and start start_button = Button("start.png") quit_button = Button("exit.png") # image for the menu's backgound bg_image = pygame.image.load("star.gif") bg_image = pygame.transform.scale(bg_image, (800, 600)) # initialize all imported pygame modules pygame.init() while True: # create hit box for start and quit rect_start = draw.rect(screen, (0, 0, 0), (250, 200, 300, 150)) rect_quit = draw.rect(screen, (0, 0, 0), (250, 300, 300, 150)) # print bg screen.blit(bg_image, (0, 0)) # print text screen.blit(text,(20,10)) # print start and quit screen.blit(start_button.button, (250, 200)) screen.blit(quit_button.button, (250, 300)) # print score screen.blit(score_text,(20,100)) # wait for ev = event.wait() # create a click able button for mouse if ev.type == MOUSEBUTTONDOWN: if rect_start.collidepoint(mouse.get_pos()): run_game() if rect_quit.collidepoint(mouse.get_pos()): sys.exit() # render new frame if ev.type == QUIT: sys.exit() # render new frame display.update() <file_sep>/Assignment 04 - Class Toll/v4.py class TollGate: car_total = [0,0,0,0,0,0] bus_total = [0,0,0,0,0,0] truck_total = [0,0,0,0,0,0] car_revenue_total = [0,0,0,0,0,0] bus_revenue_total = [0,0,0,0,0,0] truck_revenue_total = [0,0,0,0,0,0] car_revenue_cashless_total = [0,0,0,0,0,0] bus_revenue_cashless_total = [0,0,0,0,0,0] truck_revenue_cashless_total = [0,0,0,0,0,0] def __init__(self): super(TollGate,self).__init__() self.car_price = 6000 self.bus_price = 8000 self.truck_price = 10000 class TollGate2: car_total2 = [0,0,0,0,0,0] bus_total2 = [0,0,0,0,0,0] truck_total2 = [0,0,0,0,0,0] car_revenue_total2 = [0,0,0,0,0,0] bus_revenue_total2 = [0,0,0,0,0,0] truck_revenue_total2 = [0,0,0,0,0,0] car_revenue_cashless_total2 = [0,0,0,0,0,0] bus_revenue_cashless_total2 = [0,0,0,0,0,0] truck_revenue_cashless_total2 = [0,0,0,0,0,0] def __init__(self): super(TollGate2,self).__init__() self.car_price2 = 18000 self.bus_price2 = 20000 self.truck_price2 = 25000 class Vehicle(TollGate,TollGate2): def __init__(self,a): super(Vehicle,self).__init__() self.tollboth = a def add(self,vehicle_type): if vehicle_type == 'car': self.car_total[self.tollboth] += 1 self.car_revenue_total[self.tollboth] += self.car_price if vehicle_type == 'bus': self.bus_total[self.tollboth] += 1 self.bus_revenue_total[self.tollboth] += self.bus_price if vehicle_type == 'truck': self.truck_total[self.tollboth] += 1 self.truck_revenue_total[self.tollboth] += self.truck_price if vehicle_type == 'car_cashless': self.car_total[self.tollboth] += 1 self.car_revenue_cashless_total[self.tollboth] += self.car_price if vehicle_type == 'bus_cashless': self.bus_total[self.tollboth] += 1 self.bus_revenue_cashless_total[self.tollboth] += self.bus_price if vehicle_type == 'truck_cashless': self.truck_total[self.tollboth] += 1 self.truck_revenue_cashless_total[self.tollboth] += self.truck_price if vehicle_type == 'car2': self.car_total2[self.tollboth] += 1 self.car_revenue_total2[self.tollboth] += self.car_price2 if vehicle_type == 'bus2': self.bus_total2[self.tollboth] += 1 self.bus_revenue_total2[self.tollboth] += self.bus_price2 if vehicle_type == 'truck2': self.truck_total2[self.tollboth] += 1 self.truck_revenue_total2[self.tollboth] += self.truck_price2 if vehicle_type == 'car2_cashless': self.car_total2[self.tollboth] += 1 self.car_revenue_cashless_total2[self.tollboth] += self.car_price2 if vehicle_type == 'bus2_cashless': self.bus_total2[self.tollboth] += 1 self.bus_revenue_cashless_total2[self.tollboth] += self.bus_price2 if vehicle_type == 'truck2_cashless': self.truck_total2[self.tollboth] += 1 self.truck_revenue_cashless_total2[self.tollboth] += self.truck_price2 def get_total(self,vehicle_type): if vehicle_type == 'car': return self.car_total[self.tollboth] if vehicle_type == 'bus': return self.bus_total[self.tollboth] if vehicle_type == 'truck': return self.truck_total[self.tollboth] if vehicle_type == 'car2': return self.car_total2[self.tollboth] if vehicle_type == 'bus2': return self.bus_total2[self.tollboth] if vehicle_type == 'truck2': return self.truck_total2[self.tollboth] if vehicle_type == 'car_all': return self.car_total[1]+self.car_total[2]+self.car_total[3]+self.car_total[4]+self.car_total[5] if vehicle_type == 'bus_all': return self.bus_total[1]+self.bus_total[2]+self.bus_total[3]+self.bus_total[4]+self.bus_total[5] if vehicle_type == 'truck_all': return self.truck_total[1]+self.truck_total[2]+self.truck_total[3]+self.truck_total[4]+self.truck_total[5] if vehicle_type == 'car2_all': return self.car_total2[1]+self.car_total2[2]+self.car_total2[3]+self.car_total2[4]+self.car_total2[5] if vehicle_type == 'bus2_all': return self.bus_total2[1]+self.bus_total2[2]+self.bus_total2[3]+self.bus_total2[4]+self.bus_total2[5] if vehicle_type == 'truck2_all': return self.truck_total2[1]+self.truck_total2[2]+self.truck_total2[3]+self.truck_total2[4]+self.truck_total2[5] def get_revenue(self,vehicle_type): if vehicle_type == 'car': return self.car_revenue_total[self.tollboth] if vehicle_type == 'bus': return self.bus_revenue_total[self.tollboth] if vehicle_type == 'truck': return self.truck_revenue_total[self.tollboth] if vehicle_type == 'car_cashless': return self.car_revenue_cashless_total[self.tollboth] if vehicle_type == 'bus_cashless': return self.bus_revenue_cashless_total[self.tollboth] if vehicle_type == 'truck_cashless': return self.truck_revenue_cashless_total[self.tollboth] if vehicle_type == 'car2': return self.car_revenue_total2[self.tollboth] if vehicle_type == 'bus2': return self.bus_revenue_total2[self.tollboth] if vehicle_type == 'truck2': return self.truck_revenue_total2[self.tollboth] if vehicle_type == 'car2_cashless': return self.car_revenue_cashless_total2[self.tollboth] if vehicle_type == 'bus2_cashless': return self.bus_revenue_cashless_total2[self.tollboth] if vehicle_type == 'truck2_cashless': return self.truck_revenue_cashless_total2[self.tollboth] if vehicle_type == 'car_all': return self.car_revenue_total[1]+self.car_revenue_total[2]+self.car_revenue_total[3]+self.car_revenue_total[4]+self.car_revenue_total[5] if vehicle_type == 'bus_all': return self.bus_revenue_total[1]+self.bus_revenue_total[2]+self.bus_revenue_total[3]+self.bus_revenue_total[4]+self.bus_revenue_total[5] if vehicle_type == 'truck_all': return self.truck_revenue_total[1]+self.truck_revenue_total[2]+self.truck_revenue_total[3]+self.truck_revenue_total[4]+self.truck_revenue_total[5] if vehicle_type == 'car_cashless_all': return self.car_revenue_cashless_total[1]+self.car_revenue_cashless_total[2]+self.car_revenue_cashless_total[3]+self.car_revenue_cashless_total[4]+self.car_revenue_cashless_total[5] if vehicle_type == 'bus_cashless_all': return self.bus_revenue_cashless_total[1]+self.bus_revenue_cashless_total[2]+self.bus_revenue_cashless_total[3]+self.bus_revenue_cashless_total[4]+self.bus_revenue_cashless_total[5] if vehicle_type == 'truck_cashless_all': return self.truck_revenue_cashless_total[1]+self.truck_revenue_cashless_total[2]+self.truck_revenue_cashless_total[3]+self.truck_revenue_cashless_total[4]+self.truck_revenue_cashless_total[5] if vehicle_type == 'car2_all': return self.car_revenue_total2[1]+self.car_revenue_total2[2]+self.car_revenue_total2[3]+self.car_revenue_total2[4]+self.car_revenue_total2[5] if vehicle_type == 'bus2_all': return self.bus_revenue_total2[1]+self.bus_revenue_total2[2]+self.bus_revenue_total2[3]+self.bus_revenue_total2[4]+self.bus_revenue_total2[5] if vehicle_type == 'truck2_all': return self.truck_revenue_total2[1]+self.truck_revenue_total2[2]+self.truck_revenue_total2[3]+self.truck_revenue_total2[4]+self.truck_revenue_total2[5] if vehicle_type == 'car2_cashless_all': return self.car_revenue_cashless_total2[1]+self.car_revenue_cashless_total2[2]+self.car_revenue_cashless_total2[3]+self.car_revenue_cashless_total2[4]+self.car_revenue_cashless_total2[5] if vehicle_type == 'bus2_cashless_all': return self.bus_revenue_cashless_total2[1]+self.bus_revenue_cashless_total2[2]+self.bus_revenue_cashless_total2[3]+self.bus_revenue_cashless_total2[4]+self.bus_revenue_cashless_total2[5] if vehicle_type == 'truck2_cashless_all': return self.truck_revenue_cashless_total2[1]+self.truck_revenue_cashless_total2[2]+self.truck_revenue_cashless_total2[3]+self.truck_revenue_cashless_total2[4]+self.truck_revenue_cashless_total2[5] print('================================================================================\n Toll Payment Systems\n PT Jasa Marga, Tbk.\n================================================================================') while True: ask = input('\nSelect location of Toll Gate:\n1. Meruya\n2. Pondok Aren\nEnter 3 for the total number of vehicles passing and total revenue of the day on all toll booth on each/both gates.\n> ') if ask == '1': while True: ask2 = int(input('\nWhich Toll Booth? (1, 2, 3, 4, 5)\nEnter 0 to change Toll Gate\n> ')) v = Vehicle(ask2) if ask2 == 0: break while True: print('\nLocation of Toll Gate: Meruya\nToll Booth:',ask2,'\nMenu:\n1. Charge the vehicles.\n2. Count the total number of vehicles.\n3. Count the total revenue of the day.\n4. Change Toll Booth') usr=input('> ') if usr == '1': ask=input('\nCategory of vehicle:\n1. Car (RP 6000)\n2. Bus (RP 8000)\n3. Truck (RP 10000)\n> ') if ask == '1': ask3 = input('\nPay with:\n1. Cash\n2. Cashless\n> ') if ask3 == '1': v.add('car') print('\nSuccess!\n') elif ask3 == '2': v.add('car_cashless') print('\nSuccess!\n') if ask == '2': ask3 = input('\nPay with:\n1. Cash\n2. Cashless\n> ') if ask3 == '1': v.add('bus') print('\nSuccess!\n') if ask3 == '2': v.add('bus_cashless') print('\nSuccess!\n') if ask == '3': ask3 = input('\nPay with:\n1. Cash\n2. Cashless\n> ') if ask3 == '1': v.add('truck') print('\nSuccess!\n') if ask3 == '2': v.add('truck_cashless') print('\nSuccess!\n') if usr == '2': print('\nToll Booth:',ask2,'\n-------------------\nCar Bus Truck\n-------------------\n',v.get_total('car'),'\t ',v.get_total('bus'),'\t ',v.get_total('truck'),'\n-------------------') print('Total number of vehicles:',v.get_total('car')+v.get_total('bus')+v.get_total('truck'),'\n') if usr == '3': print('\nToll Booth:',ask2,'\n\nCash\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car'),'\t ',v.get_revenue('bus'),'\t',v.get_revenue('truck'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car')+v.get_revenue('bus')+v.get_revenue('truck'),'\n') print('\nCashless\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car_cashless'),'\t ',v.get_revenue('bus_cashless'),'\t',v.get_revenue('truck_cashless'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car_cashless')+v.get_revenue('bus_cashless')+v.get_revenue('truck_cashless'),'\n') print('Grand total revenue: Rp.',v.get_revenue('car')+v.get_revenue('bus')+v.get_revenue('truck')+v.get_revenue('car_cashless')+v.get_revenue('bus_cashless')+v.get_revenue('truck_cashless'),'\n') if usr == '4': break elif ask == '2': while True: ask2 = int(input('\nWhich Toll Booth? (1, 2, 3, 4, 5)\nEnter 0 to change Toll Gate\n> ')) v = Vehicle(ask2) if ask2 == 0: break while True: print('\nLocation of Toll Gate: Pondok Aren\nToll Booth:',ask2,'\nMenu:\n1. Charge the vehicles.\n2. Count the total number of vehicles.\n3. Count the total revenue of the day.\n4. Change Toll Booth') usr=input('> ') if usr == '1': ask=input('\nCategory of vehicle:\n1. Car (RP 18000)\n2. Bus (RP 20000)\n3. Truck (RP 25000)\n> ') if ask == '1': ask3 = input('\nPay with:\n1. Cash\n2. Cashless\n> ') if ask3 == '1': v.add('car2') print('\nSuccess!\n') elif ask3 == '2': v.add('car2_cashless') print('\nSuccess!\n') if ask == '2': ask3 = input('\nPay with:\n1. Cash\n2. Cashless\n> ') if ask3 == '1': v.add('bus2') print('\nSuccess!\n') if ask3 == '2': v.add('bus2_cashless') print('\nSuccess!\n') if ask == '3': ask3 = input('\nPay with:\n1. Cash\n2. Cashless\n> ') if ask3 == '1': v.add('truck2') print('\nSuccess!\n') if ask3 == '2': v.add('truck2_cashless') print('\nSuccess!\n') if usr == '2': print('\nToll Booth:',ask2,'\n-------------------\nCar Bus Truck\n-------------------\n',v.get_total('car2'),'\t ',v.get_total('bus2'),'\t ',v.get_total('truck2'),'\n-------------------') print('Total number of vehicles:',v.get_total('car2')+v.get_total('bus2')+v.get_total('truck2'),'\n') if usr == '3': print('\nToll Booth:',ask2,'\n\nCash\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car2'),'\t ',v.get_revenue('bus2'),'\t',v.get_revenue('truck2'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car2')+v.get_revenue('bus2')+v.get_revenue('truck2'),'\n') print('\nCashless\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car2_cashless'),'\t ',v.get_revenue('bus2_cashless'),'\t',v.get_revenue('truck2_cashless'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car2_cashless')+v.get_revenue('bus2_cashless')+v.get_revenue('truck2_cashless'),'\n') print('Grand total revenue: Rp.',v.get_revenue('car2')+v.get_revenue('bus2')+v.get_revenue('truck2')+v.get_revenue('car2_cashless')+v.get_revenue('bus2_cashless')+v.get_revenue('truck2_cashless'),'\n') if usr == '4': break elif ask == '3': while True: ask_again = input('\nWhich Toll Gate? (1. Meruya, 2. Pondok Aren, 3. Both)\nEnter 0 to go back.\n> ') if ask_again == '0': break if ask_again == '1': print('\nVehicles\n-------------------\nCar Bus Truck\n-------------------\n',v.get_total('car_all'),'\t ',v.get_total('bus_all'),'\t ',v.get_total('truck_all'),'\n-------------------') print('Total number of vehicles:',v.get_total('car_all')+v.get_total('bus_all')+v.get_total('truck_all'),'\n') print('Revenues\n\nCash\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car_all'),'\t ',v.get_revenue('bus_all'),'\t',v.get_revenue('truck_all'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car_all')+v.get_revenue('bus_all')+v.get_revenue('truck_all'),'\n') print('\nCashless\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car_cashless_all'),'\t ',v.get_revenue('bus_cashless_all'),'\t',v.get_revenue('truck_cashless_all'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car_cashless_all')+v.get_revenue('bus_cashless_all')+v.get_revenue('truck_cashless_all'),'\n') print('Grand total revenue: Rp.',v.get_revenue('car_all')+v.get_revenue('bus_all')+v.get_revenue('truck_all')+v.get_revenue('car_cashless_all')+v.get_revenue('bus_cashless_all')+v.get_revenue('truck_cashless_all'),'\n') elif ask_again == '2': print('\nVehicles\n-------------------\nCar Bus Truck\n-------------------\n',v.get_total('car2_all'),'\t ',v.get_total('bus2_all'),'\t ',v.get_total('truck2_all'),'\n-------------------') print('Total number of vehicles:',v.get_total('car2_all')+v.get_total('bus2_all')+v.get_total('truck2_all'),'\n') print('Revenues\n\nCash\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car2_all'),'\t ',v.get_revenue('bus2_all'),'\t',v.get_revenue('truck2_all'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car2_all')+v.get_revenue('bus2_all')+v.get_revenue('truck2_all'),'\n') print('\nCashless\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car2_cashless_all'),'\t ',v.get_revenue('bus2_cashless_all'),'\t',v.get_revenue('truck2_cashless_all'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car2_cashless_all')+v.get_revenue('bus2_cashless_all')+v.get_revenue('truck2_cashless_all'),'\n') print('Grand total revenue: Rp.',v.get_revenue('car2_all')+v.get_revenue('bus2_all')+v.get_revenue('truck2_all')+v.get_revenue('car2_cashless_all')+v.get_revenue('bus2_cashless_all')+v.get_revenue('truck2_cashless_all'),'\n') elif ask_again == '3': print('\nVehicles\n-------------------\nCar Bus Truck\n-------------------\n',v.get_total('car_all')+v.get_total('car2_all'),'\t ',v.get_total('bus_all')+v.get_total('bus2_all'),'\t ',v.get_total('truck_all')+v.get_total('truck2_all'),'\n-------------------') print('Total number of vehicles:',v.get_total('car_all')+v.get_total('bus_all')+v.get_total('truck_all')+v.get_total('car2_all')+v.get_total('bus2_all')+v.get_total('truck2_all'),'\n') print('Revenues\n\nCash\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car_all')+v.get_revenue('car2_all'),'\t ',v.get_revenue('bus_all')+v.get_revenue('bus2_all'),'\t',v.get_revenue('truck_all')+v.get_revenue('truck2_all'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car_all')+v.get_revenue('bus_all')+v.get_revenue('truck_all')+v.get_revenue('car2_all')+v.get_revenue('bus2_all')+v.get_revenue('truck2_all'),'\n') print('\nCashless\n--------------------------\nCar Bus Truck\n--------------------------\n',v.get_revenue('car_cashless_all')+v.get_revenue('car2_cashless_all'),'\t ',v.get_revenue('bus_cashless_all')+v.get_revenue('bus2_cashless_all'),'\t',v.get_revenue('truck_cashless_all')+v.get_revenue('truck2_cashless_all'),'\n--------------------------') print('Total revenue: Rp.',v.get_revenue('car_cashless_all')+v.get_revenue('bus_cashless_all')+v.get_revenue('truck_cashless_all')+v.get_revenue('car2_cashless_all')+v.get_revenue('bus2_cashless_all')+v.get_revenue('truck2_cashless_all'),'\n') print('Grand total revenue: Rp.',v.get_revenue('car_all')+v.get_revenue('bus_all')+v.get_revenue('truck_all')+v.get_revenue('car_cashless_all')+v.get_revenue('bus_cashless_all')+v.get_revenue('truck_cashless_all')+v.get_revenue('car2_all')+v.get_revenue('bus2_all')+v.get_revenue('truck2_all')+v.get_revenue('car2_cashless_all')+v.get_revenue('bus2_cashless_all')+v.get_revenue('truck2_cashless_all'),'\n') <file_sep>/Assignment 04 - Class Toll/v1.py class TollGate: def __init__(self): self.car_price = 6000 self.bus_price = 8000 self.truck_price = 10000 class Vehicle(TollGate): def car(self): print('\nFee:',self.car_price) def bus(self): print('\nFee:',self.bus_price) def truck(self): print('\nFee:',self.truck_price) v = Vehicle() print('================================================================================\n Toll Payment Systems\n PT Jasa Marga, Tbk.\n================================================================================') while True: ask=input('\nCategory of vehicle:\n1. Car (RP 6000)\n2. Bus (RP 8000)\n3. Truck (RP 10000)\n> ') if ask == '1': v.car() if ask == '2': v.bus() if ask == '3': v.truck() <file_sep>/Assignment 05 - Pygame/classes.py from pygame import * from pygame.sprite import * class Jet(Sprite): """initialize the jet""" def __init__(self, screen): Sprite.__init__(self) # load jet image self.image = image.load("nyan.gif") # resize image self.image = pygame.transform.scale(self.image, (140, 50)) # create hit box for jet self.rect = self.image.get_rect() self.rect.x = 10 self.rect.y = 50 self.screen = screen # create jet speed self.move_speed = 10 #fire rate speed self.firerates = 2 def moveleft(self): self.rect.x -= self.move_speed display.flip() def moveright(self): self.rect.x += self.move_speed display.flip() def moveup(self): self.rect.y -= self.move_speed display.flip() def movedown(self): self.rect.y += self.move_speed display.flip() class Star_bg: """initialize background""" def __init__(self,background): # load bg image for game self.background=image.load(background) # resize bg image self.background=pygame.transform.scale(self.background,(800,600)) self.background_size=self.background.get_size() self.background_rect=self.background.get_rect() self.width,self.height=self.background_size """print bg""" def draw(self,screen,x,y): screen.blit(self.background,(x,y)) class Bullet(Sprite): """initialize bullet""" def __init__(self,screen, startx, starty): Sprite. __init__(self) self.startx = startx self.starty = starty # bullet speed self.speedx = 20 # load bullet image self.image = pygame.image.load("bullets.png") # resize image self.image = pygame.transform.scale(self.image,(40,40)) # create bullet hit box self.rect=self.image.get_rect() self.rect.left = startx self.rect.top = starty self.rect.center = (startx,starty) self.screen = screen """move bullet to right""" def movement(self): self.rect.left += self.speedx class Asteroid(Sprite): """initialize the Asteroid""" def __init__(self, screen, width, height, speedx, startx, starty): Sprite.__init__(self) self.startx = startx self.starty = starty # create meteor speed self.speedx = speedx # load meteor image self.image = pygame.image.load("meteor.png") # resize image self.image = pygame.transform.scale(self.image, (width, height)) # create hitbox for meteor self.rect = self.image.get_rect() self.rect.left = startx self.rect.top = starty self.screen = screen """move the Asteroid to the right""" def movement(self): self.rect.left -= self.speedx class Button(Sprite): """initialize the start and quit button""" def __init__(self,image): Sprite. __init__(self) # load start or quit image self.button=pygame.image.load(image) # resize image self.button=pygame.transform.scale(self.button,(300,150)) <file_sep>/Assignment 01.py lebar=int(input("Enter number of rows: ")) # This is where you input the number #Triangle 1 for y in range(0,lebar): # The range of Y axis from 0 to total number of the rows you entered. for x in range(0,y+1): # The range of X axis from 0 to total number of y plus 1. print('*', end=" ") # Print asteriskt then space within the X range. print() # Print a new line after each asterisk and space printed. print() # Print a new line to seperate this triangle with below triangle. #Triangle 2 for y in range(0, lebar): # The range of Y axis from 0 to total number of the rows you entered. for x in range(0,lebar-y): # The range of X axis from 0 to total number of the rows you entered minus the Y range. print(end=" ") for x in range(0,y+1): print('*',end='') print() print() #Triangle 3 for y in range(0,lebar+1): for x in range(0,lebar-y): print('*', end=" ") print() print() #Triangle 4 for y in range(0, lebar): for x in range(0,lebar+y): print(end=" ") for x in range(0,lebar-y): print('*',end='') print() print() #Triangle 5 for y in range(0,lebar+1): for x in range(0,lebar-y): print(end=" ") for x in range(0,y): print('*', end=" ") print() print() #Triangle 6 for y in range(0, lebar): for x in range(0,lebar-y): print(end=" ") for x in range(0,y): print('*', end=" ") print() for y in range(0, lebar): for x in range(0,y): print(end=" ") for x in range(0,lebar-y): print('*',end=' ') print()
ec73bd06d564ce02d73d894231f014bc3b140d48
[ "Python" ]
13
Python
erisrp/Introduction-to-Programming---LAB
cf7f6566335318d77458d037c0d2ce69750f3eaf
28a032baa2930f71616211416ba1bedb163e645a
refs/heads/master
<repo_name>limjcst/codefacer<file_sep>/README.md # codefacer This is an auto tool for [siemens/codeface] using the local GitLab repository [siemens/codeface]: https://github.com/siemens/codeface * Setup Run `make install` to install codefacer. Edit /etc/codefacer.conf to fit your local environment. Supposing that you setup GitLab with creating an account `git`, type`sudo -u git -H codefacer` to use codeface to analyze the projects in the local GitLab repository. * Function Codefacer will create a conf file for each project, setting tagging `committer2author`, using the method translate from ``` codeface/codeface/util.py generate_analysis_windows(repo, window_size_months) ``` to create revisions, with a two week window. Tag information is ignored here. To distinguish each project, Codefacer uses `username@path` as the project name. After each configure file created, call Codeface. To use Codeface to analyze a project under a .git folder, it is necessary to replace ``` repo = pathjoin(gitdir, conf["repo"], ".git") ``` with ``` repo = pathjoin(gitdir, conf["repo"]) ``` in codeface/project.py. <file_sep>/include/global_conf.h #ifndef GLOBAL_CONF_H #define GLOBAL_CONF_H #ifndef BUFFER_SIZE #define BUFFER_SIZE 512 #endif /* global configuration */ typedef struct { char database[BUFFER_SIZE]; char username[BUFFER_SIZE]; char password[BUFFER_SIZE]; char db_mode[BUFFER_SIZE]; char address[BUFFER_SIZE]; char conf_path[BUFFER_SIZE]; char result_path[BUFFER_SIZE]; char repo_path[BUFFER_SIZE]; char codeface_path[BUFFER_SIZE]; int poll_interval; int max_running; } global_conf_t; #endif<file_sep>/codefacer.c #include <unistd.h> #include <sys/stat.h> #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <syslog.h> #include <signal.h> #include <mysql/mysql.h> #include <time.h> #include "config.h" const int SETTINGS_COUNT = 6, MAX_RUNNING = 8; MYSQL db; int rows_count, running, max_running, id; global_conf_t global_conf; #define buf_size 2047 void sigterm_handler(int signo){ if (signo == SIGTERM) { mysql_close(&db); syslog(LOG_INFO, "Codefacer daemon terminated."); closelog(); exit(0); } } void sigchld_handler(int signo){ if (signo == SIGCHLD) { while (waitpid(-1, NULL, WNOHANG) > 0) running--; } } void init(){ openlog("codefacer_daemon", LOG_PID, LOG_USER); syslog(LOG_INFO, "Codefacer daemon started."); signal(SIGTERM, sigterm_handler); signal(SIGCHLD, sigchld_handler); init_configuration(&global_conf); max_running = MAX_RUNNING; if (global_conf.max_running != 0) max_running = global_conf.max_running; mysql_init(&db); if (!mysql_real_connect(&db, global_conf.address, global_conf.username, global_conf.password, global_conf.database, 0, NULL, 0)) { syslog(LOG_ERR, "Failed to connec to database!"); syslog(LOG_ERR, "%s", mysql_error(&db)); exit(1); } srand(time(0)); running = 0; syslog(LOG_INFO, "codefacer daemon initialized"); } char recs[buf_size][43]; long long commitTime[buf_size]; int head; const int tail = buf_size - 1; /** * Translate from python code * codeface/codeface/util.py * generate_analysis_windows(repo, window_size_months) */ int generateRevision(FILE *conf, char *repo) { char command[buf_size]; char buf[buf_size]; char t_buf[buf_size]; head = buf_size; int window_size_weeks = 1; struct tm latest_commit, date_temp; time_t temp, week; week = 7 * 86400; sprintf(command, "git --git-dir=%s log --format=%%ad --date=iso8601 --all --max-count=1", repo); FILE *stream = popen(command, "r"); if (fgets(buf, buf_size, stream) == 0 || buf[0] < '0' || buf[0] > '9') { fclose(stream); return 0; } strptime(buf, "%Y-%m-%d %H:%M:%S %z", &latest_commit); fclose(stream); temp = mktime(&latest_commit); latest_commit = *localtime(&temp); strftime(buf, buf_size, "--before=%Y-%m-%dT%H:%M:%S%z", &latest_commit); sprintf(command, "git --git-dir=%s log --no-merges --format='%%H %%ct' --all --max-count=1 %s", repo, buf); stream = popen(command, "r"); while (fgets(buf, buf_size, stream)) { --head; sscanf(buf, "%s %lld", recs[head], &commitTime[head]); } fclose(stream); strftime(buf, buf_size, "--before=%Y-%m-%dT%H:%M:%S%z", &date_temp); int start = window_size_weeks; // Window size weeks ago int end = 0; while (start != end) { temp = mktime(&latest_commit); temp -= week * start; date_temp = *gmtime(&temp); strftime(buf, buf_size, "--before=%Y-%m-%dT%H:%M:%S%z", &date_temp); sprintf(command, "git --git-dir=%s log --no-merges --format='%%H %%ct' --all --max-count=1 %s", repo, buf); stream = popen(command, "r"); if (fgets(buf, buf_size, stream)) { end = start; start += window_size_weeks; } else { fclose(stream); start = end; sprintf(command, "git --git-dir=%s log --no-merges --format='%%H %%ct' --all --reverse", repo); stream = popen(command, "r"); if (fgets(buf, buf_size, stream) == 0) { fclose(stream); continue; } } buf[strlen(buf) - 1] = '\0'; sprintf(t_buf, "%s %lld", recs[head], commitTime[head]); if (strcmp(buf, t_buf) != 0) { --head; sscanf(buf, "%s %lld", recs[head], &commitTime[head]); } fclose(stream); } // Check that commit dates are monotonic, in some cases the earliest // first commit does not carry the earliest commit date if (head < tail && commitTime[head] > commitTime[head + 1]) { ++head; } int i = 0; for (; head <= tail; ++ head) { fprintf(conf, "'%s', ", recs[head]); ++i; } return i; } int createConf(char *confPath, char *repoPath, char *namespace_name, char *name) { char revisions[100 * buf_size] = "\0"; char rcs[100 * buf_size] = "\0"; FILE *conf = fopen(confPath, "wb"); char command[buf_size]; char buf[buf_size]; sprintf(command, "git --git-dir=%s for-each-ref --format='%%(*committerdate:raw)%%(committerdate:raw) %%(refname) %%(*objectname) %%(objectname)' refs/tags | sort -n | awk '{split($3, temp, \"refs/tags/\"); print temp[2]; }'", repoPath); FILE *stream = popen(command, "r"); char cur[buf_size]; char rc[buf_size] = "'', "; char preIsRC = 0; char first = 1; char tagExist = 0; while (fgets(buf, buf_size, stream)) { {//if (buf[0] == 'v') { buf[strlen(buf) - 1] = '\0'; if (first) { sprintf(cur, "'%s', ", buf); strcpy(revisions, cur); strcpy(rcs, cur); first = 0; continue; } //printf("%s ", buf); if (strstr(buf, "rc") > 0 || strstr(buf, "RC") > 0) { if (preIsRC) { //do nothing } else { preIsRC = 1; sprintf(rc, "'%s', ", buf); } //printf("\n"); } else { sprintf(cur, "'%s', ", buf); //printf("%s %s\n", cur, rc); strcat(revisions, cur); strcat(rcs, rc); strcpy(rc, "'',"); preIsRC = 0; tagExist = 1; } } } fclose(stream); fprintf(conf, "project: %s@%s\n", namespace_name, name); fprintf(conf, "description: \n"); fprintf(conf, "repo: .\n"); /** * tag analysis leads to some errors. * window analysis is proper. **/ tagExist = 0; if (tagExist) { fprintf(conf, "revisions: [%s]\n", revisions); fprintf(conf, "rcs: [%s]\n", rcs); } else { //use commit hash substitute fprintf(conf, "revisions: ["); int i = generateRevision(conf, repoPath); // empty repository or only one commit is not worth continuing if (i <= 1) { fclose(conf); return 1; } fprintf(conf, "]\n"); fprintf(conf, "rcs: ["); for (; i > 0; --i) { fprintf(conf, "'', "); } fprintf(conf, "]\n"); } fprintf(conf, "tagging: committer2author\n"); fprintf(conf, "sloccount: true\n"); fprintf(conf, "understand: true\n"); fclose(conf); return 0; } int run(int jobs){ char command[buf_size]; // remove the results left sprintf(command, "rm -f %slog/codeface.log.R.*", global_conf.codeface_path); if (system(command)) { printf("Command:'%s' failed", command); } sprintf(command, "rm -rf %s*", global_conf.result_path); if (system(command)) { printf("Command:'%s' failed", command); } // empty database sprintf(command, "mysql -ucodeface -pcodeface -Nse 'show tables' codeface | while read table; do mysql -ucodeface -pcodeface -e \"SET FOREIGN_KEY_CHECKS = 0; truncate table $table\" codeface; done"); if (system(command)) { // nothing } char query[buf_size] = "SELECT max(id) FROM projects"; int ret = mysql_query(&db, query); if (ret != 0) { syslog(LOG_ERR, "SQL Query Failed!"); return 0; } MYSQL_RES *result = mysql_store_result(&db); rows_count = mysql_num_rows(result); if (rows_count == 0) { mysql_free_result(result); return 0; } MYSQL_ROW row = mysql_fetch_row(result); int maxID = atoi(row[0]); printf("%d\n\n", maxID); mysql_free_result(result); int i; for (i = 1; i <= maxID; ++i) { sprintf(query, "select name, namespace_id from projects WHERE id=%d", i); if (mysql_query(&db, query) == 0) { result = mysql_store_result(&db); if (mysql_num_rows(result) == 0) { mysql_free_result(result); continue; } } MYSQL_ROW row = mysql_fetch_row(result); char *name = row[0]; int id = atoi(row[1]); printf("%s %d\n", name, id); char *namespace_name; sprintf(query, "select name from namespaces WHERE id=%d", id); if (mysql_query(&db, query) == 0) { MYSQL_RES *resultUN = mysql_store_result(&db); MYSQL_ROW rowUN = mysql_fetch_row(resultUN); namespace_name = rowUN[0]; char repoPath[buf_size]; strcpy(repoPath, global_conf.repo_path); strcat(repoPath, namespace_name); strcat(repoPath, "/"); strcat(repoPath, name); strcat(repoPath, ".git/"); char confPath[buf_size]; strcpy(confPath, global_conf.conf_path); mkdir(confPath, S_IRWXU | S_IRWXG); strcat(confPath, namespace_name); strcat(confPath, "/"); mkdir(confPath, S_IRWXU | S_IRWXG); strcat(confPath, name); strcat(confPath, ".conf"); if (createConf(confPath, repoPath, namespace_name, name)) { mysql_free_result(resultUN); printf("Nothing to analyze!\n"); continue; } sprintf(command, "codeface -j %d run -c %scodeface.conf -p %s %s %s", jobs, global_conf.codeface_path, confPath, global_conf.result_path, repoPath); if (system(command) < 0) {} mysql_free_result(resultUN); } mysql_free_result(result); } return 0; } int main(void) { init(); FILE *stream = popen("nproc", "r"); int jobs = 0; if (fscanf(stream, "%d", &jobs)) { jobs /= 2; } if (jobs == 0) { jobs = 1; } run(jobs); return 0; } <file_sep>/Makefile all: release release: mkdir -p bin gcc codefacer.c -o bin/codefacer -Iinclude -lmysqlclient -Wall -O2 -D_GNU_SOURCE clean: rm -rf bin install: release cp bin/codefacer /usr/bin/codefacer cp codefacer.conf /etc/codefacer.conf uninstall: rm /usr/bin/codefacer rm /etc/codefacer.conf <file_sep>/include/config.h #ifndef CONFIG_H #define CONFIG_H #include "global_conf.h" #include <string.h> #include <time.h> #include <ctype.h> #ifndef CONF_FILE #define CONF_FILE "/etc/codefacer.conf" #endif char* ltrim(char* str) { int len = strlen(str); int start = 0, i; while (start < len && isspace(str[start])) start++; if (start == len) { str[0] = '\0'; } else { for (i = start; i < len; i++) str[i - start] = str[i]; } return str; } char* rtrim(char* str) { int len = strlen(str); while (len > 0 && isspace(str[len - 1])) { len--; } str[len] = '\0'; return str; } int parse_configuration(char* buf, global_conf_t* conf) { char *item, *param; item = strtok(buf, "="); param = strtok(NULL, "\0"); rtrim(item); ltrim(param); rtrim(param); if ( !strcmp(item, "ADDRESS") ) { strcpy(conf->address, param); return 0; } else if ( !strcmp(item, "DATABASE") ) { strcpy(conf->database, param); return 0; } else if ( !strcmp(item, "USERNAME") ) { strcpy(conf->username, param); return 0; } else if ( !strcmp(item, "PASSWORD") ) { strcpy(conf->password, param); return 0; } else if ( !strcmp(item, "DB_MODE") ) { strcpy(conf->db_mode, param); return 0; } else if ( !strcmp(item, "MAX_RUNNING") ) { conf->max_running = atoi(param); return 0; } else if ( !strcmp(item, "POLL_INTERVAL") ) { conf->poll_interval = atoi(param); return 0; } else if ( !strcmp(item, "CONF_PATH") ) { strcpy(conf->conf_path, param); return 0; } else if ( !strcmp(item, "RESULT_PATH") ) { strcpy(conf->result_path, param); return 0; } else if ( !strcmp(item, "REPO_PATH") ) { strcpy(conf->repo_path, param); return 0; } else if ( !strcmp(item, "CODEFACE_PATH") ) { strcpy(conf->codeface_path, param); return 0; } return 1; } int init_configuration(global_conf_t *gconf) { FILE *conf = fopen(CONF_FILE, "r"); if (conf == NULL) { fprintf(stderr, "[ERROR]Error opening configuration file!\n"); return 1; } /* Cannot handle line longer than BUFFER_SIZE */ int line_no = 0; char buf[BUFFER_SIZE]; while ( fgets(buf, BUFFER_SIZE, conf) != NULL ) { line_no++; ltrim(buf); if (strlen(buf) == 0 || buf[0] == '#') continue; if ( parse_configuration(buf, gconf) ) { fprintf(stderr, "[WARN]Failed to parse configuration, line %d ommited.\nDetails:\"%s\"\n", line_no, buf); } } fclose(conf); return 0; } #endif // CONFIG_H
a6fae512fcb9b44aa7911751d212a503688bae8d
[ "Markdown", "C", "Makefile" ]
5
Markdown
limjcst/codefacer
22a9da9e23d9bf951c6eae41ff3a4cdece74b53a
6baf473ba55acb5a4f2558c4375f973868f17485
refs/heads/master
<repo_name>mvpopa/codedeploy_test<file_sep>/scripts/beforeInstall.sh #!/usr/bin/env bash rm -rf /var/www/topgolf mkdir -p /var/www/topgolf/app/public
d34e7136e7976644952275fc306c2a494f8c50ad
[ "Shell" ]
1
Shell
mvpopa/codedeploy_test
65a025496868aa77cfad859f66490be4b51d6d0c
e19418dd8cf6b423a266f98d61c5488f150cd80a