branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import React from 'react'; import {Component} from 'react'; class AddCity extends Component{ addCity = (event) =>{ event.preventDefault(); this.props.addCity(event.target[0].value); }; render() { return( <div className="addCityForm"> <form onSubmit={this.addCity}> <input type="text" placeholder="Добавьте новый город"></input> <button className="addCityButton">+</button> </form> </div> ); } } export default AddCity <file_sep>**Лабораторная работа 2.** При первой загрузке страницы происходит запрос пользователя на получение данных о геолокации с использованием HTML5 Geolocation API. Если пользователь соглашается предоставить данные о геолокации – получаем из внешнего API данные о погоде. Если нет – запрашиваем информацию для города по умолчанию (город по умолчанию можно выбрать самостоятельно). Информация о городе, данные о погоде (температура, ветер, давление, влажность), иконка погоды, координаты отрисовываются на странице в соответствии с макетом. Иконка и все необходимые данные есть в API https://openweathermap.org. В интерфейсе также есть кнопка с повторным запросом геолокации пользователя. У пользователя есть возможность добавления и удаления городов в избранное. Информация о погоде отображается для всех городов из избранного в соответствии с макетом. Избранное сохраняется в LocalStorage. Пока происходит загрузка данных по конкретному городу/локации – показываем loader и/или сообщение об ожидании загрузки данных. Работа с глобальным состоянием приложения (например, список избранных городов) реализуется с помощью Redux. Локальное состояние компонента (например, состояние ожидания загрузки данных) – через локальный state компонента.<file_sep>~~выгрузить приложение hello world~~ ~~Запросить данные для Сургута~~ ~~Отрисовать данные для Сургута согласно макету~~ ~~Сделать запрос на предоставление геолокации~~ ~~добавить города~~ ~~удалять города~~ ~~Работать с избранным~~ ~~redux~~ add saga add loader<file_sep>export const ADD_CITY = 'ADD_CITY'; export const REMOVE_CITY = 'REMOVE_CITY'; export function addCity(payload) { return {type: ADD_CITY, payload} } export function removeCity(payload) { return {type: REMOVE_CITY, payload} } <file_sep>import React, {Component} from 'react'; import WeatherBlock from "./WeatherBlock"; class CurrentCity extends Component{ constructor(props){ super(props); this.state = { cityName : "Surgut", latitude : undefined, longitude: undefined }; this.getLocationButtonPress = this.getLocationButtonPress.bind(this); } getLocation = () => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position => { this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude, cityName: undefined }); })); } else { this.setState({ latitude: undefined, longitude: undefined, cityName: "Surgut" }); } }; getLocationButtonPress = (event) => { event.preventDefault(); this.getLocation() }; render(){ navigator.geolocation.getCurrentPosition(function(){}); return( <div className="currentCity"> <h1>Погода здесь</h1> <form className="updateGeoLocation" onSubmit={this.getLocationButtonPress}> <button>Обновить геолокацию</button> </form> <WeatherBlock cityName={this.state.cityName} latitude={this.state.latitude} longitude={this.state.longitude} /> </div> ) }; } export default CurrentCity<file_sep>import {ADD_CITY, REMOVE_CITY} from './actions/actions'; const initialState = { cities: [] }; function rootReducer(state = initialState, action) { switch(action.type) { case ADD_CITY: return Object.assign({}, state, { cities: state.cities.concat(action.payload) }); case REMOVE_CITY: return Object.assign({}, state, { cities: state.cities.filter(function (city) { return city.id !== action.payload.id; }) }); default: return state; } } export default rootReducer;
84318bb5fa67b03d7871764b7152f673c08851ba
[ "JavaScript", "Markdown" ]
6
JavaScript
ShwarzeWolf/WLab2
bce5bd1ff48dc4286c526443d3af495fd5b669fe
ea3b88d4f52dc981b86a98d6d5fe2d2eda778058
refs/heads/master
<repo_name>JBP1996/GAA<file_sep>/src/Principal.java import java.util.Scanner; public class Principal { public Principal() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub int opcao; boolean continua = false; do{ continua = false; System.out.println("Qual deseja iniciar:\n 1- Exercicio Balanco Simples\n 2- InputBasico\n 3- Calculadora Simples\n 4- Balanco com insercao de valores\n" + " 5- Adivinhar o numero escondido\n 6- Numero1 maior que Numero2\n 7- Ciclos\n 8- CalculadoraInfinita"); opcao = (new Scanner(System.in).nextInt()); switch(opcao){ case 1: new ExercicioBalancoSimples(); break; case 2: new dia28102016.InputOutputBasico(); break; case 3: new dia28102016.CalculadoraSimples(); break; case 4: new dia28102016.ExercicioBalanco(); break; case 5: new dia28102016.AdivinhaNumero(); break; case 6: new dia02112016.Condicionais(); break; case 7: new dia02112016.Ciclos(); break; case 8: new dia02112016.CalculadoraInfinita(); break; default: System.out.println("Não existe nenhuma opcao com esse numero!"); continua = true; break; } } while(continua == true); for(int a=0; a<=5;a++){ System.out.println("\n"); } } }
75a20ee309000b1ee7494c6fdfd2d029108452a9
[ "Java" ]
1
Java
JBP1996/GAA
d314ed2758983d91698472fc4ae28ccfa3d118ce
4a59ac151c3788fa06dde4de7470df844551c76b
refs/heads/master
<file_sep><?php class Sns_model extends CI_Model { /** * @var \Aws\Sns\SnsClient */ protected $snsClient; /** * @var string */ protected $topicArn = "your topicArn"; /** * Sns constructor. */ public function __construct() { $this->load->helper("path"); require_once set_realpath('vendor/autoload.php'); $this->snsClient = Aws\Sns\SnsClient::factory(array( 'region' => 'us-east-1', 'version' => 'latest', 'credentials' => array( 'key' => 'your_key', 'secret' => 'your_secret_id', ) )); } public function createTopic() { $result = $this->snsClient->createTopic(array( // Name is required 'Name' => 'your_queue_name', )); return $result; } public function subscribe($endpoint = '') { $result = $this->snsClient->subscribe([ 'Endpoint' => $endpoint, 'Protocol' => 'email', // REQUIRED 'TopicArn' => $this->topicArn, // REQUIRED ]); return $result; } public function listSubscriptions() { $result = $this->snsClient->listSubscriptionsByTopic([ 'NextToken' => '', 'TopicArn' => $this->topicArn, // REQUIRED ])->getAll(); return $result; } public function pushNotification($subject, $message) { $result = $this->snsClient->publish([ 'Message' => $message, 'Subject' => $subject, 'TopicArn' => $this->topicArn, ]); return $result; } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Sqs extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('form'); $this->load->model('Sqs_model'); } function index(){ redirect(base_url('sqs/create/')); } function create($type = null,$message = null){ $result = null; if( $type && $message ){ $result['message'] = $this->message($type,$message); } $this->load->view('queues_view',$result); } public function createMessage() { $message_url = null; if( $this->input->post('name') ) { $post = $this->input->post('name'); $send = $this->Sqs_model->sendMessage($post); if($send == true){ $message_url = $this->message_url('success','Data has been sent to queue'); }else{ $message_url = $this->message_url('error',json_encode($send)); } } redirect(base_url('sqs/create'.$message_url)); } public function queue_list() { $receive = $this->Sqs_model->getList(); $result["allreceive"] = $receive; $this->load->view('queue_list',$result); } private function message_url($type,$message){ return '/'.$type.'/'.base64_encode($message); } private function message($type,$message){ return '<div class="alert alert-'.$type.' alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>'.ucwords($type).'!</strong> '.base64_decode($message).'</div>'; } }<file_sep><?php class Sqs_model extends CI_Model { /** * @var \Aws\Sqs\SqsClient */ protected $sqsClient; /** * @var string */ protected $queueName = 'your_queue_name'; /** * Sqs constructor. */ public function __construct() { $this->load->helper("path"); require_once set_realpath('vendor/autoload.php'); $this->sqsClient = Aws\Sqs\SqsClient::factory(array( 'region' => 'us-east-1', 'version' => 'latest', 'credentials' => array( 'key' => 'your_key', 'secret' => 'your_secret_id', ) )); } /** * @param $arguments * @return \Guzzle\Service\Resource\Model */ public function sendMessage($arguments) { // Get the queue URL from the queue name. $result = $this->sqsClient->getQueueUrl(array('QueueName' => $this->queueName)); $queue_url = $result->get('QueueUrl'); // Send the message $return = $this->sqsClient->sendMessage(array( 'QueueUrl' => $queue_url, 'MessageBody' => json_encode($arguments) )); return $return; } /** * @return array */ public function getList() { $body = array(); // Get the queue URL from the queue name. $result = $this->sqsClient->getQueueUrl(array('QueueName' => $this->queueName)); $queue_url = $result->get('QueueUrl'); /*var_dump($queue_url); die();*/ $queueAttributes = $this->sqsClient->getQueueAttributes(array( 'QueueUrl' => $queue_url, 'AttributeNames' => array('ApproximateNumberOfMessages'), )); $qsize = $queueAttributes->get('Attributes'); $qsize = $qsize['ApproximateNumberOfMessages']; for ($j = 0; $j < $qsize; ++$j) { // Receive a message from the queue using the AWS SDK for PHP function, receive_message. $result = $this->sqsClient->receiveMessage(array( 'QueueUrl' => $queue_url, )); $message = $result->get('Messages'); if( isset($message['0']['Body']) && !empty($message['0']['Body']) ){ $body[] = $message['0']['Body']; } } return $body; } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Sns extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('form'); $this->load->model('Sns_model'); } function index(){ redirect(base_url('sns/createnotification/')); } public function createsubscription($type = null,$message = null){ $result = null; if( $type && $message ){ $result['message'] = $this->message($type,$message); } $this->load->view('sns_subscription_view',$result); } public function addsubscription() { if( $this->input->post('subscriber') ) { $message_url = null; $endpoint = $this->input->post('subscriber'); $result = $this->Sns_model->subscribe($endpoint); if($result == true){ $message_url = $this->message_url('success','Successfully'); }else{ $message_url = $this->message_url('error',json_encode($result)); } redirect(base_url('sns/createsubscription'.$message_url)); } } public function createnotification($type = null,$message = null){ $result = null; if( $type && $message ){ $result['message'] = $this->message($type,$message); } $this->load->view('sns_notification_view',$result); } public function sendnotification() { if( $this->input->post('message') ) { $message_url = null; $subject = 'SNS Notification'; $message = $this->input->post('message'); $result = $this->Sns_model->pushNotification($subject, $message); if($result == true){ $message_url = $this->message_url('success','Notification has been sent.'); }else{ $message_url = $this->message_url('error',json_encode($result)); } redirect(base_url('sns/createnotification'.$message_url)); } } public function listallsubscription() { $subscriber = $this->Sns_model->listSubscriptions(); $result["allsubscriber"] = $subscriber; $this->load->view('sns_subscriptions_list',$result); } private function message_url($type,$message){ return '/'.$type.'/'.base64_encode($message); } private function message($type,$message){ return '<div class="alert alert-'.$type.' alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>'.ucwords($type).'!</strong> '.base64_decode($message).'</div>'; } }
4e400ee5a46e4dd3bfbf7114de6ba76a7d7deccb
[ "PHP" ]
4
PHP
zahiritian/AWS-SQS-SNS-PHP
2e5c543844f03e81ed084ec9edbcbe1c2b994410
6e55d55480c840342e001116978724e5d7c18f3f
refs/heads/master
<file_sep>Rails.application.routes.draw do resources :students, only: :index end
bad1a07a3eb352ca4512ed029d49ee2865048cb4
[ "Ruby" ]
1
Ruby
Andyagus/rails-restful-index-action-lab-nyc01-seng-ft-060120
12af50036a7cf510121b6e8e458ffc2a9fb73ce6
5191acefface37ce726750bc9c776dbb379d77d6
refs/heads/master
<repo_name>taokexia/JianshuProject<file_sep>/src/pages/login/store/actionCreators.js import axios from 'axios'; import * as constants from './constants'; export const getLogin = (name, password) => { return (dispatch) => { axios.get('/api/login.json?name='+name+'&password='+password).then((resp) => { const data = resp.data.data; dispatch(setLogin(data)); }) } } export const logout = () => ({ type: constants.LOGOUT }) const setLogin = (data) => ({ type: constants.SET_LOGIN, data })<file_sep>/src/pages/home/store/actionCreators.js import axios from 'axios'; import { GET_HOME_LIST, ADD_HOME_ARTICLE, TOGGLE_SCROLL_TOP } from './constants'; export const getMoreArticle = (page) => { // 获取更多文章 return (dispatch) => { axios.get('/api/articleList.json').then((resp) => { const data = resp.data; dispatch(addHomeArticle(data.data, page)); }); } } export const getHomeList = () => { return (dispatch) => { axios.get('/api/homeList.json').then((resp) => { const data = resp.data; dispatch(getHomeInfo(data.data)); }); } } export const toggleScrollShow = (show) => ({ type: TOGGLE_SCROLL_TOP, show }) const getHomeInfo = (data) => { return { type: GET_HOME_LIST, topicList: data.topicList, articleList: data.articleList, recommendList: data.recommendList, writerList: data.writerList } } const addHomeArticle = (data, page) => { return { type: ADD_HOME_ARTICLE, articleList: data, articlePage: page+1 } }<file_sep>/src/store/index.js import { createStore, compose, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import reducer from './reducer'; // 调用 redux devtools const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize... }) : compose; const store = createStore(reducer, composeEnhancers( applyMiddleware( thunk) )); export default store;<file_sep>/src/pages/home/components/Writer.js import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { WriteWrapper, WriteItem } from '../style'; class Writer extends PureComponent { render() { return ( <WriteWrapper> { this.props.list.map((item) => ( <WriteItem key={item.get('id')}> <img className="pic" src={item.get('imgUrl')} alt="" /> <p className="name">{item.get('name')}</p> <p className="desc">{item.get('desc')}</p> </WriteItem> )) } </WriteWrapper> ) } } const mapState = (state) => { return { list: state.getIn(['home', 'writerList']) } } export default connect(mapState, null)(Writer);<file_sep>/src/pages/home/store/constants.js export const GET_HOME_LIST = "home/get_home_list"; export const ADD_HOME_ARTICLE = "home/add_home_article"; export const TOGGLE_SCROLL_TOP = "home/toggle_scroll_top"; <file_sep>/src/common/header/store/reducer.js import * as constants from './constants'; import { fromJS } from 'immutable'; const defaultState = fromJS({ focused: false, list: [], mouseIn: false, page: 1, // 当前Search页数 pageTotal: 1 // Search总页数 }) export default (state=defaultState, action) => { switch(action.type) { case constants.SEARCH_FOCUS: return state.set('focused', true); case constants.SEARCH_BLUR: return state.set('focused', false); case constants.GET_HEADER_LIST: return state.merge({ 'list': action.data, 'pageTotal': action.pageTotal }) // return state.set('list', action.data).set('pageTotal', action.pageTotal); case constants.MOUSE_ENTER: return state.set('mouseIn', true); case constants.MOUSE_LEAVE: return state.set('mouseIn', false); case constants.HEADER_LIST_SWITCH: return state.set('page', action.page); default: return state; } }
1b29887605a1afd8f920972dd7b067ef7b5def8e
[ "JavaScript" ]
6
JavaScript
taokexia/JianshuProject
834248624bace142990406bcfcc06ae6f4292592
fc45d36f45a5254c62efc869f78cbe3b4dd6b91d
refs/heads/master
<repo_name>SergeyKucenko/SWIFT<file_sep>/LessonsSwiftBook 1-42/LessonsSwiftBook 28-31.playground/Contents.swift import UIKit // ДАЛЕЕ БУДУТ СТРУКТУРЫ (осноные строительыне блоки нашего кода будут СТРУКТУЫ и КЛАССЫ !!!) // 2 самых ВАЖНЫХ отличия между СТРУКТУРАМИ и КЛАССАМИ - это 1) структуры НЕ МОГУТ НАСЛЕДОВАТЬСЯ в отличие от КЛАССОВ 2)КЛАССЫ являются ССЫЛОЧНЫМ значением, СТРУКТЫРЫ являются типом ЗНАЧЕНИЯ // simple structure/class struct Site { // stored properties (свойства хранения) var siteName = "SwiftBook.ru" let visitsToday = 1000 let visitsYesterday = 1000 // computed property (вычисляемое свойство) var visitsTommorow: Int { return (visitsToday + visitsYesterday) / 2 } // lazy property (ленивое свойство ) lazy var someLazyProperty = 1 + 2 func description() -> String { // обычный МЕТОД return "We had \(visitsYesterday) visitors yesterday. Today we have \(visitsToday) visitors. Tommorow we will have about \(visitsTommorow) visitors." } } let firstWebSite = Site () // далее будет функция которая позволить изменить совйства sitename (см.выше) func changeSiteName(site: Site) -> Site { var site = site site.siteName = "iphonecoder.ru" return site } changeSiteName(site: firstWebSite) firstWebSite.siteName // другой пример работы СТРУКТУРЫ // === это оператор ТОЖДЕСТВЕННОСТИ - он проверят принадлежат ли принадлежет ли экземпляры класса одной ячейки памяти т.е. является ли один экземпляр класса , ссылкой дуругого языка класса // ДАЛЕЕ БУДУТ - Импорт фреймворков или библиотек //import UIKit import Foundation let string = "hello world" string.components(separatedBy: "") // разбивает сроку на компоненты // ДАЛЕЕ БУДЕТ 30. Оператор Проверка типов и оператор приведение типов class Furniture { // это РОДИТЕЛЬСКИЙ КЛАСС/СУПЕР КЛАСС, мебель ("каждый шкаф явлется мебелью но некаждая мебель является обязательно шкафом" ) let material: String init(material: String){ self.material = material } } class Bed: Furniture{ // полки let numberOfPlaces: Int // количество полок init(numberOfPlaces: Int, material: String){ // init это инициализатор self.numberOfPlaces = numberOfPlaces super.init(material: material) } } class Cupboard: Furniture{ // шкаф let numberOfShelves: Int // полки init (numberOfShalves: Int, material: String) { self.numberOfShelves = numberOfShalves super.init(material: material) } } var arrayOffurniture = [Furniture] () arrayOffurniture.append(Bed(numberOfPlaces: 2, material: "Wood")) arrayOffurniture.append(Bed(numberOfPlaces: 1, material: "Steel")) arrayOffurniture.append(Bed(numberOfPlaces: 2, material: "Wood")) arrayOffurniture.append(Cupboard(numberOfShalves: 4, material: "Wood")) arrayOffurniture.append(Cupboard(numberOfShalves: 6, material: "Steel")) arrayOffurniture.append(Cupboard(numberOfShalves: 3, material: "Wood")) arrayOffurniture.append(Cupboard(numberOfShalves: 5, material: "Steel")) arrayOffurniture var bed = 0 var cupboard = 0 //for item in arrayOffurniture{ //пишем цикл // if item is Bed{ // is это оператор проверки типа // bed += 1 // } else { // cupboard += 1 // } //} for item in arrayOffurniture{ // if item is Bed { // let bedForSure = item as! Bed // bed += 1 // } if let bedForSure = item as? Bed{ // это более "элегантное" написание того что закомиченно выше bed += 1 bedForSure.numberOfPlaces } } bed cupboard // ДАЛЕЕ БУДУТ - 31. Типы AnyObject и Any () class A{ } class B { } class C { } let a = A() let b = A() let c = A() let d = B() let e = C() struct D { } let f = D() enum E { case a case b } let g = E.b let array: [AnyObject] = [a, b, c, d, e] // AnyObject - это тип обозначающий экземпляр любого КЛАССА let arrayTwo: [Any] = [a, b, c, d, e, f, g, true, "String", 0.95, 5 + 4] // Any - это тип обозначающий все значения for i in arrayTwo { // раскладываем массив типа ANY switch i { case let item as Int: print("this is int") case let item as String: print("this is string") default: print("other type") } } <file_sep>/LessonsSwiftBook 1-42/func 2020.playground/Contents.swift import UIKit // 1. простая функция, ничего не принимающая и ничего не возвращающая func sayHello () { print("Hello") } sayHello() // 2. функция, принимающая один параметр func oneParam (param: Int ) { var param = param param += 1 } oneParam(param: 11) // 3. функция, не принимающая один параметр, но возвращающая значение func returnValue() -> Int { let c = 10 return c } let a = returnValue() a // 4. функция, принимающая несколько параметров и возвращающая значение func giveMeYour(name: String, andSecondName: String) -> String { return "Your full name is a \(name) \(andSecondName)" } giveMeYour(name: "Oleg", andSecondName: "Nikolaevich") // 5. функция, принимающая массив в качестве параметра и использующая вложенную функцию для работы func calcMoneyIN (array: [Int]) -> Int { var sum = 0 func sayMoney(){ print (sum) } for item in array { sum += item } sayMoney() return sum } calcMoneyIN(array:[1, 2, 3, 4, 5]) // 6. функция, которая принимает переменное число параметров func findSumm (ofIntegers inregers: Int...) -> Int { var sum = 0 for item in inregers{ sum += item } return sum } findSumm(ofIntegers: 1, 2, 3) // 7. имена параметров функции func sum (_:Int) -> Int { return 10 } // 8. функция в качестве возвращаемого значения func whatToDo (missed: Bool) -> ((Int)->Int){ func missCountUp (input: Int) -> Int {return input + 1 } func missCountDown (input: Int) -> Int {return input - 1 } return missed ? missCountUp : missCountDown } var missedCout = 0 missedCout = whatToDo(missed: false) (missedCout) whatToDo(missed: true) (0) <file_sep>/LessonsSwiftBook 1-42/LessonsSwiftBook 20-27.playground/Contents.swift import UIKit // ДАЛЕЕ БУДЕТ ОЧЕНЬ ВАЖНАЯ ТЕМА _НАСЛЕДОВАНИЕ_ (наследование происходить исключительно между классами) class Human { // это super КЛАСС ___ var name : String // properties - это свойства func tellAboutME() -> String { // metod - это МЕТОД return "Hello! My name is \(name) !" } init(name: String){ // initializer - это инициализатор self.name = name } } // далее будет еще один класс который будет наследовать свойства класса HUMAN class Child: Human { // child - явлется подклассом___ var toy = "Horse" override func tellAboutME() -> String { // переопределение метода let originalText = super.tellAboutME() // super класс это тот клас от которого этот клас наследует свои свойства return originalText + " And I have a toy \(self.toy) " } init (toy: String, name: String) { self.toy = toy super.init(name: name) } override init(name: String) { self.toy = "Hummer" super.init(name: name) } } let child = Child (name: "Klava") child.tellAboutME() child.toy let child1 = Child(toy: "Dinosaur", name: "Max") child1.tellAboutME() // можно и предотвратить наследование(ключевое слово FINAL. ставится перед классом или методом например поставить FINAL перед func tellAboutME() -> String , тогда далее нивего не будет наследоваться классом ... ) // ДАЛЕЕ БУДУТ ВЫЧЕСЯЛЕМЫЕ СВОЙСТВА (СВОЙСТВА КОТОРЫЕ ВЫЧЕСЛЯЮТ СВОЕ ЗНАЧЕНИЕ) class Rectangular { let height: Int let width: Int let depth: Int var volume: Int {// далее будут вычисляемые свойства и это всегда переменные return height * width * depth // вычисляем объем фигуры } init (height: Int, width: Int, depth: Int){ // это инизиализатор в котором будут описанны все свойства self.height = height self.width = width self.depth = depth } } let rect = Rectangular(height: 10, width: 12, depth: 13) rect.volume // далее будет еще один пример class Person { var name: String var secondName: String var fullName: String { get {return name + " " + secondName // вместо одного + пришлось написать конструкцию + " " + , благодаря ей будет пробел между именами , без нее все будет слитно } set(anotherNewValue) { let array = anotherNewValue.components(separatedBy: " ") name = array[0] secondName = array [1] } } init (name: String, secondName: String){ self.name = name self.secondName = secondName } } let person = Person(name: "Ivan", secondName: "Ivanovich") person.fullName person.name person.secondName person.fullName = "<NAME>" person.name person.secondName // ДАЛЕЕ БУДУТ СВОЙСТВА КЛАССОВ class Car { // properties let products: Int let people: Int let pets: Int class var selfWeight : Int { return 1500 } class var maxWeight : Int { return 2000 } var totalWeight: Int{ // computed property - текущий вес return products + people + pets + Car.selfWeight } // initializer init (products: Int, people:Int, pets:Int) { self.products = products self.people = people self.pets = pets } } let car = Car (products: 30, people: 300, pets: 50) car.totalWeight // далее будут примеры работы со свойствами let maxWeight = Car.maxWeight let carWeight = Car.selfWeight let totalWeight = car.totalWeight if maxWeight < totalWeight { print ("You cant drive, because car is overloaded!: \(totalWeight - maxWeight)") } else{ print ("you can drive! ") } // ДАЛЕЕ БУДУТ ЛЕНИВЫЕ СВОЙСТВА (это такое свой ство которые не инициализируется пока к нему не обратятся, имеет ключевое слово LAZY) func bigDataProcessingFunc() -> String { return "very long process" } class Processing { let smallDataProcessing = "small data processing" let averageDataProcessing = "average data processing" lazy var bigDataProcessing = bigDataProcessingFunc() } let process = Processing() process.bigDataProcessing process // ДАЛЕЕ БУДУТ НАБЛЮДАТЕЛИ СВОЙСТВА (они наблюдают за измениниями значения свойств) class SecretLabEmploye { var accessLevel = 0 { // здесь открыыает тело нашего свойства willSet(newValue) { // это будет установленно print ("new boss is about to come") print ("new access level is \(newValue)") } didSet{ // это было установленно if accessLevel > 0 { accessToBB = true } else { accessToBB = false } print ("new boss just come") print ("last time a had access level \(oldValue)") } } var accessToBB = false } let employee = SecretLabEmploye() employee.accessLevel employee.accessToBB // далее меняем значения employee.accessLevel = 1 employee.accessToBB // ДАЛЕЕ БУДУТ АЛИАСЫ ТИПОВ (ПСЕВДОНИМЫ ТИПОВ) typealias Meter = Int let leight: Meter = 50 let lenght1 = 20 let sum: Meter = leight + lenght1 print("suma") // еще одни пример typealias DoubleInterg = (Int, Int) let somuConstant = (1, 2) // это мы записали КОРТЕЖ // следующий пример (как заменить тип словаря) typealias DictionatyType = [String: Int] var dictionary: DictionatyType = [:] dictionary["Appartment 123"] = 123 dictionary // ДАЛЕЕ БУДУТ ПЕРЕЧИСЛЕНИЯ или ЭНУМЫ (ЭНУМЫ(типы первого класса в свифт) - обьединяют в себе привязанные значения и привязывают им один общий тип) // далее будет пример из игры где персонажу можно двигаться только в оределенные стороны enum Movement {// энум всегда пищется с большой буквы case forward // case - это основная состовная часть энума case backward case left case right } let movemetDirection: Movement = Movement.backward // далее будет пример энума с двумя кейсами и одним вычесляемый свойством enum Divice { case ipad(color: String), iphone var year: Int { switch self{ case .iphone: return 2007 case .ipad(let color) where color == "black" : return 2020 // цвет айпада долден быть черный и если он черный то мы возвращаем 2020 case .ipad: return 2010 } } } let yaerOfProduction = Divice.ipad(color: "black").year // в энумы мы можем вкладывать другие энумы (вложенные энумы ) enum Character{ enum Weapon: Int { // вложенный энум case sword = 4 case wand = 1 var damage: Int { return rawValue * 10 } } enum CharacterType{ case knight case mage } } let charWeapor = Character.Weapon.sword.damage // узнеем урон от конретного оружия // далее будут ИНДЕЕКТЫЕ энумы indirect enum Lunch { case salad case soup case meal (Lunch, Lunch) // в один кейс помещаем другой } let MyLanch = Lunch.meal(.salad, .soup) <file_sep>/LessonsSwiftBook 1-42/LessonsSwiftBook 32-39.playground/Contents.swift import UIKit // ДАЛЕЕ БУДЕТ ARC ( это механизм который позволяет освобождать память ) - пропустил 32 и 33 / нихуя не понял, пока мне рано это понимать/// // ДАЛЕЕ БУДЕТ 34. Опциональные цепочки class Person { let job: Job? = Job() let workers: [Worker]? = [Worker()] // знак ? - означает опциональность } class Worker { let name = "Petya" func work(){ print("I do some job") } } class Job { let salary: Salary? = Salary() } class Salary { let salary = 100000 func showSalary() -> String { return "\(salary)" } } let person = Person() // 1 варинат if let job = person.job { if let salary = job.salary{ salary.salary } } if let job = person.job , let salary = job.salary{ // 2 варинат ТОЖЕ САМОЕ что и первый но короче salary.salary } // 3 варинат как раз он называется ОПЦИОНАЛЬНОЙ ЦЕПОЧКОЙ !!! let salary = person.job?.salary?.showSalary() // мы можем узнать какая у человека зарплата только если у него его раболта и зарплата //далее попробуем создать массив и поместить туда работников var workersArray = person.workers workersArray?.append(Worker()) workersArray // ДАЛЕЕ БУДЕТ 35. Обработка ошибок и отложенные действия(ERROR HANDLING) enum PossibleErrors: Error { case notInStock case notEnoughtMoney } struct Book{ let price: Int var count: Int } class Library { var deposit = 11 var libraryBooks = ["Book1": Book (price: 10, count: 1), "Book2": Book (price: 11, count: 0), "Book3": Book(price: 12, count: 3 )] // так выглядит почленный инициализатор func getTheBook (withName: String) throws { guard var book = libraryBooks[withName] else { throw PossibleErrors.notInStock } guard book.count > 0 else { throw PossibleErrors.notInStock } guard book.price <= deposit else { throw PossibleErrors.notEnoughtMoney } deposit -= book.price book.count -= 1 libraryBooks[withName] = book print ("You got the Book \(withName)") } } let library = Library() try? library.getTheBook(withName: "Book1") // знак вопроса это опциональный варинат, тут меняем номер книги и тогда понимаем хватает ли нам деенг на книгу или нет library.deposit // проверяем остаток library.libraryBooks // показывает остаток, так как выше выбрана Book1, то и остаток/count 0 do { try library.getTheBook(withName: "Book1") } catch PossibleErrors.notInStock { print ("Book is not in Stock") } catch PossibleErrors.notEnoughtMoney { print ("Not enough money") } // далее будет будет альтернативная запись для опцилнально try? (пример выше) func doConection() throws -> Int { return 10 } let x = try? doConection() // альтернативный вариант записи выше let y:Int? do { y = try doConection() } catch { y = nil } // далее будет пример с отложенными действиями var attempt = 0 func whateverFunc (param: Int) -> Int { defer { // defer - это отложенные действуя и они выполянеются в самую последнюю очередь в независимости от того в каком месте(начало, середина) они вставленны. Но если их несколько то они выполняются с низу в верх , в нашемпримере от 10 к 2 attempt += 2 } defer { attempt *= 10 } switch param { case 0: return 100 case 1: return 200 default:return 400 } } whateverFunc(param: 1) attempt // ДУЛЕЕ БУДУТ 36. Сабскрипты (этодругими словами ИНДЕКС ) let array = [1,2,3,4] // пример использования в массиве array[1] // пример испорлзования в СТРУТУРАХ struct WorckPlace { var workPlace: [String] subscript(index:Int) -> String? {// subscript - ключевое слово при создании Сабскрипта get{ switch index { case 0..<workPlace.count: return workPlace[index] default: return nil } } set{ switch index { case 0..<workPlace.count: return workPlace[index] = newValue ?? "" default: break } } } } // далее содаем экземпляр нашей струтуры var work = WorckPlace(workPlace: ["char", "armchar", "lamp"]) work.workPlace[1] work[1] // ДАЛЕЕ БУДУТ 37. Расширения/ Extensions ( расширения спользуятля для того чтобы можно было расщить существующий функционал уже существующего типа) extension Int { // расширения не могут иметь свойства хранения и ленивые свойства, однако вычесляемые свой свойства и методы они используют var isEven: Bool { return self % 2 == 0 ? true : false // это оператор остатка от деления } } let f = 11 f.isEven // ДАЛЕЕ БУДУТ 38. Протоколы (это минимальный набор требований которые предьявляются к классу,структуре или перечислению) protocol Driver { var car: Bool {get} var license: Bool {get} func toDrive() -> Bool } class FirmDriver: Driver { let license = true let car = true func toDrive() -> Bool { return true } } let firmDriver = FirmDriver() firmDriver.license // далее будут 39. Универсальные шаблоны / generics (суть/ вместо этого типа может быть другой) class A { } let arrayN = [1, 2, 3, 4] let arrayStr = ["one", "two", "three"] let arrayCls = [A(), A(), A()] let arr = Array <Int> () //func ParamValue (param: Int) -> String { //функция которая принимает какоето значение в тип ИНТЕЖЕР и потом возвращает его в виде строки // return "\(param)" //} //____ далее будет аналогичная той что выше функция, только она будет принимать строку и возвращать тоже строку //func paramValue (param: String) -> String { // return param //} // обе ФУНКЦИИ выше абсолютно одинаковые но у них разные ТИПЫ входных параметров STRING / Int //paramValue(param: "string") // далее будет одна ФУНКЦИЯ в которую можно помещать различные типы параметров func paramValue <T>(param:T) -> String { // это как раз и есть ФУНКЦИЯ универсального типа !!! return "\(param)" } paramValue(param: 5 ) paramValue(param: "C'mon" ) paramValue(param: true ) // далее мы создадим структуру которая будет иметь сраду ДВА универсальных ТИПА struct HelpFulFunctions <T, U> { func paramValue(param:T, param2: U) -> String { return "\(param), \(param2)" } } let example = HelpFulFunctions < String, Int> () example.paramValue(param: "String1", param2: 5) // далее будет еще один пример, напишем фунция которая меняет местами значеия двух входных параметров var a = "b" var b = "a" func swappy<T> (a: inout T, b: inout T) { let temp = a a = b b = tepm } swap(&a, &b) a b // ДАЛЕЕ БУДЕТ 40. Обновление Swift 4 // проверка номер 2 гита <file_sep>/LessonsSwiftBook 1-42/LessonsSwiftBook 11-19.playground/Contents.swift import UIKit var str = "Hello, playground" // ДАЛЕЕ БУДЕТ ЦИКЛ FOR IN (это самый часто используемый цикл) //----------------- for i in 1...5 { print(i) } //----------------- //let array = [1, 2, 3, 4] // добавяем к простому цыклу массивы let arrayOfStrings = ["a", "b", "c"] for index in arrayOfStrings { print(index) } // далее пойдет следующий пример // далее будет показано как рабоатет цикл с более сложными элиментами let nameAndFingers = ["Ivan": 20, "Svetlana":18, "Nadejda": 15] for (name, numberOfFingers) in nameAndFingers { print("Pyro name is \(name) and number or fingers \(numberOfFingers)") // таким образом мы можем перебирать словари } // далее будет пример с перебором массива (нужно найти индекс элимента который делится на 2) for (index, value) in arrayOfStrings.enumerated() { print(index, value) } // для того чтобы массив преебирал через 2 элимента for i in stride(from: 0, through: 15, by: 5) { print(i) } // ДАЛЕЕ БУДУТ ЦЫКЛЫ while, repeat-write // while - значение ПОКА , пока выполняется условие - выполянется тело цыкла/ и цыкл выполянется пока уловие верно var timer = 5 print("Couting down") while timer > 0 { print(timer) timer -= 1 // до какого условия выполянется цикл } print("Start") // далее будет пример этого цикла с repeat-while //var timer = 5 //print("Couting down") // //repeat { // цикл выполянется без проверки условия // print(timer) // timer -= 1 // до какого условия выполянется цикл //} while timer > 0 //print("Start") // ДАЛЕЕ БУДУТ ФУНКЦИИ !!!! (это обособленные куски кода у которых есть свое имя ) // 1. простая функция, ничего не принимающая и ничего не возвращающая func sayHello () { print("Hello") } sayHello() // таким образом вызывается функция // 2. функция, принимающая один параметр func oneParam(param: Int) { var param = param param += 1 } oneParam(param: 11) // 3. функция, не принимающая параметров(аргументов), но возвращающая значние func returnValue() -> Int { return 10 } returnValue() let a = returnValue() // пример присваемого значения, в данном слуаче для А a //_______________________________________________________________________________________________ // 4. функция, принимающая несколько параметров и возвращающая значение (САМЫЙ ЧАСТО ИСПОЛЬЗУЕМЫЙ ТИП ФУНКЦИЙ) func giveMeYourName(name:String, andSecondName:String) -> String { // функиця принимает 2 строки и возвращает 1 return "Your fill name is \(name) \(andSecondName)" } giveMeYourName(name: "Sergey", andSecondName: "Kutsenko") //_______________________________________________________________________________________________ // 5. функция, принимающая массив в качестве параметра и использующая вложенную функцию для работы func calcMoneyIn(array: [Int]) -> Int { var sum = 0 func sayMoney() { print(sum) } // функция внутри функции "ВЛОЖЕННАЯ ФУНКЦИЯ" for item in array { sum += item } sayMoney() return sum } calcMoneyIn(array: [1, 2, 3, 4, 5]) // 6. функция, которая принимает переменное число параметров / функция которая имеет вариативные параметры внутри себя func findSum(ofIntegers integers: Int...) -> Int { // найти сумму целочисленых значений var sum = 0 for item in integers { // почему есть два имени ofIntegers и integers ? - есть два имени внутреннее и внешее, внутреннее integers используется внути самой функции вкачестве вариативного параметра а ofIntegers испольщуется при чтении самой функции sum += item } return sum } findSum(ofIntegers: 2, 4, 6) // 7. имена параметров функции // пример func sum(_:Int) -> Int { return 10 } // 8. функция в качестве возвращаемого значения (посчитаем сколько раз я сомневался в принятии какого решения) func whatToDo (missed: Bool) -> (Int) -> Int { func missCountUP(input: Int) -> Int { return input + 1} func missCountDown(input: Int) -> Int { return input + 1} return missed ? missCountUP : missCountDown } var missedCount = 0 missedCount = whatToDo(missed: true) (missedCount) missedCount = whatToDo(missed: false) (missedCount) // ДАЛЕЕ БУДУТ ЗАМЫКАНИЯ ИЛИ КЛОУЖЕРЫ (это тежи функции но у них не бывает имен, т.е. это ОБОСОБЛЕННЫЙ кусок кода но без своего имени, могут называться ЛЯМБДАМИ или БЛОКАМИ) // далее будет пример использования: func repeatThreeTimes (closure: ()->() ) { // наш тип CLOSURE ничего не принимает и ничего не возвращает for _ in 0...2 { // _ это нижнее подчеркивание, его применяют когда не хотят давать имя closure() } } repeatThreeTimes { () -> () in print("Hello World") } // далее будет более сложный пример let unsortedArray = [123, 2, 32, 67, 8797, 432] let sortedArray = unsortedArray.sorted { (nuber1: Int , nuber2: Int) -> Bool in return nuber1 > nuber2 // массив сортируется по убыванию } // ДАЛЕЕ БУДУТ КОРТЕЖИ let one = 1 let two = 2 let three = 3 (one, two, three) // создали кортеж //далее будет следующий пример let boy = (5, "Sergey") // в одну константу поставили 2 значения boy.1 // далее будет следующий пример (присвоим нескольким константам несколько значений) let (first, second, third) = (1, 2, 3) first second third // следующий случай кортежа let greenPencil = (color: "green", lenght: 20, weight: 4) // тут мы все присваиваем все в greenPencil let (greenPencilColor, greenPencilLenght, greenPencilWeight) = greenPencil // а тут мы уже все присвоили уже в greenPencil greenPencil.weight greenPencil.color greenPencil.lenght // далее будет еще один пример let agesAndNames = ["Misha":29, "Kostya":90, "Mira":30] var age = 0 var name = "" for (nameInD, ageInD) in agesAndNames { if age < ageInD { age = ageInD name = nameInD } } age name // ДАЛЕЕ БУДУТ ОПЦИОНАЛЫ (ОДНА ИЗ ГЛАВНЫХ ОСОБЕННОСТЕЙ ЯЗЫКА swift- это такие переменные котоыре могут иметь значение равное NILL (NILL - это полное отсутствие какого значения)) var fuel : Int? fuel = 20 //fuel = nil // print("\(fuel!) liters left") // без восклицательного знака будет писаться слово OPTIONAL if let availableFuel = fuel { // это опциональная привязка, она позволяет извлечь значение print("\(availableFuel) liters left") } else { print ("no fuel data available") } func checkFuel() { guard let availableFuel = fuel else { print ("no fuel data available") return } print("\(availableFuel) liters left") } checkFuel() // ДАЛЕЕ БУДУТ КЛАССЫ //class Human { // var name = "Ivan" // var age: Int? = 30 // var Hairs = true // // func description() -> String { // это медот // // if let humanAge = age { // return "Hello! My name is \(name) and I'am \(age) years old" // } else { // return "Hello! My name is \(name)" //} // } //} // //let humanOne = Human() //humanOne.name = "Natasha" //humanOne.name //humanOne.description() // //let humanTwo = Human() //humanTwo.Hairs = false //humanTwo.name = "Jack" //humanTwo // //// создаем массив из Human's // //var array = [Human]() //array.append(humanOne) //array.append(humanTwo) // ДАЛЕЕ БУДУТ ИНИЦИАЛИЗАТОРЫ КЛАССОВ_____ (это процесс осздания экземляра ) init - обозначение инициализаторов class Human { var name : String var age: Int? // без занчение 30 или иного , его значение по умолчанию будет nill - т/е/ полное отсутствие значений var hairs : Bool func description() -> String { // это медот if let humanAge = age { return "Hello! My name is \(name) and I'am \(age) years old" } else { return "Hello! My name is \(name)" } } init (){ // это инициализатор name = "Ivan" hairs = true } init (name: String, age:Int?, hairs: Bool){ // далее будет еще один нициализатор self.name = name // self значит определет что вы обращаетесь к свойству self.age = age self.hairs = hairs } } let human = Human() human.age human.name let human1 = Human(name: "Jason", age: 40, hairs: true) // новый пример инициализаторв <file_sep>/LessonsSwiftBook 1-42/README.md # SWIFT test git <file_sep>/LessonsSwiftBook 1-42/LessonsSwiftBook 1-11.playground/Contents.swift import UIKit // Character, String, Int, Double, Float, Boll let x: Character = "q" let y: String = "Russian Federation" let z: Double = 1.00005 // более точный, записывает только 15 знаков после запятой let w: Float = 1.0000064 // менее точный, записывет только 6 знаков после запятой let d: Int = 123 let u: Bool = true // false let r = false let f = Int(123.123) let v = Float(123.12312312312312334325) // ниже идет пример с ИНТЕРПОЛЯЦИЕЙ СТРОКИ let temperature = 12 let windSpees = 5 let weatheDescription = "Temperature is about 12 'C above zero and wind speed is about 5 m/s" let weatheDescriptionI = "Temperature is about \(temperature) 'C above zero and wind speed is about \(windSpees) m/s" // ИНТЕРПОЛЯЦИЯ код \(temperature) помогает брать значение из констанкты let string = "\(1+2)" + "\(2+3)" // далее пойдут массивы let arrayOne = Array<Int>() // 1 варинат написания массива let arrayTwo = [Int]() // 2 вариант написания масива var arrayThree : [Int] = [] // 3 вариант написния массива - самая частая форма записи массива let arrayFour = [1, 2, 3, 4] // 4 форма записи массива let arrayFive = [Int](repeating: 10, count: 6) // 5 форма записи массива, но уже не пустого // далее пойдут основные действия с массивам и // 1 - сложение массивов arrayThree += arrayFive arrayThree arrayFour[2] // показ одного из элиментов массива arrayThree[1...3] = [15] arrayThree arrayThree.count // count - показывает количество элиментов в массиве arrayThree.count - 1 // указывается количство итераций, 0 1 2 3 // далее будет добавление элиментов в массив arrayThree.append(100) // по умолчанию элимент добавляется конец массива arrayThree.insert(105, at: 2) // если мы ходит поместить элимент не конец массива то ипользуется этот метод // для того чтобы удалить элименты можно ипользовать несколько вариантов arrayThree.remove(at: 4) // удаляем элимент по конкретному индексу arrayThree arrayThree.removeFirst() // удаление первого элимента arrayThree arrayThree.removeLast() // удаление последнего элимента arrayThree // далее будет следущий тип колекций, называется СЛОВАРЬ // ниже возможные формы записи словаря let dictOne = Dictionary<String, String>() let dictTwo = [String: String]() let dictThree: [String: String] = [:] var namesAges = ["Ivan" : 30, // пример словаря со значениями и ключами "Vitalik": 30, "Sasha" : 25] namesAges.count namesAges.isEmpty namesAges["Ivan"] = 35 namesAges let dalatesAge = namesAges.updateValue(40, forKey: "Ivan") namesAges namesAges["Ivan"] = nil // уаление значения namesAges let deletedValue = namesAges.removeValue(forKey: "Sasha") //если нужно использовать удаленное значение namesAges namesAges.removeAll() // удаляет весь словарь namesAges namesAges = [:] // обнуление словаря // ДАЛЕЕ БУДУТ МНОЖЕСТВА- их называют SETS // ниже идут варианты написания/создания МНОЖЕСТВА let setOne = Set<String>() let setTwo: Set<String> = [] var setThree: Set = [1, 2, 3, 4] setThree.insert(5) setThree.insert(6) setThree.insert(7) setThree.isEmpty // показывает пустой ли сет или нет setThree.count setThree.remove(6) setThree setThree.contains(1) // показввает есть ли такой элииент в сете или нет let boolValue = setThree.contains(1) // создает новую константу, может потом ее использовать где ниудь еще boolValue //далее будут методы котоыре позволяют работать сетам с сетами let setFromOneToThree: Set = [1, 2, 3, 4] let setFromFourToNine: Set = [1, 2, 4, 5, 6, 7, 8, 9] let allValueArray = setFromOneToThree.union(setFromFourToNine).sorted() // создаем массив из двух сетов. let commonValueSet = setFromOneToThree.intersection(setFromFourToNine) // определяем какие значения пересекаются, коммпанда intersection как раз для этого let notRepeatedValueArray = setFromOneToThree.symmetricDifference(setFromFourToNine).sorted() // symmetricDifference - метод позволяет показать различие между двух сетов let substractedValuesArray = setFromOneToThree.subtracting(setFromFourToNine).sorted() // создаем массив который будет содержать в себе элименты 1 массива но только те которые не повторяются во втором сете // далее будет инструкции if let a = 3 let b = 1 if a == b{ // == это оператор сравнения print ("a equals to b") } else if a < b { // else значит или / "в противномслучае" выполянем "вот это" print ("b exceeds a by \(b - a)") // b превосходит А на столько то } else if b < a { print ("a exceeds b by \(a - b)") } // далее следуюший пример let isSunny = true // если сегодня солнечно то я пойду погулять? т/е выполню какоето действие var action = "" if isSunny { action = "I will go for a walk" } else { action = "I will sit at home" } action = isSunny ? "I will go for a walk" : "I will sit at home" // это называется ТЕРНАРНЫЙ оператор, по сути это тоже самое что написанно на верху с if // далее будут примеры других операторов / примеров // if a != b если a не равно b // if a <= b если а меньше или равно b // if a >= b если а больше или равно b // if a > b // if a < b // ~= этот опертаор показывает принадлежит ли число к определенному диапазону, далее будет конкретный пример: if 1...4 ~= b { print ("Hello World!") } // далее будут СОСТАВНЫЕ УСЛОВИЯ if a == b { } let c = 5 if (c == 2 && a == 10) || c == 5 { // если у нас С равно 2 и А равно 10 то выполянется условие PRINT , или С равно 5 то опять же выполняется это условие т/е PRINT print ("Hello coder!") } else { print ("!!!") // если меняешь значение С то выводится это !!! } // ДАЛЕЕ БУДЕТ НОВАЯ ИНСТРУКЦИЯ GUARD (условная инструкция на на подобие if ) func someFunc (a: Int, b: Int) { guard a == b else { return } // в отличие от IF, guard всегда имеет условие else guard b == 11 else { return } } // func это функция // далее будет пример работы с циклами и guard for i in 1...5 { guard i != 3 else {continue} // прервать работу цыкла можно и опертаором break. вместо continue print (i) } // ниже идет тоже самое что и выше но с IF for i in 1...5 { if i == 3 {break} print (i) } // ДАЛЕЕ БУДЕТ ИНСТРУКЦИЯ SWITCH // эта инструкция для условий сразными значениями, напримере ниже их 3, ИСПОЛЬЗУЕТСЯ IF let totalScore = 100 if totalScore == 10 { print("You're not jedi") } else if totalScore == 20 { print ("you're still not jedi") } else if totalScore == 100 { print("YOU'RE JEDI") } // далее будет написанно все тоже самое что и выше но с инструкцией SWITCH switch totalScore { case 10: print("You're not jedi") case 20: print ("you're still not jedi") case 50..<100: print("YOU'RE almost JEDI") case 100: print("YOU'RE almost JEDI") default: // без этого кейса switch будет проверять все значения например -1 , - 2 и тд , а так он проверят в рамках установленного диапозона и если все проходит то выдает занчение. Программа выполянется с верху в низ. break } <file_sep>/LESSONS swiftme.ru/Part 1 Basics.playground/Contents.swift import UIKit var print = "hello" print <file_sep>/LESSONS swiftme.ru/PetNomber1/PetNomber1/PetNomber1App.swift // // PetNomber1App.swift // PetNomber1 // // Created by <NAME> on 08.08.2020. // import SwiftUI @main struct PetNomber1App: App { var body: some Scene { WindowGroup { ContentView() } } } struct PetNomber1App_Previews: PreviewProvider { static var previews: some View { /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/ } } <file_sep>/LessonsSwiftBook 1-42/class 2020.playground/Contents.swift import UIKit class Human { var name = "Sergey" var age : Int? = 34 // опциональное значение var hairs = true func description () -> String { return " Hello! My name is \(name) and I'am \(age) years old ! " } } let humanOne = Human () humanOne.age humanOne.name = "Nikolay" humanOne.description() humanOne.name
db45ba35bdb0bc47cf407ce790d6d95573dcfa81
[ "Swift", "Markdown" ]
10
Swift
SergeyKucenko/SWIFT
798fad5f2dadcdf96f50539c47179c75d92ee9cf
38070138268a6ec689a314ee82b6a2beae02bca0
refs/heads/master
<repo_name>Weefle/WildSkript-Deobfuscator<file_sep>/deobfuscate.rb require 'zip/zip' if ARGV.empty? puts "USAGE: #{File.basename(__FILE__)} [FILE] [POWER]" exit 130 else filename = ARGV[0] power = ARGV[1].to_f end def unzip_file (file, destination) Zip::ZipFile.open(file) { |zip_file| zip_file.each { |f| f_path=File.join(destination, f.name) FileUtils.mkdir_p(File.dirname(f_path)) zip_file.extract(f, f_path) unless File.exist?(f_path) } } end puts "Unpacking '#{filename}'" begin unzip_file(filename, "temp") rescue puts "Failed to unpack the file. Check if the file exists and if u have write permissions to the working directory." exit end def deobfuscate(power, warnings) skript = "" last5chars = " " errors = 0 charN = 0 power -= 1 file = File.new("temp/tmp.ws", "r") while (line = file.gets) line.split("-").each do | char | number = char.to_f/power charN += 1 number = number.to_i begin skript = "#{skript}#{number.to_i.chr}" last5chars = last5chars[1..5] + number.to_i.chr rescue puts "[#{charN}] Failed to decrypt: '#{char}' '#{number}' '#{last5chars}'" if warnings errors += 1 end end end file.close return skript, errors end if power != 0 puts "Deobfuscating '#{filename}' with power #{power.to_i}" skript, errors = deobfuscate(power, true) else puts "Power not set, attempting to brute-force '#{filename}'\n\n" found = false power = 1 while found == false power += 1 skript, errors = deobfuscate(power, false) print "\r " if (skript.include? "\n") && (skript.include? " ") && (skript.include? ":\n") && (errors == 0) && (skript.include? "\non") found = true print "\rTrying power #{power.to_i} -> correct (#{errors} Errors)" puts "" puts "Deobfuscating #{filename} with power #{power.to_i}" skript, errors = deobfuscate(power, true) else print "\rTrying power #{power.to_i} -> wrong (#{errors} Errors)" end end end FileUtils.remove_dir("temp") open("#{filename}_unpacked.sk", 'w') { |f| f.puts "#{skript}" } puts "" puts "Output saved as '#{filename}_unpacked.sk'"<file_sep>/README.md # WildSkript-Deobfuscator Tool to deobfuscate Wildskript encrypted scripts with support for bruteforcing the power. ### Preview ![Preview](http://i.imgur.com/vry0Luv.gif) ### How it works: First, this tool unpacks the packed file which is actually a `.zip` containing a file named `tmp.ws`. That file contains every character code multiplied with the power separated by a `-`, so it just divides each character code by the power and converts it back into a character. ### Download: Windows: [deobfuscate.exe](https://raw.githubusercontent.com/sapphyrus/WildSkript-Deobfuscator/master/deobfuscate.exe) All OS (Requires a ruby installation): [deobfuscate.rb](https://raw.githubusercontent.com/sapphyrus/WildSkript-Deobfuscator/master/deobfuscate.rb) (Right click -> Save as) ### Usage: ```sh $ deobfuscate.exe [FILENAME] [POWER] ``` ex. ```sh $ deobfuscate.exe NoCombatHacks.txt 70 ``` To bruteforce the power use ```sh $ deobfuscate.exe [FILE] ```
c57b6ac80f409bc4009ccff84f82d1f03527c277
[ "Markdown", "Ruby" ]
2
Ruby
Weefle/WildSkript-Deobfuscator
3b1aefbd6626ec2dac2850cd656b2ff40a115b28
7f627d35d00770e9e280bde43d56e514718db3ae
refs/heads/master
<repo_name>limpingstone/pylora_gps<file_sep>/calc_prediction.py #!/usr/bin/python3 import math from datetime import datetime class Prediction: def __init__(self, local_data, received_data): self.is_realtime = False self.local_data = local_data self.received_data = received_data self.distance = None self.calc_realtime() self.calc_distance() def calc_realtime(self): time_format = "%H:%M:%S.%f" local_time = str(self.local_data.hour ) + ":" \ + str(self.local_data.minute ) + ":" \ + str(self.local_data.second ) + "." \ + str(self.local_data.msec ) + "000" received_time = str(self.received_data.hour ) + ":" \ + str(self.received_data.minute) + ":" \ + str(self.received_data.second) + "." \ + str(self.received_data.msec ) + "000" time_diff = datetime.strptime(local_time, time_format) \ - datetime.strptime(received_time, time_format) if (abs(time_diff.total_seconds()) < 0.4): self.is_realtime = True def calc_distance(self): local_lat = self.local_data.lat_deg + self.local_data.lat_min / 60 local_long = self.local_data.long_deg + self.local_data.long_min / 60 received_lat = self.received_data.lat_deg + self.received_data.lat_min / 60 received_long = self.received_data.long_deg + self.received_data.long_min / 60 local_lat_rad = local_lat * math.pi / 180 local_long_rad = local_long * math.pi / 180 received_lat_rad = received_lat * math.pi / 180 received_long_rad = received_long * math.pi / 180 dlat = received_lat_rad - local_lat_rad dlong = received_long_rad - local_long_rad rad_km = pow(math.sin(dlat / 2), 2) + math.cos(local_lat) * math.cos(received_lat) * pow(math.sin(dlong / 2), 2); self.distance = 6371000 * 2 * math.asin(math.sqrt(rad_km)) <file_sep>/README.md # pylora_gps Python scripts that program the LoRa radio module to coordinate with the GPS module for decentralized vehicle communication. This script builds on top of the pySX127x as a submodule for communication between the LoRa radio nodes. <file_sep>/main.py #!/usr/bin/python3 from MTK33X9 import MTK33X9 from MTK33X9 import MTK33X9_data from lora import LoRa from calc_prediction import Prediction import RPi.GPIO as GPIO import lora_parse import time import sys # define dev_path and dev_name in config.py import config def print_gps_info(current_data): print("%02d:%02d:%02d.%03d UTC" % ( current_data.hour, current_data.minute, current_data.second, current_data.msec ) ) print("%3d deg %.4f' %c" % ( current_data.lat_deg, current_data.lat_min, current_data.lat_pos ) ) print("%3d deg %.4f' %c" % ( current_data.long_deg, current_data.long_min, current_data.long_pos ) ) print("%.2f km/h" % current_data.speed) def lora_send_data(lora, current_data): buff = ">>>>%s:%02d%02d%02d.%03d,%2d%.4f,%c,%03d%.4f,%c,%.2f>" % ( config.dev_name, current_data.hour, current_data.minute, current_data.second, current_data.msec, current_data.lat_deg, current_data.lat_min, current_data.lat_pos, current_data.long_deg, current_data.long_min, current_data.long_pos, current_data.speed ) # Construct packet sent print("Tx sending: " + buff) len_padding = 256 - len(buff) buff = buff.ljust(len_padding, ' ') lora.write_fifo(lora_parse.str_to_byte(buff), 0) lora.transmit() def lora_receive_data(lora): if (not lora.listen()): raise TimeoutError() return None else: buff = lora.read_fifo() #print("Rx received: " + lora_parse.byte_to_str(buff)[1:80]) buff = lora_parse.byte_to_str(buff[1:80]) return lora_parse.str_to_data(buff) def main(): mtk33x9 = MTK33X9() mtk33x9.ser_init(config.dev_path) lora = LoRa() rx_data = MTK33X9_data() try: while (True): current_data = mtk33x9.get_current_data() if (current_data.is_complete()): lora_send_data(lora, current_data) #print('Sent GPS information...') print('Sent GPS information: ') print_gps_info(current_data) time.sleep(0.1) try: incoming_data = lora_receive_data(lora) if (incoming_data.is_complete()): rx_data = incoming_data #print('Received GPS information...') print('Received GPS information: ') print_gps_info(rx_data) except TimeoutError: print('Timeout reached!') except IndexError: print('Current data received not valid!') time.sleep(0.1) if (current_data.is_complete() and rx_data.is_complete()): print('-------------------------------') current_prediction = Prediction(current_data, rx_data) print("Real time data: " + str(current_prediction.is_realtime)) if (current_prediction.is_realtime): print('Distance: ' + str(current_prediction.distance) + ' m') print('===============================================') print() except KeyboardInterrupt: mtk33x9.ser_stop() GPIO.cleanup() if __name__ == "__main__": main() <file_sep>/MTK33X9.py import serial import threading class MTK33X9_data: def __init__(self): self.debug_mode = False self.hour = None self.minute = None self.second = None self.msec = None self.lat_pos = None self.lat_deg = None self.lat_min = None self.long_pos = None self.long_deg = None self.long_min = None self.speed = None def parse_time(self, time_str): if (len(time_str) != 10): raise ValueError('Invalid time string!') self.hour = int(time_str[0:2]) self.minute = int(time_str[2:4]) self.second = int(time_str[4:6]) self.msec = int(time_str[7:10]) if (self.debug_mode): print("%02d:%02d:%02d.%03d UTC" % (self.hour, self.minute, self.second, self.msec)) def parse_latitude(self, lat_str, lat_pos): if (len(lat_str) != 9): raise ValueError('Invalid latitude string!') elif (lat_pos != 'N' and lat_pos != 'S'): raise ValueError('Invalid latitude orientation!') self.lat_pos = lat_pos self.lat_deg = int (lat_str[0:2]) self.lat_min = float(lat_str[2:9]) if (self.debug_mode): print("%3d deg %.4f' %c" % (self.lat_deg, self.lat_min, self.lat_pos)) def parse_longitude(self, long_str, long_pos): if (len(long_str) != 10): raise ValueError('Invalid longitude string!') elif (long_pos != 'E' and long_pos != 'W'): raise ValueError('Invalid longitude orientation!') self.long_pos = long_pos self.long_deg = int (long_str[0:3]) self.long_min = float(long_str[3:10]) if (self.debug_mode): print("%3d deg %.4f' %c" % (self.long_deg, self.long_min, self.long_pos)) def parse_speed_km(self, speed_str, speed_unit): #if (len(speed_str) != 5): # raise ValueError('Invalid speed string!') if (speed_unit != 'K'): raise ValueError('Invalid speed unit!') self.speed = float(speed_str) if (self.debug_mode): print("%.2f km/h" % self.speed) def is_complete(self): return ((self.hour is not None) and (self.minute is not None) and (self.second is not None) and (self.msec is not None) and (self.lat_pos is not None) and (self.lat_deg is not None) and (self.lat_min is not None) and (self.long_pos is not None) and (self.long_deg is not None) and (self.long_min is not None) and (self.speed is not None)) class MTK33X9_thread(threading.Thread): def __init__(self, dev_path): threading.Thread.__init__(self) self.dev_path = dev_path self.current_data = MTK33X9_data() def ser_init(self): print('Starting serial at 9600 baud...') self.ser = serial.Serial( port = self.dev_path, \ baudrate = 9600) print('Updating serial configuration to 115200 baud...') self.ser.write(b'$PMTK251,115200*1F\r\n') # Reinitialize serial at 115200 baud self.ser.close() self.ser = serial.Serial( port = self.dev_path, \ baudrate = 115200) print('Updating NMEA frequency and fix CTL to 5 Hz...') self.ser.write(b'$PMTK220,200*2C\r\n') self.ser.write(b'$PMTK300,200,0,0,0,0*2F\r\n') def ser_stop(self): if (self.ser.isOpen()): print('\nClosing serial connection...') self.ser.close() def run(self): current_data = MTK33X9_data() while (self.kbd_interrupt == False): line = self.ser.readline() try: line_pos = line.decode('ASCII').split(',') if (line_pos[0] == '$GPGGA' or line_pos[0] == '$GNGGA'): current_data.parse_time (line_pos[1]) current_data.parse_latitude (line_pos[2], line_pos[3][0]) current_data.parse_longitude(line_pos[4], line_pos[5][0]) elif (line_pos[0] == '$GPVTG' or line_pos[0] == '$GNVTG'): current_data.parse_speed_km(line_pos[7], line_pos[8]) if (current_data.is_complete()): self.current_data = current_data except UnicodeDecodeError: print('Skipped line!') except ValueError: print('Skipped line!') except IndexError: print('No incoming GPS data!') def get_current_data(self): return self.current_data class MTK33X9: def ser_init(self, dev_path): # Initialize parameters self.thread = MTK33X9_thread(dev_path) self.thread.daemon = True # While loop flag for keyboard interrupt self.thread.kbd_interrupt = False # Open serial connection and start polling self.thread.ser_init() self.thread.start() def ser_stop(self): # Signal while loop to stop self.thread.kbd_interrupt = True # Stop polling and close serial connection self.thread.join() self.thread.ser_stop() print('Exited!') def get_current_data(self): return self.thread.get_current_data() <file_sep>/lora_reg.py PACKET_SIZE = 255 WRITE_MASK =0x80 REG_FIFO = 0x00 REG_OP_MODE = 0x01 MODE_LORA = 0x80 MODE_SLEEP = 0x0 MODE_STDBY = 0x1 MODE_FSTX = 0x2 MODE_TX = 0x3 MODE_FSRX = 0x4 MODE_RXCON = 0x5 MODE_CAD = 0x7 REG_FR_MSB = 0x6 REG_FR_MID = 0x7 REG_FR_LSB = 0x8 REG_PA_CONFIG = 0x9 REG_PA_RAMP = 0xA REG_OCP = 0xB REG_LNA = 0xC REG_FIFO_ADDR_PTR = 0xD REG_FIFO_TX_BASE_ADDR = 0xE REG_FIFO_RX_BASE_ADDR = 0xF REG_FIFO_RX_CUR_ADDR = 0x10 REG_IRQFLAGS = 0x12 MASK_IRQFLAGS_RXTIMEOUT = 0b10000000 MASK_IRQFLAGS_RXDONE = 0b01000000 MASK_IRQFLAGS_PAYLOADCRCERROR = 0b00100000 MASK_IRQFLAGS_VALIDHEADER = 0b00010000 MASK_IRQFLAGS_TXDONE = 0b00001000 MASK_IRQFLAGS_CADDONE = 0b00000100 MASK_IRQFLAGS_FHSSCHANGECHANNEL = 0b00000010 MASK_IRQFLAGS_CADDETECTED = 0b00000001 REG_MODEMSTAT = 0x18 MASK_MODEMSTAT_CLEAR = 0b00010000 MASK_MODEMSTAT_VALIDHEADER = 0b00001000 MASK_MODEMSTAT_RXONGOING = 0b00000100 MASK_MODEMSTAT_SYNCHRYONIZED = 0b00000010 MASK_MODEMSTAT_DETECTED = 0b00000001 REG_MODEM_CONFIG_1 = 0x1D REG_MODEM_CONFIG_2 = 0x1E REG_SYMB_TIMEOUT = 0x1F REG_PREAMBLE_MSB = 0x20 REG_PREAMBLE_LSB = 0x21 REG_PAYLOAD_LENGTH = 0x22 REG_MAX_PAYLOAD_LENGTH = 0x23 REG_HOP_PERIOD = 0x24 REG_RSSI_WIDEBAND = 0x2C REG_DETECT_OPTIMIZE = 0x31 REG_DETECTION_THRESHOLD = 0x37 REG_DIO_MAPPING_1 = 0x40 REG_DIO_MAPPING_2 = 0x41 REG_PA_DAC = 0x4D FXOSC = 32000000 #define FREQ_TO_REG(in_freq) ((uint32_t)(( ((uint64_t)in_freq) << 19) / FXOSC)) def freq_to_reg(in_freq): return (in_freq << 19) // FXOSC #define REG_TO_FREQ(in_reg) ((uint32_t)((FXOSC*in_reg) >> 19)) def reg_to_freq(in_reg): return (FXOSC * in_reg) >> 19 DEFAULT_MODEM_CONFIG = [ # Configure PA_BOOST with max power (REG_PA_CONFIG, 0x8f), # Enable overload current protection with max trim (REG_OCP, 0x3f), # Set RegPaDac to 0x87 (requried for SF=6) (REG_PA_DAC, 0x87), # Set the FIFO RX/TX pointers to 0 (REG_FIFO_TX_BASE_ADDR, 0x00), (REG_FIFO_RX_BASE_ADDR, 0x00), # Set RegModemConfig1 as follows: # Bw = 0b1001 (500kHz) # CodingRate = 0b001 (4/5) # ImplicitHeader = 1 (REG_MODEM_CONFIG_1, 0x93), # Set RegModemConfig2 as follows: # SpreadingFactor = 6 # TxContinuousMode = 0 # RxPayloadCrcOn = 1 (REG_MODEM_CONFIG_2, 0x64), # Set preamble length to 8 (REG_PREAMBLE_MSB, 0x00), (REG_PREAMBLE_LSB, 0x08), # Set payload length and max length to 255 #(REG_PAYLOAD_LENGTH, 0x0f), #(REG_MAX_PAYLOAD_LENGTH, 0x0f), # Disable frequency hopping (REG_HOP_PERIOD, 0x00), # Set DetectionThreshold to 0xC (for SF = 6) (REG_DETECTION_THRESHOLD, 0x0c), # Set DetectionOptimize to 0x5 (for SF = 6) (REG_DETECT_OPTIMIZE, 0x05), # Set the frequency to 915MHz # We can use FREQ_TO_REG() here because it is declared as `constexpr` # and can therefore be evaluated at compile-time (REG_FR_MSB, (freq_to_reg(920000000) >> 16) & 0b11111111), (REG_FR_MID, (freq_to_reg(920000000) >> 8) & 0b11111111), (REG_FR_LSB, freq_to_reg(920000000) & 0b11111111), ] <file_sep>/gps_serial.py import serial print('Starting serial at 9600 baud...') ser = serial.Serial( port='/dev/serial0', \ baudrate=9600) print('Updating serial configuration to 115200 baud...') ser.write(b'$PMTK251,115200*1F\r\n') ser.close() ser = serial.Serial( port='/dev/serial0', \ baudrate=115200) print('Updating NMEA frequency and fix CTL to 5 Hz...') ser.write(b'$PMTK220,200*2C\r\n') ser.write(b'$PMTK300,200,0,0,0,0*2F\r\n') def parse_time(time_str): if len(time_str) != 10: raise ValueError('Invalid time string!') hour = int(time_str[0:2]) minute = int(time_str[2:4]) second = int(time_str[4:6]) msec = int(time_str[7:10]) print("%02d:%02d:%02d.%03d UTC" % (hour, minute, second, msec)) def parse_latitude(lat_str, lat_pos): if len(lat_str) != 9: raise ValueError('Invalid latitude string!') elif lat_pos != 'N' and lat_pos != 'S': raise ValueError('Invalid latitude orientation!') lat_deg = int (lat_str[0:2]) lat_min = float(lat_str[2:9]) print("%3d deg %.4f' %c" % (lat_deg, lat_min, lat_pos)) def parse_longitude(long_str, long_pos): if len(long_str) != 10: raise ValueError('Invalid longitude string!') elif long_pos != 'E' and long_pos != 'W': raise ValueError('Invalid longitude orientation!') long_deg = int (long_str[0:3]) long_min = float(long_str[3:10]) print("%3d deg %.4f' %c" % (long_deg, long_min, long_pos)) def parse_speed_km(speed_str, speed_unit): #if len(speed_str) != 5: # raise ValueError('Invalid speed string!') if speed_unit != 'K': raise ValueError('Invalid speed unit!') print("%.2f km/h" % float(speed_str)) try: while True: line = ser.readline() # Need to catch UnicodeDecodeError line_pos = line.decode('ASCII').split(',') if line_pos[0] == '$GPGGA': parse_time (line_pos[1]) parse_latitude (line_pos[2], line_pos[3][0]) parse_longitude(line_pos[4], line_pos[5][0]) elif line_pos[0] == '$GPVTG': parse_speed_km(line_pos[7], line_pos[8]) except KeyboardInterrupt: print('\nClosing serial connection...') ser.close() print('Exited!') <file_sep>/lora.py import time import RPi.GPIO as GPIO import spidev import lora_reg as regs import threading # define timeout in config.py import config class LoRa: DIO0 = 4 RST = 22 CS = 0 def __init__(self): GPIO.setmode(GPIO.BCM) GPIO.setup (LoRa.DIO0, GPIO.IN) GPIO.setup (LoRa.RST, GPIO.OUT) GPIO.output(LoRa.RST, 0) time.sleep(0.01) GPIO.output(LoRa.RST, 1) self.spi = spidev.SpiDev() self.spi.open(0, LoRa.CS) self.spi.max_speed_hz = 5000000 self.irq_seen = False self.irq_data = None self.irq_cv = threading.Condition() self.timeout = config.timeout GPIO.add_event_detect(LoRa.DIO0, GPIO.RISING, callback=self.isr) self.write_reg(regs.REG_OP_MODE, regs.MODE_LORA | regs.MODE_SLEEP) val = self.read_reg(regs.REG_OP_MODE) if (val != regs.MODE_LORA or val != regs.MODE_LORA): raise Exception('Failed to load LoRa in sleep mode!') self.write_reg(regs.REG_PAYLOAD_LENGTH, regs.PACKET_SIZE) val = self.read_reg(regs.REG_PAYLOAD_LENGTH) if (val != regs.PACKET_SIZE): raise Exception('Failed to set payload size!') self.write_reg(regs.REG_MAX_PAYLOAD_LENGTH, regs.PACKET_SIZE) val = self.read_reg(regs.REG_MAX_PAYLOAD_LENGTH) if (val != regs.PACKET_SIZE): raise Exception('Failed to set payload size!') for pair in regs.DEFAULT_MODEM_CONFIG: self.write_reg(pair[0], pair[1]) val = self.read_reg(pair[0]) if (val != pair[1]): raise Exception('Failed to write to register!') def isr(self, channel): # Read irq_data register self.irq_data = self.read_reg(regs.REG_IRQFLAGS) # Clear IRQ flag. Needs to be done twice for some reason (hw errata?) self.write_reg(regs.REG_IRQFLAGS, 0xFF) self.write_reg(regs.REG_IRQFLAGS, 0xFF) self.irq_seen = True with self.irq_cv: self.irq_cv.notify() def write_reg(self, reg, val): self.spi.xfer([reg | regs.WRITE_MASK, val]) def read_reg(self, reg): return self.spi.xfer([reg, 0])[1] def listen(self): self.write_reg(regs.REG_DIO_MAPPING_1, 0x00) self.write_reg(regs.REG_OP_MODE, regs.MODE_LORA | regs.MODE_RXCON) while (self.irq_seen == False): with self.irq_cv: if (self.irq_cv.wait(timeout = self.timeout) == False): return False self.irq_seen = False return True def transmit(self): self.write_reg(regs.REG_DIO_MAPPING_1, 0x40) self.write_reg(regs.REG_OP_MODE, regs.MODE_LORA | regs.MODE_TX) while (self.irq_seen == False): with self.irq_cv: if (self.irq_cv.wait(timeout = self.timeout) == False): return False self.irq_seen = False return self.irq_data == regs.MASK_IRQFLAGS_TXDONE def write_fifo(self, buf, offset): self.write_reg(regs.REG_FIFO_ADDR_PTR, offset) self.spi.xfer([regs.REG_FIFO | regs.WRITE_MASK] + buf) def read_fifo(self): offset = self.read_reg(regs.REG_FIFO_RX_CUR_ADDR) self.write_reg(regs.REG_FIFO_ADDR_PTR, offset) return self.spi.xfer([regs.REG_FIFO] + [0 for _ in range(255)])[1:] <file_sep>/lora_parse.py #!/usr/bin/python3 from MTK33X9 import MTK33X9_data def str_to_byte(input_str): byte_str = [] for char in list(input_str): byte_str.append(ord(char)) return byte_str def byte_to_str(input_byte): output_str = "" for byte in input_byte: output_str += chr(byte) return output_str def str_to_data(rx_str): rx_data = MTK33X9_data() # Remove extra '>' padding rx_str_arr = rx_str.split('>') # Detect for garbled data if len(rx_str_arr) < 3: return rx_data rx_str = rx_str_arr[len(rx_str_arr) - 2] # Extract device name from received string rx_str_arr = rx_str.split(':') device_info = rx_str_arr[0] print("Device name: " + device_info) # Extract received GPS data rx_str = rx_str_arr[1] rx_str_arr = rx_str.split(',') rx_data.parse_time (rx_str_arr[0]) rx_data.parse_latitude (rx_str_arr[1], rx_str_arr[2]) rx_data.parse_longitude(rx_str_arr[3], rx_str_arr[4]) rx_data.parse_speed_km (rx_str_arr[5], 'K') return rx_data
9681ca567fa8ad4ac1e3ceb8015f2578c1f05472
[ "Markdown", "Python" ]
8
Python
limpingstone/pylora_gps
d34b74f563cec48998f7d2d16127a4d66a7dffb9
f8b89e94268756dc2c56dc15e526e021ae5fff05
refs/heads/master
<repo_name>EpicBlueCircles/td<file_sep>/theFull.py import sys import socket import math from decimal import * getcontext().prec = 4 serverip = raw_input("Ip:") serverport = 7778 #serverip = "10.10.20.241" class timers(object): def __init__(self): self.time = 0 self.iocheck = 0 self.iointerval = 300 timer = timers() class yetCreep(object): def __init__(self, coord, time, type): self.type = input[2] self.coord = input[0] self.time = input[1] def buildNew(self): return CreepEnm(self.type, self.coord) def cuttofour(number): number = str(number) leng = len(number) if leng > 4: print "Packet too long. Cutting " + str(int(number)-int(number[:4])) + " digits" number = number[:4] if leng < 4: rand = 4-leng #print "splicing " + str(rand) + " leading zeros" for i in range(rand): number = "0"+number return number class player(object): def __init__(self, clientsocket, address): #fancy connection stuff self.s = clientsocket self.ip = address[0] self.port = address[1] self.connected = True def myreceive(self): #Recieve quantity of words chunks = [] bytes_recd = 0 while bytes_recd < 4 and self.connected: chunk = self.s.recv(min(4 - bytes_recd, 2048)) if chunk == '': self.connected = False chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) if self.connected: MSGLEN = int(''.join(chunks)) #recieve the words chunks = [] bytes_recd = 0 while bytes_recd < MSGLEN and self.connected: chunk = self.s.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == '': self.connected = False chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) return ''.join(chunks) def sendinfo(self, typewords): #send size of packet try: msg = cuttofour(len(typewords)) totalsent = 0 while totalsent < 4: sent = self.s.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") break totalsent = totalsent + sent #send packet totalsent = 0 while totalsent < int(msg): sent = self.s.send(typewords[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") break totalsent = totalsent + sent except socket.error: self.connected = False def getwords(input, quant): retreving = True words = [] while retreving: word = "" getting = True for i in input: if i == " " and getting: words.append(word) word = "" if len(words)+1 >= quant: getting = False else: word = word+i words.append(word) if len(words) == quant: return words retreving = False else: print "Missing "+str(quant-len(words))+" values" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) isHost = raw_input("Are you the host?") if "y" in isHost: isHost = True print "Setting up as Host, waiting for client" #become a server socket s.bind((socket.gethostname(), serverport)) s.listen(5) (clientsocket, address) = s.accept() thisplayer = player(clientsocket, address) else: isHost = False print "Setting up as Client." s.connect((serverip, serverport)) thisplayer = player(s, [serverip, serverport]) print "waiting for host machine" print thisplayer.myreceive() friendcreeps = [] enmcreeps = [] yetcreeps = [] while True: timer.time += 1 timer.iocheck += 1 if timer.iocheck >= timer.iointerval: timer.iocheck, outgoing, outnumber = 0, "", 0 #Set tosend as list of strings: "50 40 normal", coord, time delay, type for i in tosend: outgoing += " " + str(i) outnumber += 3 if isHost: thisplayer.sendinfo(outnumber + outgoing) recieved = thisplayer.myreceive() else: recieved = thisplayer.myreceive() thisplayer.sendinfo(outgoing) tosend, recieved = [], getwords(recieved, 2) #assuming recieved is list, not who won theinfo = getwords(recieved[1], 3*int(recieved[0])) rand = [] for i in range(len(theinfo)): rand.append[theinfo[i]] if (i+1)%3 == 0: yetcreeps.append(yetCreep(rand)) rand = [] <file_sep>/td.py import random import pygame import pyganim import time import sys import socket import math from decimal import * getcontext().prec = 4 clock = pygame.time.Clock() serverport = 7778 def cuttofour(number): number = str(number) leng = len(number) if leng > 4: print "Packet too long. Cutting " + str(int(number)-int(number[:4])) + " digits" number = number[:4] if leng < 4: rand = 4-leng #print "splicing " + str(rand) + " leading zeros" for i in range(rand): number = "0"+number return number class player(object): def __init__(self, clientsocket, address): #fancy connection stuff self.s = clientsocket self.ip = address[0] self.port = address[1] self.connected = True def myreceive(self): #Recieve quantity of words chunks = [] bytes_recd = 0 while bytes_recd < 4 and self.connected: chunk = self.s.recv(min(4 - bytes_recd, 2048)) if chunk == '': self.connected = False chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) if self.connected: MSGLEN = int(''.join(chunks)) #recieve the words chunks = [] bytes_recd = 0 while bytes_recd < MSGLEN and self.connected: chunk = self.s.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == '': self.connected = False chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) return ''.join(chunks) def sendinfo(self, typewords): #send size of packet try: msg = cuttofour(len(typewords)) totalsent = 0 while totalsent < 4: sent = self.s.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") break totalsent = totalsent + sent #send packet totalsent = 0 while totalsent < int(msg): sent = self.s.send(typewords[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") break totalsent = totalsent + sent except socket.error: self.connected = False def getwords(input, quant): retreving = True words = [] while retreving: word = "" getting = True for i in input: if i == " " and getting: words.append(word) word = "" if len(words)+1 >= quant: getting = False else: word = word+i words.append(word) if len(words) == quant: return words retreving = False else: print "Missing "+str(quant-len(words))+" values" return words retreving = False s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) isHost = raw_input("Are you the host?") if "y" in isHost: isHost = True print "Setting up as Host, waiting for client" #become a server socket s.bind((socket.gethostname(), serverport)) s.listen(5) (clientsocket, address) = s.accept() thisplayer = player(clientsocket, address) thisplayer.sendinfo("Connected") else: isHost = False print "Setting up as Client." serverip = raw_input("Ip:") serverip = "192.168.1.35" s.connect((serverip, serverport)) thisplayer = player(s, [serverip, serverport]) print "waiting for host machine" print thisplayer.myreceive() pygame.mixer.pre_init(22050, -16, 3, 8) pygame.mixer.init() BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0,0,255) GREY = (100,100,100) pygame.init() size = (1250, 700) gScreen = pygame.display.set_mode(size) font = pygame.font.SysFont('Calibri', 15, True, False) text = font.render("hi",True,BLACK) pygame.display.set_caption("TD: THE MOST EPIC TD GAME EVER!") done = False def bubble_sort(items): """ Implementation of bubble sort """ for i in range(len(items)): for j in range(len(items)-1-i): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] return items class SpreetSheet(object): def __init__(self, img, row, colm): self.img = img self.row = row self.colm = colm self.animation = pyganim.PygAnimation(list(zip(pyganim.getImagesFromSpriteSheet(self.img, rows = self.row, cols = self.colm, rects = []),[200] * self.row * self.colm))) self.animation.play() def image_at(self, rectangle): rect = pygame.Rect(rectangle) image = pygame.Surface(rect.size).convert() image.blit(self.sheet, (0, 0), rect) return image def hitDetect(p1, p2, p3, p4): if p2[0] > p3[0] and p1[0] < p4[0] and p2[1] > p3[1] and p1[1] < p4[1]: return True def convertVel(input): radians = math.radians(input) x_vel = math.cos(radians) y_vel = -math.sin(radians) velocity = (x_vel, y_vel) return velocity def pointAt(source, point): deltax = source[0] - point[0] deltay = source[1] - point[1] angle = 0 #upper left if deltax > 0 and deltay > 0: angle = 270 - math.atan((math.fabs(deltay))/(math.fabs(deltax))) + 90 #lower left if deltax > 0 and deltay < 0: angle = 270 - math.atan(deltay/math.fabs(deltax)) + 90 #upper right if deltax < 0 and deltay > 0: angle = math.atan(deltay/math.fabs(deltax)) #lower right if deltax < 0 and deltay < 0: angle = math.atan(deltay/math.fabs(deltax)) return math.degrees(angle) class CreepEnm(object): def __init__(self, type, y): self.type = type self.cord = [0, y] self.tower = "" self.img = img if self.type == "normal": self.hp = 50 self.spd = 2 self.money = 25 if self.type == "tower": self.hp = 50 self.spd = 1 self.money = 50 class CreepFrd(object): def __init__(self, img): self.tower = "" self.spd = 0 self.size = (5, 100) self.center = (self.size[0] / 2, self.size[1] / 2) self.cord = [size[0] / 2, size[1] / 2] self.vel = [0,0] self.img = img self.baseimg = img self.angle = 0 def update(self, mouse_pos): #self.cord[0] += self.vel[0] * self.spd #self.cord[1] += self.vel[1] * self.spd self.angle += 1 self.img = pygame.transform.rotate(self.baseimg, pointAt(self.cord,mouse_pos)) def sendOver(): string = str(self.tower.name) + " " + timer.iocheck + " " + str(self.cord[1]) def buildNew(self): newCreep = CreepFrd(pygame.image.load(self.img)) newCreep.baseimg = newCreep.img return newCreep testCreep = CreepFrd("Assets/images/creep.png") testCreep = testCreep.buildNew() class timers(object): def __init__(self): self.time = 0 self.iocheck = 0 self.iointerval = 300 timer = timers() class yetCreep(object): def __init__(self, coord, time, type): self.type = input[2] self.coord = input[0] self.time = input[1] def buildNew(self): return CreepEnm(self.type, self.coord) class Tower(object): def __init__(self, name, type, hp, damage, cost, img): self.name = name self.type.type self.hp = hp self.damage = damage self.cost = cost self.pos = pos self.img = img def buildNew(self): newTower = Tower(self.name, self.hp, self.damage, self.cost, pygame.image.load(self.img)) return newTower friendcreeps = [] enmcreeps = [] yetcreeps = [] tosend = [] while not done: timer.time += 1 timer.iocheck += 1 if timer.iocheck >= timer.iointerval: timer.iocheck, outgoing, outnumber = 0, "", 0 #Set tosend as list of strings: "50 40 normal", coord, time delay, type for i in tosend: outgoing += " " + str(i) outnumber += 3 outgoing = str(outnumber) + outgoing print "Outgoing: ", outgoing if isHost: thisplayer.sendinfo(outgoing) recieved = thisplayer.myreceive() else: recieved = thisplayer.myreceive() thisplayer.sendinfo(outgoing) print recieved tosend, recieved = [], getwords(recieved, 2) #assuming recieved is list, not who won try: theinfo = getwords(recieved[1], 3*int(recieved[0])) rand = [] for i in range(len(theinfo)): rand.append[theinfo[i]] if (i+1)%3 == 0: yetcreeps.append(yetCreep(rand)) rand = [] except IndexError: if recieved[0] == "0": print "Nothing happens" else: print recieved[0] for i in yetcreeps: if timer.iocheck >= i.time: yetcreeps.remove(i) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: mouse_down = True elif event.type == pygame.MOUSEBUTTONUP: mouse_down = False mouse_pos = pygame.mouse.get_pos() testCreep.update(mouse_pos) gScreen.fill(WHITE) gScreen.blit(testCreep.img, [testCreep.cord[0], testCreep.cord[1]]) pygame.display.flip() clock.tick(60)
498d9c39bbb3fe4bf4c2f83ddff0a6247292ad83
[ "Python" ]
2
Python
EpicBlueCircles/td
effaaa3296d28837159f8cc1d1b4cceec8a8cee0
c482a199c398f4c5c25afff06a9eaf3e956265a2
refs/heads/master
<file_sep>import { TMithrilEvent } from './TMithrilEvent' export interface IAttributes { id?: string class?: string style?: string | {[_: string]: any} type?: string title?: string disabled?: boolean value?: any placeholder?: string role?: string onclick?: (e: TMithrilEvent<MouseEvent>) => any oninput?: (e: TMithrilEvent<KeyboardEvent>) => any onkeydown?: (e: TMithrilEvent<KeyboardEvent>) => any onfocus?: (e: TMithrilEvent<FocusEvent>) => any }<file_sep>import { booksServerSearchByTitle, handleXhrError } from '../server/BooksServer' import { data } from './data' import debounce from 'lodash/debounce' export function abortSearch() { if (data.search.xhr) { data.search.xhr.abort() data.search.xhr = undefined } } export function search() { abortSearch() data.search.response = undefined data.search.messages = [] if (data.search.query.length < 3) return booksServerSearchByTitle(data.search.query, data.search.page, xhr => data.search.xhr = xhr) .then(results => { data.search.response = results }) .catch(e => { handleXhrError(data.search.xhr, data.search.messages, e) }) .then(() => { data.search.xhr = undefined }) }<file_sep>import * as m from 'mithril' import { IHeaderCompAttrs } from './comp/HeaderComp' declare global { module JSX { interface Element extends m.Vnode<any, any> { } interface IntrinsicElements { [s: string]: any } interface ElementAttributesProperty { __jsx_attrs: any } } }<file_sep>const path = require('path') const webpack = require('webpack') const { CheckerPlugin } = require('awesome-typescript-loader') const HtmlWebpackPlugin = require('html-webpack-plugin') const ExtractTextPlugin = require('extract-text-webpack-plugin') const CleanWebpackPlugin = require('clean-webpack-plugin') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const extractLess = new ExtractTextPlugin({ filename: '[name].[contenthash].css', }) module.exports = { entry: { main: './src/ts/src/main.tsx', }, output: { path: path.resolve('./build'), filename: '[name].[chunkhash].js', }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, module: { rules: [ { test: /\.tsx?$/, loader: 'awesome-typescript-loader', options: { useBabel: true, }, }, { test: /\.(woff|woff2|eot|ttf|otf)$|glyphicons-halflings-regular.svg$/, loader: 'file-loader', options: { name: '[name].[hash].[ext]', }, }, { test: /\.less$/i, use: extractLess.extract(['css-loader', 'less-loader']), }, ] }, plugins: [ // new BundleAnalyzerPlugin(), new CleanWebpackPlugin(['build']), new CheckerPlugin(), new HtmlWebpackPlugin({ template: './src/hbs/index.hbs', }), extractLess, new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { // this assumes your vendor imports exist in the node_modules directory return module.context && module.context.indexOf('node_modules') !== -1 } }), // CommonChunksPlugin will now extract all the common modules from vendor and main bundles new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', // But since there are no more common modules between them we end up with just the runtime code included in the manifest file }), new webpack.optimize.UglifyJsPlugin(), ], }<file_sep>import * as m from 'mithril' import { ResponseSearchVolumes } from '../data/ResponseSearchVolumes' import { Volume } from '../data/Volume' import { bind } from 'illa/FunctionUtil' import { get } from '../util/MithrilUtil' const BOOKS_API_KEY = '<KEY>' export type ISaveXhr = (xhr: XMLHttpRequest) => any | undefined export function booksServerSearchByTitle(query: string, page: number, saveXhr: ISaveXhr) { return m.request<ResponseSearchVolumes>({ url: `https://www.googleapis.com/books/v1/volumes`, data: { q: `intitle:${query}`, startIndex: (page - 1) * 10, maxResults: 10, key: BOOKS_API_KEY, }, config: bind(config, null, saveXhr), }) } export function booksServerGetVolume(volumeId: string, projection: 'full' | 'lite', saveXhr: ISaveXhr) { return m.request<Volume>({ url: `https://www.googleapis.com/books/v1/volumes/${encodeURIComponent(volumeId)}`, data: { projection, key: BOOKS_API_KEY, }, config: bind(config, null, saveXhr), }) } export function handleXhrError(xhr: XMLHttpRequest, messages: string[], e: any) { messages.push(`Error while loading data: ${get(() => xhr.status)} ${get(() => xhr.statusText)} – ${e}. Check your connection and try again.`) console.error(e) } function config(saveXhr: ISaveXhr, xhr: XMLHttpRequest) { // XDomainRequest requires HTTPS to make a connection to a HTTPS site. // Google Books requires HTTPS, so commenting this out for now. // if (window.XDomainRequest) { // xhr = new XDomainRequest() // } if (saveXhr) { saveXhr(xhr) } return xhr }<file_sep>import { CartItemData } from './CartItemData' export class CartData { constructor( public items: CartItemData[] = [], ) { } }<file_sep>import { CartItemData } from './CartItemData' import { Volume } from './Volume' import { data } from './data' import { get } from '../util/MithrilUtil' const CART_KEY = 'cart-items' export function addToCart(volume: Volume) { if (getCartCount(volume.id)) { data.cart.items.filter(item => item.volumeId == volume.id)[0].quantity++ } else { data.cart.items.push(new CartItemData( volume.id, 1, volume, undefined, [], )) } persistCart() } export function removeFromCart(volumeId: string) { for (let index = data.cart.items.length - 1; index >= 0; index--) { let item = data.cart.items[index] if (item.volumeId == volumeId) { if (item.quantity > 1) { item.quantity-- } else { data.cart.items.splice(index, 1) } break } } persistCart() } export function getCartCount(volumeId: string) { return ( data.cart.items .filter(item => item.volumeId == volumeId) .map(item => item.quantity) .reduce((sum, quantity) => sum + quantity, 0) ) } export function getCartItemQuantitiesSum() { return ( data.cart.items .map(item => item.quantity) .reduce((sum, quantity) => sum + quantity, 0) ) } export function getCartCurrencyCode() { let currencyCode: string for (let item of data.cart.items) { let aCurrencyCode = get(() => item.volume.saleInfo.retailPrice.currencyCode) if (aCurrencyCode) { if (currencyCode && aCurrencyCode != currencyCode) { return undefined } else { currencyCode = aCurrencyCode } } } return currencyCode } export function getCartValueSum() { return ( data.cart.items .filter(item => !!get(() => item.volume.saleInfo.retailPrice)) .map(item => item.volume.saleInfo.retailPrice.amount * item.quantity) .reduce((sum, amount) => sum + amount, 0) ) } export function persistCart() { let itemsToPersist = data.cart.items.map(item => new CartItemData( item.volumeId, item.quantity, undefined, undefined, undefined, )) try { if (itemsToPersist.length) { localStorage.setItem(CART_KEY, JSON.stringify(itemsToPersist)) } else { localStorage.removeItem(CART_KEY) } } catch (e) { console.error(e) } } export function restoreCart() { if (!data.cart.items.length) { try { let items: CartItemData[] = JSON.parse(localStorage.getItem(CART_KEY)) if (get(() => items.length)) { data.cart.items = items } } catch (e) { console.error(e) } } }<file_sep>const webpack = require('webpack') let config = require('./webpack.config.js') config.plugins = config.plugins.filter(plugin => !(plugin instanceof webpack.optimize.UglifyJsPlugin)) module.exports = config<file_sep>import { CartData } from './CartData' import { SearchData } from './SearchData' import { VolumeDetailsData } from './VolumeDetailsData' export const data = { search: new SearchData(), volumeDetails: new VolumeDetailsData(), noHashCheck: false, cart: new CartData(), }<file_sep>import { Volume } from './Volume' export class ResponseSearchVolumes { constructor( public kind: 'books#volumes', public items: Volume[], public totalItems: number, ) { } }<file_sep>import { Volume } from './Volume' export class VolumeDetailsData { constructor( public volumeId?: string, public volume?: Volume, public xhr?: XMLHttpRequest, public messages: string[] = [], ) { } }<file_sep>export type TMithrilEvent<T> = T & { redraw?: boolean }<file_sep>import { escapeRegExp } from 'illa/StringUtil' import { get } from './MithrilUtil' let numberSuffixRe = new RegExp(escapeRegExp(formatNumber(1).slice(1)) + '$') export function formatNumber(amount: number) { let result = get(() => amount.toLocaleString(getLocale()), () => amount + '') if (numberSuffixRe) { result = result.replace(numberSuffixRe, '') } return result } export function formatPrice(amount: number, currency: string) { return get(() => amount.toLocaleString(getLocale(), { style: 'currency', currency, currencyDisplay: 'symbol' }), () => amount + '') } function getLocale() { return (navigator.language || (navigator as any).userLanguage || (navigator as any).browserLanguage || (navigator as any).systemLanguage) + '' }<file_sep>import * as m from 'mithril' // Ugly hack to work around https://github.com/MithrilJS/mithril.js/issues/1734 function getHashPath() { return location.hash.replace(/^#!/, '') } let popstatePath: string window.addEventListener('popstate', () => { // This event should trigger before hashchange, but IE11 fails to trigger it // on back button click. We save the hash path to confirm that it happened. popstatePath = getHashPath() }, false) let hashchangeTimeoutRef: number window.addEventListener('hashchange', () => { // This event triggers after popstate, and is more reliable in IE11. // We cancel timeout in the rare case that another hash change happened in // the time frame when doing a double check. clearTimeout(hashchangeTimeoutRef) let hashPath = getHashPath() if (popstatePath != hashPath) { // The popstate event never happened. This should be IE11. We need to // force it. console.info('Fixing Mithril path.', m.route.get(), popstatePath, hashPath) m.route.set(hashPath, undefined, { replace: true, // To let the browser navigate back }) } else { // The popstate event triggered, and we should be good, except... console.info('Mithril path is correct.', m.route.get(), popstatePath, hashPath) } // Despite all our efforts, Mithril does not recognize the popstate event // occasionally. Need to double check it all went fine. And what's more, if // it goes fine, it will happen in the future – hence the timeout. // To reproduce in IE11, click cart then book then back then a different // book then cart. hashchangeTimeoutRef = setTimeout(() => { hashPath = getHashPath() if (m.route.get() != hashPath) { // Mithril failed to recognize the new path, so we need to force // it. console.info('Double fixing Mithril path.') m.route.set(hashPath, undefined, { replace: true, // To let the browser navigate back }) } }, 100) }, false)<file_sep> export class Volume { constructor( public kind: 'books#volume', public id: string, public etag: string, public selfLink: string, public volumeInfo: { title: string subtitle: string authors: string[] publisher: string publishedDate: string description: string imageLinks: { smallThumbnail: string thumbnail: string small: string medium: string large: string extraLarge: string } }, public saleInfo: { retailPrice: { amount: number currencyCode: string } }, public searchInfo: { textSnippet: string }, ) { } }<file_sep>interface Window { XDomainRequest: typeof XMLHttpRequest } declare var XDomainRequest: typeof XMLHttpRequest<file_sep>import { booksServerGetVolume, handleXhrError } from '../server/BooksServer' import { data } from './data' export function abortVolumeDetailsRequest() { if (data.volumeDetails.xhr) { data.volumeDetails.xhr.abort() data.volumeDetails.xhr = undefined } } export function requestVolumeDetails() { abortVolumeDetailsRequest() data.volumeDetails.volume = undefined data.volumeDetails.messages = [] booksServerGetVolume(data.volumeDetails.volumeId, 'full', xhr => data.volumeDetails.xhr = xhr) .then(volume => { data.volumeDetails.volume = volume }) .catch(e => { handleXhrError(data.volumeDetails.xhr, data.volumeDetails.messages, e) }) .then(() => { data.volumeDetails.xhr = undefined }) }<file_sep>import { Volume } from './Volume' export class CartItemData { constructor( public volumeId: string, public quantity: number, public volume: Volume, public xhr: XMLHttpRequest, public messages: string[], ) {} }<file_sep>import { ResponseSearchVolumes } from './ResponseSearchVolumes' export class SearchData { constructor( public query = '', public page = 1, public xhr?: XMLHttpRequest, public response?: ResponseSearchVolumes, public messages: string[] = [], ) { } }<file_sep>import * as m from 'mithril' import { isArray, isUndefinedOrNull } from 'illa/Type' import assign from 'lodash/assign' import { isFunction } from 'illa/Type' export function get<T>(fn: T | (() => T), ...rest: (T | (() => T))[]): T { if (isFunction(fn)) { try { return fn() } catch (e) { return rest.length ? get.apply(null, rest) : undefined } } else { return fn } } export function nope(): never { throw 'nope' } export function classes(...a: any[]): string { return a.filter(item => !isUndefinedOrNull(item) && item !== false).map(item => isArray(item) ? classes(item) : item).join(` `) } export function extendAttrs(attrs2: { [_: string]: any }, attrs: { [_: string]: any }, keepUnderscores?: boolean) { let result: { [_: string]: any } = {} if (keepUnderscores) { assign(result, attrs2) } else { for (let key of Object.keys(attrs2)) { if (key[0] != '_') { result[key] = (attrs2 as any)[key] } } } result = assign(result, attrs) if (attrs2.class && attrs.class) result.class = `${attrs.class} ${attrs2.class}` return result }
c8ba93c7f0a90c8456bc953ebc0037b8ae7494f7
[ "JavaScript", "TypeScript" ]
20
TypeScript
andraaspar/ormm0g
8aea15525d81ed89b4f9db954e6f90925b3d5a66
0d1986c7b32ce1fd2fae34b1bc3349717cfec770
refs/heads/master
<repo_name>BBK-SDP-2015-BM/worksheets<file_sep>/src/com/sdp/helloworld/decoupled/factory/bean.properties renderer.class=com.sdp.helloworld.decoupled.interfaces.StandardOutMessageRenderer provider.class=com.sdp.helloworld.decoupled.interfaces.HelloWorldMessageProvider<file_sep>/src/com/sdp/helloworld/spring/basic/bean.properties renderer.(class)=com.sdp.helloworld.decoupled.interfaces.StandardOutMessageRenderer provider.(class)=com.sdp.helloworld.decoupled.interfaces.HelloWorldMessageProvider<file_sep>/src/com/sdp/helloworld/decoupled/basic/StandardOutMessageRenderer.java package com.sdp.helloworld.decoupled.basic; /** * Created by Basil on 14/01/2016. */ public class StandardOutMessageRenderer { // message private HelloWorldMessageProvider helloWorldMessageProvider = null; // render method public void render() { if (helloWorldMessageProvider == null) throw new RuntimeException(StandardOutMessageRenderer.class.getName() + " message provider not set."); System.out.println(helloWorldMessageProvider.getMessage()); } // setter public void setHelloWorldMessageProvider(HelloWorldMessageProvider helloWorldMessageProvider) { this.helloWorldMessageProvider = helloWorldMessageProvider; } // getter public HelloWorldMessageProvider getHelloWorldMessageProvider() { return helloWorldMessageProvider; } } <file_sep>/src/com/sdp/helloworld/decoupled/interfaces/StandardOutMessageRenderer.java package com.sdp.helloworld.decoupled.interfaces; /** * Created by Basil on 14/01/2016. */ public class StandardOutMessageRenderer implements MessageRenderer { // message private MessageProvider messageProvider = null; // render method @Override public void render() { if (messageProvider == null) throw new RuntimeException(StandardOutMessageRenderer.class.getName() + " message provider not set."); System.out.println(messageProvider.getMessage()); } // setter @Override public void setMessageProvider(MessageProvider provider) { this.messageProvider = provider; } // getter @Override public MessageProvider getMessageProvider() { return this.messageProvider; } } <file_sep>/src/com/sdp/helloworld/spring/xml/annotation/BeanConfig.java package com.sdp.helloworld.spring.xml.annotation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Created by Basil on 17/01/2016. */ @Configuration public class BeanConfig { @Bean public MessageProvider provider() { return new HelloWorldMessageProvider(); } @Bean public MessageRenderer renderer() { return new StandardOutMessageRenderer(); } } <file_sep>/src/com/sdp/helloworld/spring/xml/autowired/StandardOutMessageRenderer.java package com.sdp.helloworld.spring.xml.autowired; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Created by Basil on 15/01/2016. */ @Component("renderer") // This is the same as @Component(value="renderer") public class StandardOutMessageRenderer implements MessageRenderer { @Autowired private MessageProvider messageProvider = null; // render method @Override public void render() { if (messageProvider == null) throw new RuntimeException(StandardOutMessageRenderer.class.getName() + " message provider not set."); System.out.println(messageProvider.getMessage()); } // setter @Override public void setMessageProvider(MessageProvider provider) { this.messageProvider = provider; } // getter @Override public MessageProvider getMessageProvider() { return this.messageProvider; } } <file_sep>/README.md # worksheets SDP Worksheets <file_sep>/src/com/sdp/generics/Driver.java package com.sdp.generics; /** * Created by Basil on 11/01/2016. */ public class Driver { public static void main(String[] args) { Storage<BankAccount> accountStorage = new Storage<>(); Storage<String> stringStorage = new Storage<>(); Class<BankAccount> bankAccountClass = BankAccount.class; try { BankAccount myAccount = (BankAccount) bankAccountClass.newInstance(); accountStorage.setValue(myAccount); myAccount.deposit(15); System.out.println(accountStorage.getValue().showBalance()); if (accountStorage.getClass() == stringStorage.getClass()) { System.out.println("EQUAL"); } else { System.out.println("NOT EQUAL"); } } catch (InstantiationException e) { } catch (IllegalAccessException e) { } } } <file_sep>/src/com/sdp/helloworld/spring/xml/autowired/MessageProvider.java package com.sdp.helloworld.spring.xml.autowired; import org.springframework.stereotype.Component; /** * Created by Basil on 14/01/2016. */ @Component public interface MessageProvider { public String getMessage(); } <file_sep>/src/com/sdp/helloworld/spring/xml/autowired/MessageRenderer.java package com.sdp.helloworld.spring.xml.autowired; import org.springframework.stereotype.Component; /** * Created by Basil on 14/01/2016. */ @Component public interface MessageRenderer { public void render(); public void setMessageProvider(MessageProvider provider); public MessageProvider getMessageProvider(); }
5000d531ef9d95225e90d3d68518f6268da82f8a
[ "Markdown", "Java", "INI" ]
10
INI
BBK-SDP-2015-BM/worksheets
a7262769bdabc50c0267d0497c5b32390c99fefe
b023de0dbf695012404e5a72d123ee22aa7e90b8
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TechOnlineCSAC066 { public partial class WebForm4 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Edit_category0_Click(object sender, EventArgs e) { } protected void add_category_Click(object sender, EventArgs e) { if(Category_Id.Text == "" || Category_Name.Text== "") { Response.Write("Please fill all the fields!!"); } else { try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); string insertQuery = "insert into AddCategory(Category_Id,Category_Name)values (@Category_Id,@Category_Name)"; SqlCommand cmd = new SqlCommand(insertQuery, conn); cmd.Parameters.AddWithValue("@Category_Id", Category_Id.Text); cmd.Parameters.AddWithValue("@Category_Name", Category_Name.Text); cmd.ExecuteNonQuery(); Response.Write("Successfully!!!thank you"); conn.Close(); } catch (Exception ex) { Response.Write("error" + ex.ToString()); } } } protected void edit_category_Click(object sender, EventArgs e) { Response.Redirect("edit_category.aspx"); } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TechOnlineCSAC066 { public partial class WebForm9 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Update_product_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); string updateQuery = "update ADD_product set Category= '" + this.Category.Text + "', Sales_Price = '" + this.Sales_Price.Text + "',Available_Quantity = '" + this.Available_Quantity.Text + "',Product_Name = '" + this.Product_Name.Text + "'where Product_Id='" + this.Product_Id.Text + "'"; SqlDataAdapter SDA = new SqlDataAdapter(updateQuery, conn); SDA.SelectCommand.ExecuteNonQuery(); Response.Write("Update Successfully !!!thank you"); conn.Close(); } catch (Exception ex) { Response.Write("error" + ex.ToString()); } } protected void delete_product_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open();//Add data to the sql database string deleteQuery = "delete from ADD_product where Product_Id='" + this.Product_Id.Text + "';"; SqlDataAdapter SDA = new SqlDataAdapter(deleteQuery, conn); SDA.SelectCommand.ExecuteNonQuery(); Response.Write("Successfully deleted !!!thank you"); conn.Close(); } catch (Exception ex) { Response.Write("error" + ex.ToString()); } } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TechOnlineCSAC066 { public partial class WebForm6 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void delete_category0_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open();//Add data to the sql database string deleteQuery = "delete from AddCategory where Category_Id='" + this.editCategory_Id.Text + "';"; SqlDataAdapter SDA = new SqlDataAdapter(deleteQuery,conn); SDA.SelectCommand.ExecuteNonQuery(); Response.Write("Successfully deleted !!!thank you"); conn.Close(); } catch (Exception ex) { Response.Write("error" + ex.ToString()); } } protected void update_category_Click(object sender, EventArgs e) { try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); string updateQuery = "update AddCategory set Category_Name= '"+ this.editCategory_Name.Text + "'where Category_Id='"+this.editCategory_Id.Text+"'"; SqlDataAdapter SDA = new SqlDataAdapter(updateQuery, conn); SDA.SelectCommand.ExecuteNonQuery(); Response.Write("Update Successfully !!!thank you"); conn.Close(); } catch (Exception ex) { Response.Write("error" + ex.ToString()); } } } }<file_sep># Tech-Online-CSAC-055 Will Project <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TechOnlineCSAC066 { public partial class WebForm5 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Add_product_Click(object sender, EventArgs e) { if (Product_Id.Text == "" || Product_Name.Text == "" || Available_Quantity.Text == "" || Sales_Price.Text == "" || Category.Text == "") { Response.Write("Please fill all the fields!!"); } else { try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); string insertQuery = "insert into ADD_product (Product_Id,Category,Product_Name,Sales_Price,Available_Quantity)values (@Product_Id,@Category,@Product_Name,@Sales_Price,@Available_Quantity)"; SqlCommand cmd = new SqlCommand(insertQuery, conn); cmd.Parameters.AddWithValue("@Category", Category.Text); cmd.Parameters.AddWithValue("@Product_Id", Product_Id.Text); cmd.Parameters.AddWithValue("@Sales_Price", Sales_Price.Text); cmd.Parameters.AddWithValue("@Product_Name", Product_Name.Text); cmd.Parameters.AddWithValue("@Available_Quantity", Available_Quantity.Text); cmd.ExecuteNonQuery(); Response.Write("Successfully!!!thank you"); conn.Close(); } catch (Exception ex) { Response.Write("error" + ex.ToString()); } } } } }
6d11c3f023c05b620d3fb7009121d0a447e58bd3
[ "Markdown", "C#" ]
5
C#
Rbarto23/Tech-Online-CSAC-066
25a845a76e7c01f59ff1445b4ab88f8ff92a4cbb
5174abfff390cc9b93d160a7da8733092c0cab7e
refs/heads/master
<repo_name>RipanHalder/Backtracking-2<file_sep>/Subsets.java /* Thought Process: Had to see professor's video to remember the approach again. Need to solve it in 4 steps. Don't choose, Action, Choose and Bactracking along with Base Condition. We don't allow duplicates, so in Don't Choose we go index+1 Time Complexity - O(2 * pow(N)) -> In normal recursion solution (we copy the arraylist always) it was O(N * 2 * pow(N)) Space Complexity - O(N) -> Recursive height + 1 arraylist */ class Subsets { List<List<Integer>> result = new ArrayList<>(); public List<List<Integer>> subsets(int[] nums) { if(nums == null || nums.length == 0) return result; backtrack(nums, 0, new ArrayList<>()); return result; } private void backtrack(int[] nums, int index, ArrayList<Integer> path){ //Base if(index == nums.length){ result.add(new ArrayList<>(path)); return; } // Don't Choose backtrack(nums, index+1, path); //Action path.add(nums[index]); // Choose backtrack(nums, index+1, path); // Bactracking path.remove(path.size()-1); } }
28df71b0a5eab022aaf9ee2350e8e552b2a4c56a
[ "Java" ]
1
Java
RipanHalder/Backtracking-2
f352a187307f68e187e3d3fd8b6c8db50da4d2b3
97a2c53a020b09e973d2dda0a5b90bdedfa793a9
refs/heads/master
<repo_name>vaporhole/scripts<file_sep>/README.md # scripts Script of VAPORHole <file_sep>/users-vaporhole.sh #!/bin/bash #================HEADER==============================================| # Autor # Jefferson 'Slackjeff' Rocha <<EMAIL>> # # O que este programa faz? # Checagem em /home/ de usuários federados que existem no sistema. #====================================================================| . /etc/profile # PATH for cron #============================== VARS name="Usuários Federados" archive_html='/var/www/htdocs/users.html' link='http://vaporhole.duckdns.org/' #============================== FUNCS _START_HTML() # Inicializando html { hour="$(/bin/date)" cat <<EOF >> "$archive_html" <!DOCTYPE html> <html lang="pt-br"> <head> <title>$name</title> <meta charset="utf-8"> <style> body{background-color: #191919; color: #00ffba; font-size: 1.2em;} a{color: white;} </style> </head> <body> <a href="index.html">Retornar</a> <h1 align=center>Usuários Federados</h1> <h4 align=center>Página atualizada de 1 em 1 minuto, última atualização: $hour</h4> <ul> EOF } _BODY_HTML() # Corpo da página HTML, as listas. { local receive_user="$1" cat <<EOF>> "$archive_html" <li><a href=${link}~${receive_user}>~$receive_user</a></li> EOF } _END_HTML() # Finalizando página html { cat <<EOF>> "$archive_html" </ul> </body> </html> EOF } #============================== INICIO [[ -e "$archive_html" ]] && /bin/rm "$archive_html" _START_HTML # Inicializando página HTML for check_users in /home/*; do if [[ "$check_users" =~ .*ftp ]]; then continue else check_users="${check_users//\/home\//}" # Cut /home/ _BODY_HTML "$check_users" # send user for function fi done _END_HTML # Finalizando página HTML
2c612aa1c282f723e19b5f87834d49371dd66583
[ "Markdown", "Shell" ]
2
Markdown
vaporhole/scripts
1c45e16bae5fc89cda8f2b5fdf1cc745ec8dbdec
ae37ad4109af6d42dba416611fba1ee399d0123e
refs/heads/master
<repo_name>whaleeej/Compiler-FrontEnd<file_sep>/04-TransitionSchema/04-TransitionSchema/TransitionSchema.h #pragma once #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <stack> #include <map> #include <string> #include <unordered_map> #include <map> #include <unordered_set> using namespace std; const int inf = 0x3f3f3f3f; bool isFirstOpt = true; bool isError = false; string prog; istringstream progin; string line; istringstream linein; int line_num = 1; void ctrlFirstOpt() { if (!isFirstOpt) printf("\n"); isFirstOpt = false; } //----------------------------------------------------------------------------------- //----------------------------------Data Structure----------------------------------- enum Symbol { NT, //Non-terminal program, decls, decl, stmt, compoundstmt, stmts, ifstmt, assgstmt, boolexpr, boolop, arithexpr, arithexprprime, multexpr, multexprprime, simpleexpr, T, //Terminal LABRACKET, RABRACKET, E, IF, LCBRACKET, RCBRACKET, THEN, ELSE, ID, ASSIGN, LT, LE, GT, GE, EQ, ADD, MINUS, MULTIPLE, DIVIDE, SEMICOLON, MYINT, INTNUM, MYREAL, REALNUM, //end ENDDING }; enum TS_type { ts_int,ts_real,ts_bool }; union TS_value { int i; float r; bool b; }; class TS_Attr { public: TS_value val; TS_type type; TS_Attr(int i=0): type(ts_int) { val.i=i; } TS_Attr(bool b): type(ts_bool) { val.b=b; } TS_Attr(float r): type(ts_real) { val.r=r; } TS_Attr& operator=(TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { this->val.i = attr.val.i; } else if (type1 == ts_real && type2 == ts_real) { this->val.r = attr.val.r; } else if (type1 == ts_real && type2 == ts_int) { this->val.r = attr.val.i; } else if (type1 == ts_int && type2 == ts_real) { ctrlFirstOpt(); isError = true; cout << "error message:line " << line_num << ",realnum can not be translated into int type"; //this->val.i = attr.val.r; } else if (type1 == ts_bool && type2 == ts_bool) { this->val.b = attr.val.b; } else if (type1 == ts_bool && type2 == ts_int) { ctrlFirstOpt(); isError = true; cout << "error message:line " << line_num << ",intnum can not be translated into bool type"; this->val.b = attr.val.i; } else if (type1 == ts_int && type2 == ts_bool) { this->val.i = attr.val.b; } else { //cout << "error: "; return *this; } } bool operator<(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return this->val.i < attr.val.i; } else if (type1 == ts_real && type2 == ts_real) { return this->val.r < attr.val.r; } else if (type1 == ts_real && type2 == ts_int) { return this->val.r < attr.val.i; } else if (type1 == ts_int && type2 == ts_real) { return this->val.i < attr.val.r; } else if (type1 == ts_bool && type2 == ts_bool) { return this->val.b < attr.val.b; } else if (type1 == ts_bool && type2 == ts_int) { return this->val.b < attr.val.i; } else if (type1 == ts_int && type2 == ts_bool) { return this->val.i < attr.val.b; } else { //cout << "error: "; return false; } } bool operator<=(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return this->val.i <= attr.val.i; } else if (type1 == ts_real && type2 == ts_real) { return this->val.r <= attr.val.r; } else if (type1 == ts_real && type2 == ts_int) { return this->val.r <= attr.val.i; } else if (type1 == ts_int && type2 == ts_real) { return this->val.i <= attr.val.r; } else if (type1 == ts_bool && type2 == ts_bool) { return this->val.b <= attr.val.b; } else if (type1 == ts_bool && type2 == ts_int) { return this->val.b <= attr.val.i; } else if (type1 == ts_int && type2 == ts_bool) { return this->val.i <= attr.val.b; } else { //cout << "error: "; return false; } } bool operator==(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return this->val.i == attr.val.i; } else if (type1 == ts_real && type2 == ts_real) { return this->val.r == attr.val.r; } else if (type1 == ts_real && type2 == ts_int) { return this->val.r == attr.val.i; } else if (type1 == ts_int && type2 == ts_real) { return this->val.i == attr.val.r; } else if (type1 == ts_bool && type2 == ts_bool) { return this->val.b == attr.val.b; } else if (type1 == ts_bool && type2 == ts_int) { return this->val.b == attr.val.i; } else if (type1 == ts_int && type2 == ts_bool) { return this->val.i == attr.val.b; } else { //cout << "error: "; return false; } } bool operator>(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return this->val.i > attr.val.i; } else if (type1 == ts_real && type2 == ts_real) { return this->val.r > attr.val.r; } else if (type1 == ts_real && type2 == ts_int) { return this->val.r > attr.val.i; } else if (type1 == ts_int && type2 == ts_real) { return this->val.i > attr.val.r; } else if (type1 == ts_bool && type2 == ts_bool) { return this->val.b > attr.val.b; } else if (type1 == ts_bool && type2 == ts_int) { return this->val.b > attr.val.i; } else if (type1 == ts_int && type2 == ts_bool) { return this->val.i > attr.val.b; } else { //cout << "error: "; return false; } } bool operator>=(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return this->val.i >= attr.val.i; } else if (type1 == ts_real && type2 == ts_real) { return this->val.r >= attr.val.r; } else if (type1 == ts_real && type2 == ts_int) { return this->val.r >= attr.val.i; } else if (type1 == ts_int && type2 == ts_real) { return this->val.i >= attr.val.r; } else if (type1 == ts_bool && type2 == ts_bool) { return this->val.b >= attr.val.b; } else if (type1 == ts_bool && type2 == ts_int) { return this->val.b >= attr.val.i; } else if (type1 == ts_int && type2 == ts_bool) { return this->val.i >= attr.val.b; } else { //cout << "error: "; return false; } } TS_Attr operator+(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return TS_Attr(this->val.i + attr.val.i); } else if (type1 == ts_real && type2 == ts_real) { return TS_Attr(this->val.r + attr.val.r); } else if (type1 == ts_real && type2 == ts_int) { return TS_Attr(this->val.r + attr.val.i); } else if (type1 == ts_int && type2 == ts_real) { return TS_Attr(this->val.i + attr.val.r); } else { //cout << "error: "; return TS_Attr(); } } TS_Attr operator-(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return TS_Attr(this->val.i - attr.val.i); } else if (type1 == ts_real && type2 == ts_real) { return TS_Attr(this->val.r - attr.val.r); } else if (type1 == ts_real && type2 == ts_int) { return TS_Attr(this->val.r - attr.val.i); } else if (type1 == ts_int && type2 == ts_real) { return TS_Attr(this->val.i - attr.val.r); } else { //cout << "error: "; return TS_Attr(); } } TS_Attr operator*(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type1 == ts_int && type2 == ts_int) { return TS_Attr(this->val.i * attr.val.i); } else if (type1 == ts_real && type2 == ts_real) { return TS_Attr(this->val.r * attr.val.r); } else if (type1 == ts_real && type2 == ts_int) { return TS_Attr(this->val.r * attr.val.i); } else if (type1 == ts_int && type2 == ts_real) { return TS_Attr(this->val.i * attr.val.r); } else { //cout << "error: "; return TS_Attr(); } } TS_Attr operator/(const TS_Attr& attr) { TS_type type1 = this->type; TS_type type2 = attr.type; if (type2 == ts_int && attr.val.i == 0) { ctrlFirstOpt(); isError = true; cout << "error message:line "<<line_num<<",division by zero"; return TS_Attr(1); } if (type2 == ts_real && attr.val.r == 0) { ctrlFirstOpt(); isError = true; cout << "error message:line " << line_num << ",division by zero"; return TS_Attr(1); } if (type1 == ts_int && type2 == ts_int) { return TS_Attr(this->val.i / attr.val.i); } else if (type1 == ts_real && type2 == ts_real) { return TS_Attr(this->val.r / attr.val.r); } else if (type1 == ts_real && type2 == ts_int) { return TS_Attr(this->val.r / attr.val.i); } else if (type1 == ts_int && type2 == ts_real) { return TS_Attr(this->val.i / attr.val.r); } else { //cout << "error: "; return TS_Attr(); } } }; class Production { public: Symbol NT; vector<Symbol> alpha; bool isNullable; std::function<TS_Attr(TS_Attr)> my_func; Production(Symbol nt, Symbol a1, Symbol a2 = ENDDING, Symbol a3 = ENDDING, Symbol a4 = ENDDING, Symbol a5 = ENDDING, Symbol a6 = ENDDING, Symbol a7 = ENDDING, Symbol a8 = ENDDING) { NT = nt; alpha.push_back(a1); if (a2 != ENDDING)alpha.push_back(a2); if (a3 != ENDDING)alpha.push_back(a3); if (a4 != ENDDING)alpha.push_back(a4); if (a5 != ENDDING)alpha.push_back(a5); if (a6 != ENDDING)alpha.push_back(a6); if (a7 != ENDDING)alpha.push_back(a7); if (a8 != ENDDING)alpha.push_back(a8); isNullable = false; if (a1 == E || a2 == E || a3 == E || a4 == E || a6 == E || a7 == E || a8 == E || a5 == E) isNullable = true; } }; //----------------------------------------------------------------------------------- //----------------------------------Static Data-------------------------------------- //优化1:将读入的Symbol映射到对应的编号(enum = INT),int作为基础加速parsing table生成 //优化2:使用哈希表加速映射查找 Symbol current_Symbol; TS_Attr current_Attr; string token = ""; unordered_map<string, Symbol> StrToTerminalMap; //将读入的Symbol转化为编号的映射 string TerminalToStrMap[ENDDING]; //将编号转化为Symbol String的映射 vector<Production> productions; //生成式 //----------------------------------------------------------------------------------- //----------------------------------Data Precomputed -------------------------------- //优化3:unordered_set内涵foward_list串联set,加速遍历至O(num_of_element) unordered_set<Symbol> First[ENDDING]; //First集合 unordered_set<Symbol> Follow[T]; //Follow集合 //优化4:空间换时间,防止计算Follow时对First的二次计算 unordered_set<Symbol> ProductSentenceFormFirst[33][8]; //Production的First集合 int parsingTable[ENDDING + 1][ENDDING + 1];//分析表 //----------------------------------------------------------------------------------- //----------------------------------Data Table -------------------------------- unordered_map<string, TS_Attr> IdTable; inline bool isInteger(const std::string& s) { if (s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false; char* p; strtol(s.c_str(), &p, 10); return (*p == 0); } inline bool isReal(const std::string& s) { return true; } bool get_Symbol() { if (linein >> token) { if (StrToTerminalMap.count(token) != 0) { current_Symbol = StrToTerminalMap[token]; } else if (token.size() == 1 && isalpha(token[0])) { if (IdTable.count(token) == 0) { IdTable.emplace(token, TS_Attr()); } current_Symbol = ID; } else if (isInteger(token)) { current_Symbol = INTNUM; current_Attr.val.i = atoi(token.c_str()); current_Attr.type = ts_int; } else { current_Symbol = REALNUM; current_Attr.val.r = atof(token.c_str()); current_Attr.type = ts_real; } return true; } else { line_num++; getline(progin, line); if (line != "") { linein.clear(); linein.str(line); return get_Symbol(); } else { return false; } } } //----------------------------------------------------------------------------------- //----------------------------------Functions---------------------------------------- void InitialMapping()//初始化Str->S Mapping and X->Str Mapping { // mapping from T string to T StrToTerminalMap.insert(std::pair<string, Symbol>("{", LABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("}", RABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("E", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("e", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("if", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("If", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("IF", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("(", LCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>(")", RCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("Then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("THEN", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("Else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ELSE", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ID", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("Id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("=", ASSIGN)); StrToTerminalMap.insert(std::pair<string, Symbol>("<", LT)); StrToTerminalMap.insert(std::pair<string, Symbol>("<=", LE)); StrToTerminalMap.insert(std::pair<string, Symbol>(">", GT)); StrToTerminalMap.insert(std::pair<string, Symbol>(">=", GE)); StrToTerminalMap.insert(std::pair<string, Symbol>("==", EQ)); StrToTerminalMap.insert(std::pair<string, Symbol>("+", ADD)); StrToTerminalMap.insert(std::pair<string, Symbol>("-", MINUS)); StrToTerminalMap.insert(std::pair<string, Symbol>("*", MULTIPLE)); StrToTerminalMap.insert(std::pair<string, Symbol>("/", DIVIDE)); StrToTerminalMap.insert(std::pair<string, Symbol>("int", MYINT)); StrToTerminalMap.insert(std::pair<string, Symbol>("real", MYREAL)); StrToTerminalMap.insert(std::pair<string, Symbol>(";", SEMICOLON)); StrToTerminalMap.insert(std::pair<string, Symbol>("INTNUM", INTNUM)); StrToTerminalMap.insert(std::pair<string, Symbol>("REALNUM", REALNUM)); // mapping for NT to NT str TerminalToStrMap[program] = "program"; TerminalToStrMap[decls] = "decls"; TerminalToStrMap[decl] = "decl"; TerminalToStrMap[stmt] = "stmt"; TerminalToStrMap[compoundstmt] = "compoundstmt"; TerminalToStrMap[stmts] = "stmts"; TerminalToStrMap[ifstmt] = "ifstmt"; TerminalToStrMap[assgstmt] = "assgstmt"; TerminalToStrMap[boolexpr] = "boolexpr"; TerminalToStrMap[boolop] = "boolop"; TerminalToStrMap[arithexpr] = "arithexpr"; TerminalToStrMap[arithexprprime] = "arithexprprime"; TerminalToStrMap[multexpr] = "multexpr"; TerminalToStrMap[multexprprime] = "multexprprime"; TerminalToStrMap[simpleexpr] = "simpleexpr"; // mapping for T to T str TerminalToStrMap[LABRACKET] = "{"; TerminalToStrMap[RABRACKET] = "}"; TerminalToStrMap[E] = "E"; TerminalToStrMap[IF] = "if"; TerminalToStrMap[LCBRACKET] = "("; TerminalToStrMap[RCBRACKET] = ")"; TerminalToStrMap[THEN] = "then"; TerminalToStrMap[ELSE] = "else"; TerminalToStrMap[ID] = "ID"; TerminalToStrMap[ASSIGN] = "="; TerminalToStrMap[LT] = "<"; TerminalToStrMap[LE] = "<="; TerminalToStrMap[GT] = ">"; TerminalToStrMap[GE] = ">="; TerminalToStrMap[EQ] = "=="; TerminalToStrMap[ADD] = "+"; TerminalToStrMap[MINUS] = "-"; TerminalToStrMap[MULTIPLE] = "*"; TerminalToStrMap[DIVIDE] = "/"; TerminalToStrMap[SEMICOLON] = ";"; TerminalToStrMap[MYINT] = "int"; TerminalToStrMap[INTNUM] = "INTNUM"; TerminalToStrMap[MYREAL] = "real"; TerminalToStrMap[REALNUM] = "REALNUM"; } TS_Attr handleNT(Symbol ts_NT, TS_Attr ts_Attr = 0) {//隐式转换调用TS_ATTR(int i)的构造函数构造匿名对象然后默认拷贝构造函数拷贝 int prodnum = parsingTable[ts_NT][current_Symbol]; if (prodnum != inf) { return productions[prodnum].my_func(ts_Attr); } else { //cout << "error: "; return TS_Attr(); } } bool handleT(Symbol ts_T) { if (ts_T == current_Symbol) { return get_Symbol(); } else { //cout << "error: "; return get_Symbol(); } } void InitialProduction()//初始化产生式 { productions.push_back(Production(program, decls, compoundstmt)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleNT(decls); handleNT(compoundstmt,TS_Attr(true)); return TS_Attr(); }; productions.push_back(Production(decls, decl, SEMICOLON, decls)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleNT(decl); handleT(SEMICOLON); handleNT(decls); return TS_Attr(); }; productions.push_back(Production(decls, E)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ //do nothing return TS_Attr(); }; productions.push_back(Production(decl, MYINT, ID, ASSIGN, INTNUM)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(MYINT); //在消耗我的id之前需要对id做已知的操作 string tempt_id = token; IdTable[tempt_id].type = ts_int; handleT(ID); handleT(ASSIGN); IdTable[tempt_id] = current_Attr; handleT(INTNUM); return TS_Attr(); }; productions.push_back(Production(decl, MYREAL, ID, ASSIGN, REALNUM)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(MYREAL); //在消耗我的id之前需要对id做已知的操作 string tempt_id = token; IdTable[tempt_id].type = ts_real; handleT(ID); handleT(ASSIGN); IdTable[tempt_id] = current_Attr; handleT(REALNUM); return TS_Attr(); }; productions.push_back(Production(stmt, ifstmt)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleNT(ifstmt,attr); return TS_Attr(); }; productions.push_back(Production(stmt, assgstmt)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleNT(assgstmt,attr); return TS_Attr(); }; productions.push_back(Production(stmt, compoundstmt)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleNT(compoundstmt,attr); return TS_Attr(); }; productions.push_back(Production(compoundstmt, LABRACKET, stmts, RABRACKET)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(LABRACKET); handleNT(stmts,attr); handleT(RABRACKET); return TS_Attr(); }; productions.push_back(Production(stmts, stmt, stmts)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleNT(stmt,attr); handleNT(stmts,attr); return TS_Attr(); }; productions.push_back(Production(stmts, E)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ //do nothing return TS_Attr(); }; productions.push_back(Production(ifstmt, IF, LCBRACKET, boolexpr, RCBRACKET, THEN, stmt, ELSE, stmt)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(IF); handleT(LCBRACKET); TS_Attr boolattr = handleNT(boolexpr); bool isFirst = boolattr.val.b; bool todo = attr.val.b; handleT(RCBRACKET); handleT(THEN); handleNT(stmt, TS_Attr(isFirst && todo)); handleT(ELSE); handleNT(stmt, TS_Attr((!isFirst) && todo)); return TS_Attr(); }; productions.push_back(Production(assgstmt, ID, ASSIGN, arithexpr, SEMICOLON)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ string tempt_id = token; handleT(ID); handleT(ASSIGN); TS_Attr arithexpr_result = handleNT(arithexpr); if (attr.val.b) { IdTable[tempt_id] = arithexpr_result; } handleT(SEMICOLON); return TS_Attr(); }; productions.push_back(Production(boolexpr, arithexpr, boolop, arithexpr)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ TS_Attr arith_result1 = handleNT(arithexpr); string op = token; handleNT(boolop); TS_Attr arith_result2 = handleNT(arithexpr); if (op == "<") { return TS_Attr(arith_result1 < arith_result2); } else if (op == "<=") { return TS_Attr(arith_result1 <= arith_result2); } else if (op == ">") { return TS_Attr(arith_result1 > arith_result2); } else if (op == ">=") { return TS_Attr(arith_result1 >= arith_result2); } else if (op == "==") { return TS_Attr(arith_result1 == arith_result2); } else { return TS_Attr(false); } }; productions.push_back(Production(boolop, LT)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(LT); return TS_Attr(); }; productions.push_back(Production(boolop, GT)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(GT); return TS_Attr(); }; productions.push_back(Production(boolop, LE)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(LE); return TS_Attr(); }; productions.push_back(Production(boolop, GE)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(GE); return TS_Attr(); }; productions.push_back(Production(boolop, EQ)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(EQ); return TS_Attr(); }; productions.push_back(Production(arithexpr, multexpr, arithexprprime)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ TS_Attr param = handleNT(multexpr); return handleNT(arithexprprime, param); }; productions.push_back(Production(arithexprprime, ADD, multexpr, arithexprprime)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(ADD); TS_Attr result = handleNT(multexpr); return handleNT(arithexprprime, attr + result); }; productions.push_back(Production(arithexprprime, MINUS, multexpr, arithexprprime)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(MINUS); TS_Attr result = handleNT(multexpr); return handleNT(arithexprprime, attr - result); }; productions.push_back(Production(arithexprprime, E)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ return TS_Attr(attr); }; productions.push_back(Production(multexpr, simpleexpr, multexprprime)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ TS_Attr param = handleNT(simpleexpr); return handleNT(multexprprime, param); }; productions.push_back(Production(multexprprime, MULTIPLE, simpleexpr, multexprprime)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(MULTIPLE); TS_Attr result = handleNT(simpleexpr); return handleNT(multexprprime, attr * result); }; productions.push_back(Production(multexprprime, DIVIDE, simpleexpr, multexprprime)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(DIVIDE); TS_Attr result = handleNT(simpleexpr); return handleNT(multexprprime, attr / result); }; productions.push_back(Production(multexprprime, E)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ return TS_Attr(attr); }; productions.push_back(Production(simpleexpr, ID)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ string tempt_id = token; handleT(ID); return IdTable[tempt_id]; }; productions.push_back(Production(simpleexpr, INTNUM)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ TS_Attr tempt_attr = current_Attr; handleT(INTNUM); return tempt_attr; }; productions.push_back(Production(simpleexpr, REALNUM)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ TS_Attr tempt_attr = current_Attr; handleT(REALNUM); return tempt_attr; }; productions.push_back(Production(simpleexpr, LCBRACKET, arithexpr, RCBRACKET)); productions[productions.size()-1].my_func = [](TS_Attr attr)->TS_Attr{ handleT(LCBRACKET); TS_Attr tempt_attr = handleNT(arithexpr); handleT(RCBRACKET); return tempt_attr; }; } void calculateFirst(Symbol s)//已优化,计算First数组同时维护ProductSentenceFormFirst(额外开销,时间复杂度级别不上升) { if (!First[s].empty()) return; // decide whether to append E in First(s) for (const auto& prod : productions) { if (s == prod.NT) { if (prod.isNullable == true) First[s].insert(E); } } // using production with left side of s to append X in First(s) int prod_num = 0; for (const auto& prod : productions) { if (s == prod.NT) { bool isAllNullable = true; int rSym_num = 0; for (const auto& X : prod.alpha) { calculateFirst(X); //add all in First(X) except E into first(s) for (unordered_set<Symbol>::iterator it = First[X].begin(); it != First[X].end(); it++) { if (*it != E) { First[s].insert(*it); //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i <= rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(*it); } } } // if E not in First(x) then break the inserting and set allNullable to false if (First[X].count(E) == 0) { isAllNullable = false; //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i < rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(E); } break; } rSym_num++; } //if allnullable, add E into First(s) if (isAllNullable) { First[s].insert(E); //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i < rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(E); } } } prod_num++; } } void InitialFirst() { //Initial First for Terminals for (int i = (int)(T + 1); i < (int)ENDDING; i++) { First[i].insert((Symbol)i); } for (int i = NT + 1; i < T; i++) { calculateFirst((Symbol)i); } } void InitialFollow()//由于Follow集合的计算是循环到终止,因此必须优化<-已优化 { Follow[program].insert(ENDDING); bool hasModified = true; while (hasModified) { hasModified = false; int prod_num = 0; for (const auto& prod : productions) {//appending into follow set for NT Symbol NT = prod.NT; for (int i = 0; i < prod.alpha.size(); i++) { Symbol Xi = prod.alpha[i]; if ((int)Xi < (int)T) {//for every Xi (NT) and scan its right side for appending //优化5:若ProductSentenceFormFirst已经被计算了则不重复计算 O(n^2)->O(n) if (i < prod.alpha.size() - 1 && ProductSentenceFormFirst[prod_num][i + 1].size() != 0) { for (unordered_set<Symbol>::iterator it = ProductSentenceFormFirst[prod_num][i + 1].begin(); it != ProductSentenceFormFirst[prod_num][i + 1].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } if (ProductSentenceFormFirst[prod_num][i + 1].count(E) != 0) { for (unordered_set<Symbol>::iterator it = Follow[NT].begin(); it != Follow[NT].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } } } else { bool isAllNullable = true; for (int j = i + 1; j < prod.alpha.size(); j++) {//for every xj right to Xi Symbol Xj = prod.alpha[j]; for (unordered_set<Symbol>::iterator it = First[Xj].begin(); it != First[Xj].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } if (First[Xj].count(E) == 0) { isAllNullable = false; break; } } if (isAllNullable)//right side of Xi is e or first(right side) has e { for (unordered_set<Symbol>::iterator it = Follow[NT].begin(); it != Follow[NT].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } } } } } prod_num++; } } } void InitialParsingTable() { memset(parsingTable, 0x3f, sizeof(parsingTable)); InitialFirst(); InitialFollow(); for (int prod_num = 0; prod_num < productions.size(); prod_num++) { const Production& prod = productions[prod_num]; Symbol A = prod.NT; // prod: A->X1X2X3... //bool isAllNullable = true; //优化6:由于已经计算过每个产生式的右边句型的First集合,直接使用ProductSentenceFormFirst[prod_num][0] for (unordered_set<Symbol>::iterator it = ProductSentenceFormFirst[prod_num][0].begin(); it != ProductSentenceFormFirst[prod_num][0].end(); it++) { if (*it != E) { //if (parsingTable[A][*it] != inf) // cout << "conflict!!!!!!!!!!!!!!!!!!!!" << endl; parsingTable[A][*it] = prod_num; } } if (ProductSentenceFormFirst[prod_num][0].count(E) != 0) { for (unordered_set<Symbol>::iterator it = Follow[A].begin(); it != Follow[A].end(); it++) { if (*it != E) { //if (parsingTable[A][*it] != inf) // cout << "conflict!!!!!!!!!!!!!!!!!!!!" << endl; parsingTable[A][*it] = prod_num; } } } } } /* 不要修改这个标准输入函数 */ void read_prog(string& prog) { char c; while (scanf("%c", &c) != EOF) { prog += c; } } /* 你可以添加其他函数 */ void Analysis() { read_prog(prog); progin.str(prog); getline(progin,line); linein.clear(); linein.str(line); // string tmpt = get_Symbol(); // while(tmpt!="") // { // printf("line%d, %s\n",line_num,tmpt.c_str()); // // tmpt = get_Symbol(); // } /* 骚年们 请开始你们的表演 */ /********* Begin *********/ // initialization InitialMapping(); InitialProduction(); InitialParsingTable(); get_Symbol(); productions[0].my_func(TS_Attr()); if (!isError) { for (auto tid = IdTable.begin(); tid != IdTable.end(); tid++) { switch (tid->second.type) { case ts_int: { ctrlFirstOpt(); cout << tid->first << ": " << tid->second.val.i; break; } case ts_real: { ctrlFirstOpt(); cout << tid->first << ": " << tid->second.val.r; break; } case ts_bool: { ctrlFirstOpt(); cout << tid->first << ": " << tid->second.val.b; break; } default: { break; } } } } /********* End *********/ } <file_sep>/03-LR Parser/01-Lexical/LRparser.h #pragma once // C语言词法分析器 #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <string> #include <fstream> #include <sstream> #include <vector> #include <unordered_map> #include <unordered_set> #include <stack> #include <list> #include <functional> using namespace std; const int inf = 0x3f3f3f3f; //----------------------------------------------------------------------------------- //----------------------------------Data Structure----------------------------------- enum Symbol { NT, //Non-terminal SPrime, //Agumented Gramma with SPrime -> program program, stmt, compoundstmt, stmts, ifstmt, whilestmt, assgstmt, boolexpr, boolop, arithexpr, arithexprprime, multexpr, multexprprime, simpleexpr, T, //Terminal LABRACKET, RABRACKET, E, IF, LCBRACKET, RCBRACKET, THEN, ELSE, WHILE, ID, ASSIGN, LT, LE, GT, GE, EQ, ADD, MINUS, MULTIPLE, DIVIDE, NUM, SEMICOLON, //end ENDDING }; class LR0Item { public: int prod_num; int dot_pos; //Note: 这里dotPos代表位置,假如有XYZ则pos的范围是[0,3]->0X1Y2Z3 LR0Item(int prod, int pos) { prod_num = prod; dot_pos = pos; } bool operator==(LR0Item& item) // operator overload { return prod_num == item.prod_num&&dot_pos == item.dot_pos; } }; class Production { public: Symbol NT; vector<Symbol> alpha; bool isNullable; Production(Symbol nt, Symbol a1, Symbol a2 = ENDDING, Symbol a3 = ENDDING, Symbol a4 = ENDDING, Symbol a5 = ENDDING, Symbol a6 = ENDDING, Symbol a7 = ENDDING, Symbol a8 = ENDDING) { NT = nt; if (a1 != E)alpha.push_back(a1); if (a2 != ENDDING && a2 != E)alpha.push_back(a2); if (a3 != ENDDING && a3 != E)alpha.push_back(a3); if (a4 != ENDDING && a4 != E)alpha.push_back(a4); if (a5 != ENDDING && a5 != E)alpha.push_back(a5); if (a6 != ENDDING && a6 != E)alpha.push_back(a6); if (a7 != ENDDING && a7 != E)alpha.push_back(a7); if (a8 != ENDDING && a8 != E)alpha.push_back(a8); isNullable = false; if (a1 == E || a2 == E || a3 == E || a4 == E || a6 == E || a7 == E || a8 == E || a5 == E) isNullable = true; } }; class LR0ItemSet { public: vector<LR0Item> core; vector<LR0Item> extension; bool flg[T]; //优化7:标记closure是否考虑过当前start = NT的产生式被closure加入过 list<LR0Item> LR0ItemsAfterDot[ENDDING + 1];//优化:维护dot后为A的LR0Item,这里不需要存储reference因为每个LR0Item都是两个int //使用list的原因,无随机访问 + 没有vector allocate space的特性 int gotoMapping[ENDDING + 1];//标记goto[me,symbol]->的set LR0ItemSet() { memset(flg, false, sizeof(flg)); memset(gotoMapping, 0x3f3f3f3f, sizeof(gotoMapping)); } void addCore(LR0Item& item); void insert(LR0Item& item); void closure(); bool operator==(LR0ItemSet& set) // operator overload {//优化:只对比core的关系来决定,加速判断Set是否已经存在 if (this->core.size() != set.core.size()) { return false; } /*for (auto& item : this->core) { bool notIn = true; for (auto& itemPrime : set.core) { if (item == itemPrime) { notIn = false; break; } } if (notIn) return false; }*/ //优化: core一定是升序排列,对比复杂度O(n^2)->o(n) for (auto it1 = core.begin(), it2 = set.core.begin(); it1 != core.end();it1++,it2++) { if (*it1 == *it2) { } else return false; } return true; } private: }; //----------------------------------------------------------------------------------- //----------------------------------Static Data-------------------------------------- //优化1:将读入的Symbol映射到对应的编号(enum = INT),int作为基础加速parsing table生成 //优化2:使用哈希表加速映射查找 unordered_map<string, Symbol> StrToTerminalMap; //将读入的Symbol转化为编号的映射 string TerminalToStrMap[ENDDING]; //将编号转化为Symbol String的映射 vector<Production> productions; //生成式 bool isFirstOpt = true; //----------------------------------------------------------------------------------- //----------------------------------First Follow数据---------------------------------- //优化3:unordered_set内涵foward_list串联set,加速遍历至O(num_of_element) unordered_set<Symbol> First[ENDDING]; //First集合 unordered_set<Symbol> Follow[T]; //Follow集合 //优化4:空间换时间,防止计算Follow时对First的二次计算 unordered_set<Symbol> ProductSentenceFormFirst[30][8]; //Production的First集合 //----------------------------------------------------------------------------------- //----------------------------------------SLR数据------------------------------------ //项簇集 其中LR0ItemSet是reference 需要new and delete,同时gotoMapping包含了parsingtable vector<reference_wrapper<LR0ItemSet>> CanonicalCollection; //----------------------------------------------------------------------------------- //----------------------------------Functions---------------------------------------- void InitialMapping()//初始化Str->S Mapping and X->Str Mapping { // mapping from T string to T StrToTerminalMap.insert(std::pair<string, Symbol>("{", LABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("}", RABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("E", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("e", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("if", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("If", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("IF", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("(", LCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>(")", RCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("Then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("THEN", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("Else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ELSE", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("while", WHILE)); StrToTerminalMap.insert(std::pair<string, Symbol>("While", WHILE)); StrToTerminalMap.insert(std::pair<string, Symbol>("WHILE", WHILE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ID", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("Id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("=", ASSIGN)); StrToTerminalMap.insert(std::pair<string, Symbol>("<", LT)); StrToTerminalMap.insert(std::pair<string, Symbol>("<=", LE)); StrToTerminalMap.insert(std::pair<string, Symbol>(">", GT)); StrToTerminalMap.insert(std::pair<string, Symbol>(">=", GE)); StrToTerminalMap.insert(std::pair<string, Symbol>("==", EQ)); StrToTerminalMap.insert(std::pair<string, Symbol>("+", ADD)); StrToTerminalMap.insert(std::pair<string, Symbol>("-", MINUS)); StrToTerminalMap.insert(std::pair<string, Symbol>("*", MULTIPLE)); StrToTerminalMap.insert(std::pair<string, Symbol>("/", DIVIDE)); StrToTerminalMap.insert(std::pair<string, Symbol>("NUM", NUM)); StrToTerminalMap.insert(std::pair<string, Symbol>("num", NUM)); StrToTerminalMap.insert(std::pair<string, Symbol>(";", SEMICOLON)); StrToTerminalMap.insert(std::pair<string, Symbol>("$", ENDDING)); // mapping for NT to NT str TerminalToStrMap[program] = "program"; TerminalToStrMap[stmt] = "stmt"; TerminalToStrMap[compoundstmt] = "compoundstmt"; TerminalToStrMap[stmts] = "stmts"; TerminalToStrMap[ifstmt] = "ifstmt"; TerminalToStrMap[whilestmt] = "whilestmt"; TerminalToStrMap[assgstmt] = "assgstmt"; TerminalToStrMap[boolexpr] = "boolexpr"; TerminalToStrMap[boolop] = "boolop"; TerminalToStrMap[arithexpr] = "arithexpr"; TerminalToStrMap[arithexprprime] = "arithexprprime"; TerminalToStrMap[multexpr] = "multexpr"; TerminalToStrMap[multexprprime] = "multexprprime"; TerminalToStrMap[simpleexpr] = "simpleexpr"; // mapping for T to T str TerminalToStrMap[LABRACKET] = "{"; TerminalToStrMap[RABRACKET] = "}"; TerminalToStrMap[E] = "E"; TerminalToStrMap[IF] = "if"; TerminalToStrMap[LCBRACKET] = "("; TerminalToStrMap[RCBRACKET] = ")"; TerminalToStrMap[THEN] = "then"; TerminalToStrMap[ELSE] = "else"; TerminalToStrMap[WHILE] = "while"; TerminalToStrMap[ID] = "ID"; TerminalToStrMap[ASSIGN] = "="; TerminalToStrMap[LT] = "<"; TerminalToStrMap[LE] = "<="; TerminalToStrMap[GT] = ">"; TerminalToStrMap[GE] = ">="; TerminalToStrMap[EQ] = "=="; TerminalToStrMap[ADD] = "+"; TerminalToStrMap[MINUS] = "-"; TerminalToStrMap[MULTIPLE] = "*"; TerminalToStrMap[DIVIDE] = "/"; TerminalToStrMap[NUM] = "NUM"; TerminalToStrMap[SEMICOLON] = ";"; } void InitialProduction()//初始化产生式 { productions.push_back(Production(SPrime, program));//Agumented Gramma with SPrime -> program productions.push_back(Production(program, compoundstmt)); productions.push_back(Production(stmt, ifstmt)); productions.push_back(Production(stmt, whilestmt)); productions.push_back(Production(stmt, assgstmt)); productions.push_back(Production(stmt, compoundstmt)); productions.push_back(Production(compoundstmt, LABRACKET, stmts, RABRACKET)); productions.push_back(Production(stmts, stmt, stmts)); productions.push_back(Production(stmts, E)); productions.push_back(Production(ifstmt, IF, LCBRACKET, boolexpr, RCBRACKET, THEN, stmt, ELSE, stmt)); productions.push_back(Production(whilestmt, WHILE, LCBRACKET, boolexpr, RCBRACKET, stmt)); productions.push_back(Production(assgstmt, ID, ASSIGN, arithexpr, SEMICOLON)); productions.push_back(Production(boolexpr, arithexpr, boolop, arithexpr)); productions.push_back(Production(boolop, LT)); productions.push_back(Production(boolop, GT)); productions.push_back(Production(boolop, LE)); productions.push_back(Production(boolop, GE)); productions.push_back(Production(boolop, EQ)); productions.push_back(Production(arithexpr, multexpr, arithexprprime)); productions.push_back(Production(arithexprprime, ADD, multexpr, arithexprprime)); productions.push_back(Production(arithexprprime, MINUS, multexpr, arithexprprime)); productions.push_back(Production(arithexprprime, E)); productions.push_back(Production(multexpr, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, MULTIPLE, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, DIVIDE, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, E)); productions.push_back(Production(simpleexpr, ID)); productions.push_back(Production(simpleexpr, NUM)); productions.push_back(Production(simpleexpr, LCBRACKET, arithexpr, RCBRACKET)); } void calculateFirst(Symbol s)//已优化,计算First数组同时维护ProductSentenceFormFirst(额外开销,时间复杂度级别不上升) { if (!First[s].empty()) return; // decide whether to append E in First(s) for (const auto & prod : productions) { if (s == prod.NT) { if (prod.isNullable == true) First[s].insert(E); } } // using production with left side of s to append X in First(s) int prod_num = 0; for (const auto & prod : productions) { if (s == prod.NT) { bool isAllNullable = true; int rSym_num = 0; for (const auto& X : prod.alpha) { calculateFirst(X); //add all in First(X) except E into first(s) for (unordered_set<Symbol>::iterator it = First[X].begin(); it != First[X].end(); it++) { if (*it != E) { First[s].insert(*it); //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i <= rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(*it); } } } // if E not in First(x) then break the inserting and set allNullable to false if (First[X].count(E) == 0) { isAllNullable = false; //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i < rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(E); } break; } rSym_num++; } //if allnullable, add E into First(s) if (isAllNullable) { First[s].insert(E); //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i < rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(E); } } } prod_num++; } } void InitialFirst() { //Initial First for Terminals for (int i = (int)(T + 1); i < (int)ENDDING; i++) { First[i].insert((Symbol)i); } for (int i = NT + 1; i < T; i++) { calculateFirst((Symbol)i); } } void InitialFollow()//由于Follow集合的计算是循环到终止,因此必须优化<-已优化 { Follow[SPrime].insert(ENDDING); bool hasModified = true; while (hasModified) { hasModified = false; int prod_num = 0; for (const auto & prod : productions) {//appending into follow set for NT Symbol NT = prod.NT; for (int i = 0; i < prod.alpha.size(); i++) { Symbol Xi = prod.alpha[i]; if ((int)Xi < (int)T) {//for every Xi (NT) and scan its right side for appending //优化5:若ProductSentenceFormFirst已经被计算了则不重复计算 O(n^2)->O(n) if (i < prod.alpha.size() - 1 && ProductSentenceFormFirst[prod_num][i + 1].size() != 0) { for (unordered_set<Symbol>::iterator it = ProductSentenceFormFirst[prod_num][i + 1].begin(); it != ProductSentenceFormFirst[prod_num][i + 1].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } if (ProductSentenceFormFirst[prod_num][i + 1].count(E) != 0) { for (unordered_set<Symbol>::iterator it = Follow[NT].begin(); it != Follow[NT].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } } } else { bool isAllNullable = true; for (int j = i + 1; j < prod.alpha.size(); j++) {//for every xj right to Xi Symbol Xj = prod.alpha[j]; for (unordered_set<Symbol>::iterator it = First[Xj].begin(); it != First[Xj].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } if (First[Xj].count(E) == 0) { isAllNullable = false; break; } } if (isAllNullable)//right side of Xi is e or first(right side) has e { for (unordered_set<Symbol>::iterator it = Follow[NT].begin(); it != Follow[NT].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } } } } } prod_num++; } } } void LR0ItemSet::closure() //LR0ItemSet的Closure方法 { // for cores for (int i = 0; i < core.size(); i++) { LR0Item& item = core[i]; if (item.dot_pos < productions[item.prod_num].alpha.size() && productions[item.prod_num].alpha[item.dot_pos] < T) { Symbol start = productions[item.prod_num].alpha[item.dot_pos]; //如果以start为NT的production没有被加入过 if (flg[start] == false) { for (int j = 0; j < productions.size(); j++) { auto& prod = productions[j]; if (prod.NT == start) { LR0Item item_to_append(j, 0); //确认不在core中 bool InCore = false; for (int k = 0; k < core.size(); k++) { if (item_to_append == core[k]) { InCore = true; break; } } if (!InCore) { this->insert(item_to_append); } } } flg[start] = true; } } } // for closure for (int extension_num = 0; extension_num < extension.size(); extension_num++) { LR0Item& item = extension[extension_num]; if (item.dot_pos < productions[item.prod_num].alpha.size() && productions[item.prod_num].alpha[item.dot_pos] < T) { Symbol start = productions[item.prod_num].alpha[item.dot_pos]; //如果以start为NT的production没有被加入过 if (flg[start] == false) { for (int j = 0; j < productions.size(); j++) { auto& prod = productions[j]; if (prod.NT == start) { LR0Item item_to_append(j, 0); //确认不在core中 bool InCore = false; for (int k = 0; k < core.size(); k++) { if (item_to_append == core[k]) { InCore = true; break; } } if (!InCore) { this->insert(item_to_append); } } } flg[start] = true; } } } } void LR0ItemSet::addCore(LR0Item& item) { core.push_back(item); if (item.dot_pos < productions[item.prod_num].alpha.size()) { LR0ItemsAfterDot[productions[item.prod_num].alpha[item.dot_pos]].push_back(core[core.size() - 1]); } else { LR0ItemsAfterDot[ENDDING].push_back(core[core.size() - 1]); } } void LR0ItemSet::insert(LR0Item& item) { extension.push_back(item); if (item.dot_pos < productions[item.prod_num].alpha.size()) { LR0ItemsAfterDot[productions[item.prod_num].alpha[item.dot_pos]].push_back(extension[extension.size() - 1]); } else { LR0ItemsAfterDot[ENDDING].push_back(extension[extension.size() - 1]); } } //one pass process: canonical collection + parsing table void InitialCanonicalCollection() { //Initial First LR0Item Set LR0Item sPrimeItem(0, 0); LR0ItemSet& I0 = *(new LR0ItemSet()); I0.addCore(sPrimeItem); I0.closure(); CanonicalCollection.push_back(std::ref(I0)); for (int i = 0; i < CanonicalCollection.size(); i++) { LR0ItemSet& itemSet = CanonicalCollection[i].get(); //首先计算goto //Step1. 计算dot不在结尾的每一个goto for (int j = 0; j < ENDDING; j++) { Symbol gotoSymbol = (Symbol)j; list<LR0Item>::iterator it = (itemSet.LR0ItemsAfterDot)[gotoSymbol].begin(); LR0ItemSet& temptSet = *(new LR0ItemSet()); while (it != (itemSet.LR0ItemsAfterDot)[gotoSymbol].end()) { LR0Item rightShiftedItem((*it).prod_num, (*it).dot_pos + 1); temptSet.addCore(rightShiftedItem); it++; } if (temptSet.core.size() != 0)//core中存在元素 { //判断temptSet不存在于CanonicalCollections中 bool isExisted = false; int k; for (k = 0; k < CanonicalCollection.size(); k++) { LR0ItemSet& existingSet = CanonicalCollection[k].get(); if (existingSet == temptSet) { isExisted = true; break; } } //如果存在则需要释放内存 if (isExisted) { delete &temptSet; } else { temptSet.closure(); CanonicalCollection.push_back(std::ref(temptSet)); } //维护itemSet的goto表 itemSet.gotoMapping[gotoSymbol] = k; } else { delete &temptSet; } } auto LR0ItemsLast_it = (itemSet.LR0ItemsAfterDot)[ENDDING].begin(); while (LR0ItemsLast_it != (itemSet.LR0ItemsAfterDot)[ENDDING].end()) {//然后对A->a.的情况吧goto[A,b]in follow(A)设置为产生式的num LR0Item& tmptItem = *LR0ItemsLast_it; Symbol temptNT = productions[tmptItem.prod_num].NT; for (Symbol temptSymb : Follow[temptNT]) { itemSet.gotoMapping[temptSymb] = -tmptItem.prod_num; } LR0ItemsLast_it++; } } } void InitialParsingTable() { InitialFirst(); InitialFollow(); InitialCanonicalCollection(); } int getParsingTable(int st, Symbol symb) { return CanonicalCollection[st].get().gotoMapping[symb]; } void ctrlFirstOpt() { if (!isFirstOpt) printf("\n"); isFirstOpt = false; } /* 不要修改这个标准输入函数 */ void read_prog(string& prog) { char c; while (scanf("%c", &c) != EOF) { prog += c; } } /* 你可以添加其他函数 */ void Analysis() { string prog; read_prog(prog); prog += " $"; /* 骚年们 请开始你们的表演 */ /********* Begin *********/ // initialization InitialMapping(); InitialProduction(); InitialParsingTable(); //cout << "{" << endl; //for (int i=0;i<CanonicalCollection.size();i++) //{ // cout << "{"; // auto& vec = CanonicalCollection[i].get().gotoMapping; // int j; // for (j=0;j<ENDDING;j++) // { // int a = vec[j]; // if (a == inf) // cout << "INF " << ","; // else // cout << a << " ,"; // } // if (vec[j] == inf) // cout << "INF "; // else // cout << vec[j]; // cout << "}" << endl; //} //cout << "}" << endl; // LL1 parsing stack<int> shiftreduceStack; vector<int> productionSeq; shiftreduceStack.push(0); istringstream progin(prog); string line; int line_count = 0; //error handler -- Phrase-Level Error Recovery string lastToken; bool hasErrored = false; // stacking while (getline(progin, line)) { line_count++; istringstream linein(line); string token; if (hasErrored || (!hasErrored && linein >> token)) if (hasErrored) { token = lastToken; hasErrored = false; } while (1) { Symbol inputSymb = StrToTerminalMap[token]; int topState = shiftreduceStack.top(); int operation = getParsingTable(topState, inputSymb); if (operation == inf) { //error handler routine ctrlFirstOpt(); lastToken = token; token = ";"; hasErrored = true; printf("语法错误,第%d行,缺少\"%s\"", line_count - 1, TerminalToStrMap[SEMICOLON].c_str()); } else if (operation > 0) { //shift operation int shift = operation; //push symbol shiftreduceStack.push(inputSymb); //push state shiftreduceStack.push(shift); if (!hasErrored && !(linein >> token)) { break; } else if (hasErrored) { token = lastToken; hasErrored = false; } } else if (operation < 0) { //reduce int reduce = -operation; for (int i = 0; i < productions[reduce].alpha.size() * 2; i++) { shiftreduceStack.pop(); } //on the top should be the State, push the left side of production Symbol topSymb = productions[reduce].NT; int topGoState = shiftreduceStack.top(); shiftreduceStack.push((int)topSymb); int state_to_push = getParsingTable(topGoState, topSymb); shiftreduceStack.push(state_to_push); productionSeq.push_back(reduce); } else { break; } } } vector<Symbol> Left_NTT_Stack;//当前串最右非终结符(包含)左侧 vector<Symbol> Right_T_S;//当前串最右非终结符右侧串 Left_NTT_Stack.push_back(program); ctrlFirstOpt(); int j; for (j = 0; j < Left_NTT_Stack.size(); j++) { printf("%s ", TerminalToStrMap[Left_NTT_Stack[j]].c_str()); } for (j = Right_T_S.size() - 1; j >= 0; j--) { printf("%s ", TerminalToStrMap[Right_T_S[j]].c_str()); } for (int i = productionSeq.size() - 1; i >= 0; i--) { //优化:利用vector和queue优化输出至线性时间 Production& prod = productions[productionSeq[i]]; Left_NTT_Stack.pop_back(); for (j = 0; j < prod.alpha.size(); j++) { Left_NTT_Stack.push_back(prod.alpha[j]); } while (Left_NTT_Stack.size() != 0 && Left_NTT_Stack[Left_NTT_Stack.size() - 1] > T) { Symbol temp_symb = Left_NTT_Stack[Left_NTT_Stack.size() - 1]; Left_NTT_Stack.pop_back(); Right_T_S.push_back(temp_symb); } //输出串 printf("=> "); ctrlFirstOpt(); for (j = 0; j < Left_NTT_Stack.size(); j++) { printf("%s ", TerminalToStrMap[Left_NTT_Stack[j]].c_str()); } for (j = Right_T_S.size() - 1; j >= 0; j--) { printf("%s ", TerminalToStrMap[Right_T_S[j]].c_str()); } } /********* End *********/ } <file_sep>/04-TransitionSchema/04-TransitionSchema/TransitionSchema_old.h #pragma once // C语言词法分析器 #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <stack> #include <map> #include <string> #include <unordered_map> #include <unordered_set> using namespace std; const int inf = 0x3f3f3f3f; //----------------------------------------------------------------------------------- //----------------------------------Data Structure----------------------------------- enum Symbol { NT, //Non-terminal program, decls, decl, stmt, compoundstmt, stmts, ifstmt, assgstmt, boolexpr, boolop, arithexpr, arithexprprime, multexpr, multexprprime, simpleexpr, T, //Terminal LABRACKET, RABRACKET, E, IF, LCBRACKET, RCBRACKET, THEN, ELSE, ID, ASSIGN, LT, LE, GT, GE, EQ, ADD, MINUS, MULTIPLE, DIVIDE, SEMICOLON, MYINT, INTNUM, MYREAL, REALNUM, //end ENDDING }; class Production { public: Symbol NT; vector<Symbol> alpha; bool isNullable; Production(Symbol nt, Symbol a1, Symbol a2 = ENDDING, Symbol a3 = ENDDING, Symbol a4 = ENDDING, Symbol a5 = ENDDING, Symbol a6 = ENDDING, Symbol a7 = ENDDING, Symbol a8 = ENDDING) { NT = nt; alpha.push_back(a1); if (a2 != ENDDING)alpha.push_back(a2); if (a3 != ENDDING)alpha.push_back(a3); if (a4 != ENDDING)alpha.push_back(a4); if (a5 != ENDDING)alpha.push_back(a5); if (a6 != ENDDING)alpha.push_back(a6); if (a7 != ENDDING)alpha.push_back(a7); if (a8 != ENDDING)alpha.push_back(a8); isNullable = false; if (a1 == E || a2 == E || a3 == E || a4 == E || a6 == E || a7 == E || a8 == E || a5 == E) isNullable = true; } }; //----------------------------------------------------------------------------------- //----------------------------------Static Data-------------------------------------- //优化1:将读入的Symbol映射到对应的编号(enum = INT),int作为基础加速parsing table生成 //优化2:使用哈希表加速映射查找 unordered_map<string, Symbol> StrToTerminalMap; //将读入的Symbol转化为编号的映射 string TerminalToStrMap[ENDDING]; //将编号转化为Symbol String的映射 vector<Production> productions; //生成式 bool isFirstOpt = true; //----------------------------------------------------------------------------------- //----------------------------------Data Precomputed -------------------------------- //优化3:unordered_set内涵foward_list串联set,加速遍历至O(num_of_element) unordered_set<Symbol> First[ENDDING]; //First集合 unordered_set<Symbol> Follow[T]; //Follow集合 //优化4:空间换时间,防止计算Follow时对First的二次计算 unordered_set<Symbol> ProductSentenceFormFirst[33][8]; //Production的First集合 int parsingTable[ENDDING + 1][ENDDING + 1];//分析表 //----------------------------------------------------------------------------------- //----------------------------------Functions---------------------------------------- void InitialMapping()//初始化Str->S Mapping and X->Str Mapping { // mapping from T string to T StrToTerminalMap.insert(std::pair<string, Symbol>("{", LABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("}", RABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("E", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("e", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("if", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("If", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("IF", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("(", LCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>(")", RCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("Then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("THEN", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("Else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ELSE", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ID", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("Id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("=", ASSIGN)); StrToTerminalMap.insert(std::pair<string, Symbol>("<", LT)); StrToTerminalMap.insert(std::pair<string, Symbol>("<=", LE)); StrToTerminalMap.insert(std::pair<string, Symbol>(">", GT)); StrToTerminalMap.insert(std::pair<string, Symbol>(">=", GE)); StrToTerminalMap.insert(std::pair<string, Symbol>("==", EQ)); StrToTerminalMap.insert(std::pair<string, Symbol>("+", ADD)); StrToTerminalMap.insert(std::pair<string, Symbol>("-", MINUS)); StrToTerminalMap.insert(std::pair<string, Symbol>("*", MULTIPLE)); StrToTerminalMap.insert(std::pair<string, Symbol>("/", DIVIDE)); StrToTerminalMap.insert(std::pair<string, Symbol>("int", MYINT)); StrToTerminalMap.insert(std::pair<string, Symbol>("real", MYREAL)); StrToTerminalMap.insert(std::pair<string, Symbol>(";", SEMICOLON)); StrToTerminalMap.insert(std::pair<string, Symbol>("INTNUM", INTNUM)); StrToTerminalMap.insert(std::pair<string, Symbol>("REALNUM", REALNUM)); // mapping for NT to NT str TerminalToStrMap[program] = "program"; TerminalToStrMap[decls] = "decls"; TerminalToStrMap[decl] = "decl"; TerminalToStrMap[stmt] = "stmt"; TerminalToStrMap[compoundstmt] = "compoundstmt"; TerminalToStrMap[stmts] = "stmts"; TerminalToStrMap[ifstmt] = "ifstmt"; TerminalToStrMap[assgstmt] = "assgstmt"; TerminalToStrMap[boolexpr] = "boolexpr"; TerminalToStrMap[boolop] = "boolop"; TerminalToStrMap[arithexpr] = "arithexpr"; TerminalToStrMap[arithexprprime] = "arithexprprime"; TerminalToStrMap[multexpr] = "multexpr"; TerminalToStrMap[multexprprime] = "multexprprime"; TerminalToStrMap[simpleexpr] = "simpleexpr"; // mapping for T to T str TerminalToStrMap[LABRACKET] = "{"; TerminalToStrMap[RABRACKET] = "}"; TerminalToStrMap[E] = "E"; TerminalToStrMap[IF] = "if"; TerminalToStrMap[LCBRACKET] = "("; TerminalToStrMap[RCBRACKET] = ")"; TerminalToStrMap[THEN] = "then"; TerminalToStrMap[ELSE] = "else"; TerminalToStrMap[ID] = "ID"; TerminalToStrMap[ASSIGN] = "="; TerminalToStrMap[LT] = "<"; TerminalToStrMap[LE] = "<="; TerminalToStrMap[GT] = ">"; TerminalToStrMap[GE] = ">="; TerminalToStrMap[EQ] = "=="; TerminalToStrMap[ADD] = "+"; TerminalToStrMap[MINUS] = "-"; TerminalToStrMap[MULTIPLE] = "*"; TerminalToStrMap[DIVIDE] = "/"; TerminalToStrMap[SEMICOLON] = ";"; TerminalToStrMap[MYINT] = "int"; TerminalToStrMap[INTNUM] = "INTNUM"; TerminalToStrMap[MYREAL] = "real"; TerminalToStrMap[REALNUM] = "REALNUM"; } void InitialProduction()//初始化产生式 { productions.push_back(Production(program, decls, compoundstmt)); productions.push_back(Production(decls, decl, SEMICOLON, decls)); productions.push_back(Production(decls, E)); productions.push_back(Production(decl, MYINT, ID, ASSIGN, INTNUM)); productions.push_back(Production(decl, MYREAL, ID, ASSIGN, REALNUM)); productions.push_back(Production(stmt, ifstmt)); productions.push_back(Production(stmt, assgstmt)); productions.push_back(Production(stmt, compoundstmt)); productions.push_back(Production(compoundstmt, LABRACKET, stmts, RABRACKET)); productions.push_back(Production(stmts, stmt, stmts)); productions.push_back(Production(stmts, E)); productions.push_back(Production(ifstmt, IF, LCBRACKET, boolexpr, RCBRACKET, THEN, stmt, ELSE, stmt)); productions.push_back(Production(assgstmt, ID, ASSIGN, arithexpr, SEMICOLON)); productions.push_back(Production(boolexpr, arithexpr, boolop, arithexpr)); productions.push_back(Production(boolop, LT)); productions.push_back(Production(boolop, GT)); productions.push_back(Production(boolop, LE)); productions.push_back(Production(boolop, GE)); productions.push_back(Production(boolop, EQ)); productions.push_back(Production(arithexpr, multexpr, arithexprprime)); productions.push_back(Production(arithexprprime, ADD, multexpr, arithexprprime)); productions.push_back(Production(arithexprprime, MINUS, multexpr, arithexprprime)); productions.push_back(Production(arithexprprime, E)); productions.push_back(Production(multexpr, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, MULTIPLE, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, DIVIDE, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, E)); productions.push_back(Production(simpleexpr, ID)); productions.push_back(Production(simpleexpr, INTNUM)); productions.push_back(Production(simpleexpr, REALNUM)); productions.push_back(Production(simpleexpr, LCBRACKET, arithexpr, RCBRACKET)); } void calculateFirst(Symbol s)//已优化,计算First数组同时维护ProductSentenceFormFirst(额外开销,时间复杂度级别不上升) { if (!First[s].empty()) return; // decide whether to append E in First(s) for (const auto& prod : productions) { if (s == prod.NT) { if (prod.isNullable == true) First[s].insert(E); } } // using production with left side of s to append X in First(s) int prod_num = 0; for (const auto& prod : productions) { if (s == prod.NT) { bool isAllNullable = true; int rSym_num = 0; for (const auto& X : prod.alpha) { calculateFirst(X); //add all in First(X) except E into first(s) for (unordered_set<Symbol>::iterator it = First[X].begin(); it != First[X].end(); it++) { if (*it != E) { First[s].insert(*it); //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i <= rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(*it); } } } // if E not in First(x) then break the inserting and set allNullable to false if (First[X].count(E) == 0) { isAllNullable = false; //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i < rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(E); } break; } rSym_num++; } //if allnullable, add E into First(s) if (isAllNullable) { First[s].insert(E); //优化4,维护ProductSentenceFormFirst数组 for (int i = 0; i < rSym_num; i++) { ProductSentenceFormFirst[prod_num][i].insert(E); } } } prod_num++; } } void InitialFirst() { //Initial First for Terminals for (int i = (int)(T + 1); i < (int)ENDDING; i++) { First[i].insert((Symbol)i); } for (int i = NT + 1; i < T; i++) { calculateFirst((Symbol)i); } } void InitialFollow()//由于Follow集合的计算是循环到终止,因此必须优化<-已优化 { Follow[program].insert(ENDDING); bool hasModified = true; while (hasModified) { hasModified = false; int prod_num = 0; for (const auto& prod : productions) {//appending into follow set for NT Symbol NT = prod.NT; for (int i = 0; i < prod.alpha.size(); i++) { Symbol Xi = prod.alpha[i]; if ((int)Xi < (int)T) {//for every Xi (NT) and scan its right side for appending //优化5:若ProductSentenceFormFirst已经被计算了则不重复计算 O(n^2)->O(n) if (i < prod.alpha.size() - 1 && ProductSentenceFormFirst[prod_num][i + 1].size() != 0) { for (unordered_set<Symbol>::iterator it = ProductSentenceFormFirst[prod_num][i + 1].begin(); it != ProductSentenceFormFirst[prod_num][i + 1].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } if (ProductSentenceFormFirst[prod_num][i + 1].count(E) != 0) { for (unordered_set<Symbol>::iterator it = Follow[NT].begin(); it != Follow[NT].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } } } else { bool isAllNullable = true; for (int j = i + 1; j < prod.alpha.size(); j++) {//for every xj right to Xi Symbol Xj = prod.alpha[j]; for (unordered_set<Symbol>::iterator it = First[Xj].begin(); it != First[Xj].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } if (First[Xj].count(E) == 0) { isAllNullable = false; break; } } if (isAllNullable)//right side of Xi is e or first(right side) has e { for (unordered_set<Symbol>::iterator it = Follow[NT].begin(); it != Follow[NT].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } } } } } prod_num++; } } } void ctrlFirstOpt() { if (!isFirstOpt) printf("\n"); isFirstOpt = false; } void InitialParsingTable() { memset(parsingTable, 0x3f, sizeof(parsingTable)); InitialFirst(); InitialFollow(); for (int prod_num = 0; prod_num < productions.size(); prod_num++) { const Production& prod = productions[prod_num]; Symbol A = prod.NT; // prod: A->X1X2X3... bool isAllNullable = true; //优化6:由于已经计算过每个产生式的右边句型的First集合,直接使用ProductSentenceFormFirst[prod_num][0] for (unordered_set<Symbol>::iterator it = ProductSentenceFormFirst[prod_num][0].begin(); it != ProductSentenceFormFirst[prod_num][0].end(); it++) { if (*it != E) { //if (parsingTable[A][*it] != inf) // cout << "conflict!!!!!!!!!!!!!!!!!!!!" << endl; parsingTable[A][*it] = prod_num; } } if (ProductSentenceFormFirst[prod_num][0].count(E) != 0) { for (unordered_set<Symbol>::iterator it = Follow[A].begin(); it != Follow[A].end(); it++) { if (*it != E) { //if (parsingTable[A][*it] != inf) // cout << "conflict!!!!!!!!!!!!!!!!!!!!" << endl; parsingTable[A][*it] = prod_num; } } } } } inline bool isInteger(const std::string& s) { if (s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false; char* p; strtol(s.c_str(), &p, 10); return (*p == 0); } inline bool isReal(const std::string& s) { return true; } /* 不要修改这个标准输入函数 */ void read_prog(string& prog) { char c; while (scanf("%c", &c) != EOF) { prog += c; } } /* 你可以添加其他函数 */ void Analysis() { string prog; read_prog(prog); /* 骚年们 请开始你们的表演 */ /********* Begin *********/ // initialization InitialMapping(); InitialProduction(); InitialParsingTable(); // LL1 parsing stack<Symbol> symbStack; vector<int> productionSeq; symbStack.push(ENDDING); symbStack.push(program); istringstream progin(prog); string line; int line_count = 0; // stacking while (getline(progin, line)) { line_count++; istringstream linein(line); string token; if (linein >> token) while (1) { Symbol inputSymb = StrToTerminalMap[token]; if (inputSymb == 0) { if(token.size()==1&&(token[0]>='a'&& token[0]<='z')) {//handle for id inputSymb = ID; } else if (isInteger(token)) { inputSymb = INTNUM; } else if (isReal(token)) { inputSymb = REALNUM; } } Symbol topSymb = symbStack.top(); if (topSymb < T) { //if on the stack is Non-Terminal //turning to parsing table int prod_num = parsingTable[topSymb][inputSymb]; if (prod_num != inf) { // pop symbStack.pop(); // push n Production prod = productions[prod_num]; for (int i = prod.alpha.size() - 1; i >= 0; i--) { if (prod.alpha[i] != E) { symbStack.push(prod.alpha[i]); } } // note production num productionSeq.push_back(prod_num); } else { //ERROR //skip all nonterminal symbStack.pop(); for (int k = 0; k < productions.size(); k++) { Production prod = productions[k]; if (prod.NT == topSymb && prod.alpha.size() == 1 && prod.alpha[0] == E) { productionSeq.push_back(k); break; } } } } else if (topSymb != ENDDING) { //if is terminal if (inputSymb == topSymb) { symbStack.pop(); if (!(linein >> token)) { break; } } else { //ERROR ctrlFirstOpt(); printf("语法错误,第%d行,缺少\"%s\"", line_count - 1, TerminalToStrMap[topSymb].c_str()); symbStack.pop(); } } else { break; } } } /********* End *********/ } <file_sep>/01-Lexical/01-Lexical/Source.cpp #include <stdio.h> #include <sstream> #include <iostream> #include <string> #include <map> #include <unordered_map> #include <ctype.h> using namespace::std; //--------------------------------------------------------------------------------------------------------------------- //key到编号的映射关系 enum class TAG { //keyword AUTO = 1, BREAK = 2, CASE = 3, CHAR = 4, CONST = 5, CONTINUE = 6, DEFAULT = 7, DO = 8, DOUBLE = 9, ELSE = 10, ENUM = 11, EXTERN = 12, FLOAT = 13, FOR = 14, GOTO = 15, IF = 16, INT = 17, LONG = 18, REGISTER = 19, RETURN = 20, SHORT = 21, SIGNED = 22, SIZEOF = 23, STATIC = 24, STRUCT = 25, SWITCH = 26, TYPEDEF = 27, UNION = 28, UNSIGNED = 29, VOID = 30, VOLATILE = 31, WHILE = 32, //op and boundary MINUS = 33, DECREMENT = 34, MINUSEQUAL = 35, ARROW = 36, NOT = 37, NE = 38, MOD = 39, MODEUQAL = 40, BITWISEAND = 41, AND = 42, BITWISEANDEQUAL = 43, LBRACKET = 44, RBRACKET = 45, MULTIPLY = 46, MULTIPLYEQUAL = 47, COMMA = 48, DOT = 49, DIVIDE = 50, DIVIDEEQUAL = 51, COLON = 52, SEMICOLON = 53, CONDTERNARY = 54, LSBRACKET = 55, RSBRACKET = 56, BITWISEEXCLUSIVEOR = 57, BITWISEEXCLUSIVEOREQUAL = 58, LCBRACKET = 59, BITWISEOR = 60, OR = 61, BITWISEOREQUAL = 62, RCBRACKET = 63, COMPLEMENT = 64, ADD = 65, INCREMENT = 66, ADDEQUAL = 67, LS = 68, LEFTSHIFT = 69, LEFTSHIFTEUQAL = 70, LE = 71, ASSIGN = 72, EQ = 73, GT = 74, GE = 75, RIGHTSHIFT = 76, RIGHTSHIFTEUQAL = 77, QUOTE = 78, COMMET = 79, NUM = 80, //id ID = 81, //ERROR ERROR = 251 }; //--------------------------------------------------------------------------------------------------------------------- //基类Token class Token { public: const TAG tag; string lexeme; Token(TAG t, string lex) :tag{ t } { lexeme = lex; } virtual void get() const//使用virtual方法输出 { printf("%s", lexeme.c_str()); } }; //常数:继承Token class Num:public Token { public: int value; Num(int n) :Token{ TAG::NUM,"" }, value{ n } { } virtual void get() const { printf("%d", value); } }; //自然数:继承Token class Real: public Token { public: float value; Real(float n) :Token{ TAG::NUM,"" }, value{ n } { } virtual void get() const { printf("%f", value); } }; //--------------------------------------------------------------------------------------------------------------------- //全局变量 unordered_map<string, Token> tokens;//保留字 char nextC=' ';//peek的字符 int pos =0;//peek的位置 int count_tokens = 1; bool isFirst = true; //--------------------------------------------------------------------------------------------------------------------- //存储保留字至map void saveToTokens(Token token) { tokens.insert(pair<string, Token>(token.lexeme, token)); } //保留字初始化 void tokens_init() { //keyword saveToTokens(Token(TAG::AUTO, "auto")); //AUTO = 1, saveToTokens(Token(TAG::BREAK, "break")); //BREAK = 2, saveToTokens(Token(TAG::CASE, "case")); //CASE = 3, saveToTokens(Token(TAG::CHAR, "char")); //CHAR = 4, saveToTokens(Token(TAG::CONST, "const")); //CONST = 5, saveToTokens(Token(TAG::CONTINUE, "continue")); //CONTINUE = 6, saveToTokens(Token(TAG::DEFAULT, "default")); //DEFAULT = 7, saveToTokens(Token(TAG::DO, "do")); //DO = 8, saveToTokens(Token(TAG::DOUBLE, "double")); //DOUBLE = 9, saveToTokens(Token(TAG::ELSE, "else")); //ELSE = 10, saveToTokens(Token(TAG::ENUM, "enum")); //ENUM = 11, saveToTokens(Token(TAG::EXTERN, "extern")); //EXTERN = 12, saveToTokens(Token(TAG::FLOAT, "float")); //FLOAT = 13, saveToTokens(Token(TAG::FOR, "for")); //FOR = 14, saveToTokens(Token(TAG::GOTO, "goto")); //GOTO = 15, saveToTokens(Token(TAG::IF, "if")); //IF = 16, saveToTokens(Token(TAG::INT, "int")); //INT = 17, saveToTokens(Token(TAG::LONG, "long")); //LONG = 18, saveToTokens(Token(TAG::REGISTER, "register")); //REGISTER = 19, saveToTokens(Token(TAG::RETURN, "return")); //RETURN = 20, saveToTokens(Token(TAG::SHORT, "short")); //SHORT = 21, saveToTokens(Token(TAG::SIGNED, "signed")); //SIGNED = 22, saveToTokens(Token(TAG::SIZEOF, "sizeof")); //SIZEOF = 23, saveToTokens(Token(TAG::STATIC, "staitc")); //STATIC = 24, saveToTokens(Token(TAG::STRUCT, "struct")); //STRUCT = 25, saveToTokens(Token(TAG::SWITCH, "switch")); //SWITCH = 26, saveToTokens(Token(TAG::TYPEDEF, "typedef")); //TYPEDEF = 27, saveToTokens(Token(TAG::UNION, "union")); //UNION = 28, saveToTokens(Token(TAG::UNSIGNED, "unsigned")); //UNSIGNED = 29, saveToTokens(Token(TAG::VOID, "void")); //VOID = 30, saveToTokens(Token(TAG::VOLATILE, "volatitle")); //VOLATILE = 31, saveToTokens(Token(TAG::WHILE, "while")); //WHILE = 32, } //--------------------------------------------------------------------------------------------------------------------- //程序读取:1返回next的实际字符 2位置右移 3更新peek的字符 char my_getc(string &prog) { if (pos >= (signed)(prog.length())) return EOF; else { char tc = prog[pos++]; if (pos >= (signed)(prog.length())) { nextC=EOF; } else { nextC = prog[pos]; } return tc; } } //确定性有限自动机运行方法 Token* my_run_NFA(string &prog) { bool isComment = false; //skip直到nextc不是/w符号 while (nextC != EOF) { if (nextC == ' ' || nextC == '\n' || nextC == '\t') { my_getc(prog); continue; } else { break; } } //如果nextc是EOF则终止,异常退出 if (nextC == EOF) { return new Token(TAG::ERROR, " "); } //取出真实的nextc并且nextc右移 char tempt_char = my_getc(prog); //界符&运算符的自动机 //trick:使用nextC=' '来占有nextC保证自动机跳过nextC的读取,否则不占有nextC保证自动机的读取 switch (tempt_char) { case '-': { if (nextC == '-') { nextC = ' '; return new Token(TAG::DECREMENT, "--"); } else if (nextC == '=') { nextC = ' '; return new Token(TAG::MINUSEQUAL, "-="); } else if (nextC == '>') { nextC = ' '; return new Token(TAG::ARROW, "->"); } else return new Token(TAG::MINUS, "-"); } case '!': { if (nextC == '=') { nextC = ' '; return new Token(TAG::NE, "!="); } else return new Token(TAG::NOT, "!"); } case '%': { if (nextC == '=') { nextC = ' '; return new Token(TAG::MODEUQAL, "%="); } else return new Token(TAG::MOD, "%"); } case '&': { if (nextC == '&') { nextC = ' '; return new Token(TAG::AND, "&&"); } else if (nextC == '=') { nextC = ' '; return new Token(TAG::BITWISEANDEQUAL, "&="); } else return new Token(TAG::BITWISEAND, "&"); } case '(': { return new Token(TAG::LBRACKET, "("); } case ')': { return new Token(TAG::RBRACKET, ")"); } case '*': { if (nextC == '=') { nextC = ' '; return new Token(TAG::MULTIPLYEQUAL, "*="); } else return new Token(TAG::MULTIPLY, "*"); } case ',': { return new Token(TAG::COMMA, ","); } case '.': { return new Token(TAG::DOT, "."); } case '/': { // comment的特殊处理 if (nextC == '=') { nextC = ' '; return new Token(TAG::DIVIDEEQUAL, "/="); } else if (nextC == '/' || nextC == '*') { //todo: we got two types of commets isComment = true; break; } else return new Token(TAG::DIVIDE, "/"); } case ':': { return new Token(TAG::COLON, ":"); } case ';': { return new Token(TAG::SEMICOLON, ";"); } case '?': { return new Token(TAG::CONDTERNARY, "?"); } case '[': { return new Token(TAG::LSBRACKET, "["); } case ']': { return new Token(TAG::RSBRACKET, "]"); } case '^': { if (nextC == '=') { nextC = ' '; return new Token(TAG::BITWISEEXCLUSIVEOREQUAL, "^="); } else return new Token(TAG::BITWISEEXCLUSIVEOR, "^"); } case '{': { return new Token(TAG::LCBRACKET, "{"); } case '}': { return new Token(TAG::RCBRACKET, "}"); } case '|': { if (nextC == '=') { nextC = ' '; return new Token(TAG::BITWISEANDEQUAL, "|="); } else if (nextC == '|') { nextC = ' '; return new Token(TAG::OR, "||"); } else return new Token(TAG::BITWISEAND, "|"); } case '~': { return new Token(TAG::COMPLEMENT, "~"); } case '+': { if (nextC == '=') { nextC = ' '; return new Token(TAG::ADDEQUAL, "+="); } else if (nextC == '+') { nextC = ' '; return new Token(TAG::INCREMENT, "++"); } else return new Token(TAG::ADD, "+"); } case '<': { if (nextC == '=') { nextC = ' '; return new Token(TAG::LE, "<="); } else if (nextC == '<') { my_getc(prog); if (nextC == '=') { nextC = ' '; return new Token(TAG::LEFTSHIFTEUQAL, "<<="); } else { return new Token(TAG::LEFTSHIFT, "<<"); } } else return new Token(TAG::LS, "<"); } case '=': { if (nextC == '=') { nextC = ' '; return new Token(TAG::EQ, "=="); } else return new Token(TAG::ASSIGN, "="); } case '>': { if (nextC == '=') { nextC = ' '; return new Token(TAG::GE, ">="); } else if (nextC == '>') { my_getc(prog); if (nextC == '=') { nextC = ' '; return new Token(TAG::RIGHTSHIFTEUQAL, ">>="); } else { return new Token(TAG::RIGHTSHIFT, ">>"); } } else return new Token(TAG::GT, ">"); } case '\"': { if (!isFirst) { printf("\n"); } else { isFirst = false; } printf("%d: <\",%d>\n", count_tokens,(int)TAG::QUOTE); count_tokens++; string s; while (nextC != '\"') { s += nextC; my_getc(prog); } printf("%d: <%s,%d>", count_tokens,s.c_str(), (int)TAG::ID); count_tokens++; nextC = ' '; return new Token(TAG::QUOTE, "\""); } } //comment的自动机 if (isComment) { if (nextC == '/') //comment { string s = "/"; while ((nextC) != '\n') { s += nextC; my_getc(prog); } nextC = ' '; return new Token(TAG::COMMET, s); } else // /*comment*/ { string s = "/*"; my_getc(prog); while (1) { if (nextC == '*') { s += nextC; my_getc(prog); if (nextC == '/') { s += nextC; break; } } else { s += nextC; my_getc(prog); } // consider EOF here ERROR } nextC = ' '; return new Token(TAG::COMMET, s); } } char nowChar = prog[pos - 1]; //标识符的自动机 if (isalpha(nowChar)) { string s; s += nowChar; while (isdigit(nextC) || isalpha(nextC)) { s += nextC; my_getc(prog); } //保留字判断 if (tokens.find(s) != tokens.end()) { return &tokens.at(s); } //否则返回标识符 else { return new Token(TAG::ID, s); } } //自然数与常数的自动机 if (isdigit(nowChar)) { int value = nowChar - '0'; //常数读取 while (isdigit(nextC)) { value = value * 10 + nextC - '0'; my_getc(prog); } //小数部分读取 if (nextC == '.') { float fvalue = value; float dividing = 10; my_getc(prog); while (isdigit(nextC)) { fvalue += (nowChar - '0' / dividing); dividing *= 10; my_getc(prog); } return new Real(fvalue); } else { return new Num(value); } } string errorMsg = ""; errorMsg += tempt_char; //不被自动机接受,返回异常 return new Token(TAG::ERROR, errorMsg); } //--------------------------------------------------------------------------------------------------------------------- /* 不要修改这个标准输入函数 */ void read_prog(string& prog) { char c; while (scanf("%c", &c) != EOF) { prog += c; } } /* 你可以添加其他函数 */ void Analysis() { string prog; read_prog(prog); /* 骚年们 请开始你们的表演 */ /********* Begin *********/ tokens_init(); pos = 0; nextC = prog[0]; Token* t_ptr = NULL; while ((t_ptr = my_run_NFA(prog))) { if (t_ptr->tag != TAG::ERROR) { if (!isFirst) { printf("\n"); } else { isFirst = false; } printf("%d: <", count_tokens); t_ptr->get(); printf(",%d>", (int)t_ptr->tag); count_tokens++; } else { break; } } /********* End *********/ } //--------------------------------------------------------------------------------------------------------------------- int main() { Analysis(); return 0; } <file_sep>/02-LL Parser/01-Lexical/LLparser_old.h #pragma once // C语言词法分析器 #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <string> #include <fstream> #include <sstream> #include <vector> #include <unordered_map> #include <unordered_set> #include <stack> using namespace std; const int inf = 0x3f3f3f3f; enum Symbol { NT, //Non-terminal program, stmt, compoundstmt, stmts, ifstmt, whilestmt, assgstmt, boolexpr, boolop, arithexpr, arithexprprime, multexpr, multexprprime, simpleexpr, T, //Terminal LABRACKET, RABRACKET, E, IF, LCBRACKET, RCBRACKET, THEN, ELSE, WHILE, ID, ASSIGN, LT, LE, GT, GE, EQ, ADD, MINUS, MULTIPLE, DIVIDE, NUM, SEMICOLON, //end ENDDING }; class Production { public: Symbol NT; vector<Symbol> alpha; bool isNullable; Production(Symbol nt, Symbol a1, Symbol a2 = ENDDING, Symbol a3 = ENDDING, Symbol a4 = ENDDING, Symbol a5 = ENDDING, Symbol a6 = ENDDING, Symbol a7 = ENDDING, Symbol a8 = ENDDING) { NT = nt; alpha.push_back(a1); if (a2 != ENDDING)alpha.push_back(a2); if (a3 != ENDDING)alpha.push_back(a3); if (a4 != ENDDING)alpha.push_back(a4); if (a5 != ENDDING)alpha.push_back(a5); if (a6 != ENDDING)alpha.push_back(a6); if (a7 != ENDDING)alpha.push_back(a7); if (a8 != ENDDING)alpha.push_back(a8); isNullable = false; if (a1 == E || a2 == E || a3 == E || a4 == E || a6 == E || a7 == E || a8 == E || a5 == E) isNullable = true; } }; unordered_map<string, Symbol> StrToTerminalMap; //static string TerminalToStrMap[ENDDING]; //static vector<Production> productions; //static unordered_set<Symbol> First[ENDDING]; //pre-computed unordered_set<Symbol> Follow[T]; // pre-computed int parsingTable[ENDDING+1][ENDDING+1]; bool isFirstOpt = true; bool globalParam = false; extern int dataa[T - NT - 1][ENDDING - T]; void InitialMapping() { // mapping from T string to T StrToTerminalMap.insert(std::pair<string, Symbol>("{", LABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("}", RABRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("E", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("e", E)); StrToTerminalMap.insert(std::pair<string, Symbol>("if", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("If", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("IF", IF)); StrToTerminalMap.insert(std::pair<string, Symbol>("(", LCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>(")", RCBRACKET)); StrToTerminalMap.insert(std::pair<string, Symbol>("then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("Then", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("THEN", THEN)); StrToTerminalMap.insert(std::pair<string, Symbol>("else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("Else", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ELSE", ELSE)); StrToTerminalMap.insert(std::pair<string, Symbol>("while", WHILE)); StrToTerminalMap.insert(std::pair<string, Symbol>("While", WHILE)); StrToTerminalMap.insert(std::pair<string, Symbol>("WHILE", WHILE)); StrToTerminalMap.insert(std::pair<string, Symbol>("ID", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("Id", ID)); StrToTerminalMap.insert(std::pair<string, Symbol>("=", ASSIGN)); StrToTerminalMap.insert(std::pair<string, Symbol>("<", LT)); StrToTerminalMap.insert(std::pair<string, Symbol>("<=", LE)); StrToTerminalMap.insert(std::pair<string, Symbol>(">", GT)); StrToTerminalMap.insert(std::pair<string, Symbol>(">=", GE)); StrToTerminalMap.insert(std::pair<string, Symbol>("==", EQ)); StrToTerminalMap.insert(std::pair<string, Symbol>("+", ADD)); StrToTerminalMap.insert(std::pair<string, Symbol>("-", MINUS)); StrToTerminalMap.insert(std::pair<string, Symbol>("*", MULTIPLE)); StrToTerminalMap.insert(std::pair<string, Symbol>("/", DIVIDE)); StrToTerminalMap.insert(std::pair<string, Symbol>("NUM", NUM)); StrToTerminalMap.insert(std::pair<string, Symbol>("num", NUM)); StrToTerminalMap.insert(std::pair<string, Symbol>(";", SEMICOLON)); // mapping for NT to NT str TerminalToStrMap[program] = "program"; TerminalToStrMap[stmt] = "stmt"; TerminalToStrMap[compoundstmt] = "compoundstmt"; TerminalToStrMap[stmts] = "stmts"; TerminalToStrMap[ifstmt] = "ifstmt"; TerminalToStrMap[whilestmt] = "whilestmt"; TerminalToStrMap[assgstmt] = "assgstmt"; TerminalToStrMap[boolexpr] = "boolexpr"; TerminalToStrMap[boolop] = "boolop"; TerminalToStrMap[arithexpr] = "arithexpr"; TerminalToStrMap[arithexprprime] = "arithexprprime"; TerminalToStrMap[multexpr] = "multexpr"; TerminalToStrMap[multexprprime] = "multexprprime"; TerminalToStrMap[simpleexpr] = "simpleexpr"; // mapping for T to T str TerminalToStrMap[LABRACKET] = "{"; TerminalToStrMap[RABRACKET] = "}"; TerminalToStrMap[E] = "E"; TerminalToStrMap[IF] = "if"; TerminalToStrMap[LCBRACKET] = "("; TerminalToStrMap[RCBRACKET] = ")"; TerminalToStrMap[THEN] = "then"; TerminalToStrMap[ELSE] = "else"; TerminalToStrMap[WHILE] = "while"; TerminalToStrMap[ID] = "ID"; TerminalToStrMap[ASSIGN] = "="; TerminalToStrMap[LT] = "<"; TerminalToStrMap[LE] = "<="; TerminalToStrMap[GT] = ">"; TerminalToStrMap[GE] = ">="; TerminalToStrMap[EQ] = "=="; TerminalToStrMap[ADD] = "+"; TerminalToStrMap[MINUS] = "-"; TerminalToStrMap[MULTIPLE] = "*"; TerminalToStrMap[DIVIDE] = "/"; TerminalToStrMap[NUM] = "NUM"; TerminalToStrMap[SEMICOLON] = ";"; } void InitialProduction() { productions.push_back(Production(program,compoundstmt)); productions.push_back(Production(stmt,ifstmt)); productions.push_back(Production(stmt, whilestmt)); productions.push_back(Production(stmt, assgstmt)); productions.push_back(Production(stmt, compoundstmt)); productions.push_back(Production(compoundstmt , LABRACKET, stmts , RABRACKET)); productions.push_back(Production(stmts, stmt, stmts)); productions.push_back(Production(stmts,E)); productions.push_back(Production(ifstmt , IF, LCBRACKET,boolexpr,RCBRACKET, THEN, stmt, ELSE ,stmt)); productions.push_back(Production(whilestmt , WHILE, LCBRACKET,boolexpr,RCBRACKET, stmt)); productions.push_back(Production(assgstmt,ID, ASSIGN, arithexpr,SEMICOLON)); productions.push_back(Production(boolexpr,arithexpr, boolop ,arithexpr)); productions.push_back(Production(boolop , LT )); productions.push_back(Production(boolop,GT)); productions.push_back(Production(boolop,LE)); productions.push_back(Production(boolop,GE)); productions.push_back(Production(boolop,EQ)); productions.push_back(Production(arithexpr,multexpr ,arithexprprime)); productions.push_back(Production(arithexprprime , ADD, multexpr ,arithexprprime)); productions.push_back(Production(arithexprprime, MINUS, multexpr, arithexprprime)); productions.push_back(Production(arithexprprime, E)); productions.push_back(Production(multexpr , simpleexpr , multexprprime)); productions.push_back(Production(multexprprime , MULTIPLE, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, DIVIDE, simpleexpr, multexprprime)); productions.push_back(Production(multexprprime, E)); productions.push_back(Production(simpleexpr , ID)); productions.push_back(Production(simpleexpr, NUM)); productions.push_back(Production(simpleexpr, LCBRACKET ,arithexpr,RCBRACKET)); } void calculateFirst(Symbol s) { if (!First[s].empty()) return; // decide whether to append E in First(s) for (const auto & prod : productions) { if (s == prod.NT) { if (prod.isNullable == true) First[s].insert(E); } } // using production with left side of s to append X in First(s) for (const auto & prod : productions) { if (s == prod.NT) { bool isAllNullable = true; for (const auto& X : prod.alpha) { calculateFirst(X); //add all in First(X) except E into first(s) for (unordered_set<Symbol>::iterator it = First[X].begin(); it != First[X].end(); it++) { if (*it != E) { First[s].insert(*it); } } // if E not in First(x) then break the inserting and set allNullable to false if (First[X].count(E) == 0) { isAllNullable = false; break; } } //if allnullable, add E into First(s) if (isAllNullable) First[s].insert(E); } } } void InitialFirst() { //Initial First for Terminals for (int i = (int)(T + 1); i < (int)ENDDING; i++) { First[i].insert((Symbol)i); } for (int i = NT + 1; i < T; i++) { calculateFirst((Symbol)i); } } void InitialFollow() { Follow[program].insert(ENDDING); bool hasModified = true; while (hasModified) { hasModified = false; for (const auto & prod : productions) {//appending into follow set for NT Symbol NT = prod.NT; for (int i = 0; i < prod.alpha.size(); i++) { Symbol Xi = prod.alpha[i]; if ((int)Xi < (int)T) {//for every Xi (NT) and scan its right side for appending bool isAllNullable = true; for (int j = i + 1; j < prod.alpha.size(); j++) {//for every xj right to Xi Symbol Xj= prod.alpha[j]; for (unordered_set<Symbol>::iterator it = First[Xj].begin(); it != First[Xj].end(); it++) { if (*it != E && Follow[Xi].count(*it)==0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } if (First[Xj].count(E) == 0) { isAllNullable = false; break; } } if (isAllNullable)//right side of Xi is e or first(right side) has e { for (unordered_set<Symbol>::iterator it = Follow[NT].begin(); it != Follow[NT].end(); it++) { if (*it != E && Follow[Xi].count(*it) == 0)//not E and not existing in Follow(Xi) { Follow[Xi].insert(*it); hasModified = true; } } } } } } } } void ctrlFirstOpt() { if (!isFirstOpt) printf("\n"); isFirstOpt = false; } void outputParsingTree(vector<int>& seq,int level,int& index ) { if (index>=seq.size()||seq[index] >= productions.size()) return; Production prod = productions[seq[index++]]; //left side ctrlFirstOpt(); for (int i = 0; i < level; i++) { printf( "\t"); } printf( "%s", TerminalToStrMap[prod.NT].c_str()); //right side level++; for (int x_num = 0; x_num < prod.alpha.size(); x_num++) { Symbol X = prod.alpha[x_num]; if (X < T) // non-terminal { outputParsingTree(seq, level, index); } else // terminal { ctrlFirstOpt(); for (int i = 0; i < level; i++) { printf( "\t"); } printf( "%s", TerminalToStrMap[X].c_str()); } } } void InitialParsingTable() { memset(parsingTable, 0x3f, sizeof(parsingTable)); if (globalParam) { /*for (int i = NT+1; i < T; i++) { for (int j = T+1; j <= ENDDING; j++) { if (dataa[i - NT - 1][j - T - 1] != -1) { parsingTable[i][j] = dataa[i - NT - 1][j - T - 1]; } } }*/ } else { InitialFirst(); InitialFollow(); for (int prod_num = 0; prod_num < productions.size(); prod_num++) { const Production& prod = productions[prod_num]; Symbol A = prod.NT; // prod: A->X1X2X3... bool isAllNullable = true; for (const auto& X : prod.alpha) { //add all in First(X) except E into first(s) for (unordered_set<Symbol>::iterator it = First[X].begin(); it != First[X].end(); it++) { if (*it != E) { parsingTable[A][*it] = prod_num; } } // if E not in First(x) then break the inserting and set allNullable to false if (First[X].count(E) == 0) { isAllNullable = false; break; } } if (isAllNullable) { for (unordered_set<Symbol>::iterator it = Follow[A].begin(); it != Follow[A].end(); it++) { if (*it != E) { parsingTable[A][*it] = prod_num; } } } } } } /* 不要修改这个标准输入函数 */ void read_prog(string& prog) { char c; while (scanf("%c", &c) != EOF) { prog += c; } } /* 你可以添加其他函数 */ void Analysis() { string prog; read_prog(prog); /* 骚年们 请开始你们的表演 */ /********* Begin *********/ // initialization InitialMapping(); InitialProduction(); InitialParsingTable(); // LL1 parsing stack<Symbol> symbStack; vector<int> productionSeq; symbStack.push(ENDDING); symbStack.push(program); istringstream progin(prog); string line; int line_count = 0; // stacking while(getline(progin, line)) { line_count++; istringstream linein(line); string token; if(linein >> token) while (1) { Symbol inputSymb = StrToTerminalMap[token]; Symbol topSymb = symbStack.top(); if (topSymb < T) { //if on the stack is Non-Terminal //turning to parsing table int prod_num = parsingTable[topSymb][inputSymb]; if (prod_num != inf) { // pop symbStack.pop(); // push n Production prod = productions[prod_num]; for (int i = prod.alpha.size() - 1; i >= 0; i--) { if (prod.alpha[i] != E) { symbStack.push(prod.alpha[i]); } } // note production num productionSeq.push_back(prod_num); } else { //ERROR //skip all nonterminal symbStack.pop(); for (int k = 0; k < productions.size(); k++) { Production prod = productions[k]; if (prod.NT == topSymb && prod.alpha.size() == 1 && prod.alpha[0] == E) { productionSeq.push_back(k); break; } } } } else if (topSymb != ENDDING) { //if is terminal if (inputSymb == topSymb) { symbStack.pop(); if (!(linein >> token)) { break; } } else { //ERROR ctrlFirstOpt(); printf("语法错误,第%d行,缺少\"%s\"", line_count-1, TerminalToStrMap[topSymb].c_str()); symbStack.pop(); } } else { break; } } } int level = 0; int index = 0; outputParsingTree(productionSeq, level, index); /********* End *********/ } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //int dataa[T - NT - 1][ENDDING - T] = //{ //{0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, //{4,-1,-1,1,-1,-1,-1,-1,2,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, //{5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, //{6,7,-1,6,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, //{-1,-1,-1,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, //{-1,-1,-1,-1,-1,-1,-1,-1,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, //{-1,-1,-1,-1,-1,-1,-1,-1,-1,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, //{-1,-1,-1,-1,11,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1}, //{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,14,13,15,16,-1,-1,-1,-1,-1,-1,-1}, //{-1,-1,-1,-1,17,-1,-1,-1,-1,17,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,17,-1,-1}, //{-1,-1,-1,-1,-1,20,-1,-1,-1,-1,-1,20,20,20,20,20,18,19,-1,-1,-1,20,-1}, //{-1,-1,-1,-1,21,-1,-1,-1,-1,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,-1,-1}, //{-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,24,24,24,24,24,24,24,22,23,-1,24,-1}, //{-1,-1,-1,-1,27,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,-1,-1} //};<file_sep>/README.md # Compiler-FrontEnd The front end of a simple compiler ## Lexical Analyzer - Input ```C++ int main() { printf("HelloWorld"); return 0; } ``` - Output ``` 1: <int,17> 2: <main,81> 3: <(,44> 4: <),45> 5: <{,59> 6: <printf,81> 7: <(,44> 8: <",78> 9: <HelloWorld,81> 10: <",78> 11: <),45> 12: <;,53> 13: <return,20> 14: <0,80> 15: <;,53> 16: <},63> ``` ## LL Parser - input ```C++ { ID = NUM ; } ``` - output ``` program compoundstmt { stmts stmt assgstmt ID = arithexpr multexpr simpleexpr NUM multexprprime E arithexprprime E ; stmts E } ``` ## LR Parser - input ```C++ { ID = NUM ; } ``` - output ``` program => compoundstmt => { stmts } => { stmt stmts } => { stmt } => { assgstmt } => { ID = arithexpr ; } => { ID = multexpr arithexprprime ; } => { ID = multexpr ; } => { ID = simpleexpr multexprprime ; } => { ID = simpleexpr ; } => { ID = NUM ; } ``` ## Translation Scheme - input ```C++ int a = 1 ; int b = 2 ; real c = 3.0 ; { a = a + 1 ; b = b * a ; if ( a < b ) then c = c / 2 ; else c = c / 4 ; } ``` - output ```C++ a: 2 b: 4 c: 1.5 ``` ## Note - implement with C++
3c907a545b68670d4e9782ec3ced60f3e51afa2f
[ "Markdown", "C++" ]
6
C++
whaleeej/Compiler-FrontEnd
dc2ba930edca6e81210a829fe4344f77fdd63254
045369382d8f773e1302b5e298dd19ffe287eaed
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Hosting; using Server.Hubs; namespace Server.BackgroundServices { public class TickWorker : BackgroundService { private readonly IHubContext<TickHub, ITick> tickHub; private readonly int delay = 1000; private int tick; public TickWorker(IHubContext<TickHub, ITick> tickHub) { this.tickHub = tickHub; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { tick += delay; await tickHub.Clients.All.OnTickReceived(tick); await Task.Delay(delay, stoppingToken); } } } } <file_sep>using System; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client; namespace Client { public class Program { public static async Task Main(string[] args) { var url = args[0]; var connection = new HubConnectionBuilder() .WithUrl(url) .WithAutomaticReconnect() .Build(); connection.On("OnTickReceived", (int tick) => { Console.WriteLine($"tick: {tick}"); }); connection.On("OnConnected", () => { Console.WriteLine("Connected..."); }); await connection.StartAsync(); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Server.Hubs { public interface ITick { Task OnConnected(); Task OnTickReceived(int tick); } } <file_sep>using System; using System.Timers; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Timer = System.Timers.Timer; namespace Server.Hubs { public class TickHub : Hub<ITick> { public override async Task OnConnectedAsync() { await Clients.All.OnConnected(); } } }
3b76787c9e665a0f6dade8502ee304af56d2fbf3
[ "C#" ]
4
C#
lydongcanh/signalr-redis-backplane
2a4a6189fbf6c466900ef75a7c75ef7308541027
32969c547245c0359ea0868bc2a00fe2dc3d01d1
refs/heads/master
<file_sep>from selenium import webdriver import time import requests from bs4 import BeautifulSoup as BS import re import string import pandas as pd driver = webdriver.Chrome('chromedriver.exe') searchAddress = "https://tgstat.ru/search" driver.get(searchAddress) time.sleep(3) driver.find_element_by_id('q').send_keys("cloud.mail.ru") time.sleep(2) # driver.find_element_by_id("termsconditions").click() # driver.find_element_by_xpath('//*[@id="Искать"]').click() # class="btn btn-primary search-button" driver.find_element_by_css_selector('[class="btn btn-primary search-button"]').click() time.sleep(2) html = driver.page_source.encode('utf-8') #html = BS(html, 'html.parser') html = BS(html, 'lxml') items = html.find_all('figure', {'class': 'post-container'}) print(items) forum = [] for item in items: dostupno = '' # item.find('h3', class_='title').find('a', 'prefixLink').find('span', class_='prefix prefixSecondary') # title = item.find('div', class_='channel-post-title').get_text(strip=True) # title = item.find('div', class_='float-right').find('a','title') # title = item.find('div', class_='float-left').find('a').get('title') title = item.find('a', class_='channel-post-title').string link = item.find('div', class_='post-body') # link = link.replace('<mark>', '') # link = link.replace('</mark>', '') # pattern = r'<\/mark>\s*"(.*?)"' pattern = r'\/mark&gt;\s*(.*?)"' m = '' try: m = re.search(pattern, str(link)) print(m.group(1)) except: m = '' cloud_link = 'https://cloud.mail.ru' + m.group(1) forum.append( { 'title_post': title, 'link': cloud_link # 'date_time': date_time, # 'dostupno_sklad': item.find('h3', class_='title').find('a', 'prefixLink').find('span', class_='prefix prefixSecondary') # 'dostupno_sklad': dostupno } ) print(forum)
9952822c4bb245cca6d59e269c579653c11eed85
[ "Python" ]
1
Python
wwwparser/tgstat-rybalka
62140592371f142415d768cc93d45bf40c7f084b
347d3e89ae6c5a5d51eeff1f0d0318a091d4651a
refs/heads/master
<repo_name>Glenlexry/DS-convertion-react<file_sep>/src/App.js import React, {Component} from 'react'; // images/videos const products = [ {id: 1, img: '/static/media/frontpage.1b525a86.jpg'}, {id: 2, img: '', vid:'asset/img/digitalsymphony.mov'} ]; const getProductImageStyle = product => ({ background: 'url(' + products[0].img +')' }); class App extends Component { render() { return (<div className="App"> <div> <a onclick="slidePage.index(1)"> <div className="logo animated fadeIn"/> </a> <nav className="navbar animated fadeIn"> <div className="ambege ambege-spring" data-click-state={1}> <div className="ambege-box"> <div className="ambege-inner"/> </div> </div> </nav> <div className="menu-page animated hide zoomOut"> <div className="nav"> <ul> <li> <a href="./aboutus"> <p className="menu-link">ABOUT US</p> <p className="menu-desc">WHO WE ARE</p> </a> </li> <li> <a href="./work"> <p className="menu-link">WORK</p> <p className="menu-desc">OUR PORTFOLIO</p> </a> </li> <li> <a href="./services"> <p className="menu-link">SERVICES</p> <p className="menu-desc">WHAT WE DO</p> </a> </li> <li> <a href="./contact"> <p className="menu-link">CONTACT</p> <p className="menu-desc">CONTACT INFO</p> </a> </li> <li> <div className="social-link oren"> <a href="https://www.facebook.com/digitalsymp/" target="_blank"> <i className="fa fa-facebook"/> </a> <a href="https://www.linkedin.com/in/digital-symphony-45baa7134/" target="_blank"> <i className="fa fa-linkedin"/> </a> </div> </li> </ul> </div> </div> <div className="slidePage-container animated fadeIn" id="slidePage-container"> <div className="item active" style={{ overflow: 'hidden' }}> <div className="page1" style={getProductImageStyle(products[0])}> <div className="row"> <div className="col-xs-12"> <div className="content-wrap"> <div className="content"> <div className="animated slideInDown" data-delay={250}> <p className="heading">Orchestrating Digital</p> </div> <div className="animated slideInUp" data-delay={250}> <div className="container"> <div className="row"> <div className="col-xs-6 col-md-6 p-r-0 p-sm-l-0"> <p className="subheading text-right m-b-0"> We are a </p> </div> <div className="col-xs-6 col-md-6 p-l-0"> <span id="flipper" className="subheading flip"> <span className="word step0 set">data</span> <span className="word step1">customer</span> <span className="word step2">results </span> </span> </div> <div className="col-xs-12 col-md-12"> <p className="subheading m-t-0">first performance agency</p> </div> </div> </div> </div> </div> </div> </div> </div> <div className="scroll-down animated slideInUp hidden-xs"> <a onclick="slidePage.index(2)"> <span>SCROLL TO EXPLORE</span> <i className="icon-hexa-light"/> <i className="icon-arrow-down animated flash infinite"/> </a> </div> </div> </div> <div className="item"> <div className="page2"> <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div className="content-wrap"> <div className="content"> <div className="animated slideInLeft"> <p className="heading">Turning Clicks <br/>To SPA’S</p> </div> <div className="animated slideInLeft" data-delay={250}> <p className="subheading">Biji Living by Conlay Property</p> </div> <div className="clearfix"/> <div className="animated slideInUp" data-delay={500}> <div className="btn-border-light" onclick="window.location.href='biji-casestudy';"> <div className="btn-border-light-inner" onclick="window.location.href='biji-casestudy';"> <a href="biji-casestudy">LEARN MORE</a> </div> </div> </div> </div> </div> </div> </div> <footer className="animated slideInDown hidden-xs"> <div className="row"> <div className="col-lg-3 pull-right"> <div className="social-link"> <a href="https://www.linkedin.com/in/digital-symphony-45baa7134/" target="_blank"> <i className="fa fa-linkedin"/> </a> <a href="https://www.facebook.com/digitalsymp/" target="_blank"> <i className="fa fa-facebook"/> </a> </div> </div> <div className="col-lg-9 pull-left"> <p>© 2018 <span>Digital Symphony</span> All Rights Reserved.</p> </div> </div> </footer> </div> <div className="item"> <div className="page3"> <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div className="content-wrap"> <div className="content"> <div className="animated slideInLeft"> <p className="heading">Converting Audience <br/> to Foot Traffic</p> </div> <div className="animated slideInLeft" data-delay={250}> <p className="subheading">Melawati Mall by CapitaLand</p> </div> <div className="clearfix"/> <div className="animated slideInUp" data-delay={500}> <div className="btn-border-light" onclick="window.location.href='melawati-casestudy';"> <div className="btn-border-light-inner" onclick="window.location.href='melawati-casestudy';"> <a href="melawati-casestudy">LEARN MORE</a> </div> </div> </div> </div> </div> </div> </div> <footer className="animated slideInDown hidden-xs"> <div className="row"> <div className="col-lg-3 pull-right"> <div className="social-link"> <a href="https://www.linkedin.com/in/digital-symphony-45baa7134/" target="_blank"> <i className="fa fa-linkedin"/> </a> <a href="https://www.facebook.com/digitalsymp/" target="_blank"> <i className="fa fa-facebook"/> </a> </div> </div> <div className="col-lg-9 pull-left"> <p>© 2018 <span>Digital Symphony</span> All Rights Reserved.</p> </div> </div> </footer> </div> <div className="item"> <div className="page4"> <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div className="content-wrap"> <div className="content"> <div className="animated slideInLeft"> <p className="heading">It’s The Process <br/> Not The Industry</p> </div> <div className="animated slideInLeft" data-delay={250}> <p className="subheading">Solution building is a science</p> </div> <div className="animated slideInUp" data-delay={500}> <div className="btn-border-light" onclick="window.location.href='services';"> <div className="btn-border-light-inner" onclick="window.location.href='services';"> <a href="services">OUR SERVICES</a> </div> </div> </div> </div> </div> </div> </div> <footer className="animated slideInDown hidden-xs"> <div className="row"> <div className="col-lg-3 pull-right"> <div className="social-link"> <a href="https://www.linkedin.com/in/digital-symphony-45baa7134/" target="_blank"> <i className="fa fa-linkedin"/> </a> <a href="https://www.facebook.com/digitalsymp/" target="_blank"> <i className="fa fa-facebook"/> </a> </div> </div> <div className="col-lg-9 pull-left"> <p>© 2018 <span>Digital Symphony</span> All Rights Reserved.</p> </div> </div> </footer> </div> {/* <div class="item"> <div class="page4"> <div class="container-fluid"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <div class="content-wrap"> <div class="content"> <div class="animated slideInLeft"> <p class="heading">It’s The Process <br>Not The Industry</p> </div> <div class="animated slideInLeft" data-delay="250"> <p class="subheading">Accurate methods and tools allow us to customise business conscious solutions across business verticals and industries.</p> </div> <div class="clearfix"></div> <div class="animated slideInUp" data-delay="500"> <div class="btn-border-light" onclick="window.location.href='services.html';"> <div class="btn-border-light-inner" onclick="window.location.href='services.html';"> <a href="services.html">LEARN MORE</a> </div> </div> </div> </div> </div> </div> <div class="col-lg-5 col-md-5 col-sm-5 hidden-xs"> <div class="content-wrap"> <div class="content"> <div class="row"> <div class="col-sm-6 m-b animated slideInDown" data-delay="300"> <div class="app"> <i class="icon-rocket"></i> </div> <p class="app-heading">DIGITAL <br>MARKETING</p> </div> <div class="col-sm-6 m-b animated slideInDown"> <div class="app"> <i class="icon-all-arrow"></i> </div> <p class="app-heading">APPLICATION <br>DEVELOPMENT</p> </div> <div class="col-sm-6 animated slideInUp" data-delay="300"> <div class="app"> <i class="icon-two-slide"></i> </div> <p class="app-heading">DIGITAL <br>CONSULT</p> </div> <div class="col-sm-6 animated slideInUp"> <div class="app"> <i class="icon-mobile"></i> </div> <p class="app-heading">MOBILE <br>APPLICATION</p> </div> </div> </div> </div> </div> </div> </div> </div> <footer class="animated slideInDown hidden-xs"> <div class="row"> <div class="col-lg-3 pull-right"> <div class="social-link"> <a href="https://www.linkedin.com/in/digital-symphony-45baa7134/" target="_blank"> <i class="fa fa-linkedin"></i> </a> <a href="https://www.facebook.com/digitalsymp/" target="_blank"> <i class="fa fa-facebook"></i> </a> </div> </div> <div class="col-lg-9 pull-left"> <p>&copy; 2018 <span>Digital Symphony</span> All Rights Reserved.</p> </div> </div> </footer> </div> */ } <nav className="desktop-nav pagination hidden-xs" id="pagination"> <ul> <li> <a onclick="slidePage.index(1)"> <div className="page-label">HOME</div> <hr className="solid white"/> </a> </li> <li> <a onclick="slidePage.index(2)"> <div className="page-label">CASE STUDY 1</div> <hr className="solid white"/> </a> </li> <li> <a onclick="slidePage.index(3)"> <div className="page-label">CASE STUDY 2</div> <hr className="solid white"/> </a> </li> <li> <a onclick="slidePage.index(4)"> <div className="page-label">OUR SERVICES</div> <hr className="solid white"/> </a> </li> </ul> </nav> <nav className="mobile-nav visible-xs"> <ul> <li> <a onclick="slidePage.index(1)"/> </li> <li> <a onclick="slidePage.index(2)"/> </li> <li> <a onclick="slidePage.index(3)"/> </li> <li> <a onclick="slidePage.index(4)"/> </li> </ul> </nav> </div> </div> </div>); } } export default App; <file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import './css/style.css'; import './css/bootstrap.min.css'; import './css/font-awesome.min.css'; import './css/iconmoon.css'; import './css/slidePage.css'; import './css/animate.css'; import './css/responsive.css'; import './css/noise.css'; import $ from 'jquery'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker(); <file_sep>/src/js/functions.js var desktop = $("#pagination"); var mobile = $(".mobile-nav"); var a = "a"; var active = "active"; desktop.find(a).eq(0).addClass(active); mobile.find(a).eq(0).addClass(active); slidePage.init({ before: function(index, direction, target) { if (direction == "next") { if (target == 1) { slidePage.fire(2); } $(".item").removeClass(active).eq(index).addClass(active); desktop.find(a).removeClass(active).eq(index).addClass(active); mobile.find(a).removeClass(active).eq(index).addClass(active); } else if (direction == "prev") { $(".item").removeClass(active).eq(target - 1).addClass(active); desktop.find(a).removeClass(active).eq(target - 1).addClass(active); mobile.find(a).removeClass(active).eq(target - 1).addClass(active); } }, after: function(index, direction, target) {}, useAnimation: true, refresh: true, useWheel: true, speed: 1250 }); $(".ambege").click(function() { $(this).toggleClass("is-active"); $(".menu-page").toggleClass("hide",250).toggleClass("zoomIn").toggleClass("zoomOut"); });<file_sep>/src/js/slidePage.js (function($) { var page = location.search ? urlToObject(location.search).page : 1; var opt = { index: page, pageContainer: ".item", after: function() {}, before: function() {}, speed: false, refresh: false, useWheel: true, useKeyboard: true, useAnimation: true }; var after = true; var delay = true; var keyIndex = opt.index - 1; var defaultSpeed = $(opt.pageContainer) .css("transition-duration") .replace("s", "") * 1000; var pageCount = $(opt.pageContainer).length; var windowH = window.innerHeight; var direction = ""; var removedIndex = ""; var removedPages = {}; window.slidePage = { init: function(option, callback) { $.extend(opt, option); initDom(opt); initEvent(opt); callback && callback.call(this); }, index: function(index) { if (index > 0 && index != keyIndex + 1) { index = parseInt(index) - 1; var endheight = $(".item") .eq(index) .children() .height(); var offset = endheight - windowH > 20 ? 1 : 0; if (index > keyIndex) { for (var i = keyIndex; i < index; i++) { nextPage($(opt.pageContainer).eq(i)); isScroll(i + 2, offset); slideScroll(i + 2); } } else if (index < keyIndex) { for (var i = keyIndex; i >= index + 1; i--) { prevPage($(opt.pageContainer).eq(i)); isScroll(i, offset); slideScroll(i); } } keyIndex = index; } return keyIndex; }, next: function() { if (keyIndex < pageCount - 1) { var item = $(opt.pageContainer).eq(keyIndex++); nextPage(item); isScroll(item.index() + 2); slideScroll(item.index() + 2); delay = false; } }, prev: function() { if (keyIndex > 0) { var item = $(opt.pageContainer).eq(keyIndex--); prevPage(item); isScroll(item.index()); slideScroll(item.index()); delay = false; } }, fire: function(index) { fireAnimate(index); }, remove: function(index, callback) { if (!removedIndex.match(index)) { pageCount--; if (keyIndex > index) { keyIndex--; } removedIndex = index + "," + removedIndex; removedPages[index] = $(opt.pageContainer) .eq(index - 1) .remove(); callback && callback(); } }, recover: function(index, callback) { if (removedIndex.match(index)) { removedIndex = removedIndex.replace(index + ",", ""); if (index >= pageCount) { $(opt.pageContainer) .eq(pageCount - 1) .after(removedPages[index]); } else { $(opt.pageContainer) .eq(index - 1) .before(removedPages[index]); } if (keyIndex > index) { keyIndex++; } pageCount++; if (direction == "prev") { obj.prevSlide(removedPages[index]); } else { obj.prevSlide(removedPages[index]); } callback && callback(); } }, canNext: true, canPrev: true, isScroll: false }; var obj = { nextSlide: function(item) { item.css({ transform: "translate3d(0px, -100%, 0px)", "-webkit-transform": "translate3d(0px,-100%, 0px)" }); var css = translate("0"); item.next().css(css); }, prevSlide: function(item) { item .prev() .css({ "-webkit-transform": "scale(1)", transform: "scale(1)" }); item.css(translate("100%")); }, showSlide: function(item) { item.css({ "-webkit-transform": "scale(1)", transform: "scale(1)" }); item.next().css(translate("100%")); } }; function IsPC() { var userAgentInfo = navigator.userAgent; var Agents = [ "Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod" ]; var flag = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag; } function translate(y) { return { "-webkit-transform": "translate3d(0px, " + y + " 0px)", transform: "translate3d(0px, " + y + ", 0px)" }; } function pageActive() { if (opt.refresh && delay && opt.useAnimation) { $(opt.pageContainer) .eq(keyIndex) .find(".animated") .addClass("hide"); $(opt.pageContainer) .eq(keyIndex) .find(".lazy") .addClass("hide"); } } function urlToObject(url) { var urlObject = {}; if (/\?/.test(url)) { var urlString = url.substring(url.indexOf("?") + 1); var urlArray = urlString.split("&"); for (var i = 0, len = urlArray.length; i < len; i++) { var urlItem = urlArray[i]; var item = urlItem.split("="); urlObject[item[0]] = item[1]; } return urlObject; } } function nextPage(item) { direction = "next"; if (item.next().length) { currentItem = item.next(); orderStep(item.next(), direction); obj.nextSlide(item); } else { obj.showSlide(item); } keyindex = $(opt.pageContainer).index(item); opt.before(item.index() + 1, direction, item.index() + 2); pageActive(); } function prevPage(item) { direction = "prev"; if (item.prev().length) { currentItem = item.prev(); orderStep(item.prev(), direction); obj.prevSlide(item); item .prev() .prev() .css(translate("-100%")); } else { obj.showSlide(item); } opt.before(item.index() + 1, direction, item.index()); keyindex = $(opt.pageContainer).index(item); pageActive(); } function initDom(opt) { if (!!opt.speed) { $(opt.pageContainer).css({ "transition-duration": opt.speed + "ms", "-webkit-transition-duration": opt.speed + "ms" }); } slidePage.index(opt.index); if (!!opt.useAnimation) { var items = $(opt.pageContainer); items.find(".animated").addClass("hide"); items.find(".lazy").addClass("hide"); orderStep(items.eq(opt.index - 1)); } } function orderStep(dom, delays) { after = true; setTimeout(function() { delay = delays || delay; }, opt.speed || defaultSpeed); var steps = $(dom).find(".animated"); steps.each(function(index, item) { var time = $(item).attr("data-delay") || 100; setTimeout(function() { $(item).removeClass("hide"); }, time); }); } function fireAnimate(index) { var item = $(opt.pageContainer).eq(index - 1); var lazy = item.find(".lazy"); lazy.each(function(i, item) { var time = $(item).attr("data-delay") || 100; setTimeout(function() { $(item).removeClass("hide"); }, time); }); } function isScroll(target, offset) { var offset = offset === 0 ? 0 : false || 1; var itemheight = $(".item") .eq(target - 1) .children() .height(); if (itemheight - windowH > 20) { var isNext = direction == "next"; !isNext ? $(opt.pageContainer) .eq(target - 1) .scrollTop(itemheight - windowH - offset) : $(opt.pageContainer) .eq(target - 1) .scrollTop(offset); } } function slideScroll(target) { var itemheight = $(".item") .eq(target - 1) .children() .height(); if (itemheight - windowH > 20) { $(opt.pageContainer) .eq(target - 1) .on("scroll", function(e) { var isBottom = itemheight == this.scrollTop + windowH; var isTop = this.scrollTop == 0; slidePage.canSlide = isBottom || isTop; slidePage.canPrev = isTop && !isBottom; slidePage.canNext = isBottom && !isTop; slidePage.isScroll = !slidePage.canSlide; }); } else { slidePage.canPrev = true; slidePage.canNext = true; slidePage.canSlide = true; slidePage.isScroll = false; } } function initEvent(opt) { function wheelFunc(e) { var e = e || window.event; if (e.wheelDeltaY < 0 || e.wheelDelta < 0 || e.detail > 0) { slidePage.canNext && delay && slidePage.next(); } else if (e.wheelDeltaY > 0 || e.wheelDelta > 0 || e.detail < 0) { slidePage.canPrev && delay && slidePage.prev(); } } if (!!opt.useWheel) { document.onmousewheel = wheelFunc; document.addEventListener && document.addEventListener("DOMMouseScroll", wheelFunc, false); } if (!!opt.useKeyboard) { document.onkeydown = function(e) { if (e.keyCode == "40" && delay && keyIndex < pageCount - 1) { slidePage.canNext && slidePage.next(); } else if (e.keyCode == "38" && delay && keyIndex > 0) { slidePage.canPrev && slidePage.prev(); } }; } var touchY = 0; document .getElementById("slidePage-container") .addEventListener("touchstart", function(e) { touchY = e.touches[0].clientY; }); document .getElementById("slidePage-container") .addEventListener("touchmove", function(e) { var offsetY = e.touches[0].clientY - touchY; !slidePage.canPrev && offsetY > 5 && (slidePage.isScroll = true); !slidePage.canNext && offsetY < -5 && (slidePage.isScroll = true); !slidePage.isScroll && e.preventDefault(); }); $(opt.pageContainer).on({ swipeUp: function() { slidePage.canNext && slidePage.next(); }, swipeDown: function() { slidePage.canPrev && slidePage.prev(); } }); $(opt.pageContainer).on("transitionend webkitTransitionEnd", function( event ) { var removedLength = removedIndex.split(",").length; if (after) { if (removedLength > 1) { opt.after( direction == "next" ? keyIndex + 1 : keyIndex + 2, direction, keyIndex + 2 ); } else { opt.after( direction == "next" ? keyIndex : keyIndex + 2, direction, keyIndex + 1 ); } after = false; } }); } })($);
73c912f03c932240ea7dbac698cc93518d6a7d94
[ "JavaScript" ]
4
JavaScript
Glenlexry/DS-convertion-react
35fb4c412ce5bf3c2ae4bfcf79baac2266f9f18a
71e96a28f339f492746f2d594b2c498722c1aa44
refs/heads/master
<file_sep>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Configuration; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.Azure.Cosmos; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Planetzine.Common { public class Article { public const string CollectionId = "articles"; public const string PartitionKey = "/author"; [JsonProperty("id")] public Guid ArticleId { get; set; } [JsonProperty("heading")] [Required] public string Heading { get; set; } [JsonProperty("imageUrl")] public string ImageUrl { get; set; } [JsonProperty("body")] [Required] [AllowHtml] public string Body { get; set; } [JsonProperty("tags")] public string[] Tags { get; set; } [JsonProperty("author")] [Required] public string Author { get; set; } [JsonProperty("publishDate")] [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime PublishDate { get; set; } [JsonProperty("lastUpdate")] [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime LastUpdate { get; set; } [JsonIgnore] public string Excerpt => Body.RemoveHtmlTags().GetBeginning(300); [JsonIgnore] public string PublishDateStr => PublishDate.ToString("MMMM dd, yyyy").Capitalize(); [JsonIgnore] public string TagsStr => string.Join(",", Tags); [JsonIgnore] public bool IsNew => ArticleId == Guid.Empty; public static Article New() { return new Article { ArticleId = Guid.Empty, Heading = "Article Heading", ImageUrl = "/Images/earth-11015_640.jpg", Body = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed congue ultrices nulla nec malesuada. Etiam vitae risus sit amet dolor ultrices eleifend nec et nisi. Praesent pharetra egestas tortor ut faucibus. Suspendisse blandit nisi eu convallis consequat. Morbi ipsum nisl, viverra id eleifend et, semper gravida risus. Nunc eu erat vel elit feugiat suscipit. Maecenas turpis magna, bibendum vel lectus ac, fermentum tristique ipsum. Proin quis ipsum pretium, lacinia risus a, maximus turpis. Vivamus eu volutpat nibh, in sollicitudin purus.</p>\r\n", Tags = new[] { "Azure", "Cloud", "Microsoft" }, Author = "Anonymous", PublishDate = DateTime.Now, LastUpdate = DateTime.Now }; } public async Task Create() { await DbHelper.CreateDocumentAsync(this, CollectionId); } public async static Task Create(IEnumerable<Article> articles) { foreach (var article in articles) await article.Create(); } public async Task Upsert() { await DbHelper.UpsertDocumentAsync(this, this.Author, CollectionId); } public async Task Delete() { await DbHelper.DeleteDocumentAsync<Article>(ArticleId.ToString(), Author, CollectionId); } public static async Task<Article> Read(Guid articleId) { var article = await DbHelper.GetDocumentAsync<Article>(articleId.ToString(), null, CollectionId); return article; } public static async Task<Article> Read(Guid articleId, string author) { var article = await DbHelper.GetDocumentAsync<Article>(articleId.ToString(), author, CollectionId); return article; } public static async Task<Article[]> GetAll() { var articles = await DbHelper.ExecuteQueryAsync<Article>(CollectionId, new QueryDefinition("SELECT * FROM articles")); return articles; } public static async Task<Article[]> SearchByAuthor(string author) { var articles = await DbHelper.ExecuteQueryAsync<Article>(CollectionId, new QueryDefinition("SELECT * FROM articles AS a WHERE lower(a.author) = @author") .WithParameter("@author", author.ToLower()) , author); return articles; } public static async Task<Article[]> SearchByTag(string tag) { string sql = $"SELECT * FROM articles AS a WHERE ARRAY_CONTAINS(a.tags, '{tag}')"; var articles = await DbHelper.ExecuteQueryAsync<Article>(CollectionId, new QueryDefinition(sql)); return articles; } public static async Task<Article[]> SearchByFreetext(string freetext) { string sql = $"SELECT * FROM articles AS a WHERE CONTAINS(UPPER(a.body), '{freetext.ToUpper()}')"; var articles = await DbHelper.ExecuteQueryAsync<Article>(CollectionId, new QueryDefinition(sql)); return articles; } public async static Task<long> GetNumberOfArticles() { var articleCount = await DbHelper.ExecuteScalarQueryAsync<dynamic>("SELECT VALUE COUNT(1) FROM articles", Article.CollectionId, null); return articleCount; } public static Task<Article[]> GetRadnomArticles() { return WikipediaReader.DownloadRandomWikipediaArticles(25); } public async static Task<Article[]> GetSampleArticles(string[] titles) { var articles = new ConcurrentQueue<Article>(); var list = new List<Task>(); foreach (var title in titles) { list.Add(WikipediaReader.GenerateArticleFromWikipedia(title) .ContinueWith(t => articles.Enqueue(t.Result))); } await Task.WhenAll(list); return articles.ToArray(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Threading.Tasks; using System.Configuration; using HibernatingRhinos.Profiler.Appender.Cosmos; using Microsoft.Azure.Cosmos; using System.Runtime.InteropServices; namespace Planetzine.Common { public class DbHelper { public static readonly string DatabaseId; public static readonly int InitialThroughput; public static readonly int MaxConnectionLimit; public static readonly ConsistencyLevel ConsistencyLevel; public static readonly string EndpointUrl; public static readonly string AuthKey; public static string CurrentRegion; public static CosmosClient Client; public static double RequestCharge; static DbHelper() { // Init basic settings DatabaseId = ConfigurationManager.AppSettings["DatabaseId"]; InitialThroughput = int.Parse(ConfigurationManager.AppSettings["InitialThroughput"]); MaxConnectionLimit = int.Parse(ConfigurationManager.AppSettings["MaxConnectionLimit"]); ConsistencyLevel = (ConsistencyLevel)Enum.Parse(typeof(ConsistencyLevel), ConfigurationManager.AppSettings["ConsistencyLevel"]); EndpointUrl = ConfigurationManager.AppSettings["EndpointURL"]; AuthKey = ConfigurationManager.AppSettings["AuthKey"]; } /// <summary> /// Init() method must be called before using any other methods on DbHelper. Creates the DocumentClient. /// </summary> /// <returns></returns> public static async Task InitAsync() { CurrentRegion = GetCurrentAzureRegion(); Client = new CosmosClient(EndpointUrl, AuthKey, new CosmosClientOptions { ConsistencyLevel = ConsistencyLevel, ConnectionMode = (ConnectionMode) Enum.Parse(typeof(ConnectionMode), ConfigurationManager.AppSettings["ConnectionMode"]), EnableTcpConnectionEndpointRediscovery = true, //GatewayModeMaxConnectionLimit = MaxConnectionLimit, MaxRetryAttemptsOnRateLimitedRequests = 10, MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(10), ApplicationPreferredRegions = new List<string> {await GetNearestAzureReadRegionAsync()} }); CosmosDBProfiler.Initialize(Client); } private static async Task<IEnumerable<AccountRegion>> GetAvailableAzureReadRegionsAsync() { using (var client = new CosmosClient(EndpointUrl, AuthKey)) { var account = await client.ReadAccountAsync(); return account.ReadableRegions; } } private static string GetCurrentAzureRegion() { return Environment.GetEnvironmentVariable("REGION_NAME") ?? "local"; } private static async Task<string> GetNearestAzureReadRegionAsync() { var regions = (await GetAvailableAzureReadRegionsAsync()).ToDictionary(region => region.Name); var currentRegion = GetCurrentAzureRegion(); // If there is a readable location in the current region, chose it if (regions.ContainsKey(currentRegion)) return currentRegion; // Otherwise just pick the first region // TODO: Replace this with some logic that selects a more optimal read region (for instance using a table) return regions.Values.First().Name; } public static async Task CreateDatabaseAsync() { await Client.CreateDatabaseIfNotExistsAsync(DatabaseId); } public static async Task CreateCollectionAsync(string collectionId, string partitionKey) { var database = Client.GetDatabase(DatabaseId); await database.CreateContainerIfNotExistsAsync( new ContainerProperties(collectionId, partitionKey), InitialThroughput); } public static async Task DeleteDatabaseAsync() { await Client.GetDatabase(DatabaseId).DeleteAsync(); } public static async Task CreateDocumentAsync(object document, string collectionId) { var response = await Client.GetDatabase(DatabaseId).GetContainer(collectionId) .CreateItemAsync(document); RequestCharge += response.RequestCharge; } public static async Task UpsertDocumentAsync(object document, string partitionKey, string collectionId) { var response = await Client.GetDatabase(DatabaseId).GetContainer(collectionId) .UpsertItemAsync(document, new PartitionKey(partitionKey)); RequestCharge += response.RequestCharge; } public static async Task<ItemResponse<T>> GetDocumentAsync<T>(string documentId, string partitionKey, string collectionId) { var response = await Client.GetDatabase(DatabaseId).GetContainer(collectionId) .ReadItemAsync<T>(documentId, new PartitionKey(partitionKey)); RequestCharge += response.RequestCharge; return response; } public static async Task DeleteDocumentAsync<T>(string documentId, string partitionKey, string collectionId) { var response = await Client.GetDatabase(DatabaseId).GetContainer(collectionId) .DeleteItemAsync<T>(documentId, new PartitionKey(partitionKey)); RequestCharge += response.RequestCharge; } public static async Task DeleteAllDocumentsAsync<T>(string collectionId) { string sql = $"SELECT c.id, c.partitionId FROM {collectionId} AS c"; var documents = await ExecuteQueryAsync<dynamic>(collectionId, new QueryDefinition(sql)); foreach (var document in documents) { await DeleteDocumentAsync<T>(document.id, document.partitionId, collectionId); } } public static async Task<T[]> ExecuteQueryAsync<T>(string collectionId, QueryDefinition query, string partitionKey = null) { var requestOptions = new QueryRequestOptions(); if (partitionKey != null) requestOptions.PartitionKey = new PartitionKey(partitionKey); var q = Client.GetDatabase(DatabaseId).GetContainer(collectionId) .GetItemQueryIterator<T>(query, requestOptions: requestOptions); var results = new List<T>(); while (q.HasMoreResults) { var items = await q.ReadNextAsync(); results.AddRange(items); RequestCharge += items.RequestCharge; } return results.ToArray(); } public static async Task<T> ExecuteScalarQueryAsync<T>(string sql, string collectionId, string partitionKey) { var queryRequestOptions = new QueryRequestOptions(); if (partitionKey != null) queryRequestOptions.PartitionKey = new PartitionKey(partitionKey); var query = Client.GetDatabase(DatabaseId).GetContainer(collectionId) .GetItemQueryIterator<T>(new QueryDefinition(sql), requestOptions: queryRequestOptions); var results = new List<T>(); while (query.HasMoreResults) { var items = await query.ReadNextAsync(); results.AddRange(items); RequestCharge += items.RequestCharge; } return results[0]; } public static void ResetRequestCharge() { RequestCharge = 0.0d; } public static string Diagnostics() { var results = $"Server name: {Environment.GetEnvironmentVariable("APPSETTING_WEBSITE_SITE_NAME") ?? "local"} <br/>"; results += $"Region: {CurrentRegion} <br/>"; results += $"Total RequestCharge: {RequestCharge:f2} <br/>"; results += $"EndpointUrl: {EndpointUrl} <br/>"; results += $"ServiceEndpoint: {Client.Endpoint} <br/>"; results += $"ConsistencyLevel: {Client.ClientOptions.ConsistencyLevel} <br/>"; results += $"ConnectionMode: {Client.ClientOptions.ConnectionMode} <br/>"; results += $"MaxConnectionLimit: {Client.ClientOptions.GatewayModeMaxConnectionLimit} <br/>"; results += $"PreferredLocations: {string.Join(", ", Client.ClientOptions.ApplicationPreferredRegions)} <br/>"; return results; } } }
3d510f9dc345a413a37f1c86dbfd37715c992a36
[ "C#" ]
2
C#
ayende/Planetzine
1566977e2c8990923e008dbacec6232badb654bc
c1d41a9f838a101e394cb3a7704d83309c1eef45
refs/heads/master
<repo_name>Mayank-MP05/LoGeek_Sai_Hospital<file_sep>/implant-rehabitation.php <!DOCTYPE html> <html class="no-js"> <head> <title>Implant Rehabilitation Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Implant Rehabilitation Treatment</h3> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Implant Rehabilitation Treatment</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <p>Implant-supported rehabilitation is that aspect of dentistry that permits dental rehabilitation, the maintenance of mastication function and the patient’s appearance by replacing one or more teeth with a crown or prosthesis supported by osteointegrated implants.</p> <h4>Symptoms :</h4> <ul> <li>The gums are swollen around the implant</li> <li>The gums around the implant are red or a blue-purple color, which is evidence of inflammation</li> <li>The gums around the implant bleed at the gum line when brushing</li> <li>The area around the implant is sensitive or painful</li> <li>Pus is coming from the area around the implant</li> <li>The threads of the implant post are visible</li> <li>The implant is loose</li> </ul> <h4>Procedure :</h4> <ul> <li>Laser treatment to eliminate infection</li> <li>Antibiotic therapy</li> <li>Bone grafting to replace lost bone</li> <li>Building back the gum line with gum grafting</li> <li>Growth proteins to accelerate and enhance healing</li> <li>Low-level laser therapy to stimulate healing and reduce discomfort</li> <li>Replacing a failed implant</li> </ul> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/review.php <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Best Dental Clinic in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <![endif]--> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="css/gallery.css"> <!--<link rel="stylesheet" href="css/fonts.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script>--> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <script src="js/vendor/jquery-1.12.4.min.js"></script> <![endif]--> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <div class="row bg-color"> <h4>Customer Reviews</h4> <p>“A customer talking about their experience with you is worth ten times that which you write or say about yourself.”</p> </div> <div class="container"> <div class="card col-12 bg-dark text-center review-card border "> <div class="card-header"> <h4>Amazing and humble doctor!</h4> </div> <hr> <div class="card-body"> <p class="card-text">Took my Mom for dentures. Amazing and humble doctor with good explanation skills. Would highly recommend especially if you have senior citizens.</p> </div> <hr> <div>Sujeet</div> </div> <div class="card col-12 bg-dark text-center review-card border "> <div class="card-header"> <h4>Amazing and humble doctor!</h4> </div> <hr> <div class="card-body"> <p class="card-text">Took my Mom for dentures. Amazing and humble doctor with good explanation skills. Would highly recommend especially if you have senior citizens.</p> </div> <hr> <div>Sujeet</div> </div> <div class="card col-12 bg-dark text-center review-card border "> <div class="card-header"> <h4>Amazing and humble doctor!</h4> </div> <hr> <div class="card-body"> <p class="card-text">Took my Mom for dentures. Amazing and humble doctor with good explanation skills. Would highly recommend especially if you have senior citizens.</p> </div> <hr> <div>Sujeet</div> </div> <div class="card col-12 bg-dark text-center review-card border "> <div class="card-header"> <h4>Amazing and humble doctor!</h4> </div> <hr> <div class="card-body"> <p class="card-text">Took my Mom for dentures. Amazing and humble doctor with good explanation skills. Would highly recommend especially if you have senior citizens.</p> </div> <hr> <div>Sujeet</div> </div> <div class="card col-12 bg-dark text-center review-card border "> <div class="card-header"> <h4>Amazing and humble doctor!</h4> </div> <hr> <div class="card-body"> <p class="card-text">Took my Mom for dentures. Amazing and humble doctor with good explanation skills. Would highly recommend especially if you have senior citizens.</p> </div> <hr> <div>Sujeet</div> </div> <div class="card col-12 bg-dark text-center review-card border "> <div class="card-header"> <h4>Amazing and humble doctor!</h4> </div> <hr> <div class="card-body"> <p class="card-text">Took my Mom for dentures. Amazing and humble doctor with good explanation skills. Would highly recommend especially if you have senior citizens.</p> </div> <hr> <div>Sujeet</div> </div> </div> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/README.md # LoGeek_Sai_Hospital Task List 1. #Bug - About Page Footer Two times bug fix 2. #Bug - All Service pages footer bug fix 3. #Creativity - Curved div for All Service Pages 4. #Creativity - SYMPTOMS and PROCEDURE one some creative bootstrap styling 5. #DesignAndDevelop - Complete Gallery Page 6. #Bug - Blog link redirect fix 7. #DesignAndDevelop - Complete Contact-us Page 8. #DesignAndDevelop - Complete Appointment Page ## Task Breakdown : # Bugs : #1,#2,#6 # Creativity : #3,#4 # DesignAndDevelop : #5,#7,#8 <file_sep>/contact-us.php <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Best Dental Clinic in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <![endif]--> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="./css/contact-us.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sctions --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/contact.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Contact Us</h3> </div> <!--<div class="intro-layer" data-animation="slideExpandUp"> <p class="fontsize_20">If your smile is not becoming to you, then you should be coming to me! Family dentistry with a woman’s touch.</p> <a href="appointment.html" class="theme_button color1">Make an Appointment</a> </div>--> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12 text-center"> <h2 class="section_header margin_0 h1-responsive font-weight-bold text-center my-4">Contact / Appointment Form </h2> <hr class="main_bg_color dividersize_2_70 inline-block"> <section class="mb-4"> <!--Section description--> <p class="text-center w-responsive mx-auto mb-5">Do you have any questions? Please do not hesitate to contact us directly. Our team will come back to you within a matter of hours to help you.</p> <div class="row"> <!--Grid column--> <div class="col-md-9 mb-md-0 mb-5"> <form id="contact-form" name="contact-form" action="" method="POST"> <!--Grid row--> <div class="row"> <!--Grid column--> <div class="col-md-6"> <div class="md-form mb-0"> <input type="text" id="name" name="name" class="form-control"> <label for="name" class="">Your name</label> </div> </div> <!--Grid column--> <!--Grid column--> <div class="col-md-6"> <div class="md-form mb-0"> <input type="text" id="email" name="email" class="form-control"> <label for="email" class="">Your Phone<label> </div> </div> <!--Grid column--> </div> <!--Grid row--> <!--Grid row--> <div class="row"> <div class="col-md-12"> <div class="md-form mb-0"> <input type="text" id="subject" name="subject" class="form-control"> <label for="subject" class="">Reason for visit</label> </div> </div> </div> <!--Grid row--> <!--Grid row--> <div class="row"> <!--Grid column--> <div class="col-md-12"> <div class="md-form"> <textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea"></textarea> <label for="message">Notes for Docter</label> </div> </div> </div> <!--Grid row--> </form> <div class="text-center text-md-right"> <a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a> </div> <div class="status"></div> </div> <!--Grid column--> <!--Grid column--> <div class="col-md-3 text-center"> <ul class="list-unstyled mb-0"> <li> <img src="./images/location.png" class="image-icon" alt=""> <p>211 - PCMC , Pune</p> </li> <li> <img src="./images/phone-pnh.jpg" class="image-icon" alt=""> <p>+ 01 234 567 89</p> </li> <li> <img src="./images/gmail-png.png" class="image-icon" alt=""> <p><EMAIL></p> </li> </ul> </div> <!--Grid column--> </div> </section> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/faq.php <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Best Dental Clinic in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <![endif]--> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="css/gallery.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <div class="row bg-color"> <h4>Frequently Asked Questions</h4> </div> <div class="container"> <ul class="list-group"> <li class="faq-tab list-group-item">Cras justo odio</li> <li class="faq-tab list-group-item">Dapibus ac facilisis in</li> <li class="faq-tab list-group-item">Morbi leo risus</li> <li class="faq-tab list-group-item">Porta ac consectetur ac</li> <li class="faq-tab list-group-item">Vestibulum at eros</li> <li class="faq-tab list-group-item">Dapibus ac facilisis in</li> <li class="faq-tab list-group-item">Morbi leo risus</li> <li class="faq-tab list-group-item">Porta ac consectetur ac</li> <li class="faq-tab list-group-item">Vestibulum at eros</li> </ul> </div> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> <script src="./js/faq.js"></script> </body> </html><file_sep>/cosmetic-aesthetic-dentistry.php <!DOCTYPE html> <html class="no-js"> <head> <title>Cosmetic/ Aesthetic Dentistry Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="./css/service-card.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li class="list-group-item"> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Cosmetic/ Aesthetic Dentistry</h3> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Cosmetic/ Aesthetic Dentistry</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <!--<p>Dental implants are replacement tooth roots. Implants provide a strong foundation for fixed (permanent) or removable replacement teeth that are made to match your natural teeth.</p>--> <p>Dentistry is no longer just a case of filling and taking out teeth. Nowadays many people turn to cosmetic dentistry, or ‘aesthetic dentistry', as a way of improving their appearance.</p> <div class="row"> <div class="card col-sm-12 col-md-6 border border-primary"><h4>Types :</h4> <ul class="list-group"> <li class="list-group-item">Inlays and Onlays : These are also known as indirect fillings, which are made by a dental laboratory, and they are used when a tooth has mild to moderate decay or there is not enough tooth structure to support a filling. Provided there is no damage to the tooth cusps, according to Choice One Dental Care, the inlay is placed directly onto the tooth surface. When the cusp or a greater portion of the tooth is damaged, however, an onlay is used instead to cover the tooth's entire surface.</li> <li class="list-group-item">Composite Bonding : Composite bonding refers to the repair of decayed, damaged or discolored teeth using material that resembles the color of tooth enamel. Your dentist drills out the tooth decay and applies the composite onto the tooth's surface, then "sculpts" it into the right shape before curing it with a high-intensity light. Also referred to as simply "bonding," per the Consumer Guide to Dentistry, this effectively covers the damage to the tooth and gives the appearance of a healthy tooth in its place. Bonding is one of the least expensive cosmetic dentistry procedures available to patients with tooth decay, chipped or cracked teeth and worn-down edges.</li> <li class="list-group-item">Dental Veneers : Typically manufactured from medical-grade ceramic, dental veneers are made individually for each patient to resemble one's natural teeth, according to Bruce Wilderman, DDS. They look exceptionally realistic and can resolve numerous cosmetic problems, ranging from crooked teeth, to cracked or damaged enamel to noticeable gaps between two teeth. The dentist applies the veneer to the front of each tooth using a dental adhesive.</li> <li class="list-group-item">Teeth Whitening : One of the most basic cosmetic dentistry procedures, teeth whitening or teeth bleaching can be performed at your dentist's office. Whitening should occur after plaque, tartar and other debris are cleaned from the surface of each tooth, restoring their natural appearance. </li> <li class="list-group-item">Implants : Dental implants are used to replace teeth after tooth loss. The dentist inserts a small titanium screw into the jaw at the site of the missing tooth, which serves as the support for a crown. These implants are almost indistinguishable from the surrounding natural teeth, and once the bone and supporting tissue fuse to the implant, they are permanently secured into place. </li> </ul></div> <div class="card col-sm-12 col-md-6 border border-primary"> <h4>Procedure :</h4> <ul class="list-group"> <li class="list-group-item">Dental Bonding: The application of tooth-colored composite to the teeth. The bonding material can then be polished and shaped to look like the rest of the teeth.</li> <li class="list-group-item">Gum Contouring: Do you have a gummy smile or uneven gum line? Gum contouring treatments can reshape your gum line to produce a more beautiful smile.</li> <li class="list-group-item">Porcelain Veneers: Ceramic shells applied to the front of the teeth to conceal cracks and chips, overlay gaps, and create a whiter appearance to a person's smile.</li> <li class="list-group-item">Teeth Whitening: There are two methods for whitening teeth: laser teeth whitening (performed in the cosmetic dentist's office) and at-home teeth bleaching (involving the use of take-home bleaching kits).</li> </ul> </div> </div> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/about.php <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Best Dental Clinic in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <![endif]--> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <!--<link rel="stylesheet" href="css/fonts.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script>--> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <script src="js/vendor/jquery-1.12.4.min.js"></script> <![endif]--> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>About Us</h3> </div> <!--<div class="intro-layer" data-animation="slideExpandUp"> <p class="fontsize_20">If your smile is not becoming to you, then you should be coming to me! Family dentistry with a woman’s touch.</p> <a href="appointment.html" class="theme_button color1">Make an Appointment</a> </div>--> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12 text-center"> <h2 class="section_header margin_0">What we are</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> <p>Shree Sai Dental Clinic And Implant Center is known for housing experienced Dentists. Dr. <NAME>, a well-reputed Dentist, practices in Thane. Visit this medical health centre for Dentists recommended by 100 patients.</p> <p>Customer service is provided by a highly trained, professional staff who look after your comfort and care and are considerate of your time. Their focus is you.</p> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/root-canals.php <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Root Canals Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <![endif]--> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="./css/service-card.css"> <!--<link rel="stylesheet" href="css/fonts.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script>--> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <script src="js/vendor/jquery-1.12.4.min.js"></script> <![endif]--> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Root Canals</h3> </div> <!--<div class="intro-layer" data-animation="slideExpandUp"> <p class="fontsize_20">If your smile is not becoming to you, then you should be coming to me! Family dentistry with a woman’s touch.</p> <a href="appointment.html" class="theme_button color1">Make an Appointment</a> </div>--> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Root Canals</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <p>Root canal treatment or endodontic treatment is necessary when the centre part within the tooth, known as the pulp, housing the blood vessels, nerves and living connective tissues, become infected or inflamed.</p> <p>The root canal procedure is performed to save a damaged or badly infected tooth, instead of extracting it. This procedure is performed by an endodontist or a root canal specialist.</p> <div class="row"> <div class="card col-sm-12 col-md-6 border border-primary"> <h4 class="card-header">Symptoms :</h4> <ul class="list-group"> <li class="list-group-item">Severe toothache pain upon chewing or application of pressure.</li> <li class="list-group-item">Prolonged sensitivity (pain) to hot or cold temperatures (after the heat or cold has been removed)</li> <li class="list-group-item">Discoloration (darkening) of the tooth.</li> <li class="list-group-item">Swelling and tenderness in nearby gums.</li> </ul> </div> <div class="card col-sm-12 col-md-6 border border-primary "> <h4>Procedure :</h4> <ul class="list-group"> <li class="list-group-item" >Step 1 - Placing the rubber dam.</li> <li class="list-group-item">Step 2 - Creating the access cavity.</li> <li class="list-group-item">Step 3 - Measuring the length of the tooth.</li> <li class="list-group-item">Step 4 - Cleaning and shaping the tooth's root canals.</li> <li class="list-group-item">Step 5 - Sealing the tooth.</li> </ul> </div> </div> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/our-team.php <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Best Dental Clinic in kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <![endif]--> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="./css/card-style.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/docter-bgimg.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Our Team</h3> </div> <!--<div class="intro-layer" data-animation="slideExpandUp"> <p class="fontsize_20">If your smile is not becoming to you, then you should be coming to me! Family dentistry with a woman’s touch.</p> <a href="appointment.html" class="theme_button color1">Make an Appointment</a> </div>--> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12 text-center"> <h2 class="section_header margin_0">Know who we are</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> <p>"Individual commitment to a group effort--that is what makes a team work, a company work, a society work, a civilization work."</p> <p>Customer service is provided by a highly trained, professional staff who look after your comfort and care and are considerate of your time. Their focus is you.</p> <div class="container"> <div class="row"> <!--team-1--> <div class="col-lg-4"> <div class="our-team-main"> <div class="team-front"> <img src="http://placehold.it/110x110/9c27b0/fff?text=Parag" class="img-fluid" /> <h3>Dr. <NAME></h3> <p>Head Dental Design</p> </div> <div class="team-back"> <span> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque. </span> </div> </div> </div> <!--team-1--> <!--team-2--> <div class="col-lg-4"> <div class="our-team-main"> <div class="team-front"> <img src="http://placehold.it/110x110/336699/fff?text=Dilip" class="img-fluid" /> <h3><NAME></h3> <p>Facial neurologist</p> </div> <div class="team-back"> <span> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque. </span> </div> </div> </div> <!--team-2--> <!--team-3--> <div class="col-lg-4"> <div class="our-team-main"> <div class="team-front"> <img src="http://placehold.it/110x110/607d8b/fff?text=Rajesh" class="img-fluid" /> <h3><NAME></h3> <p>Cosmo Expert</p> </div> <div class="team-back"> <span> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque. </span> </div> </div> </div> <!--team-3--> <!--team-4--> <div class="col-lg-4"> <div class="our-team-main"> <div class="team-front"> <img src="http://placehold.it/110x110/4caf50/fff?text=Dhiraj" class="img-fluid" /> <h3><NAME></h3> <p>Root Canal Expert</p> </div> <div class="team-back"> <span> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque. </span> </div> </div> </div> <!--team-4--> <!--team-5--> <div class="col-lg-4"> <div class="our-team-main"> <div class="team-front"> <img src="http://placehold.it/110x110/e91e63/fff?text=Rohit" class="img-fluid" /> <h3>Rohit Salve</h3> <p>Eyes and Lips neurologist</p> </div> <div class="team-back"> <span> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque. </span> </div> </div> </div> <!--team-5--> <!--team-6--> <div class="col-lg-4"> <div class="our-team-main"> <div class="team-front"> <img src="http://placehold.it/110x110/2196f3/fff?text=Raghav" class="img-fluid" /> <h3><NAME></h3> <p>Hair Expert</p> </div> <div class="team-back"> <span> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque. </span> </div> </div> </div> <!--team-6--> </div> </div> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/dental-implant-fixing.php <!DOCTYPE html> <html class="no-js"> <head> <title>Dental Implant Fixing Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="./css/service-card.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li class="list-group-item"> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Dental Implant Fixing</h3> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Dental Implant Fixing</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <!--<p>Dental implants are replacement tooth roots. Implants provide a strong foundation for fixed (permanent) or removable replacement teeth that are made to match your natural teeth.</p>--> <p>Dental implants are now a well-accepted way of replacing missing teeth. We place them directly into your jawbone, where they provide an artificial replacement for the root of your missing tooth or teeth. They can then support crowns or dentures, in a similar way to the way that roots support natural teeth.</p> <div class="row"> <div class="card col-sm-12 col-md-6 border border-primary"><h4>Symptoms :</h4> <ul class="list-group"> <li class="list-group-item">Severe pain or discomfort.</li> <li class="list-group-item">A loose or shifting implant.</li> <li class="list-group-item">Swelling or inflammation of the gums.</li> <li class="list-group-item">Gum recession around dental implant.</li> <li class="list-group-item">Difficulty chewing and biting.</li> </ul></div> <div class="card col-sm-12 col-md-6 border border-primary"><h4>Procedure :</h4> <ul class="list-group"> <li class="list-group-item">Placement of the implant into your jaw and attachment of the abutment (which holds the false teeth in place) to the implant. This will be a one- or two-stage procedure.</li> <li class="list-group-item">Fusion of your new implant with the surrounding bone, which can take from six weeks to six months. You may be offered temporary artificial teeth to wear over this period.</li> <li class="list-group-item">Construction and fitting of your new artificial teeth onto your implants.</li> </ul></div> </div> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/crowns-bridges-fixing.php <!DOCTYPE html> <html class="no-js"> <head> <title>Crowns and Bridges Fixing Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="./css/service-card.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li class="list-group-item"> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Crowns and Bridges Fixing</h3> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Crowns and Bridges Fixing</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <!--<p>Dental implants are replacement tooth roots. Implants provide a strong foundation for fixed (permanent) or removable replacement teeth that are made to match your natural teeth.</p>--> <p>Both crowns and most bridges are fixed prosthetic devices. Unlike removable devices such as dentures, which you can take out and clean daily, crowns and bridges are cemented onto existing teeth or implants, and can only be removed by a dentist.</p> <div class="row"> <div class="card col-sm-12 col-md-6 border border-primary"><h4>Symptoms :</h4> <ul class="list-group"> <li class="list-group-item">Moves when Touched. When a dental bridge has loosened over time, it begins to move slightly when touched with either the fingers or the tongue.</li> <li class="list-group-item">Sensitivity</li> <li class="list-group-item">Bite Issues</li> <li class="list-group-item">Bad Taste in the Mouth.</li> </ul></div> <div class="card col-sm-12 col-md-6 border border-primary"><h4>Procedure :</h4> <ul class="list-group"> <li class="list-group-item">Diagnostics and preparation of the treatment plan.</li> <li class="list-group-item">Tooth or teeth drilling, making a dental impression, colour matching, preparing a temporary crown.</li> <li class="list-group-item">Fitting and cementing the crown or a prosthetic bridge.</li> </ul> </div> </div> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/orthodontic-treatment.php <!DOCTYPE html> <html class="no-js"> <head> <title>Orthodontic Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Orthodontic Treatment</h3> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Orthodontic Treatment</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <!--<p>Dental implants are replacement tooth roots. Implants provide a strong foundation for fixed (permanent) or removable replacement teeth that are made to match your natural teeth.</p>--> <p>Orthodontic treatment is a way of straightening or moving teeth, to improve the appearance of the teeth and how they work. It can also help to look after the long-term health of your teeth, gums and jaw joints, by spreading the biting pressure over all your teeth.</p> <h4>Symptoms :</h4> <ul> <li>Crowding – when there is not quite enough room in the jaw for the size of the teeth and the teeth are turned, tipped or at strange angles in the mouth. This can happen anywhere in the mouth but is most often seen at the front. This often worsens with age.</li> <li>Spacing – this may be due to missing teeth or may happen if the teeth and jaw sizes don’t quite match. The gap might be in one place only or gaps might appear between many teeth.</li> <li>Overbite – or “buck teeth” where the top front teeth appear to stick out too far forward of the lower teeth. Dentists and orthodontists call this an excessive overjet.</li> <li>Underbite – here the upper front teeth appear to bite directly on top of or behind the lower teeth. The dental term for this is a reverse overjet.</li> <li>Deep bite – the top front teeth cover more than a couple of millimetres of the lower front teeth so that not much, if any, of the lower front teeth can be seen when the back teeth are together.</li> <li>Open bite – when there is a gap between the biting part of some of the upper and lower teeth when the back teeth are together.</li> <li>Cross bite – when some of the upper teeth bite down on the wrong side of the lower teeth when the back teeth are together. This can be at the front or at the back.</li> </ul> <h4>Procedure :</h4> <ul> <li>The first step includes documentation of your medical and dental histories, and evaluation and explanation of your recommended treatment, and a discussion about your payment and financial arrangements.</li> <li>In the second step, the orthodontist uses 3-D imaging and photos to be included in your diagnostic records. Spacers may also be placed between the teeth in this step to make room for future orthodontic bands.</li> <li>The third step is pretty exciting! This is when the orthodontist actually places the braces on your teeth. The bands, brackets, and wires are all fitted to the teeth. Patients who have opted for Invisalign will receive the first set of aligners.</li> <li>The fourth step is also called the active phase of orthodontic treatment. The orthodontist is actively moving the teeth into their ideal positions, and you will have a series of ‘checkup’ appointments so that your progress can be monitored. These appointments typically take place every 6-8 weeks, with adjustments and elastics as needed.</li> <li>In the fifth step, once the orthodontist has achieved the perfect bite relationship, the braces can be taken off. The length of time between step 3 and step 5 can vary, depending on the severity of your particular case, but can average between 12 months and 24 months. It is also common to have a retainer placed on the teeth on the same day.</li> <li>The orthodontist will advise you on how and when to wear your retainer, and you’ll need a few periodic appointments for checkups in this sixth and final phase of your orthodontic journey.</li> </ul> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/index.php <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Best International Dental Clinic in Pune | Face & Dental International Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <![endif]--> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="css/fonts.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <script src="js/vendor/jquery-1.12.4.min.js"></script> <![endif]--> </head> <body> <!--[if lt IE 9]> <div class="bg-danger text-center">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/" class="highlight">upgrade your browser</a> to improve your experience.</div> <![endif]--> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- search modal <div class="modal" tabindex="-1" role="dialog" aria-labelledby="search_modal" id="search_modal"> <div class="widget widget_search"> <form method="get" class="searchform form-inline" action="/"> <div class="form-group"> <input type="text" value="" name="search" class="form-control" placeholder="Search keyword" id="modal-search-input"> </div> <button type="submit" class="theme_button">Search</button> </form> </div> </div>--> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- Call Header File --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/slide01.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Dental care for life</h3> </div> <div class="intro-layer" data-animation="slideExpandUp"> <p class="fontsize_20">If your smile is not becoming to you, then you should be coming to Face & Dental! Family dentistry with a woman’s touch.</p> <a href="appointment.html" class="theme_button color1">Make an Appointment</a> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> <li> <img src="images/slide02.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Dentistry with heart</h3> </div> <div class="intro-layer" data-animation="slideExpandUp"> <p class="fontsize_20">Creating the healthy smile you want through science and artistry.<br> Because everyone deserves to smile.</p> <a href="appointment.html" class="theme_button color1">Make an Appointment</a> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> <li> <img src="images/slide03.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12 text-center"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Care for your smile</h3> </div> <div class="intro-layer" data-animation="slideExpandUp"> <p class="fontsize_20">Relax, this is going to be so easy. The smart way to find a dentist. Get matched with a great dentist today. Seriously, it’s time.</p> <a href="appointment.html" class="theme_button color1">Make an Appointment</a> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls columns_padding_0 columns_margin_0" id="features-section"> <div class="container"> <div class="row"> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="with_padding maindarker3_bg_color topborder_radius_4 feature-teaser"> <img src="./img/certification.png" alt="" class="teaser_icon"> <p class="fontsize_18 semibold topmargin_15 bottommargin_5">Certification</p> <p class="margin_0"> Certified orthodontics &amp; esthetics. </p> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="with_padding maindarker2_bg_color topborder_radius_4 feature-teaser"> <img src="./img/time.png" alt="" class="teaser_icon"> <!--<p class="fontsize_18 semibold topmargin_15 bottommargin_5">24/7 Opened</p>--> <p class="fontsize_18 semibold topmargin_15 bottommargin_5">Specializations</p> <p class="margin_0"> Dental Surgeon<br/> Implantologist </p> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="with_padding maindarker1_bg_color topborder_radius_4 feature-teaser"> <img src="./img/personal.png" alt="" class="teaser_icon"> <!--<p class="fontsize_18 semibold topmargin_15 bottommargin_5">Professional Staff</p> --> <p class="fontsize_18 semibold topmargin_15 bottommargin_5">Awards and <br/>Recognitions</p> <p class="margin_0"> BDS - 2005 </p> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="with_padding main_bg_color topborder_radius_4 feature-teaser"> <img src="./img/like.png" alt="" class="teaser_icon "> <!--<p class="fontsize_18 semibold topmargin_15 bottommargin_5">Fair Prices</p> --> <p class="fontsize_18 semibold topmargin_15 bottommargin_5">Experience</p> <p class="margin_0"> 2005 - 2017 Doctor at Dental Care </p> </div> </div> </div> </div> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="side-item about-item"> <div class="row display_table_md"> <div class="col-md-6 display_table_cell_md"> <div class="with_backing"> <img src="./images/about.jpg" alt="" class="border_radius_4"> </div> </div> <div class="col-md-6 display_table_cell_md"> <div class="item-content"> <h2 class="section_header margin_0">We are Face & Dental International Clinic</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> <p> Customer service is provided by a highly trained, professional Doctors who look after your comfort and care and are considerate of your time. Their focus is you. </p> <p class="bold text-uppercase bottommargin_2"> Dental Prevention <span class="bold pull-right">75%</span> </p> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" data-transitiongoal="75"> </div> </div> <p class="bold text-uppercase bottommargin_2"> Fluoride Treatment <span class="bold pull-right">50%</span> </p> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" data-transitiongoal="50"> </div> </div> <p class="bold text-uppercase bottommargin_2"> Tooth Extraction <span class="bold pull-right">90%</span> </p> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" data-transitiongoal="90"> </div> </div> <p class="bold text-uppercase bottommargin_2"> Cavity Filling <span class="bold pull-right">85%</span> </p> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" data-transitiongoal="85"> </div> </div> <a href="about.html" class="theme_button color1 topmargin_10">learn about us</a> </div> </div> </div> </div> </div> </div> </div> </section> <section class="cs parallax section_padding_100 columns_padding_0 columns_margin_0" id="services"> <div class="container"> <div class="row"> <div class="col-sm-12 text-center"> <h2 class="section_header margin_0">our services</h2> <hr class="dividersize_2_70 inline-block"> </div> </div> <div class="row services-container topmargin_50"> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-protection"></div> <p class="fontsize_18 semibold bottommargin_5">Tooth Protection</p> <p class="margin_0"> There are only 2 dental specialties that only focus on dental esthetics... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-calculus"></div> <p class="fontsize_18 semibold bottommargin_5">Dental Calculus</p> <p class="margin_0"> Types of bridges may vary, depending upon how they are... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-paradontosis"></div> <p class="fontsize_18 semibold bottommargin_5">Paradontosis</p> <p class="margin_0"> Parodontitis is inflammation of basic dental apparatus caused by... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-cleaning"></div> <p class="fontsize_18 semibold bottommargin_5">Teeth Cleaning</p> <p class="margin_0"> Bleaching methods use carbamide peroxide which reacts with water... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-defence"></div> <p class="fontsize_18 semibold bottommargin_5">Caries Defence</p> <p class="margin_0"> The most important part of preventive dentistry is to brush... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-implants"></div> <p class="fontsize_18 semibold bottommargin_5">Dental Implants</p> <p class="margin_0"> The implant fixture is first placed, so that it is likely to osseointegrate... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-braces"></div> <p class="fontsize_18 semibold bottommargin_5">Braces</p> <p class="margin_0"> According to scholars and historians, braces date back to... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 service-item text-center"> <div class="with_padding"> <div class="service-icon service-cracked"></div> <p class="fontsize_18 semibold bottommargin_5">Cracked Tooth</p> <p class="margin_0"> There are many different types of cracked teeth. Cracked teeth show... </p> <div class="media-links"> <a class="abs-link" href="teeth_cleaning.html"></a> </div> </div> </div> </div> </div> </section> <!--<section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12 text-center"> <h2 class="section_header margin_0">Pricing tables</h2> <hr class="dividersize_2_70 inline-block main_bg_color"> </div> </div> <div class="row topmargin_30"> <div class="col-md-3 col-sm-6 col-xs-12"> <ul class="price-table style1"> <li class="plan-name maindarker3_bg_color"><h6>teeth cleaning</h6></li> <li class="plan-price"><span class="highlight">$10.00</span><p>one-fee payment</p></li> <li class="features-list"> <ul> <li class="enabled">Feature 01</li> <li class="enabled">Feature 02</li> <li class="disabled">Feature 03</li> <li class="enabled">Feature 04</li> </ul> <div class="call-to-action"><a href="#" class="theme_button color1 border_button">Order Now</a></div> </li> </ul> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <ul class="price-table style1"> <li class="plan-name maindarker2_bg_color"><h6>caries defence</h6></li> <li class="plan-price"><span class="highlight">$25.00</span><p>per day</p></li> <li class="features-list"> <ul> <li class="enabled">Feature 01</li> <li class="enabled">Feature 02</li> <li class="enabled">Feature 03</li> <li class="disabled">Feature 04</li> </ul> <div class="call-to-action"><a href="#" class="theme_button color1 border_button">Order Now</a></div> </li> </ul> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <ul class="price-table style1"> <li class="plan-name maindarker1_bg_color"><h6>braces</h6></li> <li class="plan-price"><span class="highlight">$75.00</span><p>per mounth</p></li> <li class="features-list"> <ul> <li class="enabled">Feature 01</li> <li class="enabled">Feature 02</li> <li class="disabled">Feature 03</li> <li class="enabled">Feature 04</li> </ul> <div class="call-to-action"><a href="#" class="theme_button color1 border_button">Order Now</a></div> </li> </ul> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <ul class="price-table style1"> <li class="plan-name main_bg_color"><h6>dental implants</h6></li> <li class="plan-price"><span class="highlight">$125.00</span><p>per year</p></li> <li class="features-list"> <ul> <li class="enabled">Feature 01</li> <li class="enabled">Feature 02</li> <li class="disabled">Feature 03</li> <li class="enabled">Feature 04</li> </ul> <div class="call-to-action"><a href="#" class="theme_button color1 border_button">Order Now</a></div> </li> </ul> </div> </div> </div> </section>--> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12 text-center"> <h2 class="section_header margin_0">What our patients say</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> <div class="owl-carousel testimonials-owl-carousel topmargin_50" data-margin="30" data-items="9" data-loop="true" data-dots="true" data-nav="false" data-autoplay="false" data-responsive-xs="1" data-responsive-sm="2" data-responsive-md="3" data-responsive-lg="3" > <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face01.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Boudin jerky short ribs occaecat, labore ad consectetur velit ex ground round tenderloin. Deserunt tongue sunt pork belly velit leberkas" <div class="item-meta"> <h6><NAME></h6> <div class="signature signature-signature3"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face02.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Pork chop drumstick eiusmod, short ribs short loin boudin ground round pork loin in ham hock excepteur occaecat chuck esse labore" <div class="item-meta"> <h6><NAME></h6> <div class="signature signature-signature2"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face03.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Esse duis in ut, ea pork chop aute ut tempor cupidatat. Tempor bresaola do et beef tail. In reprehenderit kevin ad jerky anim flank velit turkey officia" <div class="item-meta"> <h6><NAME></h6> <div class="signature signature-signature1"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face01.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Boudin jerky short ribs occaecat, labore ad consectetur velit ex ground round tenderloin. Deserunt tongue sunt pork belly velit leberkas" <div class="item-meta"> <h6><NAME></h6> <div class="signature signature-signature3"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face02.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Pork chop drumstick eiusmod, short ribs short loin boudin ground round pork loin in ham hock excepteur occaecat chuck esse labore" <div class="item-meta"> <h6>Kamil Ataturk</h6> <div class="signature signature2"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face03.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Esse duis in ut, ea pork chop aute ut tempor cupidatat. Tempor bresaola do et beef tail. In reprehenderit kevin ad jerky anim flank velit turkey officia" <div class="item-meta"> <h6><NAME></h6> <div class="signature signature1"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face01.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Boudin jerky short ribs occaecat, labore ad consectetur velit ex ground round tenderloin. Deserunt tongue sunt pork belly velit leberkas" <div class="item-meta"> <h6><NAME></h6> <div class="signature signature3"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face02.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Pork chop drumstick eiusmod, short ribs short loin boudin ground round pork loin in ham hock excepteur occaecat chuck esse labore" <div class="item-meta"> <h6>Kamil Ataturk</h6> <div class="signature signature-signature2"></div> </div> </blockquote> </div> </div> <div class="vertical-item testimonial-item"> <div class="item-media bottommargin_25"> <div class="with_backing small"> <img src="images/face03.jpg" alt=""> </div> </div> <div class="item-content"> <blockquote> "Esse duis in ut, ea pork chop aute ut tempor cupidatat. Tempor bresaola do et beef tail. In reprehenderit kevin ad jerky anim flank velit turkey officia" <div class="item-meta"> <h6><NAME></h6> <div class="signature signature-signature1"></div> </div> </blockquote> </div> </div> </div><!-- .owl-carousel --> </div> </div> </div> </section> <section class="ls page_portfolio columns_padding_0 columns_margin_0"> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <div class="isotope_container isotope row masonry-layout"> <div class="isotope-item col-lg-3 col-md-4 col-sm-6"> <div class="vertical-item gallery-item"> <div class="item-media"> <img src="images/gallery/05.jpg" alt=""> <div class="media-links"> <div class="links-wrap"> <a class="p-view prettyPhoto " title="" data-gal="prettyPhoto[gal]" href="images/gallery/05.jpg"></a> </div> </div> </div> </div> </div> <div class="isotope-item col-lg-3 col-md-4 col-sm-6"> <div class="vertical-item gallery-item"> <div class="item-media"> <img src="images/gallery/13.jpg" alt=""> <div class="media-links"> <div class="links-wrap"> <a class="p-view prettyPhoto " title="" data-gal="prettyPhoto[gal]" href="images/gallery/13.jpg"></a> </div> </div> </div> </div> </div> <div class="isotope-item col-lg-3 col-md-4 col-sm-6"> <div class="vertical-item gallery-item"> <div class="item-media"> <img src="images/gallery/14.jpg" alt=""> <div class="media-links"> <div class="links-wrap"> <a class="p-view prettyPhoto " title="" data-gal="prettyPhoto[gal]" href="images/gallery/14.jpg"></a> </div> </div> </div> </div> </div> <div class="isotope-item col-lg-3 col-md-4 col-sm-6"> <div class="vertical-item gallery-item"> <div class="item-media"> <img src="images/gallery/08.jpg" alt=""> <div class="media-links"> <div class="links-wrap"> <a class="p-view prettyPhoto " title="" data-gal="prettyPhoto[gal]" href="images/gallery/08.jpg"></a> </div> </div> </div> </div> </div> <div class="isotope-item col-lg-6 col-md-8 col-sm-12"> <div class="vertical-item gallery-item"> <div class="item-media"> <img src="images/gallery/15.jpg" alt=""> <div class="media-links"> <div class="links-wrap"> <a class="p-view prettyPhoto " title="" data-gal="prettyPhoto[gal]" href="images/gallery/15.jpg"></a> </div> </div> </div> </div> </div> <div class="isotope-item col-lg-3 col-md-4 col-sm-6"> <div class="vertical-item gallery-item"> <div class="item-media"> <img src="images/gallery/02.jpg" alt=""> <div class="media-links"> <div class="links-wrap"> <a class="p-view prettyPhoto " title="" data-gal="prettyPhoto[gal]" href="images/gallery/02.jpg"></a> </div> </div> </div> </div> </div> </div> </div> </div> </div> </section> <section class="ls ms page_banner section_padding_50 texture_bg"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="banner border_radius_4 scheme_background"> <div class="banner-content border_radius_4 text-center"> <div class="icon scheme_background"></div> <p class="fontsize_24 regular bottommargin_10">Dentistry For People Who Love To Smile</p> <p class="semibold highlight2 size_normal">0251 606 0222</p> <div class="scheme_background"> <a href="#" class="theme_button color1 margin_0">Make appointment</a> </div> </div> </div> </div> </div> </div> </section> <!--<section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12 text-center"> <h2 class="section_header margin_0">Latest news</h2> <hr class="dividersize_2_70 inline-block main_bg_color"> </div> </div> <div class="row topmargin_30"> <div class="col-md-4"> <article class="vertical-item with_border thick_border border_radius_4 post text-center"> <div class="item-media entry-thumbnail"> <img src="./images/gallery/07.jpg" alt=""> </div> <header class="entry-header scheme_background"> <a href="blog-single-right.html" class="with_padding"> <time datetime="2016-08-01T15:05:23+00:00" class="entry-date"> august 05, 2016 </time> <h4 class="entry-title">Dental Health at Any Age</h4> </a> </header> <div class="item-content"> <p> Beef bresaola strip steak hamburger ipsum jerky. Capicola laborum occaecat chicken pork veniam ham fugiat meatloaf eu enim. </p> <hr> </div> <div class="post-meta"> <span class="views"><i class="fa fa-eye highlight"></i> <span class="semibold">4806</span></span> <span class="likes"><i class="fa fa-heart-o highlight"></i> <span class="semibold">350</span></span> <span class="comments"><i class="fa fa-comment-o highlight"></i> <span class="semibold">45</span></span> </div> </article> </div> <div class="col-md-4"> <article class="vertical-item with_border thick_border border_radius_4 post text-center"> <div class="item-media entry-thumbnail"> <img src="./images/gallery/16.jpg" alt=""> </div> <header class="entry-header scheme_background"> <a href="blog-single-right.html" class="with_padding"> <time datetime="2016-08-01T15:05:23+00:00" class="entry-date"> august 03, 2016 </time> <h4 class="entry-title">10 Steps to a Better Smile</h4> </a> </header> <div class="item-content"> <p> Cillum officia biltong chicken voluptate eiusmod. Flank sed velit fugiat, doner ipsum landjaeger adipisicing biltong kielbasa. </p> <hr> </div> <div class="post-meta"> <span class="views"><i class="fa fa-eye highlight"></i> <span class="semibold">5640</span></span> <span class="likes"><i class="fa fa-heart-o highlight"></i> <span class="semibold">497</span></span> <span class="comments"><i class="fa fa-comment-o highlight"></i> <span class="semibold">64</span></span> </div> </article> </div> <div class="col-md-4"> <article class="vertical-item with_border thick_border border_radius_4 post text-center"> <div class="item-media entry-thumbnail"> <img src="./images/gallery/04.jpg" alt=""> </div> <header class="entry-header scheme_background"> <a href="blog-single-right.html" class="with_padding"> <time datetime="2016-08-01T15:05:23+00:00" class="entry-date"> august 01, 2016 </time> <h4 class="entry-title">What’s Inside Your Mouth</h4> </a> </header> <div class="item-content"> <p> Consequat chicken nulla boudin, consectetur ut dolore ribeye est tenderloin doner kevin quis salami. Sirloin laborum. </p> <hr> </div> <div class="post-meta"> <span class="views"><i class="fa fa-eye highlight"></i> <span class="semibold">3204</span></span> <span class="likes"><i class="fa fa-heart-o highlight"></i> <span class="semibold">640</span></span> <span class="comments"><i class="fa fa-comment-o highlight"></i> <span class="semibold">81</span></span> </div> </article> </div> </div> </div> </section>--> <!--<section id="map"></section>--> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> <!--<script src="js/switcher.js"></script> Map Scripts --> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<KEY>"></script> <script type="text/javascript"> var lat; var lng; var map; var styles = [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#a4d7ec"},{"visibility":"on"}]}]; //type your address after "address=" jQuery.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=619 Broadway, Santa Monica, CA 90401&sensor=false', function(data) { lat = data.results[0].geometry.location.lat; lng = data.results[0].geometry.location.lng; }).complete(function(){ dxmapLoadMap(); }); function attachSecretMessage(marker, message) { var infowindow = new google.maps.InfoWindow( { content: message }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } window.dxmapLoadMap = function() { var center = new google.maps.LatLng(lat, lng); var settings = { mapTypeId: google.maps.MapTypeId.ROADMAP, zoom: 14, draggable: true, scrollwheel: false, center: center, styles: styles }; map = new google.maps.Map(document.getElementById('map'), settings); var marker = new google.maps.Marker({ position: center, title: 'Map title', map: map, icon: './img/marker.png' }); marker.setTitle('Map title'.toString()); //type your map title and description here attachSecretMessage(marker, '<h3>Map title</h3><p>Map HTML description</p>'); } </script> </body> </html><file_sep>/dental-x-ray.php <!DOCTYPE html> <html class="no-js"> <head> <title>Dental X-Ray Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Dental X-Ray Treatment</h3> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Dental X-Ray Treatment</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <p></p> <h4>Symptoms :</h4> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <h4>Procedure :</h4> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html><file_sep>/child-dentistry.php <!DOCTYPE html> <html class="no-js"> <head> <title>Child Dentistry Treatment in Kalyan | Sai Clinic</title> <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css" id="color-switcher-link"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/animations.css"> <link rel="stylesheet" href="./css/service-card.css"> </head> <body> <div class="preloader"> <div class="preloader_image"></div> </div> <!-- wrappers for visual page editor and boxed version of template --> <div id="canvas"> <div id="box_wrapper"> <!-- template sections --> <?php include("header.php")?> <section class="intro_section page_mainslider ds"> <div class="flexslider"> <ul class="slides"> <li class="list-group-item"> <img src="images/aboutBanner.jpg" alt=""> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="slide_description_wrapper"> <div class="slide_description"> <div class="intro-layer" data-animation="slideExpandUp"> <h3>Child Dentistry Treatment</h3> </div> </div> <!-- eof .slide_description --> </div> <!-- eof .slide_description_wrapper --> </div> <!-- eof .col-* --> </div><!-- eof .row --> </div><!-- eof .container --> </li> </ul> </div> <!-- eof flexslider --> </section> <section class="ls section_padding_110"> <div class="container"> <div class="row topmargin_-5"> <div class="col-sm-12"> <div class="text-center"> <h2 class="section_header margin_0">Child Dentistry Treatment</h2> <hr class="main_bg_color dividersize_2_70 inline-block"> </div> <p>Proper care of your child's teeth and gums includes brushing and rinsing daily. It also includes having routine dental exams, and getting necessary treatments such as fluoride, extractions, fillings, or braces and other orthodontics.</p> <div class="row"> <div class="card col-sm-12 col-md-6 border border-primary"><h4>Symptoms :</h4> <ul class="list-group"> <li class="list-group-item">Toothache</li> <li class="list-group-item">Sensitivity to hot or cold</li> <li class="list-group-item">Brown, black, or white spots on the tooth</li> <li class="list-group-item">Bad breath</li> <li class="list-group-item">Unpleasant taste in the mouth</li> <li class="list-group-item">Swelling</li> </ul></div> <div class="card col-sm-12 col-md-6 border border-primary"> <h4>Procedure :</h4> <ul class="list-group"> <li class="list-group-item">Stainless Steel Crowns : used to restore back teeth that are too badly decayed to hold white fillings.</li> <li class="list-group-item">Tooth Colored Fillings : used to restore front or back teeth or where cosmetic appearance is important. </li> <li class="list-group-item">X-Rays : can often show weaknesses in the tooth structure (such as demineralization) that may not be visible with the naked eye.</li> <li class="list-group-item">Dental Cleaning : child’s teeth will be thoroughly cleaned to remove plaque and calculus (hard tarter deposits), which can cause cavities and gum disease.</li> <li class="list-group-item">Fluoride : Fluoride promotes the remineralization of these decalcified spots, therefore helping to prevent cavities.</li> </ul> </div> </div> </div> </div> </div> </section> <?php include("footer.php")?> </div><!-- eof #box_wrapper --> </div><!-- eof #canvas --> <script src="js/compressed.js"></script> <script src="js/main.js"></script> </body> </html>
3b11b12e580e7c45bc771b96d704d98e144bdaf1
[ "Markdown", "PHP" ]
15
PHP
Mayank-MP05/LoGeek_Sai_Hospital
98ca0690849a8bb42de70b04a9ae6c12578a4b59
2eeacf7354dffe066ae21af177939576532d33b4
refs/heads/master
<repo_name>KaminskiJakub/Contact-Book<file_sep>/README.md # Contact-Book Contact book, where User can store he's contacts. New contacts can be added (just like in a contact book: name, last name and phone number). Numbers can be shown on the screen, if it's decided. All contacts can be shown at once. Contacts are also sorted in a specific way. <file_sep>/src/MenuLogic.java import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MenuLogic { private List <Person> personList; public MenuLogic() { personList = new ArrayList<>(); } public void addPerson(Person person) { personList.add(person); } public void printAllPersons() { for (Person person : personList) { System.out.println(person); } } public void printPerson(String lastName) { Collections.sort(personList); for (Person person: personList) { if(person.getLastName().equalsIgnoreCase(lastName)) { System.out.println("Number: " + person.getNumber()); break; } } } }
7219c8185b59b64d6f0fe758d1399908b377cdc2
[ "Markdown", "Java" ]
2
Markdown
KaminskiJakub/Contact-Book
b6e8780fbb6def726aa8e580657df90cdf26bb98
79f56765ab5dabb53254d41dbdcf40c8e4611e23
refs/heads/master
<file_sep>import numpy as np import re import os from apphelper.image import calc_iou, solve, order_point # from correction import corrector def calc_axis_iou(a, b, axis = 0) : if isinstance(b, list) : if axis == 0 : ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] else : ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list) : if axis == 0 : ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else : ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else : if axis == 0 : iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else : iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def calc_distance(a, b) : dx = abs(a['cx'] - a['w'] / 2 - b['cx'] - b['w'] / 2) return dx def get_candidate_after_key(key, data) : candidates = [d for d in data if calc_axis_iou(d, key, 1) > 0.15 and d['cx'] > key['cx']] if len(candidates) : candidates = sorted(candidates, key = lambda x : x['cx'] - x['w'] / 2) if len(candidates) > 1 and calc_axis_iou(candidates[0], candidates[1 :]) > 0.3 : ref = candidates[0] candidates = [c for c in candidates if calc_axis_iou(c, ref) > 0.3] # candidates = sorted(candidates, key=lambda x:calc_axis_iou(x,key,1), reverse=True) return candidates def get_index_after_key(key, data) : index = [i for i, d in enumerate(data) if calc_axis_iou(d, key, 1) > 0.15 and d['cx'] > key['cx']] if len(index) : index = sorted(index, key = lambda i : data[i]['cx'] - data[i]['w'] / 2) if len(index) > 1 : ref = index[0] index = [i for i in index if calc_axis_iou(data[i], data[ref]) > 0.3] # candidates = sorted(candidates, key=lambda x:calc_axis_iou(x,key,1), reverse=True) return index def is_title(text) : return text.find(r'服务名称') > -1 \ or text.find(r'规格型号') > -1 \ or re.fullmatch(r'单位', text) \ or text.find(r'数量') > -1 \ or text.find(r'单价') > -1 \ or text.find(r'金额') > -1 \ or text.find(r'税率') > -1 \ or text.find(r'税额') > -1 \ or text.find(r'项目名称') > -1 \ or text.find(r'车牌号') > -1 \ or re.fullmatch(r'类型', text) \ or text.find(r'通行日期起') > -1 \ or text.find(r'通行日期止') > -1 and text.find(r'[*]') == -1 # or text.find(r'单位') > -1 \ def get_basic_checkcode(data) : checkcode = '' candidates = [d for d in data if re.search(r'校验码*', d['text'])] if len(candidates) : checkcodes = get_candidate_after_key(candidates[0], data) if len(checkcodes) : checkcode = checkcodes[0]['text'] return checkcode def get_basic_type(data) : type = '' title = '' elec = '电子' if len([d for d in data if re.search(r'发票代码', d['text'])]) > 0 else '' candidates = [d for d in data if re.search(r'.*增值税.*发票', d['text'])] if len(candidates) : title = candidates[0]['text'] if title.find('专用') >= 0 : type = elec + '专用发票' else : type = elec + '普通发票' return type, title def get_basic_code(data) : code = '' candidates = [d for d in data if re.search(r'发票代码', d['text'])] if len(candidates) : key = candidates[0] codes = get_candidate_after_key(key, data) if len(codes) : code = codes[0]['text'] else : codes = [d for d in data[:6] if re.search(r'^\d{10,12}$', d['text'])] if len(codes) : code = codes[0]['text'] return code def get_basic_sn(data) : sn = '' candidates = [d for d in data if re.search(r'发票号码', d['text'])] if len(candidates) : key = candidates[0] codes = get_candidate_after_key(key, data) if len(codes) : sn = codes[0]['text'] else : codes = [d for d in data[:10] if re.search(r'^\d{8}$', d['text'])] if len(codes) : sn = codes[0]['text'] return sn def get_basic_date(data) : date = '' candidates = [d for d in data if re.search(r'开票日期', d['text'])] if len(candidates) : key = candidates[0] dates = get_candidate_after_key(key, data) if len(dates) : date = dates[0]['text'] return date def get_basic_person(data) : payee = '' reviewer = '' drawer = '' rear = data candidates = [d for d in rear if re.search(r'收款人', d['text'])] if len(candidates) : key = candidates[0] payees = get_candidate_after_key(key, rear) # if len(payees) and calc_distance(payees[0], key) < 30 : if len(payees) and calc_distance(payees[0], key) < 35 : payee = payees[0]['text'] candidates = [d for d in rear if re.search(r'复核', d['text'])] if len(candidates) : key = candidates[0] reviewers = get_candidate_after_key(key, rear) # if len(reviewers) and calc_distance(reviewers[0], key) < 30 : if len(reviewers) and calc_distance(reviewers[0], key) < 35 : reviewer = reviewers[0]['text'] candidates = [d for d in rear if re.search(r'开票人', d['text'])] if len(candidates) : key = candidates[0] drawers = get_candidate_after_key(key, rear) if len(drawers) and calc_distance(drawers[0], key) < 30 : drawer = drawers[0]['text'] return payee, reviewer, drawer def getBasics(gt) : checkcode = get_basic_checkcode(gt) type, title = get_basic_type(gt) code = get_basic_code(gt) sn = get_basic_sn(gt) date = get_basic_date(gt) payee, reviewer, drawer = get_basic_person(gt) res = [[{'name' : r'发票类型', 'value' : type}, {'name' : r'发票名称', 'value' : title}, {'name' : r'发票代码', 'value' : code}, {'name' : r'发票号码', 'value' : sn}, {'name' : r'开票日期', 'value' : date}, {'name' : r'校验码', 'value' : checkcode}, {'name' : r'收款人', 'value' : payee}, {'name' : r'复核', 'value' : reviewer}, {'name' : r'开票人', 'value' : drawer}]] return res def getBuyer(data) : name, taxnum, address, account = ('', '', '', '') front = data candidates = [d for d in front if re.search(r'名称', d['text'])] if len(candidates) : key = min(candidates, key = lambda x : x['cy']) names = get_candidate_after_key(key, front) if len(names) : name = names[0]['text'] candidates = [d for d in front if re.search(r'纳税人识别号', d['text'])] if len(candidates) : key = min(candidates, key = lambda x : x['cy']) taxnums = get_candidate_after_key(key, front) if len(taxnums) : taxnum = taxnums[0]['text'] candidates = [d for d in front if re.search(r'地址、电话', d['text'])] if len(candidates) : key = min(candidates, key = lambda x : x['cy']) addresses = get_candidate_after_key(key, front) if len(addresses) : address = addresses[0] if abs(key['cx'] + key['w'] / 2 - address['cx'] + address['w'] / 2) < 100 : address = address['text'] else : address = '' candidates = [d for d in front if re.search(r'开户行及账号', d['text'])] if len(candidates) : key = min(candidates, key = lambda x : x['cy']) accounts = get_candidate_after_key(key, front) if len(accounts) : account = accounts[0] if abs(key['cx'] + key['w'] / 2 - account['cx'] + account['w'] / 2) < 100 : account = account['text'] else : account = '' res = [[{'name' : r'名称', 'value' : name}, {'name' : r'纳税人识别号', 'value' : taxnum}, {'name' : r'地址、电话', 'value' : address}, {'name' : r'开户行及账号', 'value' : account}]] return res def get_content_boundary(data) : titles = [d for d in data if is_title(d['text'])] right = max(titles, key = lambda x : x['cx'] + x['w'] / 2) bottom = min(titles, key = lambda x : x['cy'] + x['h'] / 2) summary = [d for d in data if re.search(r'¥\d+', d['text'])] summary = min(summary, key = lambda x : x['cy'] - x['h'] / 2) content = [d for d in data if d['cy'] > (bottom['cy'] + bottom['h'] / 2) and d['cy'] < ( summary['cy'] - summary['h'] / 2) and not is_title(d['text'])] return content def doLeft(content, item, length) : if len(item) < length : ct = [c for c in content if calc_axis_iou(c, item) > 0] if len(ct) + len(item) == length : item = sorted(item + ct, key = lambda x : x['cy']) for c in ct : content.remove(c) return item, content def getContent(data) : ret = [] content = get_content_boundary(data) titles = [d for d in data if is_title(d['text'])] titles = sorted(titles, key = lambda x : x['cx']) s = re.compile(r'[-,$()#+&*~]') for i in range(len(titles)) : if re.findall(s, titles[i]['text']) or re.findall(r'[a-zA-Z0-9]', titles[i]['text']) : del titles[i] break t_name, t_spec, t_unit, t_num, t_uprice, t_price, t_ratio, t_tax = titles isvehicle = (t_name == '项目名称') taxes = sorted([c for c in content if calc_axis_iou(c, t_tax) > 0.001 or c['cx'] >= t_tax['cx']], key = lambda x : x['cy']) names = sorted([c for c in content if calc_axis_iou(c, t_name) > 0.001], key = lambda x : x['cy']) ratios = sorted([c for c in content if calc_axis_iou(c, t_ratio) > 0.001], key = lambda x : x['cy']) prices = sorted([c for c in content if calc_axis_iou(c, t_price) > 0.001 or ( c['cx'] + c['w'] / 2 < t_ratio['cx'] - t_ratio['w'] / 2 and c['cx'] - c['w'] / 2 > t_price['cx'] + t_price['w'] / 2)], key = lambda x : x['cy']) uprices = sorted([c for c in content if calc_axis_iou(c, t_uprice) > 0.001 or ( c['cx'] + c['w'] / 2 < t_price['cx'] - t_price['w'] / 2 and c['cx'] - c['w'] / 2 > t_uprice['cx'] + t_uprice['w'] / 2)], key = lambda x : x['cy']) nums = sorted([c for c in content if calc_axis_iou(c, t_num) > 0.001 or ( c['cx'] + c['w'] / 2 < t_uprice['cx'] - t_uprice['w'] / 2 and c['cx'] - c['w'] / 2 > t_unit['cx'] + t_unit['w'] / 2)], key = lambda x : x['cy']) units = sorted([c for c in content if calc_axis_iou(c, t_unit) > 0.001], key = lambda x : x['cy']) specs = sorted([c for c in content if calc_axis_iou(c, t_spec) > 0.001 or ( c['cx'] + c['w'] / 2 < t_spec['cx'] - t_spec['w'] / 2 and c['cx'] - c['w'] / 2 > t_name['cx'] + t_name[ 'w'] / 2)], key = lambda x : x['cy']) done = taxes + names + ratios + prices + uprices + nums + units + specs left = [c for c in content if c not in done] if len(left) : specs, left = doLeft(left, specs, len(taxes)) if len(left) : units, left = doLeft(left, units, len(taxes)) if len(left) : nums, left = doLeft(left, nums, len(taxes)) if len(taxes) != len(names) : merges = [] idx = [i for i, n in enumerate(names) if re.search(r'^\*', n['text'])] j = 0 for i in idx[1 :] : merge = names[j] merge['text'] = ''.join([n['text'] for n in names[j :i]]) merges.append(merge) j = i if j < len(names) : merge = names[j] merge['text'] = ''.join([n['text'] for n in names[j :]]) merges.append(merge) names = merges for i in range(len(taxes)) : name = names[i]['text'] tax = taxes[i]['text'] ratio = ratios[i]['text'] price = prices[i]['text'] uprice = uprices[i]['text'] if i < len(uprices) else '' num = nums[i]['text'] if i < len(nums) else '' unit = units[i]['text'] if i < len(units) else '' spec = specs[i]['text'] if i < len(specs) else '' if isvehicle : ret.append([{'name' : r'项目名称', 'value' : name}, {'name' : r'车牌号', 'value' : spec}, {'name' : r'类型', 'value' : unit}, {'name' : r'通行日期起', 'value' : num}, {'name' : r'通行日期止', 'value' : uprice}, {'name' : r'金额', 'value' : price}, {'name' : r'税率', 'value' : ratio}, {'name' : r'税额', 'value' : tax}]) else : ret.append([{'name' : r'名称', 'value' : name}, {'name' : r'规格型号', 'value' : spec}, {'name' : r'单位', 'value' : unit}, {'name' : r'数量', 'value' : num}, {'name' : r'单价', 'value' : uprice}, {'name' : r'金额', 'value' : price}, {'name' : r'税率', 'value' : ratio}, {'name' : r'税额', 'value' : tax}]) return ret def getSeller(data) : name, taxnum, address, account = ('', '', '', '') rear = data candidates = [d for d in rear if re.search(r'名称', d['text'])] if len(candidates) : key = max(candidates, key = lambda x : x['cy']) # names = get_candidate_after_key(key, rear) # if len(names): # name = names[0]['text'] names = get_index_after_key(key, rear) candidates = [d for d in rear if re.search(r'纳税人识别号', d['text'])] if len(candidates) : key = max(candidates, key = lambda x : x['cy']) # taxnums = get_candidate_after_key(key, rear) # if len(taxnums): # taxnum = taxnums[0]['text'] taxnums = get_index_after_key(key, rear) candidates = [d for d in rear if re.search(r'地址、电话', d['text'])] if len(candidates) : key = max(candidates, key = lambda x : x['cy']) # addresses = get_candidate_after_key(key, rear) # if len(addresses): # address = addresses[0]['text'] addresses = get_index_after_key(key, rear) candidates = [d for d in rear if re.search(r'开户行及账号', d['text'])] if len(candidates) : key = max(candidates, key = lambda x : x['cy']) # accounts = get_candidate_after_key(key, rear) # if len(accounts): # account = accounts[0]['text'] accounts = get_index_after_key(key, rear) candidates = list(set(names + taxnums + addresses + accounts)) candidates = sorted(candidates, key = lambda x : rear[x]['cy']) length = len(candidates) if length >= 4 : name, taxnum, address, account = [rear[c]['text'] for c in candidates[0 :4]] elif length == 3 : name, taxnum, address = [rear[c]['text'] for c in candidates] account = '' elif length == 2 : name, taxnum = [rear[c]['text'] for c in candidates] address = '' account = '' elif length == 1 : name = candidates[0]['text'] taxnum = '', address = '' account = '' else : name = '' taxnum = '', address = '' account = '' res = [[{'name' : r'名称', 'value' : name}, {'name' : r'纳税人识别号', 'value' : taxnum}, {'name' : r'地址、电话', 'value' : address}, {'name' : r'开户行及账号', 'value' : account}]] return res def getSummation(data) : prices = [re.sub(r'[^\d\.]', '', d['text']) for d in data if re.search(r'¥\d+\.\d{1,2}', d['text'])] prices = sorted(prices, key = lambda x : float(x)) if len(prices) == 2 : tax = '***' price = prices[0] total = prices[1] else : tax = prices[0] price = prices[1] total = prices[2] candidates = [d for d in data if re.search(r'价税合计', d['text'])] if len(candidates) : key = candidates[0] capitals = get_candidate_after_key(key, data) if len(capitals) : capital = capitals[0]['text'] res = [[{'name' : r'金额合计', 'value' : price}, {'name' : r'税额合计', 'value' : tax}, {'name' : r'价税合计(大写)', 'value' : capital}, {'name' : r'价税合计(小写)', 'value' : total}]] return res def get_min_distance(word1, word2) : m, n = len(word1), len(word2) if m == 0 : return n if n == 0 : return m cur = [0] * (m + 1) # 初始化cur和边界 for i in range(1, m + 1) : cur[i] = i for j in range(1, n + 1) : # 计算cur pre, cur[0] = cur[0], j # 初始化当前列的第一个值 for i in range(1, m + 1) : temp = cur[i] # 取出当前方格的左边的值 if word1[i - 1] == word2[j - 1] : cur[i] = pre else : cur[i] = min(pre + 1, cur[i] + 1, cur[i - 1] + 1) pre = temp return cur[m] def calc_precision1(predict, groundtruth, errfile, canfile) : # 以字符方式计算正确率 # total = 0 # error = 0 # # with open(errfile, 'w', encoding = 'utf-8') as f : # for (p, g) in zip(predict, groundtruth) : # for (pi, gi) in zip(p['items'], g['items']) : # for (pii, gii) in zip(pi, gi) : # distance = get_min_distance(pii['value'], gii['value']) # error += distance # total += len(gii['value']) # # if distance : # text = p['title'] + ' ' + pii['name'] + ' ' + 'groundtruth: ' + gii['value'] + ' errortext: ' + \ # pii['value'] + '\n' # f.write(text) # # precision = round(100.0 * (total - error) / total, 2) # return precision total = 0 error = 0 with open(errfile, 'w', encoding = 'utf-8') as f : for (p, g) in zip(predict, groundtruth) : for (pi, gi) in zip(p['items'], g['items']) : for (pii, gii) in zip(pi, gi) : distance = get_min_distance(pii['value'], gii['value']) if distance and ("注源" in pii['value'] and "镇" in pii['value']) : error_sen = pii['value'] # pii['value'] = corrector.get_corrected(error_sen) if 'I' in pii['value'] : pii['value'] = pii['value'].replace('I', '1') if 'l' in pii['value'] : pii['value'] = pii['value'].replace('l', '1') distance = get_min_distance(pii['value'], gii['value']) error += distance total += len(gii['value']) if distance : text = p['title'] + ' ' + pii['name'] + ' ' + 'groundtruth: ' + gii['value'] + ' errortext: ' + \ pii['value'] + '\n' f.write(text) with open(canfile, 'w', encoding = 'utf-8') as fc : for (p, g) in zip(predict, groundtruth) : for (pi, gi) in zip(p['items'], g['items']) : for (pii, gii) in zip(pi, gi) : # 这个时候已经没有candidate了,就剩name和value了 text = (gii['value'] if gii['value'] else '-') + '\t' + (pii['value'] if pii['value'] else '-') + '\n' # text = (gii['value'] if gii['value'] else '-') + '\t' + (pii['value'] if pii['value'] else '-') + '\t' + str(pii['candidate']) + '\n' fc.write(text) fc.close() precision = round(100.0 * (total - error) / total, 2) return precision def calc_precision2(gt_len, errfile) : # 以字段计算正确率 with open(errfile, 'r', encoding = 'utf-8') as f : err_len = len(f.readlines()) precision = round(100.0 * (gt_len - err_len) / gt_len, 2) return precision def genGT(file) : with open(file, 'r', encoding = 'utf-8') as f : gt = [] lines = f.readlines() for line in lines : line = line.split(' ') points = line[0] text = re.sub(r'\n', '', ''.join(line[1 :])) box = [float(p) for p in points.split(',')] box = np.array(box).astype('int32') box = box.reshape(4, 2) box = order_point(box) box = box.reshape(-1) angle, w, h, cx, cy = solve(box) gt.append({'angle' : angle, 'w' : w, 'h' : h, 'cx' : cx, 'cy' : cy, 'text' : text}) basic = getBasics(gt) buyer = getBuyer(gt) content = getContent(gt) seller = getSeller(gt) summation = getSummation(gt) groundtruth = [{'title' : r'发票基本信息', 'items' : basic}, {'title' : r'购买方', 'items' : buyer}, {'title' : r'销售方', 'items' : seller}, {'title' : r'货物或应税劳务、服务', 'items' : content}, {'title' : r'合计', 'items' : summation}] return groundtruth def evaluate(file, errfile, canfile, predict = None) : with open(file, 'r', encoding = 'utf-8') as f : gt = [] precision = [] lines = f.readlines() # print("file:",file) # print("len:",len(lines)) # i = 1 for line in lines : line = line.split(',') flag = len(line) if flag==8:# 空格 points = line[:7] line = line[7].split(' ') points.append(line[0]) text = '' for i in range(1,len(line)): text += line[i] text = re.sub(r'\n', '', ''.join(text)) # print("points:",points) box = [float(p) for p in points] else:#逗号 points = line[:8] text = line[8:] text = re.sub(r'\n','',''.join(text)) box = [float(p) for p in points] pass box = np.array(box).astype('int32') box = box.reshape(4, 2) box = order_point(box) box = box.reshape(-1) angle, w, h, cx, cy = solve(box) gt.append({'angle' : angle, 'w' : w, 'h' : h, 'cx' : cx, 'cy' : cy, 'text' : text}) basic = getBasics(gt) buyer = getBuyer(gt) content = getContent(gt) seller = getSeller(gt) summation = getSummation(gt) gt_len = len(gt) groundtruth = [{'title' : r'发票基本信息', 'items' : basic}, {'title' : r'购买方', 'items' : buyer}, {'title' : r'销售方', 'items' : seller}, {'title' : r'货物或应税劳务、服务', 'items' : content}, {'title' : r'合计', 'items' : summation}] precision1 = calc_precision1(predict, groundtruth, errfile, canfile) # precision2 = calc_precision2(gt_len, errfile) # 不准 precision.append(precision1) # precision.append(precision2) return precision if __name__ == '__main__' : image_name = 'baidu-3' image_file = image_name + '.txt' error_file = image_name + '-errors.txt' file = os.path.join(os.path.dirname(__file__), '../data/gt/', image_file) genGT(file) <file_sep>#!/usr/bin/python # encoding: utf-8 # import numpy as np # from PIL import Image # # def resizeNormalize(img,imgH=32): # scale = img.size[1]*1.0 / imgH # w = img.size[0] / scale # w = int(w) # img = img.resize((w,imgH),Image.BILINEAR) # w,h = img.size # img = (np.array(img)/255.0-0.5)/0.5 # return img # # # def strLabelConverter(res,alphabet): # N = len(res) # raw = [] # for i in range(N): # if res[i] != 0 and (not (i > 0 and res[i - 1] == res[i])): # raw.append(alphabet[res[i] - 1]) # return ''.join(raw) import numpy as np from PIL import Image def resizeNormalize(img, imgH = 32) : scale = img.size[1] * 1.0 / imgH w = img.size[0] / scale w = int(w) img = img.resize((w, imgH), Image.BILINEAR) w, h = img.size img = (np.array(img) / 255.0 - 0.5) / 0.5 return img def strLabelConverter(res, alphabet) : N = len(res) raw = [] same_words = [] for i in range(N) : if res[i][0][0] != 0 and (not (i > 0 and res[i - 1][0][0] == res[i][0][0])) : raw.append(alphabet[res[i][0][0] - 1]) same_word = [] flag = True for k in range(len(res[i][0])) : if (res[i][0][k] != 0 and flag) : if k > 0 : same_word.append(alphabet[res[i][0][k] - 1]) else : flag = False same_words.append(same_word) return [''.join(raw), same_words] <file_sep># -*- coding: utf-8 -*- # @Time : 1/16/19 6:40 AM # @Author : zhoujun from .script import cal_recall_precison_f1 __all__ = ['cal_recall_precison_f1']<file_sep>import numpy as np from PIL import Image # from text.opencv_dnn_detect import angle_detect import os import cv2 import time from math import * from scipy.stats import mode def detect_angle(img): """ detect text angle in [0,90,180,270] @@img:np.array """ angle = angle_detect(img) if angle == 90: im = Image.fromarray(img).transpose(Image.ROTATE_90) img = np.array(im) elif angle == 180: im = Image.fromarray(img).transpose(Image.ROTATE_180) img = np.array(im) elif angle == 270: im = Image.fromarray(img).transpose(Image.ROTATE_270) img = np.array(im) return img, angle # 标准霍夫线变换 def line_detection_demo(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) lines = cv2.HoughLines(edges, 1, np.pi/180, 200) # 函数将通过步长为1的半径和步长为π/180的角来搜索所有可能的直线 for line in lines: rho, theta = line[0] # line[0]存储的是点到直线的极径和极角,其中极角是弧度表示的 a = np.cos(theta) # theta是弧度 b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) # 直线起点横坐标 y1 = int(y0 + 1000 * (a)) # 直线起点纵坐标 x2 = int(x0 - 1000 * (-b)) # 直线终点横坐标 y2 = int(y0 - 1000 * (a)) # 直线终点纵坐标 cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) # cv2.imshow("image_lines", image) # 统计概率霍夫线变换 def line_detect_possible_demo(image): gray = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) start = time.time() # 函数将通过步长为1的半径和步长为π/180的角来搜索所有可能的直线 # 表示成组成一条直线的最少点的数量,点数量不足的直线将被抛弃 lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 300, minLineLength=100, maxLineGap=10) # 300 50 now the best (330,100,10) # 表示能被认为在一条直线上的亮点的最大距离 print("dur:",time.time()-start) lines_corre = [] for line in lines: x1, y1, x2, y2 = line[0] cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) x1 = float(x1) y1 = float(y1) x2 = float(x2) y2 = float(y2) if x1 == x2 :# 水平 result = 0 elif y1 == y2:# 垂直 result = 90 else:# 角度 # 计算斜率 k = -(y2 - y1) / (x2 - x1) # 求反正切,再将得到的弧度转换为度 result = np.arctan(k) * 57.2957795130823 # print("直线倾斜角度为:" + str(result) + "度", int(x1), int(y1), int(x2), int(y2)) if 0 <= np.abs(result) < 45: lines_corre.append(result) sta_angle = np.zeros((100),float) for i in range(0,len(lines_corre)): # ---处理成某整数的左右形式 tem = lines_corre[i] if tem < 0: tem += 0.5 # whatever +/- should be add else : tem += 0.5 #---- x = tem + 45 x = int (x) sta_angle[x] += 1 max_value = max(sta_angle) indexs = [i for i,idx in enumerate(sta_angle) if idx == max_value] result_value = [] # 存放出现概率最高区间上的角度 for i in indexs: tmp = i -45 for j in lines_corre: if tmp - 0.5 <= j < tmp + 0.5: result_value.append(j) if len(result_value)==0: # cv2.imwrite('/home/cciip/桌面/111.jpg', image) return 0 # 在概率分布的基础上求均值 angle_mean = np.mean(result_value) # cv2.imwrite('/home/cciip/桌面/111.jpg', image) # now image is red thread img return angle_mean def rotate_bound(image, angle): # 获取宽高 (h, w) = image.shape[:2] (cX, cY) = (w // 2, h // 2) M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0) img = cv2.warpAffine(image, M, (w, h)) return img def angle_corre(path): img = cv2.imread(path) angle = line_detect_possible_demo(img) print('angle:',angle) cv_img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1) cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB) img = cv_img.copy() img = rotate_bound(img, -float(angle)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # print('/home/share/gaoluoluo/dbnet/test/test_corre_input/'+path.split('/')[-1]) cv2.imwrite('./invoices_gao_true/corre_gao/'+path.split('/')[-1], img) return img # '/home/share/gaoluoluo/dbnet/test/test_corre_input/0.jpg' # def rotate_bound(image, angle): # # 获取宽高 # (h, w) = image.shape[:2] # (cX, cY) = (w // 2, h // 2) # M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0) # img = cv2.warpAffine(image, M, (w, h)) # return img # # # def rotate_points(points, angle, cX, cY): # M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0).astype(np.float16) # a = M[:, :2] # b = M[:, 2:] # b = np.reshape(b, newshape=(1, 2)) # a = np.transpose(a) # points = np.dot(points, a) + b # points = points.astype(np.int) # return points # # # def findangle(_image): # # 用来寻找当前图片文本的旋转角度 在±90度之间 # # toWidth: 特征图大小:越小越快 但是效果会变差 # # minCenterDistance:每个连通区域坐上右下点的索引坐标与其质心的距离阈值 大于该阈值的区域被置0 # # angleThres:遍历角度 [-angleThres~angleThres] # # toWidth = _image.shape[1] // 2 # 500 # minCenterDistance = toWidth / 20 # 10 # angleThres = 45 # # image = _image.copy() # h, w = image.shape[0:2] # if w > h: # maskW = toWidth # maskH = int(toWidth / w * h) # else: # maskH = toWidth # maskW = int(toWidth / h * w) # # 使用黑色填充图片区域 # swapImage = cv2.resize(image, (maskW, maskH)) # # print(swapImage) # # print("---------------------") # grayImage = cv2.cvtColor(swapImage, cv2.COLOR_BGR2GRAY) # # print(grayImage) # gaussianBlurImage = cv2.GaussianBlur(grayImage, (3, 3), 0, 0) # histImage = cv2.equalizeHist(~gaussianBlurImage) # binaryImage = cv2.adaptiveThreshold(histImage, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -2) # # pointsNum: 遍历角度时计算的关键点数量 越多越慢 建议[5000,50000]之中 # pointsNum = np.sum(binaryImage != 0) // 2 # # # # 使用最小外接矩形返回的角度作为旋转角度 # # # >>一步到位 不用遍历 # # # >>如果输入的图像切割不好 很容易受干扰返回0度 # # element = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) # # dilated = cv2.dilate(binaryImage*255, element) # # dilated = np.pad(dilated,((50,50),(50,50)),mode='constant') # # cv2('dilated', dilated) # # coords = np.column_stack(np.where(dilated > 0)) # # angle = cv2.minAreaRect(coords) # # print(angle) # # # 使用连接组件寻找并删除边框线条 # # >>速度比霍夫变换快5~10倍 25ms左右 # # >>计算每个连通区域坐上右下点的索引坐标与其质心的距离,距离大的即为线条 # connectivity = 8 # num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binaryImage, connectivity, cv2.CV_8U) # # print(num_labels) # # print("-----------------------") # # print(labels) # # print("------------------------") # # print(stats) # # print("------------------------") # # print(centroids) # # print("--------------------------") # # labels = np.array(labels) # maxnum = [(i, stats[i][-1], centroids[i]) for i in range(len(stats))] # maxnum = sorted(maxnum, key=lambda s: s[1], reverse=True) # if len(maxnum) <= 1: # return 0 # for i, (label, count, centroid) in enumerate(maxnum[1:]): # cood = np.array(np.where(labels == label)) # distance1 = np.linalg.norm(cood[:, 0] - centroid[::-1]) # distance2 = np.linalg.norm(cood[:, -1] - centroid[::-1]) # if distance1 > minCenterDistance or distance2 > minCenterDistance: # binaryImage[labels == label] = 0 # else: # break # # # minRotate = 0 # minCount = -1 # (cX, cY) = (maskW // 2, maskH // 2) # points = np.column_stack(np.where(binaryImage > 0))[:pointsNum].astype(np.int16) # print("points:",np.shape(points)) # (208986, 2) # for rotate in range(-angleThres, angleThres): # rotatePoints = rotate_points(points, rotate, cX, cY) # rotatePoints = np.clip(rotatePoints[:, 0], 0, maskH - 1) # hist, bins = np.histogram(rotatePoints, maskH, [0, maskH]) # # 横向统计非零元素个数 越少则说明姿态越正 # zeroCount = np.sum(hist > toWidth / 50) # if zeroCount <= minCount or minCount == -1: # minCount = zeroCount # minRotate = rotate # # # print("over: rotate = ", minRotate) # return minRotate # # def get_rotate_img(path): # # # # assert os.path.exists(path), 'file is not exists' # # img = cv2.imread(path, 1 if self.img_mode != 'GRAY' else 0) # # # cv_img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1) # # print("cv_img") # # print(cv_img) # cv_img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR) # # # img = cv_img.copy() # # print("img") # # print(img) # angle = findangle(img) # # print(cv2.__version__) # print("angle:",angle) # img = rotate_bound(img, -angle) # # misc.imsave(Path,img) # # img = cv2.cvtColor(img,cv2.COLOR_BAYER_BG2RGB) # 转换为RGB # # print("img") # # print(img) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # return img # # # # 角度旋转 # # class ImgCorrect() : # def __init__(self, img) : # self.img = img # self.h, self.w, self.channel = self.img.shape # if self.w <= self.h : # self.scale = 2000 / self.w # self.w_scale = 2000 # self.h_scale = self.h * self.scale # self.img = cv2.resize(self.img, (0, 0), fx = self.scale, fy = self.scale, interpolation = cv2.INTER_NEAREST) # else : # self.scale = 1190 / self.h # self.h_scale = 1190 # self.w_scale = self.w * self.scale # self.img = cv2.resize(self.img, (0, 0), fx = self.scale, fy = self.scale, interpolation = cv2.INTER_NEAREST) # self.gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) # # def img_lines(self) : # ret, binary = cv2.threshold(self.gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) # # cv2.imshow("bin",binary) # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 矩形结构 # binary = cv2.dilate(binary, kernel) # 膨胀 # edges = cv2.Canny(binary, 50, 200) # # cv2.imshow("edges", edges) # self.lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength = 100, maxLineGap = 20) # # print(self.lines) # if self.lines is None : # print("Line segment not found") # return None # # lines1 = self.lines[:, 0, :] # 提取为二维 # # print(lines1) # imglines = self.img.copy() # for x1, y1, x2, y2 in lines1[:] : # cv2.line(imglines, (x1, y1), (x2, y2), (0, 255, 0), 3) # return imglines # # def search_lines(self) : # lines = self.lines[:, 0, :] # 提取为二维 # # k = [(y2 - y1) / (x2 - x1) for x1, y1, x2, y2 in lines] # # sorted_k = sorted(lines, key=lambda x:(x[3] - x[1]) / (x[2] - x[0])) # number_inexistence_k = 0 # sum_positive_k45 = 0 # number_positive_k45 = 0 # sum_positive_k90 = 0 # number_positive_k90 = 0 # sum_negative_k45 = 0 # number_negative_k45 = 0 # sum_negative_k90 = 0 # number_negative_k90 = 0 # sum_zero_k = 0 # number_zero_k = 0 # for x in lines : # if x[2] == x[0] : # number_inexistence_k += 1 # continue # # print(degrees(atan((x[3] - x[1]) / (x[2] - x[0]))), "pos:", x[0], x[1], x[2], x[3], "斜率:", # # (x[3] - x[1]) / (x[2] - x[0])) # if 0 < degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) < 45 : # number_positive_k45 += 1 # sum_positive_k45 += degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) # if 45 <= degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) < 90 : # number_positive_k90 += 1 # sum_positive_k90 += degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) # if -45 < degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) < 0 : # number_negative_k45 += 1 # sum_negative_k45 += degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) # if -90 < degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) <= -45 : # number_negative_k90 += 1 # sum_negative_k90 += degrees(atan((x[3] - x[1]) / (x[2] - x[0]))) # if x[3] == x[1] : # number_zero_k += 1 # # max_number = max(number_inexistence_k, number_positive_k45, number_positive_k90, number_negative_k45, # number_negative_k90, number_zero_k) # # print(number_inexistence_k,number_positive_k45, number_positive_k90, number_negative_k45, number_negative_k90,number_zero_k) # if max_number == number_inexistence_k : # return 90 # if max_number == number_positive_k45 : # return sum_positive_k45 / number_positive_k45 # if max_number == number_positive_k90 : # return sum_positive_k90 / number_positive_k90 # if max_number == number_negative_k45 : # return sum_negative_k45 / number_negative_k45 # if max_number == number_negative_k90 : # return sum_negative_k90 / number_negative_k90 # if max_number == number_zero_k : # return 0 # # def rotate_image(self, degree) : # """ # 正角 逆时针旋转 # :param degree: # :return: # """ # print("degree:", degree) # if -45 <= degree <= 0 : # degree = degree # #负角度 顺时针 # if -90 <= degree < -45 : # degree = 90 + degree # 正角度 逆时针 # if 0 < degree <= 45 : # degree = degree # 正角度 逆时针 # if 45 < degree < 90 : # degree = degree - 90 # 负角度 顺时针 # print("rotate degree:", degree) # # degree = -45 # # # 获取旋转后4角的填充色 # filled_color = -1 # if filled_color == -1 : # filled_color = mode([self.img[0, 0], self.img[0, -1], # self.img[-1, 0], self.img[-1, -1]]).mode[0] # if np.array(filled_color).shape[0] == 2 : # if isinstance(filled_color, int) : # filled_color = (filled_color, filled_color, filled_color) # else : # filled_color = tuple([int(i) for i in filled_color]) # # # degree = degree - 90 # height, width = self.img.shape[:2] # heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree)))) # 这个公式参考之前内容 # widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree)))) # # matRotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1) # 逆时针旋转 degree # # matRotation[0, 2] += (widthNew - width) / 2 # 因为旋转之后,坐标系原点是新图像的左上角,所以需要根据原图做转化 # matRotation[1, 2] += (heightNew - height) / 2 # # imgRotation = cv2.warpAffine(self.img, matRotation, (widthNew, heightNew), borderValue = filled_color) # # return imgRotation # # # def angle_correct(img_path) : # im = cv2.imread(img_path) # imgcorrect = ImgCorrect(im) # # cv2.imshow('ormalization image', mgcorrect.img) # lines_img = imgcorrect.img_lines() # # print(type(lines_img)) # if lines_img is None : # imgcorrect = imgcorrect.rotate_image(0) # # cv2.imshow("lines_img",lines_img) # else : # # cv2.imshow("lines_img", lines_img) # degree = imgcorrect.search_lines() # # degree = degree * 0.5 # imgcorrect = imgcorrect.rotate_image(degree) # img_name = str(img_path).split('/')[-1] # new_path = '/home/share/gaoluoluo/dbnet/test/test_corre_input/'+img_name # cv2.imwrite(new_path, imgcorrect) # return new_path # # cv2.waitKey() <file_sep># -*- coding:utf-8 -*- import math import util from apphelper.image import calc_iou from crnn import crnnRec # from angle import * def recognize(im=None, path=None): ret = None try: file = None if im: pass elif path: # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im: dir = '/home/share/gaoluoluo/complete_ocr/data/images/tmp/' file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(tmpfile) if data: ret = data except Exception as e: print(e) return ret def get_right_marge(data): # 排除备注中的信息,以图片的中间为限 max_r = 0 for dd in data: tem_r = float(dd['cx']) + float(dd['w']) / 2 if tem_r > max_r: max_r = tem_r return max_r + 200 def get_min_distance_index(tem,indexes,near): x = float(tem['cx']) + float(tem['w']) / 2 y = float(tem['cy']) + float(tem['h']) / 2 distance_min = 100000 ii = 0 for i in range(0,len(near)): x_tem = float(near[i]['cx']) - float(near[i]['w']/2) y_tem = float(near[i]['cy']) + float(near[i]['h']/2) distance_tem = math.sqrt(math.pow((x-x_tem),2) + math.pow((y-y_tem),2)) if distance_tem < distance_min and len(near[i]['text']) and calc_axis_iou(near[i],tem,1) > 0.3 and float(tem['cx']) < float(near[i]['cx']): ii = i distance_min = distance_tem # if distance_tem < 30 and re.search(r'[\u4e00-\u9fa5]{6,}',near[i]['text']): # return i return ii def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) import os import sys import pathlib __dir__ = pathlib.Path(os.path.abspath(__file__)) sys.path.append(str(__dir__)) sys.path.append(str(__dir__.parent.parent)) import time import cv2 import torch from dbnet.data_loader import get_transforms from dbnet.models import build_model from dbnet.post_processing import get_post_processing def resize_image(img, short_size): height, width, _ = img.shape if height < width: new_height = short_size new_width = new_height / height * width else: new_width = short_size new_height = new_width / width * height new_height = int(round(new_height / 32) * 32) new_width = int(round(new_width / 32) * 32) resized_img = cv2.resize(img, (new_width, new_height)) return resized_img class Pytorch_model: def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): ''' 初始化pytorch模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) model_path='/home/share/gaoluoluo/dbnet/output/DBNet_resnet18_FPN_DBHead/checkpoint/model_latest.pth' :param gpu_id: 在哪一块gpu上运行 ''' self.gpu_id = gpu_id if self.gpu_id is not None and isinstance(self.gpu_id, int) and torch.cuda.is_available(): self.device = torch.device("cuda:%s" % self.gpu_id) else: self.device = torch.device("cpu") # print('device:', self.device) checkpoint = torch.load(model_path, map_location=self.device) # print("checkpoint:",checkpoint) config = checkpoint['config'] # print(checkpoint['config']) config['arch']['backbone']['pretrained'] = False self.model = build_model(config['arch']) self.post_process = get_post_processing(config['post_processing']) self.post_process.box_thresh = post_p_thre self.img_mode = config['dataset']['train']['dataset']['args']['img_mode'] self.model.load_state_dict(checkpoint['state_dict']) self.model.to(self.device) self.model.eval() self.transform = [] for t in config['dataset']['train']['dataset']['args']['transforms']: if t['type'] in ['ToTensor', 'Normalize']: self.transform.append(t) self.transform = get_transforms(self.transform) def predict(self, img, is_output_polygon=False, short_size: int = 1024): ''' 对传入的图像进行预测,支持图像地址,opecv 读取图片,偏慢 :param img_path: 图像地址 :param is_numpy: :return: ''' # assert os.path.exists(img_path), 'file is not exists' # img = cv2.imread(img_path, 1 if self.img_mode != 'GRAY' else 0) if self.img_mode == 'RGB': img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w = img.shape[:2] # 2550 3507 img = resize_image(img, short_size) # 将图片由(w,h)变为(1,img_channel,h,w) tensor = self.transform(img) tensor = tensor.unsqueeze_(0) tensor = tensor.to(self.device) batch = {'shape': [(h, w)]} with torch.no_grad(): if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) start = time.time() preds = self.model(tensor) if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) box_list, score_list = self.post_process(batch, preds, is_output_polygon=is_output_polygon) box_list, score_list = box_list[0], score_list[0] if len(box_list) > 0: if is_output_polygon: idx = [x.sum() > 0 for x in box_list] box_list = [box_list[i] for i, v in enumerate(idx) if v] score_list = [score_list[i] for i, v in enumerate(idx) if v] else: idx = box_list.reshape(box_list.shape[0], -1).sum(axis=1) > 0 # 去掉全为0的框 box_list, score_list = box_list[idx], score_list[idx] else: box_list, score_list = [], [] t = time.time() - start return preds[0, 0, :, :].detach().cpu().numpy(), box_list, score_list, t def init_args(): import argparse parser = argparse.ArgumentParser(description='DBNet.pytorch') # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/dbnet/output/DBNet_resnet50_FPN_DBHead/checkpoint/model_latest.pth', type=str) # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/模型/model50_ch_epoch510_latest.pth', type=str) parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/模型/model50_latest_epoch152.pth', type=str) # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/invoices_gao_true/img/', type=str, help='img path for predict') parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_IDCard/input/', type=str, help='img path for predict') parser.add_argument('--img_correct',default='/home/share/gaoluoluo/dbnet/test/test_corre_input/',type=str,help='img_correct path for predict') # parser.add_argument('--input_folder',default='/home/share/gaoluoluo/dbnet/test/test_corre_input', type=str, help='img path for predict') # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_ocr/data/images/tmp', type=str,help='img path for predict') parser.add_argument('--output_folder', default='/home/share/gaoluoluo/dbnet/test/test_output/', type=str, help='img path for output') # parser.add_argument('--output_folder', default='/home/share/gaoluoluo/invoices_gao_true/outputs/', type=str, help='img path for output') parser.add_argument('--gt_txt', default='/home/share/gaoluoluo/complete_ocr/data/txt_not_use', type=str, help='img 对应的 txt') parser.add_argument('--thre', default=0.1, type=float, help='the thresh of post_processing') parser.add_argument('--polygon', action='store_true', help='output polygon or box') parser.add_argument('--show', action='store_true', help='show result') parser.add_argument('--save_result', action='store_true', help='save box and score to txt file') parser.add_argument('--evaluate', nargs='?', type=bool, default=False, help='evalution') args = parser.parse_args() return args def test(tmpfile): import pathlib from tqdm import tqdm import matplotlib.pyplot as plt from dbnet.utils.util import show_img, draw_bbox, save_result, get_file_list args = init_args() # print(args) os.environ['CUDA_VISIBLE_DEVICES'] = str('0') # 初始化网络 0.1 model = Pytorch_model(args.model_path, post_p_thre=args.thre, gpu_id=0) total_frame = 0.0 total_time = [] names = [] for ind in range(0,1): # img_path /home/share/gaoluoluo/dbnet/test/input/2018实验仪器发票.jpg # print("img_path:",img_path) /home/share/gaoluoluo/dbnet/test/input/2018实验仪器发票.jpg img_path = tmpfile print("\nimg_path:", img_path) # img_path = '/home/share/gaoluoluo/IDCard/corre_id/3.jpg' start_time = time.time() img = angle_corre(img_path)# 调整图片角度 # img = cv2.imread(img_path) img_path = args.img_correct + img_path.split('/')[-1] # After correct angle img path names.append(img_path.split('/')[-1]) # names_tem.append(str(iii)+img_path.split('.')[-1]) # iii += 1 # print("img_path:",img_path) preds, boxes_list, score_list, t = model.predict(img, is_output_polygon=args.polygon) img_path1 = img_path boxes_list_save = boxes_list box = [] for i in range(0,len(boxes_list)): for j in range(0,len(boxes_list[0])): b = [] b.append(np.float32(boxes_list[i][j][0])) b.append(np.float32(boxes_list[i][j][1])) box.append(b) boxes_list = boxes_list.reshape(-1,2) boxes_list = box #---hekuang <NAME> yige kuang bei fencheng liangge bufen i = 4 points_kuang = [] remove_mark = [] max_X = -1 while(i<=len(boxes_list)): points = boxes_list[i-4:i] for _,p in enumerate(points): if p[0] > max_X: max_X = p[0] i = i+4 points = np.array(points) points_kuang.append(points) for i in range(10,len(points_kuang)-10): point3 = points_kuang[i][2] start_point = i - 8 end_point = i + 8 if start_point < 0: start_point = 0 if end_point > len(points_kuang): end_point = len(points_kuang) if i not in remove_mark: for j in range(start_point,end_point): point4 = points_kuang[j][3] min_dis = math.sqrt(math.pow((point3[0] - point4[0]),2) + math.pow((point3[1] - point4[1]),2)) Y_cha = math.fabs(point3[1] - point4[1]) if min_dis < 15 and point4[0] > max_X / 2 and Y_cha < 25 and j not in remove_mark and i != j: # 10 reasonable # if min_dis < 0: point1_1 = points_kuang[i][0] point1_2 = points_kuang[j][0] x_min = min(point1_1[0],point1_2[0]) y_min = min(point1_1[1],point1_2[1]) point3_2 = points_kuang[j][2] x_max = max(point3[0],point3_2[0]) y_max = max(point3[1],point3_2[1]) points_kuang[i][0,0] = x_min points_kuang[i][0,1] = y_min points_kuang[i][1,0] = x_max points_kuang[i][1,1] = y_min points_kuang[i][2,0] = x_max points_kuang[i][2,1] = y_max points_kuang[i][3,0] = x_min points_kuang[i][3,1] = y_max remove_mark.append(j) # print("i=",i," j=",j) # print('x:',point4[0]) break remove_mark = sorted(remove_mark,reverse=True) # print("---------------------------") for _,i in enumerate(remove_mark): # print('x:',points_kuang[i][3][0]) del points_kuang[i] boxes_list_save = points_kuang # 决定保存的画框图片是否是 合框之后的图片 #--- i = 0; rects = [] while(i<len(points_kuang)): points = points_kuang[i] # points = [[0, 0], [1, 0], [1, 1], [0, 1]] # points = np.array(points, np.float32) # print(cv2.minAreaRect(points)) # print(type(points)) rect = cv2.minAreaRect(points) # 4个点 -> d cx cy w h rec = [] rec.append(rect[-1]) rec.append(rect[1][1]) rec.append(rect[1][0]) rec.append(rect[0][0]) rec.append(rect[0][1]) rects.append(rec) i += 1 ori_img = cv2.imread(img_path1) # ori_img = cv2.imread('/home/share/gaoluoluo/IDCard/outputs/part_id/0.png') # print(img_path1) result = crnnRec(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) # result = crnnRec_tmp(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) result = list(reversed(result)) # print("result:",result) dur = time.time() - start_time print("dur:",dur) # 保存画框图片--------- # img = draw_bbox(img(img_path)[:, :, ::-1], boxes_list_save) img = draw_bbox(cv2.imread(img_path)[:, :, ::-1], boxes_list_save) if args.show: show_img(preds) show_img(img, title=os.path.basename(img_path)) plt.show() # 保存结果到路径 os.makedirs(args.output_folder, exist_ok=True) img_path = pathlib.Path(img_path) output_path = os.path.join(args.output_folder, img_path.stem + '_result.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_result.jpg pred_path = os.path.join(args.output_folder,img_path.stem + '_pred.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_pred.jpg cv2.imwrite(output_path, img[:, :, ::-1]) cv2.imwrite(pred_path, preds * 255) save_result(output_path.replace('_result.jpg', '.txt'), boxes_list_save, score_list, args.polygon) # -------- total_frame += 1 total_time.append(dur) print("--------------") # print("-------------------11") result = formatResult(result) return result import re def calc_axis_iou(a,b,axis=0): if isinstance(b, list): # b 是list类型时 if axis == 0: # x 方向的交叉率 # 左 右 左 右 ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] # else: # y fangxinag de jiaocha lv ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else: # a b 都不是 list类型 if axis == 0:# iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def getName(data): indexes = [i for i, d in enumerate(data) if re.search(r'^姓[\u4e00-\u9fa5]{1,}', d['text'])] index = 0 if len(indexes): max_cal = 0 for i in range(0,len(data)): if i != indexes[0]: tmp_cal = calc_axis_iou(data[indexes[0]],data[i],1) if tmp_cal > max_cal: max_cal = tmp_cal index = i else: indexes = [i for i, d in enumerate(data) if re.search(r'[\u4e00-\u9fa5]{2,}', d['text'])] index = indexes[0] name = data[index] name = name['text'] name = name.split('姓名',1)[-1] # name = re.sub(r, '', name) return name, index NATIONS = ['汉', '满', '蒙古', '回', '藏', '维吾尔', '苗', '彝', '壮', '布依', '侗', '瑶', '白', '土家', '哈尼', '哈萨克', '傣', '黎', '傈僳', '佤', '畲', '高山', '拉祜', '水', '东乡', '纳西', '景颇', '柯尔克孜', '土', '达斡尔', '仫佬', '羌', '布朗', '撒拉', '毛南', '仡佬', '锡伯', '阿昌', '普米', '朝鲜', '塔吉克', '怒', '乌孜别克', '俄罗斯', '鄂温克', '德昂', '保安', '裕固', '京', '塔塔尔', '独龙', '鄂伦春', '赫哲', '门巴', '珞巴', '基诺'] def getNation(data): sex = '' nation = '' indexes = [i for i, d in enumerate(data) if re.search(r'性别|民族', d['text']) ] index = 0 if len(indexes): sex_nation_list = [] sex_nation_list.append(data[indexes[0]]) for i in range(0, len(data)): if i != indexes[0]: tmp_cal = calc_axis_iou(data[indexes[0]], data[i], 1) if tmp_cal > 0.5 and data[i] not in sex_nation_list: sex_nation_list.append(data[i]) max_x = 0 for i in range(0,len(sex_nation_list)): if sex_nation_list[i]['cx'] > max_x: max_x = sex_nation_list[i]['cx'] nation = sex_nation_list[i] sex = [d for i, d in enumerate(sex_nation_list) if re.search(r'男|女', d['text'])] if len(sex): sex = sex[0] else: indexes = [i for i, d in enumerate(data) if re.search(r'男', d['text'])] if len(indexes): sex = '男' else: sex = '女' nation = '汉' return sex,nation if sex != '' and sex != []: sex = sex['text'] sex = sex.split('性',1)[-1] sex = sex.split('别', 1)[-1] # sex = re.sub(r'^', '', sex) if nation != '': nation = nation['text'] nation = nation.split('民',1)[-1] nation = nation.split('族', 1)[-1] for i in range(0,len(NATIONS)): if NATIONS[i] in nation: nation = NATIONS[i] break # nation = re.sub(r'民族','',nation) return sex, nation def filterChinese(date): year = '' month = '' day = '' flag = 0 flag2 = 0 for i in range(0,len(date)): if re.search(r'\d{1}',date[i]) and len(year) < 4: year += date[i] continue if re.search(r'\d{1}',date[i]) and len(year) == 4 and flag == 0 and flag2 == 1: month += date[i] continue if flag == 1 and re.search(r'\d{1}',date[i]): day += date[i] if len(year) == 4 and len(month) and re.search(r'[\u4e00-\u9fa5]{1}',date[i]): flag = 1 if len(year) == 4 and re.search(r'[\u4e00-\u9fa5]{1}',date[i]): flag2 = 1 if len(year)==4 and len(month) and len(day): return year + '年' + month + '月' + day + '日' else: return date def getBrithday(data): candidates = [d for d in data if re.search(r'\d{4}|^(19|20).?.?年?|^出生?|.月|.日', d['text'])] candidates = sorted(candidates, key=lambda d: d['cx'] - d['w'] / 2) if len(candidates):# 原来的Pse wangluo shi zhengti kuangde min_x = 9999 for i in range(0, len(candidates)): if candidates[i]['cx'] < min_x: min_x = candidates[i]['cx'] year = candidates[i] tmp_year= re.sub(r'出','',year['text']) tmp_year= re.sub(r'生','',tmp_year) if len(tmp_year) > 6: date = tmp_year else: index = get_min_distance_index(year,None,candidates) date = tmp_year + candidates[index]['text'] if len(date) < 6: index = get_min_distance_index(candidates[index],None,candidates) date = date + candidates[index]['text'] date = re.sub(r'出生','',date) date = filterChinese(date) return date def getAddress(data): indexes = [i for i, d in enumerate(data) if re.search(r'[\u4e00-\u9fa5]{8,}', d['text'])] if len(indexes): index = indexes[0] tmp_x = data[index]['cx'] - data[index]['w'] / 2 address = data[index]['text'] for _,da in enumerate(data[index + 1:]): xx = math.fabs(int(da['cx'] - da['w'] / 2) - int(tmp_x)) # get_min_distance_index() if math.fabs(int(da['cx'] - da['w'] / 2) - int(tmp_x)) < 20: address += da['text'] return address def getIDCode(data): indexes = [i for i, d in enumerate(data) if re.search(r'\d{10,}', d['text'])] code = data[indexes[0]]['text'] code = re.sub(r'公民身份号码', '', code) return code def formatResult(data): name, index = getName(data[:5]) sex, nation = getNation(data[index+1:]) brithday = getBrithday(data) addr = getAddress(data) IDCode = getIDCode(data) # res = [{'title':r'姓名', 'items':name}, # {'title':r'性别', 'items':sex}, # {'title':r'民族', 'items':nation}, # {'title': r'出生', 'items':brithday}, # {'title':r'住址', 'items':addr}, # {'title':r'公民身份号码', 'items':IDCode}] if name: title = '正面信息' res = [{'title':title, 'items':[[{'name':r'姓名', 'value':name}, {'name':r'性别', 'value':sex}, {'name':r'民族', 'value':nation}, {'name':r'出生', 'value':brithday}, {'name':r'住址', 'value':addr}, {'name':r'公民身份号码', 'value':IDCode}]]}] else: title = '反面信息' res = [{'title': title, 'items': [[{'name': r'签发机关', 'value': org}, {'name': r'有效期限', 'value': expire}]]}] return res if __name__ == '__main__': test() <file_sep># import os # import subprocess # import cv2 # import numpy as np # from PIL import Image # from config import * # from crnn.keys import alphabetChinese,alphabetEnglish # from apphelper.image import rotate_cut_img,sort_box,union_rbox # # if ocrFlag=='keras': # from crnn.network_keras import CRNN # if chineseModel: # alphabet = alphabetChinese # if LSTMFLAG: # ocrModel = ocrModelKerasLstm # else: # ocrModel = ocrModelKerasDense # else: # ocrModel = ocrModelKerasEng # alphabet = alphabetEnglish # LSTMFLAG = True # elif ocrFlag=='torch': # from crnn.network_torch import CRNN # if chineseModel: # alphabet = alphabetChinese # if LSTMFLAG: # ocrModel = ocrModelTorchLstm # else: # ocrModel = ocrModelTorchDense # # else: # ocrModel = ocrModelTorchEng # alphabet = alphabetEnglish # LSTMFLAG = True # elif ocrFlag=='opencv': # from crnn.network_dnn import CRNN # ocrModel = ocrModelOpencv # alphabet = alphabetChinese # else: # print( "err,ocr engine in keras\opencv\darknet") # # nclass = len(alphabet)+1 # if ocrFlag=='opencv': # crnn = CRNN(alphabet=alphabet) # else: # crnn = CRNN( 32, 1, nclass, 256, leakyRelu=False,lstmFlag=LSTMFLAG,GPU=GPU,alphabet=alphabet) # if os.path.exists(ocrModel): # crnn.load_weights(ocrModel) # else: # print("download model or tranform model with tools!") # # recognizer = crnn.predict # # def crnnRec(im, boxes, leftAdjust=False, rightAdjust=False, alph=0.2, f=1.0): # """ # crnn模型,ocr识别 # @@model, # @@converter, # @@im:Array # @@text_recs:text box # @@ifIm:是否输出box对应的img # # """ # results = [] # # im = Image.fromarray(im) # boxes = sort_box(boxes) # for index, box in enumerate(boxes): # # degree, w, h, cx, cy = box # # # partImg, newW, newH = rotate_cut_img(im, 90 + degree , cx, cy, w, h, leftAdjust, rightAdjust, alph) # partImg = crop_rect(im, ((cx, cy), (h, w), degree)) # newW, newH = partImg.size # # partImg.thumbnail(newW*2,newH*2) # # partImg_array = np.uint8(partImg) # # # if newH > 1.5 * newW: # # partImg_array = np.rot90(partImg_array, 1) # # # partImg = Image.fromarray(partImg_array).convert("RGB") # # # partImg.save("./debug_im/{}.jpg".format(index)) # # # angel_index = angle_handle.predict(partImg_array) # # # # angel_class = lable_map_dict[angel_index] # # # print(angel_class) # # rotate_angle = rotae_map_dict[angel_class] # # # # if rotate_angle != 0: # # partImg_array = np.rot90(partImg_array, rotate_angle // 90) # # # partImg, box = rotate_cut_img(im, box, leftAdjust, rightAdjust) # # partImg = Image.fromarray(partImg_array).convert("RGB") # # partImg.save("./debug_im/{}.jpg".format(index)) # partImg.save(r'outputs/vis_invoice/{}.png'.format(index)) # # partImg_ = partImg.convert('L') # try: # # if crnn_vertical_handle is not None and angel_class in ["shudao", "shuzhen"]: # # # # simPred = crnn_vertical_handle.predict(partImg_) # # else: # # simPred = crnn_handle.predict(partImg_) ##识别的文本 # simPred = recognizer(partImg_) # except: # continue # # if simPred.strip() != u'': # # results.append({'cx': box['cx'] * f, 'cy': box['cy'] * f, 'text': simPred, 'w': box['w'] * f, 'h': box['h'] * f, # # 'degree': box['degree']}) # results.append({'cx': cx * f, 'cy': cy * f, 'text': simPred, 'w': newW * f, 'h': newH * f, # 'degree': degree}) # # return results # # def crop_rect(img, rect ,alph = 0.2): # img = np.asarray(img) # # get the parameter of the small rectangle # # print("rect!") # # print(rect) # center, size, angle = rect[0], rect[1], rect[2] # min_size = min(size) # # if(angle>-45): # center, size = tuple(map(int, center)), tuple(map(int, size)) # # angle-=270 # size = ( int(size[0] + min_size*alph ) , int(size[1] + min_size*alph) ) # height, width = img.shape[0], img.shape[1] # M = cv2.getRotationMatrix2D(center, angle, 1) # # size = tuple([int(rect[1][1]), int(rect[1][0])]) # img_rot = cv2.warpAffine(img, M, (width, height)) # # cv2.imwrite("debug_im/img_rot.jpg", img_rot) # img_crop = cv2.getRectSubPix(img_rot, size, center) # else: # center=tuple(map(int,center)) # size = tuple([int(rect[1][1]), int(rect[1][0])]) # size = ( int(size[0] + min_size*alph) ,int(size[1] + min_size*alph) ) # angle -= 270 # height, width = img.shape[0], img.shape[1] # M = cv2.getRotationMatrix2D(center, angle, 1) # img_rot = cv2.warpAffine(img, M, (width, height)) # # cv2.imwrite("debug_im/img_rot.jpg", img_rot) # img_crop = cv2.getRectSubPix(img_rot, size, center) # img_crop = Image.fromarray(img_crop) # return img_crop import os import subprocess import cv2 import numpy as np from PIL import Image from config import * from crnn.keys import alphabetChinese,alphabetEnglish from apphelper.image import rotate_cut_img,sort_box,union_rbox if ocrFlag=='keras': from crnn.network_keras import CRNN if chineseModel: alphabet = alphabetChinese if LSTMFLAG: ocrModel = ocrModelKerasLstm else: ocrModel = ocrModelKerasDense else: ocrModel = ocrModelKerasEng alphabet = alphabetEnglish LSTMFLAG = True elif ocrFlag=='torch': from crnn.network_torch import CRNN if chineseModel: alphabet = alphabetChinese if LSTMFLAG: ocrModel = ocrModelTorchLstm else: ocrModel = ocrModelTorchDense else: ocrModel = ocrModelTorchEng alphabet = alphabetEnglish LSTMFLAG = True elif ocrFlag=='opencv': from crnn.network_dnn import CRNN ocrModel = ocrModelOpencv alphabet = alphabetChinese else: print( "err,ocr engine in keras\opencv\darknet") nclass = len(alphabet)+1 if ocrFlag=='opencv': crnn = CRNN(alphabet=alphabet) else: crnn = CRNN( 32, 1, nclass, 256, leakyRelu=False,lstmFlag=LSTMFLAG,GPU=GPU,alphabet=alphabet) if os.path.exists(ocrModel): crnn.load_weights(ocrModel) else: print("download model or tranform model with tools!") recognizer = crnn.predict def crnnRec(im, boxes, leftAdjust=False, rightAdjust=False, alph=0.2, f=1.0): """ crnn模型,ocr识别 @@model, @@converter, @@im:Array @@text_recs:text box @@ifIm:是否输出box对应的img """ results = [] # print("orcModel:",ocrModel) # print("ocrFlag:",ocrFlag) im = Image.fromarray(im) # print("boxes:",boxes) boxes = sort_box(boxes) # 没有排序 # print("boxes:",boxes) import time i=1 for index, box in enumerate(boxes): start_time = time.time() degree, w, h, cx, cy = box # partImg, newW, newH = rotate_cut_img(im, 90 + degree , cx, cy, w, h, leftAdjust, rightAdjust, alph) partImg = crop_rect(im, ((cx, cy), (h, w), degree)) newW, newH = partImg.size # partImg.thumbnail(newW*2,newH*2) # partImg_array = np.uint8(partImg) # if newH > 1.5 * newW: # partImg_array = np.rot90(partImg_array, 1) # partImg = Image.fromarray(partImg_array).convert("RGB") # partImg.save("./debug_im/{}.jpg".format(index)) # angel_index = angle_handle.predict(partImg_array) # # angel_class = lable_map_dict[angel_index] # # print(angel_class) # rotate_angle = rotae_map_dict[angel_class] # # if rotate_angle != 0: # partImg_array = np.rot90(partImg_array, rotate_angle // 90) # partImg, box = rotate_cut_img(im, box, leftAdjust, rightAdjust) # partImg = Image.fromarray(partImg_array).convert("RGB") # partImg.save("./debug_im/{}.jpg".format(index)) # partImg.save(r'outputs/vis_invoice/{}.png'.format(index)) partImg_ = partImg.convert('L') try: # if crnn_vertical_handle is not None and angel_class in ["shudao", "shuzhen"]: # # simPred = crnn_verticv2.cvtColor(cal_handle.predict(partImg_) # else: pre = time.time() simPred = crnn.predict(partImg_) # print("simPred:",simPred)##识别的文本 # simPred = recognizer(partImg_) except: continue if simPred[0].strip() != []: # results.append({'cx': box['cx'] * f, 'cy': box['cy'] * f, 'text': simPred, 'w': box['w'] * f, 'h': box['h'] * f, # 'degree': box['degree']}) # f 默认为 1 results.append({'cx': cx * f, 'cy': cy * f, 'text': simPred[0], 'candidate': simPred[1], 'w': newW * f, 'h': newH * f, 'degree': degree}) # print("results:",results) i += 1 return results def crop_rect(img, rect ,alph = 0.2): """ :param img: :param rect: list 里面是元祖形式 :param alph: :return: """ img = np.asarray(img) # get the parameter of the small rectangle # print("rect!") # print(rect) center, size, angle = rect[0], rect[1], rect[2] min_size = min(size) if(angle>-45): center, size = tuple(map(int, center)), tuple(map(int, size)) # angle-=270 size = ( int(size[0] + min_size*alph ) , int(size[1] + min_size*alph) ) height, width = img.shape[0], img.shape[1] M = cv2.getRotationMatrix2D(center, angle, 1) # size = tuple([int(rect[1][1]), int(rect[1][0])]) img_rot = cv2.warpAffine(img, M, (width, height)) # cv2.imwrite("debug_im/img_rot.jpg", img_rot) img_crop = cv2.getRectSubPix(img_rot, size, center) else: center=tuple(map(int,center)) size = tuple([int(rect[1][1]), int(rect[1][0])]) size = ( int(size[0] + min_size*alph) ,int(size[1] + min_size*alph) ) angle -= 270 height, width = img.shape[0], img.shape[1] M = cv2.getRotationMatrix2D(center, angle, 1) img_rot = cv2.warpAffine(img, M, (width, height)) # cv2.imwrite("debug_im/img_rot.jpg", img_rot) img_crop = cv2.getRectSubPix(img_rot, size, center) img_crop = Image.fromarray(img_crop) return img_crop<file_sep># -*- coding: utf-8 -*- # @Time : 2019/8/23 21:55 # @Author : zhoujun import copy from .model import Model from .losses import build_loss __all__ = ['build_loss', 'build_model'] support_model = ['Model'] def build_model(config): """ get architecture model class """ copy_config = copy.deepcopy(config) arch_type = copy_config.pop('type') assert arch_type in support_model, f'{arch_type} is not developed yet!, only {support_model} are support now' arch_model = eval(arch_type)(copy_config) # Model(copy_config) # print("****************") # print("arch_model:",arch_model) # print("****************") return arch_model <file_sep>from .base_trainer import BaseTrainer from .base_dataset import BaseDataSet<file_sep>import os import cv2 import sys import re import time import math import copy from functools import reduce import collections import torch import argparse import numpy as np import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch.autograd import Variable from torch.utils import data from dataset import DataLoader import models import util # c++ version pse based on opencv 3+ from pse import pse # from angle import detect_angle from apphelper.image import order_point, calc_iou, xy_rotate_box from crnn import crnnRec # python pse # from pypse import pse as pypse from pse2 import pse2 def get_params(): parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='resnet50') parser.add_argument('--resume', nargs='?', type=str, default='./checkpoints/ctw1500_res50_pretrain_ic17.pth.tar', help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=0.5, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=7, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=1680, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') args = parser.parse_args() return args def recognize(im=None, path=None): ret = None try: file = None if im: pass elif path: # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im: dir = os.path.join(os.path.dirname(__file__), '../data/images/invoice/') file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(get_params(), tmpfile) if data: ret = format(data) except Exception as e: print(e) return ret def format(data): return data def extend_3c(img): img = img.reshape(img.shape[0], img.shape[1], 1) img = np.concatenate((img, img, img), axis=2) return img def debug(idx, img_paths, imgs, output_root): if not os.path.exists(output_root): os.makedirs(output_root) col = [] for i in range(len(imgs)): row = [] for j in range(len(imgs[i])): # img = cv2.copyMakeBorder(imgs[i][j], 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=[255, 0, 0]) row.append(imgs[i][j]) res = np.concatenate(row, axis=1) col.append(res) res = np.concatenate(col, axis=0) img_name = img_paths[idx].split('/')[-1] print(idx, '/', len(img_paths), img_name) cv2.imwrite(output_root + img_name, res) def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes = np.empty([1, 8], dtype='int32') resBoxes[0, 0] = int(points[0]) resBoxes[0, 4] = int(points[1]) resBoxes[0, 1] = int(points[2]) resBoxes[0, 5] = int(points[3]) resBoxes[0, 2] = int(points[4]) resBoxes[0, 6] = int(points[5]) resBoxes[0, 3] = int(points[6]) resBoxes[0, 7] = int(points[7]) pointMat = resBoxes[0].reshape([2, 4]).T return plg.Polygon(pointMat) def test(args, file=None): result = [] data_loader = DataLoader(long_size=args.long_size, file=file) test_loader = torch.utils.data.DataLoader( data_loader, batch_size=1, shuffle=False, num_workers=2, drop_last=True) slice = 0 # Setup Model if args.arch == "resnet50": model = models.resnet50(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet101": model = models.resnet101(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet152": model = models.resnet152(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "mobilenet": model = models.Mobilenet(pretrained=True, num_classes=6, scale=args.scale) slice = -1 for param in model.parameters(): param.requires_grad = False # model = model.cuda() if args.resume is not None: if os.path.isfile(args.resume): print("Loading model and optimizer from checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) # model.load_state_dict(checkpoint['state_dict']) d = collections.OrderedDict() for key, value in checkpoint['state_dict'].items(): tmp = key[7:] d[tmp] = value try: model.load_state_dict(d) except: model.load_state_dict(checkpoint['state_dict']) print("Loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) sys.stdout.flush() else: print("No checkpoint found at '{}'".format(args.resume)) sys.stdout.flush() model.eval() total_frame = 0.0 total_time = 0.0 for idx, (org_img, img) in enumerate(test_loader): print('progress: %d / %d' % (idx, len(test_loader))) sys.stdout.flush() # img = Variable(img.cuda(), volatile=True) org_img = org_img.numpy().astype('uint8')[0] text_box = org_img.copy() # torch.cuda.synchronize() start = time.time() # angle detection # org_img, angle = detect_angle(org_img) outputs = model(img) score = torch.sigmoid(outputs[:, slice, :, :]) outputs = (torch.sign(outputs - args.binary_th) + 1) / 2 text = outputs[:, slice, :, :] kernels = outputs # kernels = outputs[:, 0:args.kernel_num, :, :] * text score = score.data.cpu().numpy( )[0].astype(np.float32) text = text.data.cpu().numpy()[0].astype(np.uint8) kernels = kernels.data.cpu().numpy()[0].astype(np.uint8) if args.arch == 'mobilenet': pred = pse2(kernels, args.min_kernel_area / (args.scale * args.scale)) else: # c++ version pse pred = pse(kernels, args.min_kernel_area / (args.scale * args.scale)) # python version pse # pred = pypse(kernels, args.min_kernel_area / (args.scale * args.scale)) # scale = (org_img.shape[0] * 1.0 / pred.shape[0], org_img.shape[1] * 1.0 / pred.shape[1]) scale = (org_img.shape[1] * 1.0 / pred.shape[1], org_img.shape[0] * 1.0 / pred.shape[0]) label = pred label_num = np.max(label) + 1 bboxes = [] rects = [] for i in range(1, label_num): points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1] if points.shape[0] < args.min_area / (args.scale * args.scale): continue score_i = np.mean(score[label == i]) if score_i < args.min_score: continue rect = cv2.minAreaRect(points) bbox = cv2.boxPoints(rect) * scale bbox = bbox.astype('int32') bbox = order_point(bbox) # bbox = np.array([bbox[1], bbox[2], bbox[3], bbox[0]]) bboxes.append(bbox.reshape(-1)) rec = [] rec.append(rect[-1]) rec.append(rect[1][1] * scale[1]) rec.append(rect[1][0] * scale[0]) rec.append(rect[0][0] * scale[0]) rec.append(rect[0][1] * scale[1]) rects.append(rec) # torch.cuda.synchronize() end = time.time() total_frame += 1 total_time += (end - start) print('fps: %.2f' % (total_frame / total_time)) sys.stdout.flush() for bbox in bboxes: cv2.drawContours(text_box, [bbox.reshape(4, 2)], -1, (0, 255, 0), 2) image_name = data_loader.img_paths[idx].split('/')[-1].split('.')[0] write_result_as_txt(image_name, bboxes, 'outputs/submit_invoice/') text_box = cv2.resize(text_box, (text.shape[1], text.shape[0])) debug(idx, data_loader.img_paths, [[text_box]], 'data/images/tmp/') result = crnnRec(cv2.cvtColor(org_img, cv2.COLOR_BGR2RGB), rects) result = formatResult(result) # cmd = 'cd %s;zip -j %s %s/*' % ('./outputs/', 'submit_invoice.zip', 'submit_invoice') # print(cmd) # sys.stdout.flush() # util.cmd.Cmd(cmd) return result def calc_axis_iou(a,b,axis=0): if isinstance(b, list): if axis == 0: ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] else: ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else: if axis == 0: iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def getBasics(data): data = sorted(data, key=lambda x:x['cy']) s = [i for i,d in enumerate(data) if re.match(r'住址', d['text'])] e = [i for i,d in enumerate(data) if re.match(r'公民身份号码', d['text'])] s = max(s) if len(s) else 0 e = min(e) if len(e) else 0 title = '' name = '' sex = '' nation = '' born = '' addr = '' no = '' org = '' expire = '' res = [] for i,d in enumerate(data): text = d['text'] if re.match(r'姓名', text): name = text[2:] elif re.match(r'性别', text): sex = text[2] idx = text.find(r'民族') if idx > -1: nation = text[idx+2:idx+3] elif re.match(r'民族', text): nation = text[2] elif re.match(r'出生', text): born = text[2:] elif re.match(r'住址', text): addr = text[2:] + addr s = i elif re.match(r'公民身份号码', text): no = text[6:] elif re.match(r'签发机关', text): org = text[4:] elif re.match(r'有效期限', text): expire = text[4:] else: if i > s and i < e: addr = addr + text if name: title = '正面信息' res = [{'title':title, 'items':[[{'name':r'姓名', 'value':name}, {'name':r'性别', 'value':sex}, {'name':r'民族', 'value':nation}, {'name':r'出生', 'value':born}, {'name':r'住址', 'value':addr}, {'name':r'公民身份号码', 'value':no}]]}] else: title = '反面信息' res = [{'title': title, 'items': [[{'name': r'签发机关', 'value': org}, {'name': r'有效期限', 'value': expire}]]}] return res def formatResult(data): res = getBasics(data) return res if __name__ == '__main__': parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='resnet50') parser.add_argument('--resume', nargs='?', type=str, default=None, help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=1.0, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=7, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=2240, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') args = parser.parse_args() test(args) <file_sep># -*- coding: utf-8 -*- # @Time : 2019/12/4 10:53 # @Author : zhoujun from .iaa_augment import IaaAugment from .augment import * from .random_crop_data import EastRandomCropData,PSERandomCrop from .make_border_map import MakeBorderMap from .make_shrink_map import MakeShrinkMap <file_sep>import os import cv2 import sys import time import math import copy from functools import reduce import collections import torch import argparse import numpy as np import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch.autograd import Variable from torch.utils import data from dataset import DataLoader import models import util # c++ version pse based on opencv 3+ from pse import pse # from angle import detect_angle from apphelper.image import order_point, calc_iou, xy_rotate_box from crnn import crnnRec from eval.invoice.eval_invoice import evaluate # from layout.VGGLocalization import VGGLoc, trans_image # python pse # from pypse import pse as pypse from pse2 import pse2 def get_params(): parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='resnet50') parser.add_argument('--resume', nargs='?', type=str, default='./checkpoints/ctw1500_res50_pretrain_ic17.pth.tar', help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=0.5, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=7, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=2240, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') parser.add_argument('--image_fgbg', nargs='?', type=bool, default=False, help='split image into foreground and background') parser.add_argument('--evaluate', nargs='?', type=bool, default=True, help='evalution') args = parser.parse_args() return args def recognize(im=None, path=None): ret = None try: file = None if im: pass elif path: # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im: dir = os.path.join(os.path.dirname(__file__), '../data/images/invoice/') file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(get_params(), tmpfile) if data: ret = format(data) except Exception as e: print(e) return ret def format(data): return data def extend_3c(img): img = img.reshape(img.shape[0], img.shape[1], 1) img = np.concatenate((img, img, img), axis=2) return img def debug(idx, img_paths, imgs, output_root): if not os.path.exists(output_root): os.makedirs(output_root) col = [] for i in range(len(imgs)): row = [] for j in range(len(imgs[i])): # img = cv2.copyMakeBorder(imgs[i][j], 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=[255, 0, 0]) row.append(imgs[i][j]) res = np.concatenate(row, axis=1) col.append(res) res = np.concatenate(col, axis=0) img_name = img_paths[idx].split('/')[-1] print(idx, '/', len(img_paths), img_name) cv2.imwrite(output_root + img_name, res) def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes = np.empty([1, 8], dtype='int32') resBoxes[0, 0] = int(points[0]) resBoxes[0, 4] = int(points[1]) resBoxes[0, 1] = int(points[2]) resBoxes[0, 5] = int(points[3]) resBoxes[0, 2] = int(points[4]) resBoxes[0, 6] = int(points[5]) resBoxes[0, 3] = int(points[6]) resBoxes[0, 7] = int(points[7]) pointMat = resBoxes[0].reshape([2, 4]).T return plg.Polygon(pointMat) def test(args, file=None): result = [] data_loader = DataLoader(long_size=args.long_size, file=file) test_loader = torch.utils.data.DataLoader( data_loader, batch_size=1, shuffle=False, num_workers=2, drop_last=True) slice = 0 # Setup Model if args.arch == "resnet50": model = models.resnet50(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet101": model = models.resnet101(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet152": model = models.resnet152(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "mobilenet": model = models.Mobilenet(pretrained=True, num_classes=6, scale=args.scale) slice = -1 for param in model.parameters(): param.requires_grad = False # model = model.cuda() if args.resume is not None: if os.path.isfile(args.resume): print("Loading model and optimizer from checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) # model.load_state_dict(checkpoint['state_dict']) d = collections.OrderedDict() for key, value in checkpoint['state_dict'].items(): tmp = key[7:] d[tmp] = value try: model.load_state_dict(d) except: model.load_state_dict(checkpoint['state_dict']) print("Loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) sys.stdout.flush() else: print("No checkpoint found at '{}'".format(args.resume)) sys.stdout.flush() model.eval() total_frame = 0.0 total_time = 0.0 precisions = [] for idx, (org_img, img) in enumerate(test_loader): print('progress: %d / %d' % (idx, len(test_loader))) sys.stdout.flush() # img = Variable(img.cuda(), volatile=True) org_img = org_img.numpy().astype('uint8')[0] text_box = org_img.copy() # torch.cuda.synchronize() start = time.time() # angle detection # org_img, angle = detect_angle(org_img) outputs = model(img) score = torch.sigmoid(outputs[:, slice, :, :]) outputs = (torch.sign(outputs - args.binary_th) + 1) / 2 text = outputs[:, slice, :, :] kernels = outputs # kernels = outputs[:, 0:args.kernel_num, :, :] * text score = score.data.cpu().numpy( )[0].astype(np.float32) text = text.data.cpu().numpy()[0].astype(np.uint8) kernels = kernels.data.cpu().numpy()[0].astype(np.uint8) if args.arch == 'mobilenet': pred = pse2(kernels, args.min_kernel_area / (args.scale * args.scale)) else: # c++ version pse pred = pse(kernels, args.min_kernel_area / (args.scale * args.scale)) # python version pse # pred = pypse(kernels, args.min_kernel_area / (args.scale * args.scale)) # scale = (org_img.shape[0] * 1.0 / pred.shape[0], org_img.shape[1] * 1.0 / pred.shape[1]) scale = (org_img.shape[1] * 1.0 / pred.shape[1], org_img.shape[0] * 1.0 / pred.shape[0]) label = pred label_num = np.max(label) + 1 bboxes = [] rects = [] for i in range(1, label_num): points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1] if points.shape[0] < args.min_area / (args.scale * args.scale): continue score_i = np.mean(score[label == i]) if score_i < args.min_score: continue rect = cv2.minAreaRect(points) bbox = cv2.boxPoints(rect) * scale bbox = bbox.astype('int32') bbox = order_point(bbox) # bbox = np.array([bbox[1], bbox[2], bbox[3], bbox[0]]) bboxes.append(bbox.reshape(-1)) rec = [] rec.append(rect[-1]) rec.append(rect[1][1] * scale[1]) rec.append(rect[1][0] * scale[0]) rec.append(rect[0][0] * scale[0]) rec.append(rect[0][1] * scale[1]) rects.append(rec) # torch.cuda.synchronize() end = time.time() total_frame += 1 total_time += (end - start) print('fps: %.2f' % (total_frame / total_time)) sys.stdout.flush() for bbox in bboxes: cv2.drawContours(text_box, [bbox.reshape(4, 2)], -1, (0, 255, 0), 2) image_name = data_loader.img_paths[idx].split('/')[-1].split('.')[0] write_result_as_txt(image_name, bboxes, 'outputs/submit_invoice/') text_box = cv2.resize(text_box, (text.shape[1], text.shape[0])) debug(idx, data_loader.img_paths, [[text_box]], 'data/images/tmp/') result = crnnRec(cv2.cvtColor(org_img, cv2.COLOR_BGR2RGB), rects) result = formatResult(result) if args.evaluate: image_file = image_name + '.txt' error_file = image_name + '-errors.txt' file = os.path.join(os.path.dirname(__file__), '../data/gt/', image_file) errfile = os.path.join(os.path.dirname(__file__), '../data/error/', error_file) if os.path.exists(file): precision = evaluate(file, errfile, result) print('precision:' + str(precision) + '%') precisions.append(precision) if len(precisions): mean = np.mean(precisions) print('mean precision:' + str(mean) + '%') # cmd = 'cd %s;zip -j %s %s/*' % ('./outputs/', 'submit_invoice.zip', 'submit_invoice') # print(cmd) # sys.stdout.flush() # util.cmd.Cmd(cmd) return result def predict_bbox(args, model, org_img, img, slice): # angle detection # org_img, angle = detect_angle(org_img) outputs = model(img) score = torch.sigmoid(outputs[:, slice, :, :]) outputs = (torch.sign(outputs - args.binary_th) + 1) / 2 text = outputs[:, slice, :, :] kernels = outputs # kernels = outputs[:, 0:args.kernel_num, :, :] * text score = score.data.cpu().numpy()[0].astype(np.float32) text = text.data.cpu().numpy()[0].astype(np.uint8) kernels = kernels.data.cpu().numpy()[0].astype(np.uint8) if args.arch == 'mobilenet': pred = pse2(kernels, args.min_kernel_area / (args.scale * args.scale)) else: # c++ version pse pred = pse(kernels, args.min_kernel_area / (args.scale * args.scale)) # python version pse # pred = pypse(kernels, args.min_kernel_area / (args.scale * args.scale)) # scale = (org_img.shape[0] * 1.0 / pred.shape[0], org_img.shape[1] * 1.0 / pred.shape[1]) scale = (org_img.shape[1] * 1.0 / pred.shape[1], org_img.shape[0] * 1.0 / pred.shape[0]) label = pred label_num = np.max(label) + 1 bboxes = [] rects = [] for i in range(1, label_num): points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1] if points.shape[0] < args.min_area / (args.scale * args.scale): continue score_i = np.mean(score[label == i]) if score_i < args.min_score: continue rect = cv2.minAreaRect(points) bbox = cv2.boxPoints(rect) * scale bbox = bbox.astype('int32') bbox = order_point(bbox) # bbox = np.array([bbox[1], bbox[2], bbox[3], bbox[0]]) bboxes.append(bbox.reshape(-1)) rec = [] rec.append(rect[-1]) rec.append(rect[1][1] * scale[1]) rec.append(rect[1][0] * scale[0]) rec.append(rect[0][0] * scale[0]) rec.append(rect[0][1] * scale[1]) rects.append(rec) return bboxes, rects, text import re def isTitle(text): return re.search(r'(货物|劳务|服.?名称|规.?型号|^单[位价]|^数|.?额$|^税.$|项目|类型|车牌|通行日期)', text) != None # return text.find(r'服务名称') > -1 \ # or text.find(r'规格型号') > -1 \ # or text.find(r'单位') > -1 \ # or text.find(r'数量') > -1 \ # or text.find(r'单价') > -1 \ # or text.find(r'金额') > -1 \ # or text.find(r'税率') > -1 \ # or text.find(r'税额') > -1 def isSummary(text): pattern = re.compile(r'[¥|Y|羊]\d+?\.?\d*') return text==r'计' or text == r'合' or text == r'合计' or pattern.search(text) != None def get_content_boundary(data): title = [i for i, d in enumerate(data) if isTitle(d['text'])] s = title[0] e = title[-1] title.extend([i+s-4 for i,d in enumerate(data[s-4:s]) if abs(d['cy'] - data[s]['cy']) < 10]) title.extend([i+e+1 for i,d in enumerate(data[e+1:e+6]) if abs(d['cy'] - data[e]['cy']) < 10]) s = min(title) e = max(title) lf = min(data[s:e+1], key=lambda x:x['cx']-x['w']/2) summary = [i for i, d in enumerate(data) if isSummary(d['text'])] s = summary[0] summary.extend([i+s-4 for i, d in enumerate(data[s-4:s]) if abs(d['cy'] - data[summary[-1]]['cy']) < 10]) s = min(summary) start = e end = s # rt = [d for d in data[start:end] if re.match(r'\d+\.?\d*$', d['text'])] rt = max(data[start:end], key=lambda x: x['cx']+x['w']/2) left = lf['cx']-lf['w']/2 right = rt['cx']+rt['w']/2 return (start, end, left, right) def check(data, placeholder, dir = 0): try: i = None if isinstance(placeholder,list): for pld in placeholder: f = [x for x,d in enumerate(data) if d == pld] if len(f): i = f[-1] break else: f = [x for x,d in enumerate(data) if d == placeholder] if len(f): i = f[-1] return i except: return None LEFT_MARGIN = 70 RIGHT_MARGIN = 20 def parseLine(line, boundary, isvehicle=False): xmin, xmax = boundary copyed = copy.deepcopy(line) copyed = preprocess_line(copyed) if isvehicle: # ratio, price = get_ratio(copyed, xmax) ratio, price, tax = get_ratio_price_tax(copyed, xmax) # title title = get_title(copyed, xmin) sdate, edate, price, ratio = get_date(copyed, price, ratio) platenum, cartype, sdate, edate = get_platenum_cartype(copyed, sdate, edate) return postprocess_line(title, platenum, cartype, sdate, edate, price, ratio, tax) else: # ratio # ratio, price = get_ratio(copyed, xmax) ratio, price, tax = get_ratio_price_tax(copyed, xmax) # title title = get_title(copyed, xmin) # tax # tax = get_tax(copyed, xmax, ratio) # prices specs, amount, uprice, price, ratio = get_numbers(copyed, price, ratio) #specs specs,unit = get_specs_unit(copyed, specs) return postprocess_line(title, specs, unit, amount, uprice, price, ratio, tax) def preprocess_line(line): line = sorted(line, key=lambda x: x['cx'] - x['w'] / 2) res = [] i = 0 j = 1 while i < len(line) and j < len(line): x = line[i] y = line[j] x1 = x['cx'] + x['w'] / 2 y1 = y['cx'] - y['w'] / 2 if abs(x1 - y1) < 8: x['w'] = y['cx'] + y['w']/2 - x['cx'] + x['w']/2 x['cx'] = (y['cx'] + x['cx']) / 2 x['text'] = x['text'] + y['text'] j = j + 1 else: res.append(x) i = j j = j + 1 res.append(line[i]) return res def is_number(s): try: float(s) return True except ValueError: pass return False def postprocess_line(title, specs, unit, amount, uprice, price, ratio, tax): if tax != '***' and (not tax or not is_number(tax) or float(tax) > float(price) or not '.' in tax) and price and ratio: tax = '%.2f' % (float(price) / 100 * float(ratio[:-1])) return [title, specs, unit, amount, uprice, price, ratio, tax] def get_title(line, xmin): title = '' candidates = [d for d in line if abs(d['cx'] - d['w'] / 2 - xmin) < LEFT_MARGIN] if len(candidates): candidates = sorted(candidates, key=lambda x:x['cy']) for c in candidates: title += c['text'] line.remove(c) if title and not title.startswith('*'): title = '*' + title return title def get_ratio_price_tax(line, xmax): ratio = '' price = '' tax = '' pat = re.compile(r'(\-?[\dBG]+\.?[\dBG]{2})*(([\dBG]+[\%])|([\u4e00-\u9fa5]+税))$') pat2 = re.compile(r'(\-?[\dBG]+\.[\dBG]{2})([\dBG]{1,2}[8])') ratioitem = None for i in range(len(line)-1, -1, -1): text = line[i]['text'] m = pat.match(text) if m: price, ratio = (m.group(1), m.group(2)) if m.group(1) else ('', m.group(2)) else: m = pat2.match(text) if m: price, ratio = (m.group(1), m.group(2)) ratio = ratio[:-1] + '%' if ratio: ratioitem = line.pop(i) break if not ratio: numbers = sorted([i for i,d in enumerate(line) if re.match(r'([\dBG]+\.?[\dBG]{2})*', d['text'])], key=lambda x:line[x]['cx']-line[x]['w']/2) if len(numbers)>=3: i = numbers[-2] d = line[i] m = re.match(r'(\d{1,2})\D+', d['text']) if m: ratio = m.group(1) ratioitem = line.pop(i) if re.search(r'税$', ratio): tax = '***' else: if ratioitem: taxes = [l for l in line if l['cx'] > ratioitem['cx']] if len(taxes): tax = taxes[0]['text'] line.remove(taxes[0]) if not tax: idx = [i for i, d in enumerate(line) if abs(d['cx'] + d['w'] / 2 - xmax) < RIGHT_MARGIN] if len(idx): idx = idx[0] ln = line[idx] tax = ln['text'] line.pop(idx) if len(tax) > 2 and tax.find('.') == -1: tax = tax[:-2] + '.' + tax[-2:] if len(price) and not '.' in price: if tax and ratio: while float(price) > float(tax): prc = price[:-2] + '.' + price[-2:] f_tax = float(tax) f_ratio = float(ratio[:-1]) f_price = float(prc) if abs(f_price * f_ratio / 100.0 - f_tax) > 0.1 and f_ratio < 10: ratio = price[-1] + ratio price = price[:-1] else: price = prc break else: price = price[:-2] + '.' + price[-2:] if price and ratio and not tax: tax = str(round(float(price) * float(ratio[:-1]) / 100.0, 2)) return ratio, price, tax def get_tax(line, xmax, ratio): tax = '' if re.search(r'税$', ratio): tax = '***' idx = [i for i, d in enumerate(line) if abs(d['cx'] + d['w'] / 2 - xmax) < RIGHT_MARGIN] if len(idx): idx = idx[0] ln = line[idx] tax = ln['text'] line.pop(idx) if len(tax) > 2 and tax.find('.') == -1: tax = tax[:-2] + '.' + tax[-2:] return tax def get_ratio(line, xmax): ratio = '' price = '' pat = re.compile(r'(\-?[\dBG]+\.?[\dBG]{2})*(([\dBG]+[\%])|([\u4e00-\u9fa5]+税))$') for i in range(len(line)-1, -1, -1): text = line[i]['text'] m = pat.match(text) if m: price, ratio = (m.group(1), m.group(2)) if m.group(1) else ('', m.group(2)) if ratio: line.pop(i) break if not ratio: numbers = sorted([i for i,d in enumerate(line) if re.match(r'([\dBG]+\.?[\dBG]{2})*', d['text'])], key=lambda x:line[x]['cx']-line[x]['w']/2) if len(numbers)>=3: i = numbers[-2] d = line[i] m = re.match(r'(\d{1,2})\D+', d['text']) if m: ratio = m.group(1) + '%' line.pop(i) return ratio, price def get_numbers(line, price, ratio): specs = '' amount = '' uprice = '' pattern = re.compile(r'\-?[\dBG:]+\.?[\dBG]*$') numbers = [] for d in line: if pattern.match(d['text']): d['text'] = d['text'].replace('B','8').replace('G', '6').replace(':','') numbers.append(d) if len(numbers): for n in numbers: line.remove(n) # preprocess_number(numbers) numbers = sorted(numbers, key=lambda x: x['cx'] - x['w'] / 2) if not ratio and re.match(r'^\d{2,3}$', numbers[-1]['text']): ratio = numbers[-1]['text'] ratio = ratio[:-1] + '%' numbers = numbers[0:-1] if not price: price = numbers[-1]['text'] m = re.match(r'(\d+\.\d{2})\d*(\d{2})$', price) if m and not ratio: price = m.group(1) ratio = m.group(2) + '%' numbers = numbers[0:-1] numlen = len(numbers) if numlen == 3: specs = numbers[0]['text'] amount = numbers[1]['text'] uprice = numbers[2]['text'] elif numlen == 2: num1 = numbers[0]['text'] num2 = numbers[1]['text'] if abs(float(num1) * float(num2) - float(price)) < 0.01: specs = '' amount = num1 uprice = num2 elif abs(float(num2) - float(price)) < 0.01: specs = num1 amount = '1' uprice = num2 else: specs, amount, uprice = get_amount_uprice(price, num2, num1) elif numlen == 1: specs = '' num = numbers[0]['text'] if abs(float(num) - float(price)) < 0.01: amount = '1' uprice = num else: specs, amount, uprice = get_amount_uprice(price, num) if not amount: amount = num return specs, amount, uprice, price, ratio def get_date(line, price, ratio): sdate = '' edate = '' pattern = re.compile(r'\-?[\dBG:]+\.?[\dBG]*$') numbers = [] for d in line: if pattern.match(d['text']): d['text'] = d['text'].replace('B','8').replace('G', '6').replace(':','') numbers.append(d) if len(numbers): for n in numbers: line.remove(n) # preprocess_number(numbers) numbers = sorted(numbers, key=lambda x: x['cx'] - x['w'] / 2) if not ratio and re.match(r'^\d{2,3}$', numbers[-1]['text']): ratio = numbers[-1]['text'] ratio = ratio[:-1] + '%' numbers = numbers[0:-1] if not price: price = numbers[-1]['text'] m = re.match(r'(\d+\.\d{2})\d*(\d{2})$', price) if m and not ratio: price = m.group(1) ratio = m.group(2) + '%' numbers = numbers[0:-1] numlen = len(numbers) if numlen == 2: sdate = numbers[0]['text'] edate = numbers[1]['text'] elif numlen == 1: edate = numbers[0]['text'] return sdate, edate, price, ratio def get_platenum_cartype(line, sdate, edate): platenum = '' cartype = '' pattern = re.compile(r'([\u4e00-\u9fa5]+)(\d{8,})$') if len(line) == 2: platenum = line[0]['text'] cartype = line[1]['text'] elif len(line) == 1: if not sdate: cartype = line[0]['text'] else: platenum = line[0]['text'] if cartype and not sdate: m = pattern.match(cartype) if m: cartype, sdate = m.group(1), m.group(2) if len(sdate) > 8 and not edate: edate = sdate[8:] sdate = sdate[:8] return platenum, cartype, sdate, edate def preprocess_number(numbers): number = [i for i,n in enumerate(numbers) if n['text'].find(':')>-1] adds = [] removes = [] for i in number: d = numbers[i] text = d['text'] splits = text.split(':') d1 = dict(d) d1['text'] = splits[0] d1['w'] = d['w'] * len(d1['text']) / len(text) d1['cx'] = d['cx'] - d['w'] / 2 + d1['w'] / 2 d2 = dict(d) d2['text'] = splits[1] d2['w'] = d['w'] * len(d2['text']) / len(text) d2['cx'] = d['cx'] + d['w'] / 2 - d2['w'] / 2 removes.append(d) adds.extend([d1, d2]) for d in removes: numbers.remove(d) numbers.extend(adds) def get_amount_uprice(price, upricecand, amtcand=None): price = float(price) specs = '' amount = '' uprice = '' copyprice = upricecand dotplace = upricecand.find('.') if dotplace > 0: upricecand = upricecand[:dotplace] + upricecand[dotplace + 1:] if amtcand: upr = str(math.trunc(float(price) / float(amtcand) * 100)) idx = upricecand.find(upr) if idx >= 0: amount = amtcand upricecand = upricecand[idx:] dot = len(upr[:-2]) uprice = upricecand[:dot] + '.' + upricecand[dot:] if not uprice: end = dotplace - 1 if dotplace else len(upricecand) - 2 for idx in range(2, end): amt = int(upricecand[:idx]) upr = upricecand[idx:] if not amt: break calcupr = price / amt if calcupr < 1: break dot = str(calcupr).find('.') if dot > len(upr): break upr = float(upr[0:dot] + '.' + upr[dot:]) if abs(upr - calcupr) < 1: amount = str(amt) uprice = str(upr) break # upr = str(math.trunc(price / amt * 100)) # if len(upr) < 3: # break # i = upricecand.find(upr, idx) # if i > 0: # amount = upricecand[0:i] # uprice = upricecand[i:] # dotplace = str(price / int(amount)).find('.') # uprice = uprice[:dotplace] + '.' + uprice[dotplace:] # break if not uprice: m = re.match(r'(\d+0+)([1-9]\d*\.\d+)', copyprice) if m: amount = m.group(1) uprice = m.group(2) else: uprice = copyprice if amtcand: amount = amtcand else: if amtcand: specs = amtcand return specs,amount,uprice def get_specs_unit(line, specs): unit = '' linelen = len(line) if linelen == 2: specs = line[0]['text'] unit = line[1]['text'] if linelen == 1: text = line[0]['text'] if specs: unit = text else: if len(text) == 1: unit = text else: specs = text return specs,unit def is_wrapped_title(data, line, boundary): res = False xmin = boundary[0] dx = abs(data['cx'] - data['w'] / 2 - xmin) text = data['text'] if dx < LEFT_MARGIN and text[0] != '*': res = True return res def check_title(line, data, start, end, boundary): xmin = boundary[0] lf = min(line, key=lambda d:d['cx'] - d['w'] / 2) dx = abs(lf['cx'] - lf['w'] / 2 - xmin) if dx > LEFT_MARGIN: for d in data[start:end]: dx = abs(d['cx'] - d['w'] / 2 - xmin) if dx < LEFT_MARGIN: iou = [calc_axis_iou(d,l,1) for l in line] if np.mean(iou) > 0.3: line.append(d) data.remove(d) break def check_wrap_title(res, wraptitles, line=None): title = res[-1][0] wraplen = len(wraptitles) if wraplen: idx = 0 if not line: wrap = wraptitles[:] else: wrap = [] ref = min(line, key=lambda x:x['cx']-x['w']/2) for i,w in enumerate(wraptitles): if w['cy'] < ref['cy']: wrap.append(w) else: break if len(wrap): del wraptitles[0:len(wrap)] title = reduce(lambda a,b:a+b, [w['text'] for w in wrap], title) res[-1][0] = title def get_basic_boundary(data): indexes = [i for i, d in enumerate(data) if re.search(r'开.?日期|票日期|校.?码', d['text'])] if len(indexes): end = max(indexes) else: end = 8 lt = min(data[:end+1]+data[-10:], key=lambda x:x['cx']-x['w']/2) rt = max(data[:end+1]+data[-10:], key=lambda x:x['cx']+x['w']/2) left = lt['cx'] - lt['w'] / 2 right = rt['cx'] + rt['w'] / 2 return (0, end, left, right) def get_basic_checkcode(basic): checkcode = '' candidates = [d for d in basic if re.search(r'^校.?码*', d['text'])] if len(candidates): m = re.match(r'^校.?码.*?(\d+)', candidates[0]['text']) checkcode = m.group(1) if m else '' return checkcode PROVINCE = ['河北','山西','辽宁','吉林','黑龙江','江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','海南','四川','贵州','云南','陕西'] def get_basic_type(basic): type = '' title = '' elec = '电子' if len([d for d in basic if re.search(r'发票代码', d['text'])])>0 else '' candidates = [d for d in basic if re.search(r'.*(专?用?|通)?发票', d['text'])] if len(candidates): text = candidates[0]['text'] if text.find('用') >= 0 or text.find('专') >= 0: type = elec + '专用发票' else: type = elec + '普通发票' suffix = '增值税' + type if text[:2] in PROVINCE: title = text[:2] + suffix elif text[:3] in PROVINCE: title = text[:3] + suffix else: titles = [d for d in basic if re.search(r'^.*增值?', d['text'])] if len(titles): title = titles[0]['text'] i = title.find('增') title = title[:i] + suffix else: i = basic.index(candidates[0]) titles = [basic[i-1], basic[i+1]] for t in titles: if re.match(r'[\u4e00-\u9fa5]{2,3}', t['text']): title = t['text'] + suffix break return type,title def get_basic_title(basic, type): title = '' elec = '电子' if len([d for d in basic if re.search(r'发票代码', d['text'])]) > 0 else '' candidates = [d for d in basic if re.search(r'^.*增值?', d['text'])] if len(candidates): title = candidates[0]['text'] i = title.find('增') title = title[:i] + '增值税' + elec + type return title def get_basic_date(basic): date = '' candidates = [d for d in basic if re.search(r'开?票?日期', d['text'])] if len(candidates): date = candidates[0]['text'] date = re.sub(r'开?票?日期:?', '', date) return date def get_basic_code(basic): code = '' candidates = [d for d in basic if re.search(r'(发票代码:?\d+)|(^\d{10,12}$)', d['text'])] if len(candidates): code = max(candidates, key=lambda x:x['cx']+x['w']/2) m = re.match(r'.*?(\d+)$', code['text']) code = m.group(1) if m else '' return code def get_basic_sn(basic): sn = '' candidates = [d for d in basic if re.search(r'(发票号码:?\d+)|(^\d{8}$)', d['text'])] if len(candidates): code = max(candidates, key=lambda x: x['cx'] + x['w'] / 2) m = re.match('.*?(\d+)$', code['text']) sn = m.group(1) if m else '' return sn def get_basic_payee(data): payee = '' candidates = [d for d in data if re.search(r'收款人', d['text'])] if len(candidates): payee = max(candidates, key=lambda x: x['cy']) payee = re.sub(r'收款人:?', '', payee['text']) return payee def get_basic_reviewer(data): reviewer = '' candidates = [d for d in data if re.search(r'(复核|发校)', d['text'])] if len(candidates): reviewer = max(candidates, key=lambda x: x['cy']) reviewer = re.sub(r'(复核|发校):?', '', reviewer['text']) return reviewer def get_basic_drawer(data): drawer = '' candidates = [d for d in data if re.search(r'开票人', d['text'])] if len(candidates): drawer = max(candidates, key=lambda x: x['cy']) drawer = re.sub(r'开票人:?', '', drawer['text']) return drawer def parse_person(text): if text.find(':') >= 0: text = text.split(':')[1] else: text = re.sub(r'.*((开?票?人)|(复?核)|(复)|(收?款?人))', '', text) return text def get_basic_person(data, boundary): payee = '' reviewer = '' drawer = '' xmin = boundary[0] rear = data[-10:] indexes = [i for i,d in enumerate(rear) if re.search(r'收款|开票|复核|人:|复.:', d['text'])] finded = len(indexes) if finded < 3: s = min(indexes) - 3 e = min(10, max(indexes)+3) for i in range(s,e): if i not in indexes: text = rear[i]['text'] l = len(text) if (text.find(':') > -1 and l < 8) or (text.find('钠售') < 0 and l < 4 and l > 1): indexes.append(i) candidates = [rear[i] for i in indexes] if len(candidates): candidates = sorted(candidates, key=lambda x:x['cx']-x['w']/2) left = candidates[0]['cx'] - candidates[0]['w'] / 2 - xmin if left < 25: payee = candidates[0] candidates.pop(0) s = max([i for i, d in enumerate(data) if re.search(r'\(?大写\)?', d['text'])]) e = min([i for i, d in enumerate(data) if re.search(r'\(?小写\)?.*(¥|Y|羊)?\d+', d['text'])]) ref = data[e] s, e = (e-1, s+2) if e < s else (s, e+1) refs = sorted([data[i] for i in range(s,e) if calc_axis_iou(ref, data[i], 1)>0.01], key=lambda x: x['cx']-x['w']/2) if len(refs) >= 3: idx = refs.index(ref) ref = refs[idx-1] rl = ref['cx'] - ref['w'] / 2 rr = ref['cx'] + ref['w'] / 2 for c in candidates: cl = c['cx'] - c['w'] / 2 cr = c['cx'] + c['w'] / 2 if cr > rr: drawer = c break elif rl < c['cx'] and rr > c['cx']: reviewer = c elif finded == 3: payee,reviewer,drawer = sorted([rear[i] for i in indexes],key=lambda x:x['cx']-x['w']/2) if payee: payee = parse_person(payee['text']) if reviewer: reviewer = parse_person(reviewer['text']) if drawer: drawer = parse_person(drawer['text']) return payee, reviewer, drawer def getBasics(data): s, e, left, right = get_basic_boundary(data) basic = data[s:e+1] checkcode = get_basic_checkcode(basic) type, title = get_basic_type(basic) # title = basic_title(basic, checkcode, type) code = get_basic_code(basic) sn = get_basic_sn(basic) date = get_basic_date(basic) # payee = basic_payee(data[-10:]) # reviewer = basic_reviewer(data[-10:]) # drawer = basic_drawer(data[-10:]) payee, reviewer, drawer = get_basic_person(data, [left, right]) res = [[{'name': r'发票类型','value': type}, {'name': r'发票名称','value': title}, {'name': r'发票代码','value': code}, {'name': r'发票号码','value': sn}, {'name': r'开票日期','value': date}, {'name': r'校验码','value': checkcode}, {'name': r'收款人','value': payee}, {'name': r'复核','value': reviewer}, {'name': r'开票人','value': drawer}]] return res # return {"type":type, "title":title, "code":code, "sn":sn, "date":date, "checkcode":checkcode, "payee":payee, "reviewer":reviewer, "drawer":drawer} def get_buyer_boundary(data): indexes = [i for i, d in enumerate(data) if isTitle(d['text'])] end = min(indexes) indexes = [i for i, d in enumerate(data) if i < end and re.search(r'(开票日期)|(校.?码)', d['text'])] start = max(indexes) + 1 indexes = [i for i, d in enumerate(data[start:end]) if calc_axis_iou(data[start-1], d, 1) > 0.3] if len(indexes): start = start + max(indexes) + 1 return start, end def get_buyer_name(buyer): indexes = [i for i, d in enumerate(buyer) if re.search(r'^称:[\u4e00-\u9fa5]{6,}', d['text'])] if len(indexes): index = indexes[0] else: indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{6,}', d['text'])] index = indexes[0] name = buyer[index] text = name['text'] if text.find(':') >= 0: name = text.split(':')[1] else: name = re.sub(r'^[^\u4e00-\u9fa5]+?', '', text) name = re.sub(r'^称', '', name) return name, index def get_buyer_taxnumber(buyer): indexes = [i for i, d in enumerate(buyer) if re.search(r'[0-9A-Z]{16,}', d['text'])] index = indexes[0] taxnumber = buyer[index] text = taxnumber['text'] if text.find(':') >= 0: taxnumber = text.split(':')[1] else: taxnumber = re.sub(r'^[^0-9A-Z]+?', '', text) return taxnumber, index def get_buyer_address(buyer): address = '' index = 0 indexes = [i for i, d in enumerate(buyer) if re.search(r'电话:[\u4e00-\u9fa5]{7,}', d['text'])] if not len(indexes): indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text'])] if len(indexes): index = indexes[0] address = buyer[index] text = address['text'] if text.find(':') >= 0: address = text.split(':')[1] else: address = text if not re.search(r'[0-9\-]{11,}$', address): indexes = [i for i, d in enumerate(buyer) if re.match(r'\d+$', d['text']) and i > index] if len(indexes): index = indexes[0] address += buyer[index]['text'] for prov in PROVINCE: idx = address.find(prov) if idx > 0: address = address[idx:] break return address, index def get_buyer_account(buyer): account = '' indexes = [i for i, d in enumerate(buyer) if re.search(r'账号:[\u4e00-\u9fa5]{7,}', d['text'])] if not len(indexes): indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text'])] if len(indexes): index = indexes[0] account = buyer[index] text = account['text'] if text.find(':') >= 0: account = text.split(':')[1] else: account = text if not re.search(r'\d{12,}$', account): indexes = [i for i, d in enumerate(buyer) if re.match(r'\d{12,}$', d['text']) and i > index] if len(indexes): index = indexes[0] account += buyer[index]['text'] idx = account.find(r'账号') if idx >= 0: account = account[idx+2:] return account def getBuyer(data): start, end = get_buyer_boundary(data) buyer = data[start:end] name, index = get_buyer_name(buyer) buyer = buyer[index+1:] taxnum, index = get_buyer_taxnumber(buyer) buyer = buyer[index+1:] address, index = get_buyer_address(buyer) buyer = buyer[index+1:] account = get_buyer_account(buyer) res = [[{'name':r'名称', 'value':name}, {'name':r'纳税人识别号', 'value':taxnum}, {'name':r'地址、电话', 'value':address}, {'name':r'开户行及账号','value':account}]] return res # return {"name":name, "taxnum":taxnum, "address":address, "account":account} def isVehicle(data): ret = False l = len(data) for d in data[:int(l/2)]: if re.search(r'项目|类型|车牌|通行日期', d['text']): ret = True break return ret def getContent(data): res = [] start,end,left,right = get_content_boundary(data) content = data[start+1:end] isvehicle = isVehicle(data) # top = min(content, key=lambda x:float(x['cy'])-float(x['h']/2)) # bottom = max(content, key=lambda x: float(x['cy'])+float(x['h']/2)) # lh = (bottom['cy'] + bottom['h']/2 - top['cy'] + top['h']/2) / 8 lt = min(content, key=lambda x:float(x['cx'])-float(x['w']/2)) rb = max(content, key=lambda x: float(x['cx'])+float(x['w']/2)) left = float(lt['cx'])-float(lt['w']/2) right = float(rb['cx'])+float(rb['w']/2) line = [] wraptitle = [] for idx,ct in enumerate(content): deal = False iswrap = is_wrapped_title(ct, line, [left,right]) if not iswrap: linelen = len(line) if linelen: y_ious = [] for l in line: x_iou = calc_axis_iou(l, ct) y_iou = calc_axis_iou(l, ct, 1) y_ious.append(y_iou) if x_iou > 0.3: deal = True break if not deal and np.mean(y_ious) < 0.05: deal = True if deal == False: line.append(ct) else: check_title(line, content, idx+1, idx+4, [left,right]) if len(res): check_wrap_title(res, wraptitle, line) parsed = parseLine(line, [left, right], isvehicle) res.append(parsed) line = [ct] else: wraptitle.append(ct) if len(line) + len(wraptitle) >= 3: if len(res): check_wrap_title(res, wraptitle, line) if len(wraptitle): line.extend(wraptitle) parsed = parseLine(line, [left, right], isvehicle) res.append(parsed) ret = [] calcprice = 0 calctax = 0 for r in res: if isvehicle: title, platenum, type, sdate, edate, price, ratio, tax = r ret.append([{'name': r'项目名称', 'value': title}, {'name': r'车牌号', 'value': platenum}, {'name': r'类型', 'value': type}, {'name': r'通行日期起', 'value': sdate}, {'name': r'通行日期止', 'value': edate}, {'name': r'金额', 'value': price}, {'name': r'税率', 'value': ratio}, {'name': r'税额', 'value': tax}]) else: title, specs, unit, amount, uprice, price, ratio, tax = r ret.append([{'name': r'名称', 'value': title}, {'name': r'规格型号', 'value': specs}, {'name': r'单位', 'value': unit}, {'name': r'数量', 'value': amount}, {'name': r'单价', 'value': uprice}, {'name': r'金额', 'value': price}, {'name': r'税率', 'value': ratio}, {'name': r'税额', 'value': tax}]) calcprice += float(price) calctax += float(tax) if is_number(tax) else 0 calctotal = '%.2f' % (calcprice + calctax) calcprice = '%.2f' % calcprice if calctax <= 0.001: calctax = '***' else: calctax = '%.2f' % calctax return ret, (calctotal, calcprice, calctax) def get_seller_boundary(data): s = max([i for i, d in enumerate(data) if re.search(r'\(?大写\)?', d['text'])]) e = min([i for i, d in enumerate(data) if re.search(r'\(?小写\)?.*(¥|Y|羊)?\d+', d['text'])]) start = max([s,e]) + 1 if abs(s-e) == 1: start = start + 1 end = len(data) - 2 return start, end def get_seller_name(buyer): name = '' index = -1 indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{6,}', d['text'])] if len(indexes): index = indexes[0] name = buyer[index] text = name['text'] if text.find(':') >= 0: name = text.split(':')[1] else: name = re.sub(r'^[^\u4e00-\u9fa5]+?', '', text) name = re.sub(r'^称|你', '', name) return name, index def get_seller_taxnumber(buyer): taxnumber = '' index = -1 indexes = [i for i, d in enumerate(buyer) if re.search(r':[0-9A-Z]{16,}|^[0-9A-Z]{16,}', d['text'])] if len(indexes): index = indexes[0] taxnumber = buyer[index] text = taxnumber['text'] if text.find(':') >= 0: taxnumber = text.split(':')[1] else: taxnumber = re.sub(r'^[^0-9A-Z]+?', '', text) return taxnumber, index def get_seller_address(buyer): address = '' index = -1 indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text'])] if len(indexes): index = indexes[0] address = buyer[index] text = address['text'] if text.find(':') >= 0: address = text.split(':')[1] else: address = text address = re.sub(r'^地址、?电话', '', address) if not re.search(r'[0-9\-]{11,}$', address): indexes = [i for i, d in enumerate(buyer) if re.match(r'\d+$', d['text']) and i > index] if len(indexes): index = indexes[0] address += buyer[index]['text'] for prov in PROVINCE: idx = address.find(prov) if idx > 0: address = address[idx:] break return address, index def get_seller_account(buyer): account = '' indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text'])] if len(indexes): index = indexes[0] account = buyer[index] text = account['text'] if text.find(':') >= 0: splittxt = text.split(':') account = ''.join(splittxt[1:]) else: account = text if not re.search(r'\d{12,}$', account): indexes = [i for i, d in enumerate(buyer) if re.match(r'\d+$', d['text']) and i > index] if len(indexes): index = indexes[0] account += buyer[index]['text'] idx = account.find(r'账号') if idx >= 0: account = account[idx+2:] return account def getSeller(data): start, end = get_seller_boundary(data) seller = data[start:end] name, index = get_seller_name(seller) seller = seller[index + 1:] taxnum, index = get_seller_taxnumber(seller) seller = seller[index + 1:] address, index = get_seller_address(seller) seller = seller[index + 1:] account = get_seller_account(seller) res = [[{'name': r'名称', 'value': name}, {'name': r'纳税人识别号', 'value': taxnum}, {'name': r'地址、电话', 'value': address}, {'name': r'开户行及账号', 'value': account}]] return res # return {"name": name, "taxnum": taxnum, "address": address, "account": account} def get_summation_boundary(data): summation = [i for i, d in enumerate(data) if re.search(r'\(?大写\)?', d['text'])] summation.extend([i for i, d in enumerate(data) if re.search(r'\(?小写\)?.*(¥|Y|羊)?[\d\.]+$', d['text'])]) summation.extend([i for i, d in enumerate(data) if re.search(r'(¥|Y|羊)[\d+\.]+$', d['text'])]) start = min(summation) - 1 end = max(summation) + 1 return start, end def check_price(price, calc): if price: price = re.sub(r'^\D+', '', price['text']) if re.search(r'[^\d\.]', price): price = calc else: idx = price.rfind(r'.') if idx <= 0: if len(price) > 2: price = price[:-2] + '.' + price[-2:] else: price = price[:idx].replace(r'.', '') + (price[idx:] if len(price[idx:]) <= 3 else price[idx:idx + 3]) if len(price) <= 2: price = calc else: price = calc return price def getSummation(data, calcsum): benchmark = ['仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '圆', '角', '分'] chinesedigit = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖','拾'] tax = '' price = '' total = '' capital = '' calctotal, calcprice, calctax = calcsum _,_,_,right = get_content_boundary(data) start, end = get_summation_boundary(data) summation = data[start:end] prices = [d for d in summation if re.search(r'(¥|Y|羊)?[\d\.]+$', d['text'])] if len(prices): prices = sorted(prices, key=lambda x: x['cy'], reverse=True) p = prices[0] if calc_axis_iou(p, prices[1:], 1) < 0.01: total = p prices.remove(p) if len(prices): prices = sorted(prices, key=lambda x: x['cx'], reverse=True) p = prices[0] if abs(p['cx']+p['w']/2 - right) < RIGHT_MARGIN: tax = p prices.remove(p) if len(prices): price = prices[0] total = check_price(total, calctotal) price = check_price(price, calcprice) tax = check_price(tax, calctax) strtotal = re.sub(r'\.', '', total) bm = benchmark[-len(strtotal):] for (c, b) in zip(strtotal, bm): capital += chinesedigit[int(c)] + b if int(total[-2:]) == 0: capital = capital[:-4] + '整' capital = re.sub(r'零[仟佰拾角分]', '零', capital) capital = re.sub(r'零{2,}', '零', capital) capital = re.sub(r'零$', '', capital) capital = re.sub(r'零圆', '圆', capital) res = [[{'name': r'金额合计', 'value': price}, {'name': r'税额合计', 'value': tax}, {'name': r'价税合计(大写)', 'value': capital}, {'name': r'价税合计(小写)', 'value': total}]] return res def calc_axis_iou(a,b,axis=0): if isinstance(b, list): if axis == 0: ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] else: ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else: if axis == 0: iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def sort_result(data): data = sorted(data, key=lambda d: d['cy']) lines = [] line = [] for i in range(len(data)): d = data[i] if not len(line): line.append(d) else: iou_x = calc_axis_iou(d, line, 0) iou_y = calc_axis_iou(d, line, 1) if iou_y > 0.6 and iou_x < 0.1: line.append(d) else: line = sorted(line, key=lambda l:l['cx']-l['w']/2) lines.append(line) line = [d] if len(line): line = sorted(line, key=lambda l: l['cx'] - l['w'] / 2) lines.append(line) return lines def formatResult(data): basic = getBasics(data) buyer = getBuyer(data) content,calcsum = getContent(data) seller = getSeller(data) summation = getSummation(data, calcsum) res = [{'title':r'发票基本信息', 'items':basic}, {'title':r'购买方', 'items':buyer}, {'title':r'销售方', 'items':seller}, {'title':r'货物或应税劳务、服务', 'items':content}, {'title':r'合计', 'items':summation}] return res # return {"basic":basic, "buyer":buyer, "content":content, "seller":seller} if __name__ == '__main__': parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='resnet50') parser.add_argument('--resume', nargs='?', type=str, default=None, help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=1.0, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=7, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=960, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') args = parser.parse_args() test(args) <file_sep>import os import cv2 import sys import time import math import copy from functools import reduce import collections import torch import argparse import numpy as np import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch.autograd import Variable from torch.utils import data from dataset import DataLoader import models import util # c++ version pse based on opencv 3+ from pse import pse # from angle import detect_angle from apphelper.image import order_point, calc_iou, xy_rotate_box, solve from crnn import crnnRec from eval.invoice.eval_invoice import evaluate from layout.VGGLocalization import VGGLoc, trans_image from layout.invoice_layout import detect_layout, get_roi from app import invoice as EI # python pse # from pypse import pse as pypse from pse2 import pse2 # localization for cross point vggloc = VGGLoc() vggloc.load_pretrain("cpu") vggloc.load_state_dict(torch.load('./checkpoints/layout_model.pth', map_location = "cpu")) def get_params() : parser = argparse.ArgumentParser(description = 'Hyperparams') parser.add_argument('--arch', nargs = '?', type = str, default = 'resnet50') parser.add_argument('--resume', nargs = '?', type = str, default = './checkpoints/ctw1500_res50_pretrain_ic17.pth.tar', help = 'Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs = '?', type = float, default = 0.7, help = 'Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs = '?', type = int, default = 7, help = 'Path to previous saved model to restart from') parser.add_argument('--scale', nargs = '?', type = int, default = 1, help = 'Path to previous saved model to restart from') parser.add_argument('--long_size', nargs = '?', type = int, default = 2240, help = 'Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs = '?', type = float, default = 5.0, help = 'min kernel area') parser.add_argument('--min_area', nargs = '?', type = float, default = 300.0, help = 'min area') parser.add_argument('--min_score', nargs = '?', type = float, default = 0.5, help = 'min score') parser.add_argument('--evaluate', nargs = '?', type = bool, default = True, help = 'evalution') args = parser.parse_args() return args def recognize(im = None, path = None) : ret = None try : file = None if im : pass elif path : # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im : dir = os.path.join(os.path.dirname(__file__), '../data/images/invoice/') file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(get_params(), tmpfile) if data : ret = format(data) except Exception as e : print(e) return ret def format(data) : return data def extend_3c(img) : img = img.reshape(img.shape[0], img.shape[1], 1) img = np.concatenate((img, img, img), axis = 2) return img def debug(idx, img_paths, imgs, output_root) : if not os.path.exists(output_root) : os.makedirs(output_root) col = [] for i in range(len(imgs)) : row = [] for j in range(len(imgs[i])) : # img = cv2.copyMakeBorder(imgs[i][j], 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=[255, 0, 0]) row.append(imgs[i][j]) res = np.concatenate(row, axis = 1) col.append(res) res = np.concatenate(col, axis = 0) img_name = img_paths[idx].split('/')[-1] print(idx, '/', len(img_paths), img_name) cv2.imwrite(output_root + img_name, res) def write_result_as_txt(image_name, bboxes, path) : filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes) : values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) def polygon_from_points(points) : """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes = np.empty([1, 8], dtype = 'int32') resBoxes[0, 0] = int(points[0]) resBoxes[0, 4] = int(points[1]) resBoxes[0, 1] = int(points[2]) resBoxes[0, 5] = int(points[3]) resBoxes[0, 2] = int(points[4]) resBoxes[0, 6] = int(points[5]) resBoxes[0, 3] = int(points[6]) resBoxes[0, 7] = int(points[7]) pointMat = resBoxes[0].reshape([2, 4]).T return plg.Polygon(pointMat) def test(args, file = None) : result = [] data_loader = DataLoader(long_size = args.long_size, file = file) test_loader = torch.utils.data.DataLoader( data_loader, batch_size = 1, shuffle = False, num_workers = 2, drop_last = True) slice = 0 # Setup Model if args.arch == "resnet50" : model = models.resnet50(pretrained = True, num_classes = 7, scale = args.scale) elif args.arch == "resnet101" : model = models.resnet101(pretrained = True, num_classes = 7, scale = args.scale) elif args.arch == "resnet152" : model = models.resnet152(pretrained = True, num_classes = 7, scale = args.scale) elif args.arch == "mobilenet" : model = models.Mobilenet(pretrained = True, num_classes = 6, scale = args.scale) slice = -1 for param in model.parameters() : param.requires_grad = False # model = model.cuda() if args.resume is not None : if os.path.isfile(args.resume) : print("Loading model and optimizer from checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) # model.load_state_dict(checkpoint['state_dict']) d = collections.OrderedDict() for key, value in checkpoint['state_dict'].items() : tmp = key[7 :] d[tmp] = value try : model.load_state_dict(d) except : model.load_state_dict(checkpoint['state_dict']) print("Loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) sys.stdout.flush() else : print("No checkpoint found at '{}'".format(args.resume)) sys.stdout.flush() model.eval() total_frame = 0.0 total_time = 0.0 precisions1 = [] for idx, (org_img, img) in enumerate(test_loader) : try : print('progress: %d / %d' % (idx, len(test_loader))) sys.stdout.flush() # img = Variable(img.cuda(), volatile=True) org_img = org_img.numpy().astype('uint8')[0] text_box = org_img.copy() # torch.cuda.synchronize() start = time.time() crop_img = crop_image(org_img) iselectric = is_electric_invoice(crop_img) if iselectric : bboxes, rects, text = predict_bbox(EI.get_params(), model, org_img, img, slice) data = crnnRec(cv2.cvtColor(org_img, cv2.COLOR_BGR2RGB), rects) result = EI.formatResult(data) else : fg_img, bg_img = split_fgbg_from_image(crop_img) text_box = crop_img.copy() bg_scaled = data_loader.scale(bg_img) bg_bboxes, bg_rects, text = predict_bbox(args, model, crop_img, bg_scaled, slice) bg_data = crnnRec(cv2.cvtColor(bg_img, cv2.COLOR_BGR2RGB), bg_rects) fg_scaled = data_loader.scale(fg_img) fg_bboxes, fg_rects, text = predict_bbox(args, model, crop_img, fg_scaled, slice) fg_data = crnnRec(cv2.cvtColor(crop_img, cv2.COLOR_BGR2RGB), fg_rects) fg_data, fg_bboxes = layout_adjustment(fg_data, fg_bboxes, crop_img, args, model, slice, data_loader.scale) bboxes = fg_bboxes result = formatResult(bg_data, fg_data) # torch.cuda.synchronize() end = time.time() total_frame += 1 total_time += (end - start) print('fps: %.2f' % (total_frame / total_time)) sys.stdout.flush() for bbox in bboxes : cv2.drawContours(text_box, [bbox.reshape(4, 2)], -1, (0, 255, 0), 2) image_name = data_loader.img_paths[idx].split('/')[-1].split('.')[0] write_result_as_txt(image_name, bboxes, 'outputs/submit_invoice/') text_box = cv2.resize(text_box, (text.shape[1], text.shape[0])) debug(idx, data_loader.img_paths, [[text_box]], '../data/images/tmp/') # result = crnnRec(cv2.cvtColor(org_img, cv2.COLOR_BGR2RGB), rects) # result = formatResult(bg_data, fg_data) if args.evaluate : image_file = image_name + '.txt' error_file = image_name + '-errors.txt' file = os.path.join(os.path.dirname(__file__), '../data/gt/', image_file) errfile = os.path.join(os.path.dirname(__file__), '../data/error/', error_file) if os.path.exists(file) : precision = evaluate(file, errfile, result) print('precision1:' + str(precision[0]) + '%') precisions1.append(precision[0]) if not iselectric : bg_file = image_name + '_background.jpg' file = os.path.join(os.path.dirname(__file__), '../data/error/images/', bg_file) cv2.imwrite(file, bg_img) fg_file = image_name + '_foreground.jpg' file = os.path.join(os.path.dirname(__file__), '../data/error/images/', fg_file) cv2.imwrite(file, fg_img) except Exception as e : print(e) # cmd = 'cd %s;zip -j %s %s/*' % ('./outputs/', 'submit_invoice.zip', 'submit_invoice') # print(cmd) sys.stdout.flush() # util.cmd.Cmd(cmd) if len(precisions1) : mean = np.mean(precisions1) print('mean precision1:' + str(mean) + '%') return result def predict_bbox(args, model, org_img, img, slice) : # angle detection # org_img, angle = detect_angle(org_img) outputs = model(img) score = torch.sigmoid(outputs[:, slice, :, :]) outputs = (torch.sign(outputs - args.binary_th) + 1) / 2 text = outputs[:, slice, :, :] kernels = outputs # kernels = outputs[:, 0:args.kernel_num, :, :] * text score = score.data.cpu().numpy()[0].astype(np.float32) text = text.data.cpu().numpy()[0].astype(np.uint8) kernels = kernels.data.cpu().numpy()[0].astype(np.uint8) if args.arch == 'mobilenet' : pred = pse2(kernels, args.min_kernel_area / (args.scale * args.scale)) else : # c++ version pse pred = pse(kernels, args.min_kernel_area / (args.scale * args.scale)) # python version pse # pred = pypse(kernels, args.min_kernel_area / (args.scale * args.scale)) # scale = (org_img.shape[0] * 1.0 / pred.shape[0], org_img.shape[1] * 1.0 / pred.shape[1]) scale = (org_img.shape[1] * 1.0 / pred.shape[1], org_img.shape[0] * 1.0 / pred.shape[0]) label = pred label_num = np.max(label) + 1 bboxes = [] rects = [] for i in range(1, label_num) : points = np.array(np.where(label == i)).transpose((1, 0))[:, : :-1] if points.shape[0] < args.min_area / (args.scale * args.scale) : continue score_i = np.mean(score[label == i]) if score_i < args.min_score : continue rect = cv2.minAreaRect(points) bbox = cv2.boxPoints(rect) * scale bbox = bbox.astype('int32') bbox = order_point(bbox) # bbox = np.array([bbox[1], bbox[2], bbox[3], bbox[0]]) bboxes.append(bbox.reshape(-1)) rec = [] rec.append(rect[-1]) rec.append(rect[1][1] * scale[1]) rec.append(rect[1][0] * scale[0]) rec.append(rect[0][0] * scale[0]) rec.append(rect[0][1] * scale[1]) rects.append(rec) return bboxes, rects, text def is_electric_invoice(crop_image) : h, w, c = crop_image.shape l = int(w * 0.08) r = int(w * 0.125) t = int(h * 0.02) b = int(h * 0.125) img = crop_image[t :b, l :r, :] show_image('bar code', img) color_dict = { 'blue' : [np.array([100, 43, 46]), np.array([125, 255, 255])], 'black' : [np.array([0, 0, 0]), np.array([180, 255, 46])], # 'white': [np.array([0,0,221]), np.array([180,30,255])], } hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) maxsum = 500 color = None for d in color_dict : mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1]) binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)[1] binary = cv2.dilate(binary, None, iterations = 2) cnts, hiera = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) sum = 0 for c in cnts : sum += cv2.contourArea(c) if sum > maxsum : maxsum = sum color = d return color == 'black' def show_image(winname, img) : # cv2.namedWindow(winname, 0) # cv2.resizeWindow(winname, 800, 600) # cv2.imshow(winname, img) # cv2.waitKey(0) # cv2.destroyAllWindows() # cv2.imwrite('data/images/tmp/'+winname+'.jpg', img) pass def calc_std(data) : a = np.array(data) b = np.mean(a) c = a - b d = c ** 2 e = np.mean(d) f = e ** 0.5 return f def gamma_trans(img) : # gamma函数处理 grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mean = np.mean(grey) gamma = math.log10(mean / 255) / math.log10(0.5) gamma_table = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)] # 建立映射表 gamma_table = np.round(np.array(gamma_table)).astype(np.uint8) # 颜色值为整数 return cv2.LUT(img, gamma_table) # 图片颜色查表。另外可以根据光强(颜色)均匀化原则设计自适应算法。 def get_dark_area(img, bright) : contours, hierarchy = cv2.findContours(bright, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key = cv2.contourArea, reverse = True) contour = contours[0] epsilon = 0.001 * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True) mask = np.zeros(img.shape[:2], np.uint8) cv2.drawContours(mask, [approx], -1, 255, -1) mask = cv2.GaussianBlur(mask, (5, 5), 0) target = cv2.bitwise_and(img, img, mask = mask) target = gamma_trans(target) return target def get_color_mask(img) : color_dict = { 'blue' : [np.array([100, 43, 46]), np.array([125, 255, 255])], # 'blue' : [np.array([69, 43, 46]), np.array([125, 255, 255])], 'black' : [np.array([0, 0, 0]), np.array([180, 255, 46])], 'grey' : [np.array([0, 0, 46]), np.array([180, 10, 110])] } h, w, c = img.shape boxes = [ [h // 2 - h // 8, h // 2 + h // 8, 0, w // 4], # left [h // 2 - h // 8, h // 2 + h // 8, w * 3 // 4, w], # right ] # t = h // 2 - h // 8 # b = h // 2 + h // 8 # l = w // 4 - w // 8 # r = w // 4 + w // 8 # crop = img[t:b, l:r, :] # hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV) # main_color = [255, 255, 255] text_color = 'blue' # for box in boxes: # t,b,l,r = box # crop = img[t:b, l:r, :] # # # image = Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)) # # small_image = image.resize((80, 80)) # # result = small_image.convert('P', palette=Image.ADAPTIVE, colors=5) # image with 5 dominating colors # # result = result.convert('RGB') # # # result.show() # 显示图像 # # main_colors = result.getcolors(80 * 80) # # main_colors = sorted(main_colors, key=lambda x: x[0]) # # main_color = min([main_color, list(main_colors[0][1])]) # # if text_color != 'blue': # hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV) # maxsum = 0 # for d in color_dict: # mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1]) # binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)[1] # binary = cv2.dilate(binary, None, iterations=2) # cnts, hiera = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # sum = 0 # for c in cnts: # sum += cv2.contourArea(c) # if sum > maxsum: # maxsum = sum # text_color = d # print('main color: {}'.format(main_color)) print('text color: {}'.format(text_color)) if text_color == 'blue' : normalized, scale = trans_image(img) # yuv = cv2.cvtColor(normalized, cv2.COLOR_BGR2YUV) # Y, U, V = cv2.split(yuv) # # mean = round(np.mean(Y)) # std = calc_std(Y) # print('mean Y: {}, stand deviance Y: {}'.format(mean, std)) B, G, R = cv2.split(normalized) mean = round(np.mean(B)) std = calc_std(B) print('mean B: {}, stand deviance B: {}'.format(mean, std)) yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) Y, U, V = cv2.split(yuv) if mean > 1 or 0.35 < std < 0.41 : mask = cv2.inRange(U, 135, 255) # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # mask = cv2.inRange(hsv, color_dict[text_color][0], color_dict[text_color][1]) # grey_mask = cv2.inRange(hsv, color_dict['black'][0], color_dict['black'][1]) # mask = cv2.bitwise_or(mask, grey_mask) else : mask = cv2.inRange(U, 130, 255) bright = cv2.inRange(Y, 150, 255) dark = get_dark_area(img, bright) hsv = cv2.cvtColor(dark, cv2.COLOR_BGR2HSV) bmask = cv2.inRange(hsv, np.array([90, 0, 43]), np.array([150, 255, 255])) mask = cv2.bitwise_or(mask, bmask) elif text_color == 'black' : hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, color_dict[text_color][0], color_dict[text_color][1]) grey_mask = cv2.inRange(hsv, color_dict['grey'][0], color_dict['grey'][1]) mask = cv2.bitwise_or(mask, grey_mask) return mask def crop_image(org_img) : h, w, c = org_img.shape points = vggloc.get_points(org_img) t = min(points, key = lambda x : x[1])[1] b = max(points, key = lambda x : x[1])[1] l = min(points, key = lambda x : x[0])[0] r = max(points, key = lambda x : x[0])[0] dy = b - t dx = r - l t = max([0, int(t - dy * 0.3)]) b = min([h, int(b + dy * 0.14)]) l = max([0, int(l - dx * 0.05)]) r = min([w, int(r + dx * 0.05)]) crop = org_img[t :b, l :r, :] show_image('croped', crop) return crop # def get_roi(img, points): # t = min(points, key=lambda x: x[1])[1] # b = max(points, key=lambda x: x[1])[1] # l = min(points, key=lambda x: x[0])[0] # r = max(points, key=lambda x: x[0])[0] # # return img[t:b, l:r, :] def split_fgbg_from_image(img) : # set blue thresh 设置HSV中蓝色、天蓝色范围 mask_color = [255, 255, 255] mask = get_color_mask(img) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 13)) dilated = cv2.dilate(mask, kernel) bg_img = np.copy(img) bg_img[dilated != 0] = mask_color fg_img = np.copy(img) fg_img[dilated == 0] = mask_color show_image('background', bg_img) show_image('foreground', fg_img) return fg_img, bg_img def layout_adjustment(target, tboxes, img, args, model, slice, scaleFunc) : layouts = detect_layout(vggloc, img) if layouts['content'] is not None : content = layouts['content'] replace = {} insert = {} for c in content : roi = get_roi(img, c) show_image('roi', roi) scaled = scaleFunc(roi) bboxes, rects, text = predict_bbox(args, model, roi, scaled, slice) data = crnnRec(cv2.cvtColor(roi, cv2.COLOR_BGR2RGB), rects) s = [i for i, d in enumerate(data) if re.search(r'服?务?名称$|规?格?型号$', d['text'])] e = [i for i, d in enumerate(data) if re.search(r'(^合$|^计$|^合计$)', d['text'])] s = max(s) + 1 if len(s) else 0 e = min(e) if len(e) else len(data) if not s : break data = data[s :e] for d in data : t = [i for i, t in enumerate(target) if calc_axis_iou(d, t, 1) > 0.6 and (calc_axis_iou(d, t) > 0.6 or ( d['cx'] - d['w'] / 2 > t['cx'] - t['w'] / 2 and d['cx'] + d['w'] / 2 < t['cx'] + t[ 'w'] / 2))] if len(t) : k = t[0] if not k in replace : replace[k] = d else : if not k in insert : insert[k] = [] insert[k].append(d) else : for k, v in replace.items() : y_iou = calc_axis_iou(v, d, 1) if y_iou > 0.4 : if not k in insert : insert[k] = [] insert[k].append(d) break for k, v in replace.items() : target[k] = v keys = sorted([k for k in insert], key = lambda x : x, reverse = True) for k in keys : target = target[:k + 1] + insert[k] + target[k + 1 :] return target, tboxes import re def isTitle(text) : return re.search(r'(货物.?|.?服务名|服.?名称|.?务名称|规.?型号|^单.?|^数|^金.?|.?额$|^税.{0,2}$|项目|类型|车牌|通行日期)', text) != None # return re.search(r'(货物.?|.?服务名|服.?名称|.?务名称|规.?型号|^单.?|^数|.?额$|^税.$|项目|类型|车牌|通行日期)', text) != None # return text.find(r'服务名称') > -1 \ # or text.find(r'规格型号') > -1 \ # or text.find(r'单位') > -1 \ # or text.find(r'数量') > -1 \ # or text.find(r'单价') > -1 \ # or text.find(r'金额') > -1 \ # or text.find(r'税率') > -1 \ # or text.find(r'税额') > -1 def isSummary(text) : return text == r'合' or text == r'计' or text == r'合计' def get_content_boundary(bg_data, fg_data) : titles = [d for d in bg_data if isTitle(d['text'])] titles = [d for d in bg_data if calc_axis_iou(d, titles, 1) > 0.2] titles = sorted(titles, key = lambda x : x['cy'] + x['h'] / 2, reverse = True) if len(titles) > 8 : titles = titles[:8] # right = max(titles, key=lambda x:x['cx']+x['w']/2) bottom = titles[0] summary = [d for d in fg_data if re.search(r'(¥|Y|羊)\d+', d['text'])] if len(summary) > 3 : summary = summary[-3 :] right = max(summary, key = lambda x : x['cx'] + x['w'] / 2) summary = min(summary, key = lambda x : x['cy'] - x['h'] / 2) content = [d for d in fg_data if d['cy'] > (bottom['cy'] - bottom['h'] / 2) and d['cy'] < summary['cy'] and ( d['cx'] < right['cx'] or calc_axis_iou(d, right) > 0.1)] while len(content) : left = min(content, key = lambda x : x['cx'] - x['w'] / 2) if len(left['text']) < 3 : content.remove(left) else : break return content def check(data, placeholder, dir = 0) : try : i = None if isinstance(placeholder, list) : for pld in placeholder : f = [x for x, d in enumerate(data) if d == pld] if len(f) : i = f[-1] break else : f = [x for x, d in enumerate(data) if d == placeholder] if len(f) : i = f[-1] return i except : return None LEFT_MARGIN = 70 RIGHT_MARGIN = 30 def parseLine(line, boundary) : xmin, xmax = boundary copyed = copy.deepcopy(line) copyed = preprocess_line(copyed) # ratio # ratio, price = get_ratio(copyed, xmax) ratio, price, tax = get_ratio_price_tax(copyed, xmax) # title title = get_title(copyed, xmin) # tax # tax = get_tax(copyed, xmax, ratio) # prices specs, amount, uprice, price, ratio = get_numbers(copyed, price, ratio) # specs specs, unit = get_specs_unit(copyed, specs) return postprocess_line(title, specs, unit, amount, uprice, price, ratio, tax) def is_merge_str(x1, x2) : ret = False eng_pattern = re.compile(r'[a-zA-Z\s]') chn_pattern = re.compile(r'[\u4e00-\u9fa5]') num_pattern = re.compile(r'[\d\.]') s1 = x1['text'][-1] s2 = x2['text'][0] if num_pattern.match(s1) and num_pattern.match(s2) : ret = True elif chn_pattern.match(s1) and chn_pattern.match(s2) : ret = True elif eng_pattern.match(s1) and eng_pattern.match(s2) : ret = True return ret def is_disturb(i, line) : ret = False pi = i - 1 ni = i + 1 eng_pattern = re.compile(r'[a-zA-Z\s]') chn_pattern = re.compile(r'[\u4e00-\u9fa5]') num_pattern = re.compile(r'[\d\.]') if ni < len(line) : cur = line[i]['text'] prev = line[pi]['text'] next = line[ni]['text'] for pattern in [num_pattern, chn_pattern, eng_pattern] : if pattern.match(prev[-1]) and pattern.match(next[0]) and len(cur) <= 2 \ and (not pattern.match(cur[0]) or not pattern.match(cur[-1])) : ret = True break return ret def correct_number(text) : m = re.match(r'\d{3,}\.?\d*([^\d\.])\d*\.?\d*$', text) if m : nodigit = m.group(1) if nodigit == '年' : replace = '4' elif nodigit == '日' : replace = '6' elif nodigit == 'F' : replace = '1' else : replace = '' text = re.sub(nodigit, replace, text) return text def preprocess_line(line) : line = sorted(line, key = lambda x : x['cx'] - x['w'] / 2) res = [] i = 0 j = 1 while i < len(line) and j < len(line) : x = line[i] y = line[j] x1 = x['cx'] + x['w'] / 2 y1 = y['cx'] - y['w'] / 2 if abs(x1 - y1) < 8 and i : if not is_disturb(j, line) : w = y['cx'] + y['w'] / 2 - x['cx'] + x['w'] / 2 cx = x['cx'] - x['w'] / 2 + w / 2 x['w'] = w x['cx'] = cx x['text'] = x['text'] + y['text'] j = j + 1 else : x1 = x['cx'] - x['w'] / 2 x2 = x['cx'] + x['w'] / 2 y1 = y['cx'] - y['w'] / 2 y2 = y['cx'] + y['w'] / 2 if x1 < y1 and x2 > y2 : j = j + 1 elif x1 > y1 and x2 < y2 : i = j j = j + 1 else : res.append(x) i = j j = j + 1 res.append(line[i]) for i in range(max(len(res) - 3, 0), len(res)) : res[i]['text'] = correct_number(res[i]['text']) return res def postprocess_line(title, specs, unit, amount, uprice, price, ratio, tax) : if not tax and price and ratio : tax = str(round(float(price) / 100 * float(ratio[:-1]), 2)) elif tax and price : r = str(int(round(float(tax) / float(price) * 100))) if not ratio or ratio[:-1] == '1' or (r != ratio[:-1] and r.find(ratio[:-1]) >= 0) : ratio = r + '%' return [title, specs, unit, amount, uprice, price, ratio, tax] def get_title(line, xmin) : title = '' candidates = [d for d in line if abs(d['cx'] - d['w'] / 2 - xmin) < LEFT_MARGIN] if len(candidates) : candidates = sorted(candidates, key = lambda x : x['cy']) for c in candidates : title += c['text'] line.remove(c) if title and not title.startswith('*') : title = '*' + title return title def get_tax(line, xmax, ratio) : tax = '' if ratio == '免税' : tax = '***' idx = [i for i, d in enumerate(line) if abs(d['cx'] + d['w'] / 2 - xmax) < RIGHT_MARGIN] if len(idx) : idx = idx[0] ln = line[idx] tax = ln['text'] line.pop(idx) if len(tax) > 2 and tax.find('.') == -1 : tax = tax[:-2] + '.' + tax[-2 :] return tax def get_ratio(line, xmax) : ratio = '' price = '' pat = re.compile(r'(\-?[\dBG]+\.?[\dBG]{2})*(([\dBG]+[\%])|(免税))$') for i in range(len(line) - 1, -1, -1) : text = line[i]['text'] m = pat.match(text) if m : price, ratio = (m.group(1), m.group(2)) if m.group(1) else ('', m.group(2)) if ratio : line.pop(i) break if not ratio : numbers = sorted([i for i, d in enumerate(line) if re.match(r'([\dBG]+\.?[\dBG]{2})*', d['text'])], key = lambda x : line[x]['cx'] - line[x]['w'] / 2) if len(numbers) >= 3 : i = numbers[-2] d = line[i] m = re.match(r'(\d{1,2})\D+', d['text']) if m : ratio = m.group(1) + '%' line.pop(i) return ratio, price def get_ratio_price_tax(line, xmax) : ratio = '' price = '' tax = '' pat = re.compile(r'(\-?[\dBG]+\.?[\dBG]{2})*(([\dBG]+[\%m\u4e00-\u9fa5])|([\u4e00-\u9fa5]+税))$') pat2 = re.compile(r'(\-?[\dBG]+\.[\dBG]{2})([\dBG]{1,2}[8])') ratioitem = None for i in range(len(line) - 1, -1, -1) : text = line[i]['text'] m = pat.match(text) if m : price, ratio = (m.group(1), m.group(2)) if m.group(1) else ('', m.group(2)) ratio = ratio[:-1] + '%' else : m = pat2.match(text) if m : price, ratio = (m.group(1), m.group(2)) ratio = ratio[:-1] + '%' if ratio : ratioitem = line.pop(i) break if not ratio : numbers = sorted([i for i, d in enumerate(line) if re.match(r'([\dBG]+\.?[\dBG]{2})*', d['text'])], key = lambda x : line[x]['cx'] - line[x]['w'] / 2) if len(numbers) >= 3 : i = numbers[-2] d = line[i] m = re.match(r'(\d{1,2})\D+', d['text']) if m : ratio = m.group(1) ratioitem = line.pop(i) if re.search(r'税$', ratio) : tax = '***' else : if ratioitem : taxes = [l for l in line if l['cx'] > ratioitem['cx']] if len(taxes) : tax = taxes[0]['text'] line.remove(taxes[0]) if not tax : idx = [i for i, d in enumerate(line) if abs(d['cx'] + d['w'] / 2 - xmax) < RIGHT_MARGIN] if len(idx) : idx = idx[0] ln = line[idx] tax = ln['text'] line.pop(idx) if len(tax) > 2 and tax.find('.') == -1 : tax = tax[:-2] + '.' + tax[-2 :] if len(price) and not '.' in price : if tax and ratio : while float(price) > float(tax) : prc = price[:-2] + '.' + price[-2 :] f_tax = float(tax) f_ratio = float(ratio[:-1]) f_price = float(prc) if abs(f_price * f_ratio / 100.0 - f_tax) > 0.1 and f_ratio < 10 : ratio = price[-1] + ratio price = price[:-1] else : price = prc break else : price = price[:-2] + '.' + price[-2 :] if price and ratio and not tax : tax = str(round(float(price) * float(ratio[:-1]) / 100.0, 2)) return ratio, price, tax def get_numbers(line, price, ratio) : specs = '' amount = '' uprice = '' pattern = re.compile(r'\-?[\dBG:]+\.?[\dBG]*$') numbers = [] for d in line : if pattern.match(d['text']) : d['text'] = d['text'].replace('B', '8').replace('G', '6').replace(':', '') numbers.append(d) if len(numbers) : for n in numbers : line.remove(n) # preprocess_number(numbers) numbers = sorted(numbers, key = lambda x : x['cx'] - x['w'] / 2) if not ratio and re.match(r'^\d{2,3}$', numbers[-1]['text']) : ratio = numbers[-1]['text'] ratio = ratio[:-1] + '%' numbers = numbers[0 :-1] if not price : price = numbers[-1]['text'] m = re.match(r'(\d+\.\d{2})\d*(\d{2})$', price) if m and not ratio : price = m.group(1) ratio = m.group(2) + '%' if not '.' in price : price = price[0 :-2] + '.' + price[-2 :] numbers = numbers[0 :-1] numlen = len(numbers) if numlen == 3 : specs = numbers[0]['text'] amount = numbers[1]['text'] uprice = numbers[2]['text'] elif numlen == 2 : num1 = numbers[0]['text'] num2 = numbers[1]['text'] if abs(float(num1) * float(num2) - float(price)) < 0.01 : specs = '' amount = num1 uprice = num2 elif abs(float(num2) - float(price)) <= 0.1 : specs = num1 amount = '1' uprice = num2 else : specs, amount, uprice = get_amount_uprice(price, num2, num1) elif numlen == 1 : specs = '' num = numbers[0]['text'] if abs(float(num) - float(price)) < 0.01 : amount = '1' uprice = num else : specs, amount, uprice = get_amount_uprice(price, num) if not amount : amount = num return specs, amount, uprice, price, ratio def preprocess_number(numbers) : number = [i for i, n in enumerate(numbers) if n['text'].find(':') > -1] adds = [] removes = [] for i in number : d = numbers[i] text = d['text'] splits = text.split(':') d1 = dict(d) d1['text'] = splits[0] d1['w'] = d['w'] * len(d1['text']) / len(text) d1['cx'] = d['cx'] - d['w'] / 2 + d1['w'] / 2 d2 = dict(d) d2['text'] = splits[1] d2['w'] = d['w'] * len(d2['text']) / len(text) d2['cx'] = d['cx'] + d['w'] / 2 - d2['w'] / 2 removes.append(d) adds.extend([d1, d2]) for d in removes : numbers.remove(d) numbers.extend(adds) def get_min_distance(word1, word2) : m, n = len(word1), len(word2) if m == 0 : return n if n == 0 : return m cur = [0] * (m + 1) # 初始化cur和边界 for i in range(1, m + 1) : cur[i] = i for j in range(1, n + 1) : # 计算cur pre, cur[0] = cur[0], j # 初始化当前列的第一个值 for i in range(1, m + 1) : temp = cur[i] # 取出当前方格的左边的值 if word1[i - 1] == word2[j - 1] : cur[i] = pre else : cur[i] = min(pre + 1, cur[i] + 1, cur[i - 1] + 1) pre = temp return cur[m] def get_max_commonsubstr(s1, s2) : # 求两个字符串的最长公共子串 # 思想:建立一个二维数组,保存连续位相同与否的状态 len_s1 = len(s1) len_s2 = len(s2) # 生成0矩阵,为方便后续计算,多加了1行1列 # 行: (len_s1+1) # 列: (len_s2+1) record = [[0 for i in range(len_s2 + 1)] for j in range(len_s1 + 1)] maxNum = 0 # 最长匹配长度 p = 0 # 字符串匹配的终止下标 for i in range(len_s1) : for j in range(len_s2) : if s1[i] == s2[j] : # 相同则累加 record[i + 1][j + 1] = record[i][j] + 1 if record[i + 1][j + 1] > maxNum : maxNum = record[i + 1][j + 1] p = i # 匹配到下标i # 返回 子串长度,子串 return maxNum, s1[p + 1 - maxNum : p + 1] def get_amount_uprice(price, upricecand, amtcand = None) : price = float(price) specs = '' amount = '' uprice = '' copyprice = upricecand dotplace = upricecand.find('.') if dotplace > 0 : upricecand = upricecand[:dotplace] + upricecand[dotplace + 1 :] if amtcand : upr = str(math.trunc(float(price) / float(amtcand) * 100)) idx = upricecand.find(upr) if idx >= 0 : amount = amtcand upricecand = upricecand[idx :] dot = len(upr[:-2]) uprice = upricecand[:dot] + '.' + upricecand[dot :] if not uprice : end = dotplace - 1 if dotplace > 0 else len(upricecand) - 2 for idx in range(2, end) : amt = int(upricecand[:idx]) upr = upricecand[idx :] if not amt : break calcupr = price / amt if calcupr < 1 : break dot = str(calcupr).find('.') if dot > len(upr) : break upr = float(upr[0 :dot] + '.' + upr[dot :]) dis = abs(upr - calcupr) if dis < 1 : amount = str(amt) uprice = str(upr) break # upr = str(math.trunc(price / amt * 100)) # if len(upr) < 3: # break # i = upricecand.find(upr, idx) # if i > 0: # amount = upricecand[0:i] # uprice = upricecand[i:] # dotplace = str(price / int(amount)).find('.') # uprice = uprice[:dotplace] + '.' + uprice[dotplace:] # break if not uprice : m = re.match(r'(\d+0+)([1-9]\d*\.\d+)', copyprice) if m : amount = m.group(1) uprice = m.group(2) else : m = re.search(r'(\d+)(0{2,})(\d+)', upricecand) if m : amount = m[1] + m[2] uprice = m[3] calcupr = str(price / float(amount)) n, s = get_max_commonsubstr(calcupr, uprice) uprice = calcupr[:calcupr.find(s)] + uprice[uprice.find(s) :] else : uprice = copyprice if amtcand : amount = amtcand else : amount = str(int(price / float(uprice))) else : if amtcand : specs = amtcand return specs, amount, uprice def get_specs_unit(line, specs) : unit = '' linelen = len(line) if linelen >= 2 : specs = line[0]['text'] unit = line[1]['text'] if linelen == 1 : text = line[0]['text'] if specs : unit = text else : if len(text) == 1 : unit = text else : specs = text return specs, unit def zh_count(str) : count = 0 for s in str : if '\u4e00' <= s <= '\u9fff' : count += 1 return count def is_wrapped_title(data, line, content, next, boundary) : ret = False xmin = boundary[0] dx = abs(data['cx'] - data['w'] / 2 - xmin) text = data['text'] if dx < LEFT_MARGIN : if len(text) < 6 and len(line) : ret = True else : if not re.search(r'\*[\u4e00-\u9fa5]', text) : if next == len(content) : if (not len(line) or calc_axis_iou(data, line) > 0.2) : ret = True else : end = min([next + 8, len(content)]) neighbor = None title = None for c in content[next :end] : if calc_axis_iou(c, data) > 0.2 : title = c else : if neighbor is None : neighbor = c else : dx = c['cx'] - data['cx'] if (neighbor['cx'] - data['cx'] > dx > 0) and calc_axis_iou(c, neighbor) < 0.1 : neighbor = c if neighbor is None : ret = True else : y_iou = calc_axis_iou(neighbor, data, 1) if y_iou > 0.3 : if calc_axis_iou(neighbor, line, 1) > 0.1 and calc_axis_iou(neighbor, line) < 0.1 and calc_axis_iou( data, line) > 0.1 : ret = True elif y_iou < 0.1 : ret = True else : if title is not None : if calc_axis_iou(neighbor, title, 1) > 0.25 : ret = True else : if calc_axis_iou(data, line) > 0.2 : ret = True # if dx < LEFT_MARGIN and len(line) and calc_axis_iou(data, line) > 0.2 and (len(text) < 5 or not re.search(r'\*[\u4e00-\u9fa5]', text)): # ret = True return ret def check_title(elem, line, data, start, end, boundary) : ret = False xmin = boundary[0] lf = min(line, key = lambda d : d['cx'] - d['w'] / 2) dx = abs(lf['cx'] - lf['w'] / 2 - xmin) if dx > LEFT_MARGIN : dx = abs(elem['cx'] - elem['w'] / 2 - xmin) if dx < LEFT_MARGIN : line.append(elem) ret = True else : for d in data[start :end] : dx = abs(d['cx'] - d['w'] / 2 - xmin) if dx < LEFT_MARGIN : # iou = [calc_axis_iou(d,l,1) for l in line] iou = calc_axis_iou(d, line, 1) if iou > 0.3 : line.append(d) data.remove(d) break return ret def find_omit(line, content, start, end) : ret = False for i, d in enumerate(content[start :end]) : if calc_axis_iou(d, line, 1) > 0.3 and calc_axis_iou(d, line) < 0.01 : line.append(d) content.remove(d) if i == 0 : ret = True return ret def check_wrap_title(res, wraptitles, line = None) : title = res[-1][0] wraplen = len(wraptitles) if wraplen : idx = 0 if not line : wrap = wraptitles[:] else : wrap = [] ref = min(line, key = lambda x : x['cx'] - x['w'] / 2) for i, w in enumerate(wraptitles) : if w['cy'] < ref['cy'] : wrap.append(w) else : break if len(wrap) : # if not res[-1][1]: # m = re.match(r'([\*\(\)\u4e00-\u9fa5]+.*?)([\S]+?$)', title) # if m: # title, res[-1][1] = m.group(1), m.group(2) del wraptitles[0 :len(wrap)] title = reduce(lambda a, b : a + b, [w['text'] for w in wrap], title) res[-1][0] = title def get_basic_boundary(data) : indexes = [i for i, d in enumerate(data) if re.search(r'开票日期|校验码', d['text'])] if len(indexes) : end = max(indexes) else : end = 8 lt = min(data[:end + 1] + data[-10 :], key = lambda x : x['cx'] - x['w'] / 2) rt = max(data[:end + 1] + data[-10 :], key = lambda x : x['cx'] + x['w'] / 2) left = lt['cx'] - lt['w'] / 2 right = rt['cx'] + rt['w'] / 2 return (0, end, left, right) def get_basic_checkcode(bg_data, fg_data) : checkcode = '' candidates = [d for d in bg_data if re.search(r'校验码*', d['text'])] if len(candidates) : checkcodes = get_candidate_after_key(candidates[0], fg_data) if len(checkcodes) : checkcode = re.sub(r'[^0-9]', '', checkcodes[0]['text']) return checkcode PROVINCE = ['河北', '山西', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西'] def get_basic_type(bg_data) : type = '' title = '' elec = '电子' if len([d for d in bg_data if re.search(r'发票代码', d['text'])]) > 0 else '' candidates = [d for d in bg_data if re.search(r'.*(增?专?用?|通)?发票', d['text'])] if len(candidates) : text = candidates[0]['text'] # if text.find('用') >= 0 or text.find('专') or text.find('增') >= 0: if text.find('用') >= 0 or text.find('专') >= 0 : type = elec + '专用发票' else : type = elec + '普通发票' suffix = '增值税' + type if text[:2] in PROVINCE : title = text[:2] + suffix elif text[:3] in PROVINCE : title = text[:3] + suffix else : titles = [d for d in bg_data if re.search(r'^.*增值?', d['text'])] if len(titles) : title = titles[0]['text'] i = title.find('增') title = title[:i] + suffix else : i = bg_data.index(candidates[0]) titles = [bg_data[i - 1], bg_data[i + 1]] for t in titles : if re.match(r'[\u4e00-\u9fa5]{2,3}', t['text']) : text = t['text'] if text[:2] in PROVINCE : text = text[:2] elif text[:3] in PROVINCE : text = text[:3] else : text = text[:len(text) - 1] title = text + suffix break return type, title def get_basic_title(basic, type) : title = '' elec = '电子' if len([d for d in basic if re.search(r'发票代码', d['text'])]) > 0 else '' candidates = [d for d in basic if re.search(r'^.*增值?', d['text'])] if len(candidates) : title = candidates[0]['text'] i = title.find('增') title = title[:i] + '增值税' + elec + type return title def get_basic_date(bg_data, fg_data) : date = '' candidates = [d for d in bg_data if re.search(r'开?票?日期', d['text'])] if len(candidates) : key = candidates[0] dates = get_candidate_after_key(key, fg_data) if len(dates) : date = re.sub(r'[^0-9年月日]', '', dates[0]['text']) if date[-1] != '日' : date += '日' return date def get_basic_code(bg_data, fg_data) : code = '' candidates = [d for d in bg_data if re.search(r'发票代码', d['text'])] if len(candidates) : key = max(candidates, key = lambda x : x['cx'] + x['w'] / 2) codes = get_candidate_after_key(key, fg_data) if len(codes) : code = re.sub(r'[^0-9]', '', codes[0]['text']) else : codes = [d for d in fg_data[:10] if re.search(r'^\d{10,12}$', d['text'])] if len(codes) : code = re.sub(r'[^0-9]', '', codes[0]['text']) if not code : codes = [d for d in bg_data[:10] if re.search(r'^\d{8,}$', d['text'])] if len(codes) : code = re.sub(r'[^0-9]', '', codes[0]['text']) return code def get_basic_sn(bg_data, fg_data) : sn = '' candidates = [d for d in bg_data if re.search(r'发票号码', d['text'])] if len(candidates) : key = max(candidates, key = lambda x : x['cx'] + x['w'] / 2) codes = get_candidate_after_key(key, fg_data) if len(codes) : sn = re.sub(r'[^0-9]', '', codes[0]['text']) else : codes = [d for d in fg_data[:10] if re.search(r'^\d{8}$', d['text'])] if len(codes) : sn = re.sub(r'[^0-9]', '', codes[0]['text']) return sn def get_basic_person(bg_data, fg_data) : payee = '' reviewer = '' drawer = '' bg_rear = bg_data[-6 :] fg_rear = fg_data[-6 :] candidates = [d for d in bg_rear if re.search(r'收|款', d['text'])] if len(candidates) : key = candidates[0] payees = get_candidate_after_key(key, fg_rear) if len(payees) : payee = payees[0]['text'] if ':' in payee : payee = payee.split(':')[1] candidates = [d for d in bg_rear if re.search(r'复|核', d['text'])] if len(candidates) : key = candidates[0] reviewers = get_candidate_after_key(key, fg_rear) if len(reviewers) : reviewer = reviewers[0]['text'] if ':' in reviewer : reviewer = reviewer.split(':')[1] candidates = [d for d in bg_rear if re.search(r'开票|票人|^开$|[^款]人:', d['text'])] if len(candidates) : key = candidates[0] drawers = get_candidate_after_key(key, fg_rear) if len(drawers) : drawer = drawers[0]['text'] if ':' in drawer : drawer = drawer.split(':')[1] return payee, reviewer, drawer def getBasics(bg_data, fg_data) : checkcode = get_basic_checkcode(bg_data, fg_data) type, title = get_basic_type(bg_data) code = get_basic_code(bg_data, fg_data) sn = get_basic_sn(bg_data, fg_data) date = get_basic_date(bg_data, fg_data) payee, reviewer, drawer = get_basic_person(bg_data, fg_data) res = [[{'name' : r'发票类型', 'value' : type}, {'name' : r'发票名称', 'value' : title}, {'name' : r'发票代码', 'value' : code}, {'name' : r'发票号码', 'value' : sn}, {'name' : r'开票日期', 'value' : date}, {'name' : r'校验码', 'value' : checkcode}, {'name' : r'收款人', 'value' : payee}, {'name' : r'复核', 'value' : reviewer}, {'name' : r'开票人', 'value' : drawer}]] return res # return {"type":type, "title":title, "code":code, "sn":sn, "date":date, "checkcode":checkcode, "payee":payee, "reviewer":reviewer, "drawer":drawer} def get_buyer_boundary(data) : indexes = [i for i, d in enumerate(data) if isTitle(d['text'])] end = min(indexes) indexes = [i for i, d in enumerate(data) if i < end and re.search(r'(开?票?日期)|(校验码)', d['text'])] start = max(indexes) + 1 return start, end def get_buyer_name(bg_data, fg_data) : name = '' candidates = [d for d in bg_data if re.search(r'名|称', d['text'])] if len(candidates) : key = candidates[0] names = get_candidate_after_key(key, fg_data) if len(names) : name = names[0]['text'] return name def get_buyer_taxnumber(bg_data, fg_data) : taxnumber = '' candidates = [d for d in bg_data if re.search(r'纳|税|人|识|别|号', d['text'])] if len(candidates) : key = candidates[0] taxnumbers = get_candidate_after_key(key, fg_data) if len(taxnumbers) : taxnumber = taxnumbers[0]['text'] return taxnumber def get_buyer_address(bg_data, fg_data) : address = '' candidates = [d for d in bg_data if re.search(r'地|址|电|话', d['text'])] if len(candidates) : key = candidates[0] addresses = get_candidate_after_key(key, fg_data) if len(addresses) : address = addresses[0]['text'] if not re.search(r'[0-9\-]{11,}$', address) : if len(addresses) > 1 : number = addresses[1] if re.match(r'\d+$', number['text']) : address += number['text'] for prov in PROVINCE : idx = address.find(prov) if idx > 0 : address = address[idx :] return address def get_buyer_account(bg_data, fg_data) : account = '' candidates = [d for d in bg_data if re.search(r'开|户|行|及|账号?', d['text'])] if len(candidates) : key = candidates[0] accounts = get_candidate_after_key(key, fg_data) if len(accounts) : account = accounts[0]['text'] if not re.search(r'\d{12,}$', account) : if len(accounts) > 1 : number = accounts[1] if re.match(r'\d+$', number['text']) : account += number['text'] return account def get_name_by_taxnum(taxnum, fg_data) : name = '' idx = [i for i, d in enumerate(fg_data) if d['text'] == taxnum] if len(idx) : idx = idx[0] tax = fg_data[idx] names = [d for d in fg_data[:idx] if calc_axis_iou(d, tax) > 0.6] if len(names) : name = names[-1]['text'] return name def getBuyer(bg_data, fg_data) : # start, end = get_buyer_boundary(bg_data) # bg_buyer = bg_data[start:end] # # name = get_buyer_name(bg_buyer, fg_data) # taxnum = get_buyer_taxnumber(bg_buyer, fg_data) # address = get_buyer_address(bg_buyer, fg_data) # account = get_buyer_account(bg_buyer, fg_data) # # if not name: # name = get_name_by_taxnum(taxnum, fg_data) name, taxnum, address, account = ('', '', '', '') date = [d for d in bg_data if re.search(r'开?票?日期|校?验码', d['text'])] if len(date) : date = max(date, key = lambda x : x['cy']) titles = [d for d in bg_data if isTitle(d['text'])] for b in titles : if b['cy'] < date['cy'] : titles.remove(b) continue if len(titles) : title = min(titles, key = lambda x : x['cy'] - x['h'] / 2) candidates = [d for d in fg_data if d['cy'] > date['cy'] and (d['cx'] + d['w'] / 2) < (date['cx'] - date['w'] / 2) and d['cy'] < title[ 'cy'] and len(d['text']) > 5] if len(candidates) : sample = [c for c in candidates if re.search(r'公司|银行|学$', c['text'])] candidate = [c for c in candidates if calc_axis_iou(c, sample[0]) > 0.3] length = len(candidate) if length == 4 : candidate = sorted(candidate, key = lambda x : x['cy']) name, taxnum, address, account = [c['text'] for c in candidate] elif length == 2 : candidate = sorted(candidate, key = lambda x : x['cy']) name, taxnum = [c['text'] for c in candidate] res = [[{'name' : r'名称', 'value' : name}, {'name' : r'纳税人识别号', 'value' : taxnum}, {'name' : r'地址、电话', 'value' : address}, {'name' : r'开户行及账号', 'value' : account}]] return res def getContent(bg_data, fg_data) : res = [] content = get_content_boundary(bg_data, fg_data) left = min(content, key = lambda x : x['cx'] - x['w'] / 2) right = max(content, key = lambda x : x['cx'] + x['w'] / 2) xmin = left['cx'] - left['w'] / 2 xmax = right['cx'] + right['w'] / 2 # top = min(content, key=lambda x:float(x['cy'])-float(x['h']/2)) # bottom = max(content, key=lambda x: float(x['cy'])+float(x['h']/2)) # lh = (bottom['cy'] + bottom['h']/2 - top['cy'] + top['h']/2) / 8 # lt = min(content, key=lambda x:float(x['cx'])-float(x['w']/2)) # rb = max(content, key=lambda x: float(x['cx'])+float(x['w']/2)) # left = float(lt['cx'])-float(lt['w']/2) # right = float(rb['cx'])+float(rb['w']/2) line = [] wraptitle = [] for idx, ct in enumerate(content) : deal = False iswrap = is_wrapped_title(ct, line, content, idx + 1, [xmin, xmax]) if not iswrap : linelen = len(line) if linelen : y_ious = [] for l in line : x_iou = calc_axis_iou(l, ct) y_iou = calc_axis_iou(l, ct, 1) y_ious.append(y_iou) if x_iou > 0.2 : deal = True break if not deal and np.mean(y_ious) < 0.05 : deal = True # x_iou = calc_axis_iou(ct, line) # y_iou = calc_axis_iou(ct, line, 1) # if x_iou > 0.3 or y_iou < 0.05: # deal = True if deal == False : line.append(ct) else : # ret = check_title(ct, line, content, idx+1, idx+4, [xmin,xmax]) ret = find_omit(line, content, idx, idx + 4) if len(res) : check_wrap_title(res, wraptitle, line) parsed = parseLine(line, [xmin, xmax]) res.append(parsed) line = [] if not ret : line.append(ct) else : wraptitle.append(ct) if len(line) + len(wraptitle) >= 3 : if len(res) : check_wrap_title(res, wraptitle, line) # if len(wraptitle): # line.extend(wraptitle) parsed = parseLine(line, [xmin, xmax]) res.append(parsed) if len(wraptitle) : check_wrap_title(res, wraptitle) ret = [] for r in res : title, specs, unit, amount, uprice, price, ratio, tax = r # if not specs: # m = re.match(r'([\*\(\)\u4e00-\u9fa5]+.*?)([\S]+?$)', title) # if m: # title, specs = m.group(1), m.group(2) if re.findall(r'[*]', title) : specs = specs.replace('8', 'g').replace('1', 'l') ret.append([{'name' : r'名称', 'value' : title}, {'name' : r'规格型号', 'value' : specs}, {'name' : r'单位', 'value' : unit}, {'name' : r'数量', 'value' : amount}, {'name' : r'单价', 'value' : uprice}, {'name' : r'金额', 'value' : price}, {'name' : r'税率', 'value' : ratio}, {'name' : r'税额', 'value' : tax}]) else : continue return ret def get_seller_boundary(data) : s = max([i for i, d in enumerate(data) if re.search(r'\(?大写\)?', d['text'])]) e = min([i for i, d in enumerate(data) if re.search(r'\(?小写\)?', d['text'])]) start = max([s, e]) + 1 end = len(data) - 2 return start, end def get_seller_name(bg_data, fg_data) : name = '' candidates = [d for d in bg_data if re.search(r'名|称', d['text'])] if len(candidates) : key = candidates[0] names = get_candidate_after_key(key, fg_data) if len(names) : name = names[0]['text'] return name def get_seller_taxnumber(bg_data, fg_data) : taxnumber = '' candidates = [d for d in bg_data if re.search(r'纳|税|人|识|别|号', d['text'])] if len(candidates) : key = candidates[0] taxnumbers = get_candidate_after_key(key, fg_data) if len(taxnumbers) : taxnumber = taxnumbers[0]['text'] return taxnumber def get_seller_address(bg_data, fg_data) : address = '' candidates = [d for d in bg_data if re.search(r'地|址|电|话', d['text'])] if len(candidates) : key = candidates[0] addresses = get_candidate_after_key(key, fg_data) if len(addresses) : address = addresses[0]['text'] if not re.search(r'[0-9\-]{11,}$', address) : if len(addresses) > 1 : number = addresses[1] if re.match(r'\d+$', number['text']) : address += number['text'] for prov in PROVINCE : idx = address.find(prov) if idx > 0 : address = address[idx :] return address def get_seller_account(bg_data, fg_data) : account = '' candidates = [d for d in bg_data if re.search(r'开|户|行|及|账号?', d['text'])] if len(candidates) : key = candidates[0] accounts = get_candidate_after_key(key, fg_data) if len(accounts) : account = accounts[0]['text'] if not re.search(r'\d{12,}$', account) : if len(accounts) > 1 : number = accounts[1] if re.match(r'\d+$', number['text']) : account += number['text'] return account def merge_candidates(candidates) : candidates = sorted(candidates, key = lambda x : x['cy']) merged = [] i = 0 while i < len(candidates) - 1 : x = candidates[i] y = candidates[i + 1] if calc_axis_iou(x, y, 1) > 0.4 : x, y = sorted([x, y], key = lambda x : x['cx']) if abs(x['cx'] + x['w'] / 2 - y['cx'] + y['w'] / 2) < 20 : x['text'] = x['text'] + y['text'] i += 1 merged.append(x) i += 1 if i < len(candidates) : merged.append(candidates[i]) return merged def getSeller(bg_data, fg_data) : # start, end = get_seller_boundary(bg_data) # bg_seller = bg_data[start:end] # # name = get_seller_name(bg_seller, fg_data) # taxnum = get_seller_taxnumber(bg_seller, fg_data) # address = get_seller_address(bg_seller, fg_data) # account = get_seller_account(bg_seller, fg_data) # # if not name: # name = get_name_by_taxnum(taxnum, fg_data) top = [d for d in bg_data if re.search(r'\(?(价税合计|大写|小写)\)?', d['text'])] if len(top) : top = max(top, key = lambda x : x['cy']) candidates = [d for d in fg_data[-18 :] if d['cy'] > (top['cy'] + 15) and len(d['text']) >= 8] if len(candidates) : candidates = merge_candidates(candidates) sample = [c for c in candidates if re.search(r'公司|银行', c['text'])] candidate = [c for c in candidates if calc_axis_iou(c, sample[0]) > 0.3] if len(candidate) == 4 : candidate = sorted(candidate, key = lambda x : x['cy']) name, taxnum, address, account = [c['text'] for c in candidate] res = [[{'name' : r'名称', 'value' : name}, {'name' : r'纳税人识别号', 'value' : taxnum}, {'name' : r'地址、电话', 'value' : address}, {'name' : r'开户行及账号', 'value' : account}]] return res # return {"name": name, "taxnum": taxnum, "address": address, "account": account} def get_summation_boundary(bg_data, fg_data) : # keys = [d for d in bg_data if re.search(r'\(?大写\)?', d['text'])] # keys.extend([d for d in bg_data if re.search(r'\(?小写\)?', d['text'])]) # keys.extend([d for d in bg_data if re.search(r'(合计?)', d['text'])]) summation = [i for i, d in enumerate(fg_data) if re.search(r'(¥|Y|羊|F|单)\d+?\.?\d*[^\d\.]?\d*$', d['text'])] summdata = [fg_data[i] for i in summation] summation.extend([i for i, d in enumerate(fg_data) if re.search(r'^\d+\.\d{2}$', d['text']) and calc_axis_iou(d, summdata, 1) > 0.4]) keys = [d for d in bg_data if re.search(r'\(?(大写|小写)\)?', d['text'])] if len(keys) : key = max(keys, key = lambda x : x['cx']) summation.extend([i for i, d in enumerate(fg_data) if re.search(r'^\d+\.\d{1,2}$', d['text']) and calc_axis_iou(d, key, 1) > 0.4]) start = min(summation) end = max(summation) + 1 return start, end def getSummation(bg_data, fg_data) : benchmark = ['仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '圆', '角', '分'] chinesedigit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾'] tax = '' price = '' total = '' capital = '' start, end = get_summation_boundary(bg_data, fg_data) summation = fg_data[start :end] prices = [re.sub(r'[^\d\.]', '', d['text']) for d in summation if re.search(r'(¥|Y|羊|F)?\d+?\.?\d*', d['text']) and len(d['text']) > 2] for i in range(len(prices)) : price = prices[i] idx = price.rfind(r'.') if idx <= 0 : price = price[:-2] + '.' + price[-2 :] else : price = price[:idx].replace(r'.', '') + (price[idx :] if len(price[idx :]) <= 3 else price[idx :idx + 3]) prices[i] = price prices = list(set(prices)) if len(prices) == 3 : prices = sorted(prices, key = lambda x : float(x)) tax = prices[0] price = prices[1] total = prices[2] str = re.sub(r'\.', '', total) bm = benchmark[-len(str) :] for (c, b) in zip(str, bm) : capital += chinesedigit[int(c)] + b if int(total[-2 :]) == 0 : capital = capital[:-4] + '整' capital = re.sub(r'零[仟佰拾角分]', '零', capital) capital = re.sub(r'零{2,}', '零', capital) capital = re.sub(r'零$', '', capital) capital = re.sub(r'零圆', '圆', capital) res = [[{'name' : r'金额合计', 'value' : price}, {'name' : r'税额合计', 'value' : tax}, {'name' : r'价税合计(大写)', 'value' : capital}, {'name' : r'价税合计(小写)', 'value' : total}]] return res def calc_axis_iou(a, b, axis = 0) : if isinstance(b, list) : if len(b) : if axis == 0 : ious = [ calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] else : ious = [ calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) else : iou = 0.0 elif isinstance(a, list) : if len(a) : if axis == 0 : ious = [ calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else : ious = [ calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else : iou = 0.0 else : if axis == 0 : iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else : iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def get_candidate_after_key(key, data) : candidates = [d for d in data if d['cx'] > key['cx'] and (calc_axis_iou(d, key, 1) > 0.3 or ( calc_axis_iou(d, key, 1) > 0.001 and -5 < (d['cx'] - d['w'] / 2 - key['cx'] - key['w'] / 2) < 30))] if len(candidates) : candidates = sorted(candidates, key = lambda x : x['cx'] - x['w'] / 2) return candidates def sort_result(data) : data = sorted(data, key = lambda d : d['cy']) lines = [] line = [] for i in range(len(data)) : d = data[i] if not len(line) : line.append(d) else : iou_x = calc_axis_iou(d, line, 0) iou_y = calc_axis_iou(d, line, 1) if iou_y > 0.6 and iou_x < 0.1 : line.append(d) else : line = sorted(line, key = lambda l : l['cx'] - l['w'] / 2) lines.append(line) line = [d] if len(line) : line = sorted(line, key = lambda l : l['cx'] - l['w'] / 2) lines.append(line) return lines def formatResult(bg_data, fg_data) : basic = getBasics(bg_data, fg_data) buyer = getBuyer(bg_data, fg_data) content = getContent(bg_data, fg_data) seller = getSeller(bg_data, fg_data) summation = getSummation(bg_data, fg_data) res = [{'title' : r'发票基本信息', 'items' : basic}, {'title' : r'购买方', 'items' : buyer}, {'title' : r'销售方', 'items' : seller}, {'title' : r'货物或应税劳务、服务', 'items' : content}, {'title' : r'合计', 'items' : summation}] return res # return {"basic":basic, "buyer":buyer, "content":content, "seller":seller} if __name__ == '__main__' : parser = argparse.ArgumentParser(description = 'Hyperparams') parser.add_argument('--arch', nargs = '?', type = str, default = 'resnet50') parser.add_argument('--resume', nargs = '?', type = str, default = './DB-master/models/ic15_resnet50', help = 'Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs = '?', type = float, default = 0.7, help = 'Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs = '?', type = int, default = 7, help = 'Path to previous saved model to restart from') parser.add_argument('--scale', nargs = '?', type = int, default = 1, help = 'Path to previous saved model to restart from') parser.add_argument('--long_size', nargs = '?', type = int, default = 2240, help = 'Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs = '?', type = float, default = 5.0, help = 'min kernel area') parser.add_argument('--min_area', nargs = '?', type = float, default = 300.0, help = 'min area') parser.add_argument('--min_score', nargs = '?', type = float, default = 0.5, help = 'min score') parser.add_argument('--evaluate', nargs = '?', type = bool, default = True, help = 'evalution') args = parser.parse_args() test(args)<file_sep># -*- coding: utf-8 -*- # @Time : 2019/8/23 21:58 # @Author : zhoujun from .util import * from .metrics import * from .schedulers import * from .cal_recall.script import cal_recall_precison_f1 from .ocr_metric import get_metric<file_sep>import os import cv2 import sys import re import time import math import copy from functools import reduce import collections import torch import argparse import numpy as np import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch.autograd import Variable from torch.utils import data from dataset import DataLoader import models import util # c++ version pse based on opencv 3+ from pse import pse # from angle import detect_angle from apphelper.image import order_point, calc_iou, xy_rotate_box from crnn import crnnRec # python pse # from pypse import pse as pypse from pse2 import pse2 def get_params(): parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='mobilenet') parser.add_argument('--resume', nargs='?', type=str, default='./checkpoints/psenet_lite_mbv2.pth', help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=0.5, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=6, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=2240, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') args = parser.parse_args() return args def recognize(im=None, path=None): ret = None try: file = None if im: pass elif path: # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im: dir = os.path.join(os.path.dirname(__file__), '../data/images/invoice/') file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(get_params(), tmpfile) if data: ret = format(data) except Exception as e: print(e) return ret def format(data): return data def extend_3c(img): img = img.reshape(img.shape[0], img.shape[1], 1) img = np.concatenate((img, img, img), axis=2) return img def debug(idx, img_paths, imgs, output_root): if not os.path.exists(output_root): os.makedirs(output_root) col = [] for i in range(len(imgs)): row = [] for j in range(len(imgs[i])): # img = cv2.copyMakeBorder(imgs[i][j], 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=[255, 0, 0]) row.append(imgs[i][j]) res = np.concatenate(row, axis=1) col.append(res) res = np.concatenate(col, axis=0) img_name = img_paths[idx].split('/')[-1] print(idx, '/', len(img_paths), img_name) cv2.imwrite(output_root + img_name, res) def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes = np.empty([1, 8], dtype='int32') resBoxes[0, 0] = int(points[0]) resBoxes[0, 4] = int(points[1]) resBoxes[0, 1] = int(points[2]) resBoxes[0, 5] = int(points[3]) resBoxes[0, 2] = int(points[4]) resBoxes[0, 6] = int(points[5]) resBoxes[0, 3] = int(points[6]) resBoxes[0, 7] = int(points[7]) pointMat = resBoxes[0].reshape([2, 4]).T return plg.Polygon(pointMat) def test(args, file=None): result = [] data_loader = DataLoader(long_size=args.long_size, file=file) test_loader = torch.utils.data.DataLoader( data_loader, batch_size=1, shuffle=False, num_workers=2, drop_last=True) slice = 0 # Setup Model if args.arch == "resnet50": model = models.resnet50(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet101": model = models.resnet101(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet152": model = models.resnet152(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "mobilenet": model = models.Mobilenet(pretrained=True, num_classes=6, scale=args.scale) slice = -1 for param in model.parameters(): param.requires_grad = False # model = model.cuda() if args.resume is not None: if os.path.isfile(args.resume): print("Loading model and optimizer from checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) # model.load_state_dict(checkpoint['state_dict']) d = collections.OrderedDict() for key, value in checkpoint['state_dict'].items(): tmp = key[7:] d[tmp] = value try: model.load_state_dict(d) except: model.load_state_dict(checkpoint['state_dict']) print("Loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) sys.stdout.flush() else: print("No checkpoint found at '{}'".format(args.resume)) sys.stdout.flush() model.eval() total_frame = 0.0 total_time = 0.0 for idx, (org_img, img) in enumerate(test_loader): print('progress: %d / %d' % (idx, len(test_loader))) sys.stdout.flush() # img = Variable(img.cuda(), volatile=True) org_img = org_img.numpy().astype('uint8')[0] text_box = org_img.copy() # torch.cuda.synchronize() start = time.time() # angle detection # org_img, angle = detect_angle(org_img) outputs = model(img) score = torch.sigmoid(outputs[:, slice, :, :]) outputs = (torch.sign(outputs - args.binary_th) + 1) / 2 text = outputs[:, slice, :, :] kernels = outputs # kernels = outputs[:, 0:args.kernel_num, :, :] * text score = score.data.cpu().numpy( )[0].astype(np.float32) text = text.data.cpu().numpy()[0].astype(np.uint8) kernels = kernels.data.cpu().numpy()[0].astype(np.uint8) if args.arch == 'mobilenet': pred = pse2(kernels, args.min_kernel_area / (args.scale * args.scale)) else: # c++ version pse pred = pse(kernels, args.min_kernel_area / (args.scale * args.scale)) # python version pse # pred = pypse(kernels, args.min_kernel_area / (args.scale * args.scale)) # scale = (org_img.shape[0] * 1.0 / pred.shape[0], org_img.shape[1] * 1.0 / pred.shape[1]) scale = (org_img.shape[1] * 1.0 / pred.shape[1], org_img.shape[0] * 1.0 / pred.shape[0]) label = pred label_num = np.max(label) + 1 bboxes = [] rects = [] for i in range(1, label_num): points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1] if points.shape[0] < args.min_area / (args.scale * args.scale): continue score_i = np.mean(score[label == i]) if score_i < args.min_score: continue rect = cv2.minAreaRect(points) bbox = cv2.boxPoints(rect) * scale bbox = bbox.astype('int32') bbox = order_point(bbox) # bbox = np.array([bbox[1], bbox[2], bbox[3], bbox[0]]) bboxes.append(bbox.reshape(-1)) rec = [] rec.append(rect[-1]) rec.append(rect[1][1] * scale[1]) rec.append(rect[1][0] * scale[0]) rec.append(rect[0][0] * scale[0]) rec.append(rect[0][1] * scale[1]) rects.append(rec) # torch.cuda.synchronize() end = time.time() total_frame += 1 total_time += (end - start) print('fps: %.2f' % (total_frame / total_time)) sys.stdout.flush() for bbox in bboxes: cv2.drawContours(text_box, [bbox.reshape(4, 2)], -1, (0, 255, 0), 2) image_name = data_loader.img_paths[idx].split('/')[-1].split('.')[0] write_result_as_txt(image_name, bboxes, 'outputs/submit_invoice/') text_box = cv2.resize(text_box, (text.shape[1], text.shape[0])) debug(idx, data_loader.img_paths, [[text_box]], 'data/images/tmp/') result = crnnRec(cv2.cvtColor(org_img, cv2.COLOR_BGR2RGB), rects) result = formatResult(result) # cmd = 'cd %s;zip -j %s %s/*' % ('./outputs/', 'submit_invoice.zip', 'submit_invoice') # print(cmd) # sys.stdout.flush() # util.cmd.Cmd(cmd) return result def calc_axis_iou(a,b,axis=0): if isinstance(b, list): if axis == 0: ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] else: ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = min(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = min(ious) else: if axis == 0: iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def mergeRow(row): row = sorted(row, key=lambda x: x['cx'] - x['w'] / 2) res = [] i = 0 j = 1 while i < len(row) and j < len(row): x = row[i] y = row[j] x1 = x['cx'] + x['w'] / 2 y1 = y['cx'] - y['w'] / 2 if abs(x1 - y1) < 8: x['w'] = y['cx'] + y['w']/2 - x['cx'] + x['w']/2 x['cx'] = (y['cx'] + x['cx']) / 2 x['text'] = x['text'] + y['text'] j = j + 1 else: res.append(x) i = j j = j + 1 res.append(row[i]) return res def getRows(data): data = sorted(data, key=lambda x: x['cy']-x['h']/2) rows = [] row = [] for d in data: if len(row): if calc_axis_iou(d, row, 1) < 0.05: row = mergeRow(row) rows.append(row) row = [] row.append(d) if len(row): row = mergeRow(row) rows.append(row) return rows def get_socialcode(rows): socialcode = '' for idx,rw in enumerate(rows): d = [r for r in rw if re.match(r'[A-Z0-9]{15,20}', r['text'])] if len(d): socialcode = d[0]['text'] break return socialcode def get_companyname(rows): cname = '' for idx, rw in enumerate(rows): i = [i for i,r in enumerate(rw) if re.match(r'(名|称)', r['text'])] if len(i): i = max(i) cname = rw[i+1]['text'] break return cname def get_regcapital(rows): regcapital = '' for idx, rw in enumerate(rows): i = [i for i,r in enumerate(rw) if r['text'] == r'注册资本'] if len(i): i = max(i) regcapital = rw[i+1]['text'] break return regcapital def get_busitype(rows): busitype = '' for idx, rw in enumerate(rows): i = [i for i, r in enumerate(rw) if re.match(r'(类|型)', r['text'])] if len(i): i = max(i) busitype = rw[i+1]['text'] break return busitype def get_establishdate(rows): estdate = '' for idx, rw in enumerate(rows): i = [i for i, r in enumerate(rw) if re.match(r'成立日期', r['text'])] if len(i): i = max(i) estdate = rw[i+1]['text'] break return estdate def get_legalperson(rows): legalperson = '' for idx, rw in enumerate(rows): i = [i for i, r in enumerate(rw) if re.match(r'法定代表人', r['text'])] if len(i): i = max(i) legalperson = rw[i+1]['text'] break return legalperson def get_busiterm(rows): busiterm = '' for idx, rw in enumerate(rows): i = [i for i, r in enumerate(rw) if r['text'] == r'营业期限'] if len(i): i = max(i) busiterm = rw[i+1]['text'] break return busiterm def get_busiscope(rows): busiscope = [] busiscope_item = None pattern = r'登记机关' for idx, rw in enumerate(rows): if not busiscope_item: i = [i for i, r in enumerate(rw) if re.match(r'(经营范围|住|所)', r['text'])] if len(i): if len(i) == 1: pattern = r'(住|所)' s = i[0] e = s + 1 else: i = sorted(i) s = i[0]+1 e = i[1] for d in rw[s:e]: if not busiscope_item: busiscope_item = d else: busiscope_item['w'] = busiscope_item['w'] + d['w'] busiscope_item['cx'] = (busiscope_item['cx'] + d['cx']) / 2 busiscope_item['text'] = busiscope_item['text'] + d['text'] busiscope.append(busiscope_item['text']) else: i = [i for i, r in enumerate(rw) if re.match(pattern, r['text'])] if not len(i): for r in rw: if calc_axis_iou(busiscope_item, r) > 0.1: busiscope.append(r['text']) else: break busiscope = ''.join(busiscope) return busiscope def get_addr(rows): addr = [] addr_item = None pattern = r'登记机关' for idx, rw in enumerate(rows): if not addr_item: i = [i for i, r in enumerate(rw) if re.match(r'(住|所)', r['text'])] if len(i): i = max(i) addr_item = rw[i+1] addr.append(addr_item['text']) else: i = [i for i, r in enumerate(rw) if re.match(pattern, r['text'])] if not len(i): if len(addr) < 2: r = [r for r in rw if calc_axis_iou(addr_item, r) > 0.1] if len(r): addr.append(r[0]['text']) break else: break addr = ''.join(addr) return addr def formatResult(data): rows = getRows(data) socialcode = get_socialcode(rows) companyname = get_companyname(rows) regcapital = get_regcapital(rows) busitype = get_busitype(rows) estdate = get_establishdate(rows) legalperson = get_legalperson(rows) busiterm = get_busiterm(rows) busiscope = get_busiscope(rows) addr = get_addr(rows) res = [{'title': r'营业执照信息', 'items': [[{'name': r'统一社会信用代码', 'value': socialcode}, {'name': r'名称', 'value': companyname}, {'name': r'注册资本', 'value': regcapital}, {'name': r'类型', 'value': busitype}, {'name': r'成立日期', 'value': estdate}, {'name': r'法定代表人', 'value': legalperson}, {'name': r'营业期限', 'value': busiterm}, {'name': r'经营范围', 'value': busiscope}, {'name': r'住所', 'value': addr} ]] }] return res if __name__ == '__main__': parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='mobilenet') parser.add_argument('--resume', nargs='?', type=str, default='./checkpoints/psenet_lite_mbv2.pth', help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=0.5, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=6, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=2240, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') args = parser.parse_args() test(args) <file_sep>import os import cv2 import sys import json import time # import collections # import torch # import argparse # import numpy as np # import torch.nn as nn # import torch.nn.functional as F #import web from flask import Flask, request, url_for, send_from_directory from flask_cors import CORS # from app import invoice2 as invoice import test_app as invoice from app import idcard_gao from app import businesslicense_gao from app import driverlicense_gao ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) MAX_DEAL_FILES = 6 app = Flask(__name__) cors = CORS(app, resources = {r"/*" : {"origins" : "*"}}) # app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd(), 'data/images/tmp/') app.config['UPLOAD_FOLDER'] = './test/test_output' app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS def is_pdf(filename) : return '.' in filename and filename.rsplit('.', 1)[1] == 'pdf' def pdf2image(path, filename): # return send_from_directory(app.config['UPLOAD_FOLDER'], filename) images = [] pdf = fitz.open(os.path.join(path, filename)) # 逐页读取PDF for pg in range(1, min(pdf.pageCount, MAX_DEAL_FILES)) : page = pdf[pg] # 设置缩放和旋转系数 trans = fitz.Matrix(5, 5).preRotate(0) pm = page.getPixmap(matrix = trans, alpha = False) # 开始写图像 img = os.path.join(path, str(pg) + ".png") pm.writePNG(img) images.append(img) pdf.close() return images def image2text(params, images) : res = [] recognize = None type = params.get('ocrtype', '') if type == 'invoice' : recognize = invoice.recognize elif type == 'idcard' : recognize = idcard_gao.recognize elif type == 'businesslicense': recognize = businesslicense_gao.recognize elif type == 'driverlicense' : recognize = driverlicense_gao.recognize if recognize : for img in images : result = recognize(path = img) res.append({"image" : os.path.basename(img), "res" : result}) return res # def text2excel(data, path): # if len(data): # workbook = xlwt.Workbook(encoding='utf-8') # sheet = workbook.add_sheet('demo') # # head = ["image", "name", "text"] # for i in range(len(head)): # sheet.write(0, i, head[i]) # # i = 1 # for d in data: # j = i # img = d['image'] # for res in d['res']: # # sheet.write(i, 0, img) # sheet.write(i, 1, res['name']) # sheet.write(i, 2, res['text']) # i += 1 # sheet.write_merge(j, i-1, 0, 0, img) # workbook.save(path) @app.route('/image/<filename>', methods = ['GET', 'POST']) def get_images(filename) : # filename = filename[:-4] + '_result' + filename[-4:] filename = filename.rsplit('.')[0] + '_result.jpg' return send_from_directory(app.config['UPLOAD_FOLDER'], filename) @app.route('/upload', methods = ['GET', 'POST']) def upload_file() : print("--------------------------------------------") t = time.time() res = [] if request.method == 'POST' : file = request.files['file'] params = request.values filename = file.filename if file : if allowed_file(filename) : # filename = secure_filename(file.filename) path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(path) images = [path] # file_url = url_for('uploaded_file', filename=filename) elif is_pdf(filename) : file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) images = pdf2image(path = app.config['UPLOAD_FOLDER'], filename = filename) res = image2text(params = params, images = images) timeTake = time.time() - t # 保存结果到xls # text2excel(res, './demo.xlsx') return json.dumps({'res' : res, 'timeTake' : round(timeTake, 4)}, ensure_ascii = False) if __name__ == '__main__' : app.run(debug = False, threaded = False, host = '0.0.0.0', port = 12345) <file_sep>from dataset.data_loader import DataLoader<file_sep># -*- coding:utf-8 -*- import math import util from apphelper.image import calc_iou from crnn import crnnRec # from angle import * # from eval.eval_driving_license import evaluate def get_min_distance_index(tem,indexes,near,maxRight = 100): x = float(tem['cx']) + float(tem['w']) / 2 y = float(tem['cy']) + float(tem['h']) / 2 distance_min = 100000 ii = -1 for i in range(0,len(near)): x_tem = float(near[i]['cx']) - float(near[i]['w']/2) y_tem = float(near[i]['cy']) + float(near[i]['h']/2) distance_tem = math.sqrt(math.pow((x-x_tem),2) + math.pow((y-y_tem),2)) if distance_tem < distance_min and near[i]['cx'] < maxRight and len(near[i]['text']) and calc_axis_iou(near[i],tem,1) > 0.3 and float(tem['cx']) < float(near[i]['cx']): ii = i distance_min = distance_tem # if distance_tem < 30 and re.search(r'[\u4e00-\u9fa5]{6,}',near[i]['text']): # return i return ii def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) import os import sys import pathlib __dir__ = pathlib.Path(os.path.abspath(__file__)) sys.path.append(str(__dir__)) sys.path.append(str(__dir__.parent.parent)) import time import cv2 import torch from dbnet.data_loader import get_transforms from dbnet.models import build_model from dbnet.post_processing import get_post_processing def resize_image(img, short_size): height, width, _ = img.shape if height < width: new_height = short_size new_width = new_height / height * width else: new_width = short_size new_height = new_width / width * height new_height = int(round(new_height / 32) * 32) new_width = int(round(new_width / 32) * 32) resized_img = cv2.resize(img, (new_width, new_height)) return resized_img class Pytorch_model: def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): ''' 初始化pytorch模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) model_path='/home/share/gaoluoluo/dbnet/output/DBNet_resnet18_FPN_DBHead/checkpoint/model_latest.pth' :param gpu_id: 在哪一块gpu上运行 ''' self.gpu_id = gpu_id if self.gpu_id is not None and isinstance(self.gpu_id, int) and torch.cuda.is_available(): self.device = torch.device("cuda:%s" % self.gpu_id) else: self.device = torch.device("cpu") # print('device:', self.device) checkpoint = torch.load(model_path, map_location=self.device) # print("checkpoint:",checkpoint) config = checkpoint['config'] # print(checkpoint['config']) config['arch']['backbone']['pretrained'] = False self.model = build_model(config['arch']) self.post_process = get_post_processing(config['post_processing']) self.post_process.box_thresh = post_p_thre self.img_mode = config['dataset']['train']['dataset']['args']['img_mode'] self.model.load_state_dict(checkpoint['state_dict']) self.model.to(self.device) self.model.eval() self.transform = [] for t in config['dataset']['train']['dataset']['args']['transforms']: if t['type'] in ['ToTensor', 'Normalize']: self.transform.append(t) self.transform = get_transforms(self.transform) def predict(self, img, is_output_polygon=False, short_size: int = 1024): ''' 对传入的图像进行预测,支持图像地址,opecv 读取图片,偏慢 :param img_path: 图像地址 :param is_numpy: :return: ''' # assert os.path.exists(img_path), 'file is not exists' # img = cv2.imread(img_path, 1 if self.img_mode != 'GRAY' else 0) if self.img_mode == 'RGB': img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w = img.shape[:2] # 2550 3507 img = resize_image(img, short_size) # 将图片由(w,h)变为(1,img_channel,h,w) tensor = self.transform(img) tensor = tensor.unsqueeze_(0) tensor = tensor.to(self.device) batch = {'shape': [(h, w)]} with torch.no_grad(): if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) start = time.time() preds = self.model(tensor) if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) box_list, score_list = self.post_process(batch, preds, is_output_polygon=is_output_polygon) box_list, score_list = box_list[0], score_list[0] if len(box_list) > 0: if is_output_polygon: idx = [x.sum() > 0 for x in box_list] box_list = [box_list[i] for i, v in enumerate(idx) if v] score_list = [score_list[i] for i, v in enumerate(idx) if v] else: idx = box_list.reshape(box_list.shape[0], -1).sum(axis=1) > 0 # 去掉全为0的框 box_list, score_list = box_list[idx], score_list[idx] else: box_list, score_list = [], [] t = time.time() - start return preds[0, 0, :, :].detach().cpu().numpy(), box_list, score_list, t def recognize(im=None, path=None): ret = None try: file = None if im: pass elif path: # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im: dir = '/home/share/gaoluoluo/complete_ocr/data/images/tmp/' file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(tmpfile) if data: # ret = format(data) ret = data except Exception as e: print(e) return ret def init_args(): import argparse parser = argparse.ArgumentParser(description='DBNet.pytorch') # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/dbnet/output/DBNet_resnet50_FPN_DBHead/checkpoint/model_latest.pth', type=str) # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/模型/model50_ch_epoch510_latest.pth', type=str) parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/模型/model50_ch_epoch510_latest.pth', type=str) # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/invoices_gao_true/img/', type=str, help='img path for predict') parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_drivingLicense/input/img/', type=str, help='img path for predict') parser.add_argument('--img_correct',default='/home/share/gaoluoluo/dbnet/test/test_corre_input/',type=str,help='img_correct path for predict') # parser.add_argument('--input_folder',default='/home/share/gaoluoluo/dbnet/test/test_corre_input', type=str, help='img path for predict') # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_ocr/data/images/tmp', type=str,help='img path for predict') parser.add_argument('--output_folder', default='/home/share/gaoluoluo/dbnet/test/test_output/', type=str, help='img path for output') # parser.add_argument('--output_folder', default='/home/share/gaoluoluo/invoices_gao_true/outputs/', type=str, help='img path for output') parser.add_argument('--gt_txt', default='/home/share/gaoluoluo/complete_drivingLicense/input/gt/', type=str, help='img 对应的 txt') parser.add_argument('--thre', default=0.1, type=float, help='the thresh of post_processing') parser.add_argument('--polygon', action='store_true', help='output polygon or box') parser.add_argument('--show', action='store_true', help='show result') parser.add_argument('--save_result', action='store_true', help='save box and score to txt file') parser.add_argument('--evaluate', nargs='?', type=bool, default=False, help='evalution') args = parser.parse_args() return args def test(tmpfile): import pathlib from tqdm import tqdm import matplotlib.pyplot as plt from dbnet.utils.util import show_img, draw_bbox, save_result, get_file_list args = init_args() # print(args) os.environ['CUDA_VISIBLE_DEVICES'] = str('0') # 初始化网络 0.1 model = Pytorch_model(args.model_path, post_p_thre=args.thre, gpu_id=0) total_frame = 0.0 total_time = [] names = [] for ind in range(0,1): img_path = tmpfile print("\nimg_path:", img_path) # img_path = '/home/share/gaoluoluo/IDCard/corre_id/3.jpg' start_time = time.time() img = angle_corre(img_path)# 调整图片角度 wei调整 # img = cv2.imread(img_path) img_path = args.img_correct + img_path.split('/')[-1] # After correct angle img path names.append(img_path.split('/')[-1]) # names_tem.append(str(iii)+img_path.split('.')[-1]) # iii += 1 # print("img_path:",img_path) preds, boxes_list, score_list, t = model.predict(img, is_output_polygon=args.polygon) img_path1 = img_path boxes_list_save = boxes_list box = [] for i in range(0,len(boxes_list)): for j in range(0,len(boxes_list[0])): b = [] b.append(np.float32(boxes_list[i][j][0])) b.append(np.float32(boxes_list[i][j][1])) box.append(b) boxes_list = boxes_list.reshape(-1,2) boxes_list = box #---合框 只能合一个框被分成两个的部分 i = 4 points_kuang = [] remove_mark = [] max_X = -1 while(i<=len(boxes_list)): points = boxes_list[i-4:i] for _,p in enumerate(points): if p[0] > max_X: max_X = p[0] i = i+4 points = np.array(points) points_kuang.append(points) for i in range(0,len(points_kuang)):# 逆时针 1 -> 2 -> 3 -> 4 point3 = points_kuang[i][2] start_point = i - 3 end_point = i + 3 if start_point < 0: start_point = 0 if end_point > len(points_kuang): end_point = len(points_kuang) if i not in remove_mark: for j in range(start_point,end_point): point4 = points_kuang[j][3] min_dis = math.sqrt(math.pow((point3[0] - point4[0]),2) + math.pow((point3[1] - point4[1]),2)) Y_cha = math.fabs(point3[1] - point4[1]) if min_dis < 10 and Y_cha < 1 and j not in remove_mark and i != j : # 10 reasonable # if min_dis < 0: point1_1 = points_kuang[i][0] point1_2 = points_kuang[j][0] x_min = min(point1_1[0],point1_2[0]) y_min = min(point1_1[1],point1_2[1]) point3_2 = points_kuang[j][2] x_max = max(point3[0],point3_2[0]) y_max = max(point3[1],point3_2[1]) points_kuang[i][0,0] = x_min points_kuang[i][0,1] = y_min points_kuang[i][1,0] = x_max points_kuang[i][1,1] = y_min points_kuang[i][2,0] = x_max points_kuang[i][2,1] = y_max points_kuang[i][3,0] = x_min points_kuang[i][3,1] = y_max remove_mark.append(j) # print("i=",i," j=",j) # print('x:',point4[0]) break remove_mark = sorted(remove_mark,reverse=True) # print("---------------------------") for _,i in enumerate(remove_mark): # print('x:',points_kuang[i][3][0]) del points_kuang[i] boxes_list_save = points_kuang # 决定保存的画框图片是否是 合框之后的图片 #--- i = 0; rects = [] while(i<len(points_kuang)): points = points_kuang[i] rect = cv2.minAreaRect(points) # 4个点 -> d cx cy w h rec = [] rec.append(rect[-1]) rec.append(rect[1][1]) rec.append(rect[1][0]) rec.append(rect[0][0]) rec.append(rect[0][1]) rects.append(rec) i += 1 ori_img = cv2.imread(img_path1) # ori_img = cv2.imread('/home/share/gaoluoluo/IDCard/outputs/part_id/0.png') # print(img_path1) rects = reversed(rects) result = crnnRec(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) # result = crnnRec_tmp(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) # result = list(reversed(result)) # print("result:",result) dur = time.time() - start_time print("dur:",dur) # 保存画框图片--------- # img = draw_bbox(img(img_path)[:, :, ::-1], boxes_list_save) img = draw_bbox(cv2.imread(img_path)[:, :, ::-1], boxes_list_save) if args.show: show_img(preds) show_img(img, title=os.path.basename(img_path)) plt.show() # 保存结果到路径 os.makedirs(args.output_folder, exist_ok=True) img_path = pathlib.Path(img_path) output_path = os.path.join(args.output_folder, img_path.stem + '_result.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_result.jpg pred_path = os.path.join(args.output_folder,img_path.stem + '_pred.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_pred.jpg cv2.imwrite(output_path, img[:, :, ::-1]) cv2.imwrite(pred_path, preds * 255) save_result(output_path.replace('_result.jpg', '.txt'), boxes_list_save, score_list, args.polygon) total_frame += 1 total_time.append(dur) result = formatResult(result) return result import re def calc_axis_iou(a,b,axis=0): if isinstance(b, list): # b 是list类型时 if axis == 0: # x 方向的交叉率 # 左 右 左 右 ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] # else: # y 方向的交叉类 ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else: # a b 都不是 list类型 if axis == 0:# iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou # ------------------------------------------------------------------------------------ def getIDCode(data): indexes = [i for i, d in enumerate(data) if re.search(r'\d{11,}', d['text'])] code = data[indexes[0]]['text'] code = re.sub(r'证号', '', code) return code def getName_Sex_Nation(data,maxRight): name = '' sex = '' nation = '' indexes = [i for i, d in enumerate(data) if re.search(r'性.|姓名|国籍|^国.?|^.?别', d['text'])] candidates = [] if len(indexes): index = indexes[0] candidates.append(data[index]) for i in range(0,len(data)): tmp_cal = calc_axis_iou(data[index],data[i],1) if calc_axis_iou(data[index],data[i],1) > 0.15 and data[i] not in candidates: candidates.append(data[i]) # ---nation indexes = [i for i, d in enumerate(candidates) if re.search(r'CHN|中国|^(中|虫).', d['text'])] if len(indexes): nation = '中国' else: candidates = sorted(candidates, key=lambda d: d['cx'] - d['w'] / 2) nation = candidates[-1]['text'] # --- name candidates = sorted(candidates, key=lambda d: d['cx'] - d['w'] / 2) indexes = [i for i, d in enumerate(candidates) if re.search(r'[\u4e00-\u9fa5]{2,}', d['text'])] name = candidates[indexes[0]]['text'] if len(name) >= 3: name = name.split('名')[-1] else: index = get_min_distance_index(candidates[indexes[0]],None,candidates,maxRight/2) if index != -1 : name += candidates[index]['text'] name = name.split('名')[-1] if len(candidates[index]['text']) <= 1: index = get_min_distance_index(candidates[index], None, candidates) name += candidates[index]['text'] first_name = '赵钱孙李周吴郑王冯陈卫蒋沈韩杨朱秦尤许何吕张孔曹严华金魏陶姜戚谢邹喻苏潘葛范彭郎鲁韦马苗花方俞任袁柳鲍史唐薛雷贺倪' \ '汤殷罗毕郝邬安常乐于时傅卞齐康伍余元卜顾孟平黄和穆萧尹姚邵汪祁毛禹狄米贝明臧计成戴宋庞熊纪舒屈项祝董粱杜阮季强贾路' \ '娄危江童颜郭梅盛林钟徐邱骆高夏蔡田胡凌霍万柯卢莫房解应宗丁宣邓郁单杭洪包左石崔吉龚程邢裴陆荣翁荀甄家封储靳焦牧山蔡' \ '田胡霍万柯卢莫房干谷车侯伊宁仇祖武符刘景詹束龙叶幸司韶黎乔苍双闻莘逄姬冉桂牛燕尚温庄晏瞿习容向古居步耿文东曾关红' for i in range(0,len(name)): if re.search(name[i],first_name): name = name[i:] break # ---sex indexes = [i for i, d in enumerate(candidates) if re.search(r'男|胃', d['text'])] if len(indexes): sex = '男' else: indexes = [i for i, d in enumerate(candidates) if re.search(r'女', d['text'])] if len(indexes): sex = '女' else: idCode = getIDCode(data) number = int(idCode[-2:-1]) if number % 2 == 0: sex = '女' else: sex = '男' # ---- return name,sex,nation def getAddress(data): address = '' indexes = [i for i, d in enumerate(data) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text'])] if len(indexes): index = indexes[0] address = data[index]['text'] for i in range(index + 1,len(data)): tmp_cal = calc_axis_iou(data[index],data[i]) tmp_dis = math.fabs(float(data[index]['cy'] + data[index]['h'] / 2) - float(data[i]['cy'] - data[i]['h'] / 2)) if calc_axis_iou(data[index],data[i]) > 0 and tmp_dis < 20 and data[i]['h'] > 40: address += data[i]['text'] return address,index + 5 def getBirthday(data,IDCode): date = '' year = IDCode[6:6 + 4] month = IDCode[10:10 + 2] day = IDCode[12:12 + 2] candidates = [] for _,d in enumerate(data[:-7]): if re.search('-'+day,d['text']): candidates.append(d) if re.search(month,d['text']): candidates.append(d) if re.search(year,d['text']): candidates.append(d) if len(candidates): candidates = sorted(candidates, key=lambda d: d['cy'] - d['h'] / 2, reverse=True) else: candidates = [d for d in data[:-7] if re.search(r'\d{4}|^(19|20|28)|-..-', d['text'])] if year[1] == '8': year = year[0] + '8' + year[2:] if month[0] == '8' or month[0] == '6': month = '0' + month[1] if month[1] == '8' or month[1] == '6': if month[0] != '0': month = '10' if day[0] == '8' or day[0] == '6': day = '0' + day[1] return year + '-' + month + '-' + day, data.index(candidates[0]) if len(candidates):# 原来的Pse wangluo shi zhengti kuangde candidates = sorted(candidates, key=lambda d: d['cy'] - d['h'] / 2) date = candidates[0]['text'] dates= date.split('-') if len(dates) == 3: # year---- year = dates[0] tmp_year = '' for i in range(0,len(year)): if i < 2: tmp_year += year[i] else: tmp_year = re.sub(r'8','0',tmp_year) if year[i] == '8': if i == 2: if year[i] == '8': if tmp_year == '19': tmp_year += year[i] else: tmp_year += '0' if i == 3: tmp1 = re.search(tmp_year+'8',IDCode) tmp2 = re.search(tmp_year+'0',IDCode) if tmp1: tmp_year =+ '8' if tmp2: tmp_year += '0' else: tmp_year += year[i] year = tmp_year # month---- tmp_month = '' month = dates[1] if month[0] == '8' or month[0] == '6': tmp_month += '0' else: tmp_month = month[0] if month[1] == '8' or month[1] == '6': if month[0] == '0': tmp_month += month[1] else: tmp_month += '0' pass else: tmp_month += month[1] month = tmp_month # day ------ day = dates[2] tmp_day = '' if day[0] == '8': tmp_day = '0' else: tmp_day = day[0] if day[1] == '8': if day[0] == '0': tmp_day = day[1] else: tmp1 = re.search(year + tmp_month + tmp_day + '8', IDCode) tmp2 = re.search(year + tmp_month + tmp_day + '0', IDCode) if tmp1 : tmp_day += '8' if tmp2: tmp_day += '0' else: tmp_day += day[1] day = tmp_day # ----- return year + '-' + month + '-' + day,data.index(candidates[0]) return date,data.index(candidates[0]) def getClassType(data): classType = '' indexes = [i for i, d in enumerate(data) if re.search(r'A1|AI|A2|A3|B1|BI|B2|c1|C1|CI', d['text'])] # indexes = [i for i, d in enumerate(data) if re.search(r'A1', d['text'])] if len(indexes): classType = data[indexes[0]]['text'] else: indexes = [i for i, d in enumerate(data) if re.search(r'准?驾?车型', d['text'])] if len(indexes): candidates = [] candidates.append(data[indexes[0]]) for i in range(0,len(data)): if calc_axis_iou(data[indexes[0]],data[i],1) > 0.3 and data[i] not in candidates: candidates.append(data[i]) candidates = sorted(candidates, key=lambda d: d['cx'] + d['w'] / 2) classType = candidates[-1]['text'] classType = re.sub(r'I','1',classType) return classType def getValidPeriod(data): start_time = '' end_time = '' candidates = [d for d in data if re.search(r'\d{4}-|^(19|20|28)|-..-|.?..-..', d['text']) and len(d['text']) <= 13] if len(candidates): candidates = sorted(candidates, key=lambda d: d['cx'] - d['w'] / 2) start_time = candidates[0]['text'] if start_time.find('至') != -1 and len(start_time) > 13: start_time, end_time = start_time.split('至') else: # del candidates[:1] if len(candidates) > 1: end_time = candidates[1]['text'] if len(end_time) < 5: tmp_index = get_min_distance_index(candidates[-1],None,candidates) if end_time[-1] == '-' or candidates[tmp_index]['text'][0] == '-': end_time += candidates[tmp_index]['text'] else: end_time += '-' + candidates[tmp_index]['text'] start_time = re.sub(r'Z','2',start_time) start_time = re.sub(r'Q', '0', start_time) start_time = re.sub(r'T', '1', start_time) end_time = re.sub(r'Z','2',end_time) end_time = re.sub(r'Q', '0', end_time) end_time = re.sub(r'T', '1', end_time) start_time = re.sub('至','',start_time) end_time = re.sub('至','',end_time) # date1 = start_time.split('-') # date2 = end_time.split('-') if len(start_time.split('-')) == 3 and len(end_time.split('-') )== 3: # 6/10/forever # year------ date1 = start_time.split('-') date2 = end_time.split('-') year1 = date1[0] year2 = date2[0] else: year1 = start_time[:4] year2 = end_time[:4] if year1[1] == '8' or year1[1] == '6': year1 = year1[0] + '0' + year1[2:] if year2[1] == '8' or year2[1] == '6': year2 = year2[0] + '0' + year2[2:] if year1[2] == '7': year1 = year1[:2] + '1' +year1[3:] if year1[2] == '8' and year1[:2] == '20': year1 = '200' + year1[-1] if year2[2] == '8' and year2[:2] == '20': year2 = '200' + year2[-1] if year1[-1] == '8': # 最后一位矫正不了 if int(year2) - int(year1) == 6 or int(year2) - int(year1) == 10: pass else: year1 = year1[:3] + '0' # ---------- # month----- if len(start_time.split('-')) == 3: month = start_time.split('-')[1] day = start_time.split('-')[2] if len(end_time.split('-')) == 3: month = end_time.split('-')[1] day = end_time.split('-')[2] # month = date1[1] if len(month) != 2: month = date2[1] if month[0] == '8' or month[0] == '6': month = '0' + month[1] if month[1] == '8' or month[1] == '6': if month[0] != '0': month = month[0] + '0' # ---------- # day------- 最后一位矫正不了 # day = date1[2] if len(day) != 2: day = date2[2] if day[0] == '8': day ='0' + day[1] # ---------- start_time = year1 + '-' + month + '-' + day end_time = year2 + '-' + month + '-' +day return start_time, end_time def getDateOfFirstIssue(data): dateFirstIssue = '' try : candidates = [d for d in data if re.search(r'\d{4}-|^(19|20|28)|-..-|.?..-..|初|次|领|证', d['text']) and len(d['text']) <= 13] if len(candidates): candidates = sorted(candidates, key=lambda d: d['cy'] - d['h'] / 2) tmp_candidate = candidates[0] number_list = [] for i in range(0,len(candidates)): tmp = calc_axis_iou(tmp_candidate,candidates[i],1) if calc_axis_iou(tmp_candidate,candidates[i],1) > 0.3: number_list.append(candidates[i]) candidates = [d for d in number_list if re.search(r'\d{4}-|^(19|20|28)|-..-|.?..-..|-..', d['text']) and len(d['text']) <= 13] if len(candidates): candidates = sorted(candidates, key=lambda d:d['cx'] - d['w'] / 2) for i in range(0,len(candidates)): dateFirstIssue += candidates[i]['text'] year = dateFirstIssue[:4] if year[1] == '8': year = year[0] + '0' + year[2:] if year[2] == '8': if year[:2] != '19': year = year[:2] + '0' + year[-1] dateFirstIssue = year + dateFirstIssue[4:] except Exception as e: print("getDateOfFirstIssue flase ") return dateFirstIssue def getMaxRight(data): maxRight = -1 for i in range(0,len(data)): if data[i]['cx'] + data[i]['w'] / 2 > maxRight: maxRight = data[i]['cx'] + data[i]['w'] / 2 return maxRight def formatResult(data): maxRight = getMaxRight(data) IDCode = getIDCode(data) name, sex, nation = getName_Sex_Nation(data,maxRight) address, index = getAddress(data[5:]) tmp_index = index birthday, index = getBirthday(data[index+1:],IDCode) index += tmp_index + 1 classType = getClassType(data[index + 1:]) start_time, end_time = getValidPeriod(data[-7:]) first_issue = getDateOfFirstIssue(data[index + 1:]) if first_issue[:4] == start_time[:4] or first_issue == '': first_issue = start_time # res = [{'title':r'证号', 'items':IDCode}, # {'title':r'姓名', 'items':name}, # {'title':r'性别', 'items':sex}, # {'title':r'国籍', 'items':nation}, # {'title': r'住址', 'items': address}, # {'title': r'出生日期', 'items':birthday}, # {'title':r'初次领证日期', 'items':first_issue}, # {'title':r'准驾车型', 'items':classType}, # {'title':r'有效期限', 'items':start_time + ' 至 ' + end_time}] res = [{'title': r'驾驶证信息', 'items': [[{'name': r'证号', 'value': IDCode}, {'name': r'姓名', 'value': name}, {'name': r'性别', 'value': sex}, {'name': r'国籍', 'value': nation}, {'name': r'住址', 'value': address}, {'name': r'出生日期', 'value': birthday}, {'name': r'初次领证日期', 'value': first_issue}, {'name': r'准驾车型', 'value': classType}, {'name': r'有效期限', 'value': start_time + ' 至 ' + end_time} ]] }] return res if __name__ == '__main__': test() <file_sep>import os import cv2 import sys import re import time import datetime import math import copy from functools import reduce import collections import torch import argparse import numpy as np import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch.autograd import Variable from torch.utils import data from dataset import DataLoader import models import util # c++ version pse based on opencv 3+ from pse import pse # from angle import detect_angle from apphelper.image import order_point, calc_iou, xy_rotate_box from crnn_lite import crnnRec # python pse # from pypse import pse as pypse from pse2 import pse2 def get_params(): parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='mobilenet') parser.add_argument('--resume', nargs='?', type=str, default='./checkpoints/psenet_lite_mbv2.pth', help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=0.3, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=6, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=960, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') args = parser.parse_args() return args def recognize(im=None, path=None): ret = None try: file = None if im: pass elif path: # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im: dir = os.path.join(os.path.dirname(__file__), '../data/images/invoice/') file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(get_params(), tmpfile) if data: ret = format(data) except Exception as e: print(e) return ret def format(data): return data def extend_3c(img): img = img.reshape(img.shape[0], img.shape[1], 1) img = np.concatenate((img, img, img), axis=2) return img def debug(idx, img_paths, imgs, output_root): if not os.path.exists(output_root): os.makedirs(output_root) col = [] for i in range(len(imgs)): row = [] for j in range(len(imgs[i])): # img = cv2.copyMakeBorder(imgs[i][j], 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=[255, 0, 0]) row.append(imgs[i][j]) res = np.concatenate(row, axis=1) col.append(res) res = np.concatenate(col, axis=0) img_name = img_paths[idx].split('/')[-1] print(idx, '/', len(img_paths), img_name) cv2.imwrite(output_root + img_name, res) def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes = np.empty([1, 8], dtype='int32') resBoxes[0, 0] = int(points[0]) resBoxes[0, 4] = int(points[1]) resBoxes[0, 1] = int(points[2]) resBoxes[0, 5] = int(points[3]) resBoxes[0, 2] = int(points[4]) resBoxes[0, 6] = int(points[5]) resBoxes[0, 3] = int(points[6]) resBoxes[0, 7] = int(points[7]) pointMat = resBoxes[0].reshape([2, 4]).T return plg.Polygon(pointMat) def test(args, file=None): result = [] data_loader = DataLoader(long_size=args.long_size, file=file) test_loader = torch.utils.data.DataLoader( data_loader, batch_size=1, shuffle=False, num_workers=2, drop_last=True) slice = 0 # Setup Model if args.arch == "resnet50": model = models.resnet50(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet101": model = models.resnet101(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "resnet152": model = models.resnet152(pretrained=True, num_classes=7, scale=args.scale) elif args.arch == "mobilenet": model = models.Mobilenet(pretrained=True, num_classes=6, scale=args.scale) slice = -1 for param in model.parameters(): param.requires_grad = False # model = model.cuda() if args.resume is not None: if os.path.isfile(args.resume): print("Loading model and optimizer from checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) # model.load_state_dict(checkpoint['state_dict']) d = collections.OrderedDict() for key, value in checkpoint['state_dict'].items(): tmp = key[7:] d[tmp] = value try: model.load_state_dict(d) except: model.load_state_dict(checkpoint['state_dict']) print("Loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) sys.stdout.flush() else: print("No checkpoint found at '{}'".format(args.resume)) sys.stdout.flush() model.eval() total_frame = 0.0 total_time = 0.0 for idx, (org_img, img) in enumerate(test_loader): print('progress: %d / %d' % (idx, len(test_loader))) sys.stdout.flush() # img = Variable(img.cuda(), volatile=True) org_img = org_img.numpy().astype('uint8')[0] text_box = org_img.copy() (h,w,c) = org_img.shape if w < h: args.binary_th = 1 # torch.cuda.synchronize() start = time.time() # angle detection # org_img, angle = detect_angle(org_img) outputs = model(img) score = torch.sigmoid(outputs[:, slice, :, :]) outputs = (torch.sign(outputs - args.binary_th) + 1) / 2 text = outputs[:, slice, :, :] kernels = outputs # kernels = outputs[:, 0:args.kernel_num, :, :] * text score = score.data.cpu().numpy( )[0].astype(np.float32) text = text.data.cpu().numpy()[0].astype(np.uint8) kernels = kernels.data.cpu().numpy()[0].astype(np.uint8) if args.arch == 'mobilenet': pred = pse2(kernels, args.min_kernel_area / (args.scale * args.scale)) else: # c++ version pse pred = pse(kernels, args.min_kernel_area / (args.scale * args.scale)) # python version pse # pred = pypse(kernels, args.min_kernel_area / (args.scale * args.scale)) # scale = (org_img.shape[0] * 1.0 / pred.shape[0], org_img.shape[1] * 1.0 / pred.shape[1]) scale = (org_img.shape[1] * 1.0 / pred.shape[1], org_img.shape[0] * 1.0 / pred.shape[0]) label = pred label_num = np.max(label) + 1 bboxes = [] rects = [] for i in range(1, label_num): points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1] if points.shape[0] < args.min_area / (args.scale * args.scale): continue score_i = np.mean(score[label == i]) if score_i < args.min_score: continue ((cx,cy),(w,h),degree) = cv2.minAreaRect(points) rect = ((cx,cy),(w+8,h+8),degree) bbox = cv2.boxPoints(rect) * scale bbox = bbox.astype('int32') bbox = order_point(bbox) # bbox = np.array([bbox[1], bbox[2], bbox[3], bbox[0]]) bboxes.append(bbox.reshape(-1)) rec = [] rec.append(rect[-1]) rec.append((rect[1][1]) * scale[1]) rec.append((rect[1][0]) * scale[0]) rec.append(rect[0][0] * scale[0]) rec.append(rect[0][1] * scale[1]) rects.append(rec) # torch.cuda.synchronize() end = time.time() total_frame += 1 total_time += (end - start) print('fps: %.2f' % (total_frame / total_time)) sys.stdout.flush() for bbox in bboxes: cv2.drawContours(text_box, [bbox.reshape(4, 2)], -1, (0, 255, 0), 2) image_name = data_loader.img_paths[idx].split('/')[-1].split('.')[0] write_result_as_txt(image_name, bboxes, 'outputs/submit_invoice/') text_box = cv2.resize(text_box, (text.shape[1], text.shape[0])) debug(idx, data_loader.img_paths, [[text_box]], 'data/images/tmp/') # result = crnnRec(binarize(org_img), rects) result = crnnRec(cv2.cvtColor(org_img, cv2.COLOR_BGR2RGB), rects) result = formatResult(result) # cmd = 'cd %s;zip -j %s %s/*' % ('./outputs/', 'submit_invoice.zip', 'submit_invoice') # print(cmd) # sys.stdout.flush() # util.cmd.Cmd(cmd) return result def calc_axis_iou(a,b,axis=0): if isinstance(b, list): if axis == 0: ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] else: ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else: if axis == 0: iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def mergeRow(row): row = sorted(row, key=lambda x: x['cx'] - x['w'] / 2) res = [] i = 0 j = 1 while i < len(row) and j < len(row): x = row[i] y = row[j] x1 = x['cx'] + x['w'] / 2 y1 = y['cx'] - y['w'] / 2 if abs(x1 - y1) < 8: x['w'] = y['cx'] + y['w']/2 - x['cx'] + x['w']/2 x['cx'] = (y['cx'] + x['cx']) / 2 x['text'] = x['text'] + y['text'] j = j + 1 else: res.append(x) i = j j = j + 1 res.append(row[i]) return res def getRows(data): data = sorted(data, key=lambda x: x['cy']-x['h']/2) rows = [] row = [] for d in data: if len(row): if calc_axis_iou(d, row, 1) < 0.2: # row = mergeRow(row) row = sorted(row, key=lambda x: x['cx']) rows.append(row) row = [] row.append(d) if len(row): # row = mergeRow(row) row = sorted(row, key=lambda x: x['cx']) rows.append(row) return rows def get_cardno(rows): cardno = '' # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'证号', r['text'])] # if len(i): # i = max(i) # r = [r for r in rw[i+1:] if re.match(r'\d{15,}[a-zA-Z]?', r['text'])] # if len(r): # cardno = r[0]['text'] # break row = rows[2] rw = [r['text'] for r in row if re.search(r'\d{15,}[a-zA-Z]?', r['text'])] if len(rw): rw = rw[0] m = re.search(r'(\d{15,}[a-zA-Z]?)', rw) cardno = m.group(1) return cardno def get_name(rows): name = '' # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'姓名', r['text'])] # if len(i): # i = max(i) # name = rw[i+1]['text'] # break row = rows[3] i = [i for i, r in enumerate(row) if re.search(r'姓名|me', r['text'])] if len(i): i = max(i) names = [r for r in row[i+1:i+3] if re.search('[\u4e00-\u9fa5]{1,}', r['text']) and calc_axis_iou(row[i],r)<0.001] if len(names): prev = names[-1] for n in names: if calc_axis_iou(n, prev) > 0: name = name + re.sub(r'[^\u4e00-\u9fa5]', '', n['text']) prev = n else: break return name def get_sex(rows): sex = '' # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'性别', r['text'])] # if len(i): # i = max(i) # r = [r for r in rw[i + 1:] if re.search(r'(男|女)', r['text'])] # if len(r): # text = r[0]['text'] # if text.find(r'男') >= 0: # sex = r'男' # else: # sex = r'女' # break row = rows[3] i = [i for i, r in enumerate(row) if re.search(r'性别|[S|s]ex', r['text'])] if len(i): i = max(i) r = [r['text'] for r in row[i + 1:min(i + 3,len(row))] if re.match('[\u4e00-\u9fa5]{1}', r['text'])] if len(r): sex = r[0] if not sex: r = [r for r in row if re.match(r'女|男', r['text'])] if len(r): text = r[0]['text'] if text.find(r'女') >= 0: sex = r'女' else: sex = r'男' return sex def get_nationality(rows): nation = '' # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'国籍', r['text'])] # if len(i): # i = max(i) # text = rw[i+1]['text'] # if len(text) < 2: # r = [r for r in rw[:i] if re.search(r'(男|女)', r['text']) and len(r'text') > 3] # if len(r): # text = r[-1]['text'] # i = max([text.find(r'男'), text.find(r'女')]) # if i >= 0: # nation = re.sub(r'[^\u4e00-\u9fa5]', '', text[i+1:]) # else: # nation = text # break row = rows[3] i = [i for i, r in enumerate(row) if re.search(r'国籍|ity', r['text'])] if len(i): i = max(i) r = [r['text'] for r in row[i + 1:min(i + 3, len(row))] if re.search('[\u4e00-\u9fa5]{2,}', r['text'])] if len(r): nation = re.sub(r'[^\u4e00-\u9fa5]', '', r[0]) return nation def get_addr(rows): addr = '' # s = 0 # e = 0 # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'住址', r['text'])] # if len(i): # s = idx # continue # i = [i for i, r in enumerate(rw) if re.match(r'出生日期', r['text'])] # if len(i): # e = idx # # if s and e: # for rw in rows[s:e]: # addr = addr + ''.join([r['text'] for r in rw if r['text'].find(r'住址') < 0]) # break row = rows[4] r = [r for r in row if re.match('[\u4e00-\u9fa5]{5,}', r['text'])] if len(r): addr = r[0]['text'] next = rows[5] nxt = [n for n in next if re.search(r'\d{4,}[\-\.\d]+', n['text'])] if not len(nxt): addr = addr + ''.join([n['text'] for n in next if calc_axis_iou(r[0],n)>0.1]) rows.pop(5) return addr def get_birthday(rows): birthday = '' # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'出生日期', r['text'])] # if len(i): # i = max(i) # birthday = rw[i+1]['text'] # birthday = validate_date(birthday) # break row = rows[5] r = [r for r in row if re.search(r'\d{4,}[\-\.\d]+', r['text'])] if len(r): birthday = r[0]['text'] birthday = validate_date(birthday) return birthday def get_issuedate(rows): issuedate = '' row = rows[6] r = [r for r in row if re.search(r'\d{4,}[\-\.\d]+', r['text'])] if len(r): issuedate = r[0]['text'] issuedate = validate_date(issuedate) return issuedate def get_class(rows): cls = '' # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'准驾车型', r['text'])] # if len(i): # cls = rw[-1]['text'] # break row = rows[7] text = row[-1]['text'] cls = text if len(text) <= 2 else '' if cls: letter = cls[-1] if letter == 'L' or letter == 'I': cls = cls[:-1] + '1' return cls def get_validperiod(rows): validperiod = '' # for idx, rw in enumerate(rows): # i = [i for i, r in enumerate(rw) if re.match(r'有效期限', r['text'])] # if len(i): # validperiod = rw[-1]['text'] # dates = validperiod.split(r'至') # if len(dates) > 1: # start = validate_date(dates[0]) # end = str(int(start[0:4])+6) + start[4:] # validperiod = start + r'至' + end # break row = rows[8] rw = [r for r in row if re.search(r'\d{4,}[\-\.\d]+', r['text'])] if len(rw): dates = [] for r in rw: dt = re.findall(r'\d{4,}[\-\.\d]+', r['text'], re.I) dates.extend([validate_date(d) for d in dt]) validperiod = r'至'.join(dates) return validperiod def validate_date(date): date = re.sub(r'[^0-9\-]' ,'', date) dates = date.split('-') l = len(dates) if l == 1: date = dates[0] year = date[0:4] if len(date[4:]) == 4: mon = date[4:6] day = date[6:] else: day = date[-2:] mon = date[-4:-2] elif l == 2: year = dates[0] if len(dates[1]) == 4: mon = dates[1][0:2] day = dates[1][2:] else: day = dates[1][-2:] mon = dates[1][-4:-2] elif l == 3: year = dates[0] mon = dates[1] day = dates[2] now = datetime.datetime.now() if int(year) > now.year: year = correct_date(year, now.year) if int(mon) > 12: mon = correct_date(mon, 12) if int(day) > 31: day = correct_date(day, 31) date = year + '-' + mon + '-' + day return date def correct_date(date, thresh): date = list(date) for i in range(0, len(date)): if int(''.join(date)) <= thresh: break date[i] = correct_digit(date[i]) date = ''.join(date) return date def correct_digit(digit): if digit == '8': digit = '0' elif digit == '9': digit = '0' elif digit == '6': digit = '0' elif digit == '3': digit = '2' return digit from skimage.filters import threshold_sauvola def binarize(image): gray = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) thresh_sauvola = threshold_sauvola(gray, window_size=25) binary_sauvola = gray > thresh_sauvola binary_sauvola.dtype = 'uint8' binary_sauvola = binary_sauvola * 255 blur = cv2.GaussianBlur(binary_sauvola, (3, 3), 1) # edges = cv2.Canny(gray, 50, 150, apertureSize=3) # # 函数将通过步长为1的半径和步长为π/180的角来搜索所有可能的直线 # lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=300, maxLineGap=10) # for line in lines: # x1, y1, x2, y2 = line[0] # cv2.line(image, (x1, y1), (x2, y2), (255, 255, 255), 1) # cv2.imshow("line_detect_possible_demo", image) return blur def formatResult(data): rows = getRows(data) cardno = get_cardno(rows) name = get_name(rows) sex = get_sex(rows) nation = get_nationality(rows) addr = get_addr(rows) birthday = get_birthday(rows) issuedate = get_issuedate(rows) cls = get_class(rows) validperiod = get_validperiod(rows) res = [{'title': r'驾驶证信息', 'items': [[{'name': r'证号', 'value': cardno}, {'name': r'姓名', 'value': name}, {'name': r'性别', 'value': sex}, {'name': r'国籍', 'value': nation}, {'name': r'住址', 'value': addr}, {'name': r'出生日期', 'value': birthday}, {'name': r'初次领证日期', 'value': issuedate}, {'name': r'准驾车型', 'value': cls}, {'name': r'有效期限', 'value': validperiod} ]] }] return res if __name__ == '__main__': parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('--arch', nargs='?', type=str, default='resnet50') parser.add_argument('--resume', nargs='?', type=str, default='./checkpoints/ctw1500_res50_pretrain_ic17.pth.tar', help='Path to previous saved model to restart from') parser.add_argument('--binary_th', nargs='?', type=float, default=1.5, help='Path to previous saved model to restart from') parser.add_argument('--kernel_num', nargs='?', type=int, default=7, help='Path to previous saved model to restart from') parser.add_argument('--scale', nargs='?', type=int, default=1, help='Path to previous saved model to restart from') parser.add_argument('--long_size', nargs='?', type=int, default=1080, help='Path to previous saved model to restart from') parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0, help='min kernel area') parser.add_argument('--min_area', nargs='?', type=float, default=300.0, help='min area') parser.add_argument('--min_score', nargs='?', type=float, default=0.5, help='min score') args = parser.parse_args() test(args) <file_sep># OCR项目(发票识别,驾驶证识别,身份证识别,营业执照识别) ## Requirements * Python 3.6 * PyTorch 1.8 * pyclipper * Polygon2 * opencv-python 4.0.0.21 ##几个必要的文件说明 ``` . ├── app 执行 python app.py 时,从这个目录下调, │   ├── businesslicense_gao.py 仿写的 │   └── businesslicense.py 原版 │   ... 其他类似 ├── app.py 执行 python app.py ,从浏览器访问 localhost/#/test,用于向用户展示识别效果 ├── crnn 文本识别模型 │   ├── ... │ ... │   └── ... ├── dbnet 文本检测模型 │   ├── ... │ ... │   └── ... ├── test_tmp.py 执行 python test_tmp.py 用于测试检测和识别效果 └── test_app.py 执行 python app.py 会被调用 ``` ## 模型及数据集 ``` crnn文本识别模型放在./model/recognition/下 dbnet文本识别模型根据 init_args()函数里的 --model_path 存放 模型链接:https://pan.baidu.com/s/1_rSLbprQCTfhj0819FbFAA 提取码:8ma7 数据集链接:https://pan.baidu.com/s/1TOVmWaLmilqGszr8Pw7Kxw 提取码: g42d ```<file_sep># -*- coding:utf-8 -*- import math import copy from functools import reduce import argparse import numpy as np import util from apphelper.image import order_point, calc_iou, xy_rotate_box from crnn import crnnRec from eval.invoice.eval_invoice import evaluate def get_right_marge(data): # 排除备注中的信息,以图片的中间为限 max_r = 0 for dd in data: tem_r = float(dd['cx']) + float(dd['w']) / 2 if tem_r > max_r: max_r = tem_r return max_r + 200 def get_min_distance_index(tem,indexes,near): x = float(tem['cx']) + float(tem['w']) / 2 y = float(tem['cy']) + float(tem['h']) / 2 distance_min = 100000 ii = 0 for i in indexes: x_tem = float(near[i]['cx']) - float(near[i]['w']/2) y_tem = float(near[i]['cy']) + float(near[i]['h']/2) distance_tem = math.sqrt(math.pow((x-x_tem),2) + math.pow((y-y_tem),2)) if distance_tem < distance_min and len(near[i]['text']) and calc_axis_iou(near[i],tem,1) > 0.3: ii = i distance_min = distance_tem # if distance_tem < 30 and re.search(r'[\u4e00-\u9fa5]{6,}',near[i]['text']): # return i return ii def format(data): return data def extend_3c(img): img = img.reshape(img.shape[0], img.shape[1], 1) img = np.concatenate((img, img, img), axis=2) return img def debug(idx, img_paths, imgs, output_root): if not os.path.exists(output_root): os.makedirs(output_root) col = [] for i in range(len(imgs)): row = [] for j in range(len(imgs[i])): # img = cv2.copyMakeBorder(imgs[i][j], 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=[255, 0, 0]) row.append(imgs[i][j]) res = np.concatenate(row, axis=1) col.append(res) res = np.concatenate(col, axis=0) img_name = img_paths[idx].split('/')[-1] print(idx, '/', len(img_paths), img_name) cv2.imwrite(output_root + img_name, res) def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes = np.empty([1, 8], dtype='int32') resBoxes[0, 0] = int(points[0]) resBoxes[0, 4] = int(points[1]) resBoxes[0, 1] = int(points[2]) resBoxes[0, 5] = int(points[3]) resBoxes[0, 2] = int(points[4]) resBoxes[0, 6] = int(points[5]) resBoxes[0, 3] = int(points[6]) resBoxes[0, 7] = int(points[7]) pointMat = resBoxes[0].reshape([2, 4]).T return plg.Polygon(pointMat) # ----------------------------------------------------------------------------------- import os import sys import pathlib __dir__ = pathlib.Path(os.path.abspath(__file__)) sys.path.append(str(__dir__)) sys.path.append(str(__dir__.parent.parent)) # project = 'DBNet.pytorch' # 工作项目根目录 # sys.path.append(os.getcwd().split(project)[0] + project) import time import cv2 import torch from dbnet.data_loader import get_transforms from dbnet.models import build_model from dbnet.post_processing import get_post_processing def resize_image(img, short_size): height, width, _ = img.shape if height < width: new_height = short_size new_width = new_height / height * width else: new_width = short_size new_height = new_width / width * height new_height = int(round(new_height / 32) * 32) new_width = int(round(new_width / 32) * 32) resized_img = cv2.resize(img, (new_width, new_height)) return resized_img class Pytorch_model: def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): ''' 初始化pytorch模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) model_path='/home/share/gaoluoluo/dbnet/output/DBNet_resnet18_FPN_DBHead/checkpoint/model_latest.pth' :param gpu_id: 在哪一块gpu上运行 ''' self.gpu_id = gpu_id if self.gpu_id is not None and isinstance(self.gpu_id, int) and torch.cuda.is_available(): self.device = torch.device("cuda:%s" % self.gpu_id) else: self.device = torch.device("cpu") # print('device:', self.device) checkpoint = torch.load(model_path, map_location=self.device) # print("checkpoint:",checkpoint) config = checkpoint['config'] # print(checkpoint['config']) config['arch']['backbone']['pretrained'] = False self.model = build_model(config['arch']) self.post_process = get_post_processing(config['post_processing']) self.post_process.box_thresh = post_p_thre self.img_mode = config['dataset']['train']['dataset']['args']['img_mode'] self.model.load_state_dict(checkpoint['state_dict']) self.model.to(self.device) self.model.eval() self.transform = [] for t in config['dataset']['train']['dataset']['args']['transforms']: if t['type'] in ['ToTensor', 'Normalize']: self.transform.append(t) self.transform = get_transforms(self.transform) def predict(self, img, is_output_polygon=False, short_size: int = 1024): ''' 对传入的图像进行预测,支持图像地址,opecv 读取图片,偏慢 :param img_path: 图像地址 :param is_numpy: :return: ''' # assert os.path.exists(img_path), 'file is not exists' # img = cv2.imread(img_path, 1 if self.img_mode != 'GRAY' else 0) if self.img_mode == 'RGB': img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w = img.shape[:2] # 2550 3507 img = resize_image(img, short_size) # 将图片由(w,h)变为(1,img_channel,h,w) tensor = self.transform(img) tensor = tensor.unsqueeze_(0) tensor = tensor.to(self.device) batch = {'shape': [(h, w)]} with torch.no_grad(): if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) start = time.time() preds = self.model(tensor) if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) box_list, score_list = self.post_process(batch, preds, is_output_polygon=is_output_polygon) box_list, score_list = box_list[0], score_list[0] if len(box_list) > 0: if is_output_polygon: idx = [x.sum() > 0 for x in box_list] box_list = [box_list[i] for i, v in enumerate(idx) if v] score_list = [score_list[i] for i, v in enumerate(idx) if v] else: idx = box_list.reshape(box_list.shape[0], -1).sum(axis=1) > 0 # 去掉全为0的框 box_list, score_list = box_list[idx], score_list[idx] else: box_list, score_list = [], [] t = time.time() - start return preds[0, 0, :, :].detach().cpu().numpy(), box_list, score_list, t def init_args(): import argparse parser = argparse.ArgumentParser(description='DBNet.pytorch') # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/dbnet/output/DBNet_resnet50_FPN_DBHead/checkpoint/model_latest.pth', type=str) # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/模型/model50_ch_epoch510_latest.pth', type=str) parser.add_argument('--model_path', default=r'./models/detective/model50_ch_epoch248_latest.pth', type=str) # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/invoices_gao_true/img/', type=str, help='img path for predict') parser.add_argument('--input_folder', default='./data/img_not_use/', type=str, help='img path for predict') # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_ocr/data/img_debug/', type=str, help='img path for predict') parser.add_argument('--img_correct',default='./invoices_gao_true/corre_gao/',type=str,help='img_correct path for predict') # parser.add_argument('--input_folder',default='/home/share/gaoluoluo/dbnet/test/test_corre_input', type=str, help='img path for predict') # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_ocr/data/images/tmp', type=str,help='img path for predict') parser.add_argument('--output_folder', default='./dbnet/test/test_output', type=str, help='img path for output') parser.add_argument('--gt_txt', default='/home/share/gaoluoluo/complete_ocr/data/txt_not_use', type=str, help='img 对应的 txt') parser.add_argument('--thre', default=0.1, type=float, help='the thresh of post_processing') parser.add_argument('--polygon', action='store_true', help='output polygon or box') parser.add_argument('--show', action='store_true', help='show result') parser.add_argument('--save_result', action='store_true', help='save box and score to txt file') parser.add_argument('--evaluate', nargs='?', type=bool, default=True, help='evalution') args = parser.parse_args() return args def test(): import pathlib from tqdm import tqdm import matplotlib.pyplot as plt from dbnet.utils.util import show_img, draw_bbox, save_result, get_file_list args = init_args() # print(args) os.environ['CUDA_VISIBLE_DEVICES'] = str('0') # 初始化网络 0.1 model = Pytorch_model(args.model_path, post_p_thre=args.thre, gpu_id=0) img_folder = pathlib.Path(args.input_folder) # dbnet/test/input/ # i = 0 total_frame = 0.0 total_time = [] precisions = [] names = [] names_tem = [] # iii = 1 for img_path in tqdm(get_file_list(args.input_folder, p_postfix=['.jpg','.png'])): # img_path /home/share/gaoluoluo/dbnet/test/input/2018实验仪器发票.jpg # print("img_path:",img_path) /home/share/gaoluoluo/dbnet/test/input/2018实验仪器发票.jpg print("\nimg_path:", img_path) start_time = time.time() from angle import angle_corre img = angle_corre(img_path)# 调整图片角度 # img = cv2.imread(img_path) img_path = args.img_correct + img_path.split('/')[-1] # After correct angle img path names.append(img_path.split('/')[-1]) # names_tem.append(str(iii)+img_path.split('.')[-1]) # iii += 1 print("img_path:",img_path) preds, boxes_list, score_list, t = model.predict(img, is_output_polygon=args.polygon) img_path1 = img_path boxes_list_save = boxes_list box = [] for i in range(0,len(boxes_list)): for j in range(0,len(boxes_list[0])): b = [] b.append(np.float32(boxes_list[i][j][0])) b.append(np.float32(boxes_list[i][j][1])) box.append(b) boxes_list = boxes_list.reshape(-1,2) boxes_list = box #---合框只能处理一个框被分成两个部分 i = 4 points_kuang = [] remove_mark = [] max_X = -1 while(i<=len(boxes_list)): points = boxes_list[i-4:i] for _,p in enumerate(points): if p[0] > max_X: max_X = p[0] i = i+4 points = np.array(points) points_kuang.append(points) for i in range(10,len(points_kuang)-10): point3 = points_kuang[i][2] start_point = i - 8 end_point = i + 8 if start_point < 0: start_point = 0 if end_point > len(points_kuang): end_point = len(points_kuang) if i not in remove_mark: for j in range(start_point,end_point): point4 = points_kuang[j][3] min_dis = math.sqrt(math.pow((point3[0] - point4[0]),2) + math.pow((point3[1] - point4[1]),2)) Y_cha = math.fabs(point3[1] - point4[1]) if min_dis < 15 and point4[0] > max_X / 2 and Y_cha < 25 and j not in remove_mark and i != j: # 10 reasonable # if min_dis < 0: point1_1 = points_kuang[i][0] point1_2 = points_kuang[j][0] x_min = min(point1_1[0],point1_2[0]) y_min = min(point1_1[1],point1_2[1]) point3_2 = points_kuang[j][2] x_max = max(point3[0],point3_2[0]) y_max = max(point3[1],point3_2[1]) points_kuang[i][0,0] = x_min points_kuang[i][0,1] = y_min points_kuang[i][1,0] = x_max points_kuang[i][1,1] = y_min points_kuang[i][2,0] = x_max points_kuang[i][2,1] = y_max points_kuang[i][3,0] = x_min points_kuang[i][3,1] = y_max remove_mark.append(j) # print("i=",i," j=",j) # print('x:',point4[0]) break remove_mark = sorted(remove_mark,reverse=True) # print("---------------------------") for _,i in enumerate(remove_mark): # print('x:',points_kuang[i][3][0]) del points_kuang[i] boxes_list_save = points_kuang # 决定保存的画框图片是否是 合框之后的图片 #--- i = 0; rects = [] while(i<len(points_kuang)): points = points_kuang[i] rect = cv2.minAreaRect(points) # 4个点 -> d cx cy w h rec = [] rec.append(rect[-1]) rec.append(rect[1][1]) rec.append(rect[1][0]) rec.append(rect[0][0]) rec.append(rect[0][1]) rects.append(rec) i += 1 ori_img = cv2.imread(img_path1) result = crnnRec(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) # result = crnnRec_tmp(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) result = list(reversed(result)) dur = time.time() - start_time print("dur:",dur) # 保存画框图片--------- # img = draw_bbox(img(img_path)[:, :, ::-1], boxes_list_save) img = draw_bbox(cv2.imread(img_path)[:, :, ::-1], boxes_list_save) if args.show: show_img(preds) show_img(img, title=os.path.basename(img_path)) plt.show() # 保存结果到路径 os.makedirs(args.output_folder, exist_ok=True) img_path = pathlib.Path(img_path) output_path = os.path.join(args.output_folder, img_path.stem + '_result.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_result.jpg pred_path = os.path.join(args.output_folder,img_path.stem + '_pred.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_pred.jpg cv2.imwrite(output_path, img[:, :, ::-1]) cv2.imwrite(pred_path, preds * 255) save_result(output_path.replace('_result.jpg', '.txt'), boxes_list_save, score_list, args.polygon) # -------- total_frame += 1 total_time.append(dur) result = formatResult(result) # 计算准确率 if args.evaluate: file = os.path.join(args.gt_txt,img_path.stem + '.txt') errfile = os.path.join(args.output_folder, 'error_txt/' + img_path.stem + '-errors.txt') canfile = os.path.join(args.output_folder, 'candidate_txt/' + img_path.stem + '-candidate.txt') if os.path.exists(file): precision = evaluate(file, errfile,canfile,result) print('precision:' + str(precision[0]) + '%') precisions.append(precision[0]) for i in range(0,len(precisions)): # print(names[i],precisions[i]) print(precisions[i]) if len(precisions): mean = np.mean(precisions) print("names:",names) # print("names:",names_tem) print("precisions:",precisions) time_mean = np.mean(total_time) print('mean precision:' + str(mean) + '%') print('mean time:' + str(time_mean) + 's') return 0; #-------------------------------------------------- import re def isTitle(text): # return re.search(r'(货物|劳务|服.?名称|规.?型号|^单[位价]|^数|.?额$|^税.$|项目|类型|车牌|通行日期)', text) != None # return re.search(r'(货物|劳务|服.?名称|规.?型号|^单[位价]|^数|.?额$|税率|税额|项目|类型|车牌|通行日期)', text) != None return re.search(r'(货物|劳务|服.?名称|规.?型号|^单[位价]|^数量|税率|税额)', text) != None return re.search(r'(货物|劳务|服.?名称|规.?型号|^单[位价]|^数量|.?额$|税率|税额|项目|类型|车牌|通行日期)', text) != None def isSummary(text): # pattern = re.compile(r'[¥|Y|羊]\d+?\.?\d*') # pattern = re.compile(r'(¥|Y|羊)[0-9]+(.[0-9]{2})?$') pattern = re.compile(r'(¥|Y|羊)[0-9]+(.[0-9]{2})$') return text==r'计' or text == r'合' or text == r'合计' or pattern.search(text) != None def get_content_boundary(data): # #--- 过滤左边的无用信息 left = [d for i, d in enumerate(data) if isTitle(d['text'])] left = sorted(left,key=lambda x: x['cx'] - x['w'] / 2) left = left[0] cx_tem = float(left['cx'] - float(left['w']) / 2) # 标题的左 if re.search(r'(货物|劳务|服.?名称)', left['text']) != None: for i in range(len(data)-1,-1,-1): cx = float(data[i]['cx']) + float(data[i]['w']) / 2 # 其他的右 if(0 < cx_tem -cx): # print(data[i]) data.pop(i) #---- #---- while len(data): left_tem = min(data, key = lambda x : x['cx'] - x['w'] / 2) if len(left_tem['text']) < 3 : data.remove(left_tem) else : break while len(data): right_tem = max(data, key = lambda x : x['cx'] + x['w'] / 2) if len(right_tem['text']) < 3 : data.remove(right_tem) else : break #---- title = [i for i, d in enumerate(data) if isTitle(d['text'])] # print(data[31]['text']) s = title[0] e = title[-1] title.extend([i+s-4 for i,d in enumerate(data[s-4:s]) if abs(d['cy'] - data[s]['cy']) < 10]) title.extend([i+e+1 for i,d in enumerate(data[e+1:e+6]) if abs(d['cy'] - data[e]['cy']) < 10]) s = min(title) e = max(title) lf = min(data[s:e+1], key=lambda x:x['cx']-x['w']/2) summary = [i for i, d in enumerate(data) if isSummary(d['text'])] s = summary[0] summary.extend([i+s-4 for i, d in enumerate(data[s-4:s]) if abs(d['cy'] - data[summary[-1]]['cy']) < 10]) s = min(summary) start = e # print("start:",start) end = s # print("end:",end) # rt = [d for d in data[start:end] if re.match(r'\d+\.?\d*$', d['text'])] rt = max(data[start:end], key=lambda x: x['cx']+x['w']/2) left = lf['cx']-lf['w']/2 # 20为经验值 right = rt['cx']+rt['w']/2 # 80 为经验值 return (start, end, left, right) def check(data, placeholder, dir = 0): try: i = None if isinstance(placeholder,list): for pld in placeholder: f = [x for x,d in enumerate(data) if d == pld] if len(f): i = f[-1] break else: f = [x for x,d in enumerate(data) if d == placeholder] if len(f): i = f[-1] return i except: return None LEFT_MARGIN = 70 RIGHT_MARGIN = 20 def parseLine(line, boundary, isvehicle=False): xmin, xmax = boundary copyed = copy.deepcopy(line) copyed = preprocess_line(copyed) # 主要处理的是框框交叉,并对cx排序 if isvehicle: # ratio, price = get_ratio(copyed, xmax) ratio, price, tax = get_ratio_price_tax(copyed, xmax) # title title = get_title(copyed, xmin) sdate, edate, price, ratio = get_date(copyed, price, ratio) platenum, cartype, sdate, edate = get_platenum_cartype(copyed, sdate, edate) return postprocess_line(title, platenum, cartype, sdate, edate, price, ratio, tax) else: # ratio # ratio, price = get_ratio(copyed, xmax) ratio, price, tax = get_ratio_price_tax(copyed, xmax) # title title = get_title(copyed, xmin) # jin # tax # tax = get_tax(copyed, xmax, ratio) # prices # specs, amount, uprice, price, ratio = get_numbers(copyed, price, ratio,tax) #specs specs,unit = get_specs_unit(copyed, specs) return postprocess_line(title, specs, unit, amount, uprice, price, ratio, tax) def preprocess_line(line): line = sorted(line, key=lambda x: x['cx'] - x['w'] / 2) res = [] i = 0 j = 1 while i < len(line) and j < len(line): x = line[i] y = line[j] x1 = x['cx'] + x['w'] / 2 # 左的右边 y1 = y['cx'] - y['w'] / 2 # 右的左边 if abs(x1 - y1) < 8: # 说明是同一个框 合并 x['w'] = y['cx'] + y['w']/2 - x['cx'] + x['w']/2 x['cx'] = y['cx'] + y['w']/2 - x['w']/2 x['text'] = x['text'] + y['text'] j = j + 1 else: # 不是同一个框,继续向you遍历 res.append(x) i = j j = j + 1 res.append(line[i]) return res def is_number(s): try: float(s) return True except ValueError: pass return False def postprocess_line(title, specs, unit, amount, uprice, price, ratio, tax): if tax != '***' and is_number(price) and ratio and (not tax or not is_number(tax) or float(tax) > float(price) or not '.' in tax) : tax = '%.2f' % (float(price) / 100 * float(ratio[:-1])) return [title, specs, unit, amount, uprice, price, ratio, tax] def get_title(line, xmin): title = '' candidates = [d for d in line if abs(d['cx'] - d['w'] / 2 - xmin) < LEFT_MARGIN] if len(candidates): candidates = sorted(candidates, key=lambda x:x['cy']) for c in candidates: title += c['text'] line.remove(c) if title and not title.startswith('*'): title = '*' + title return title def get_ratio_price_tax(line, xmax): ratio = '' price = '' tax = '' pat = re.compile(r'(\-?[\dBG]+\.?[\dBG]{2})*(([\dBG]+[\%])|([\u4e00-\u9fa5]+税))$') pat2 = re.compile(r'(\-?[\dBG]+\.[\dBG]{2})([\dBG]{1,2}[8])') ratioitem = None for i in range(len(line)-1, -1, -1): text = line[i]['text'] m = pat.match(text) if m: price, ratio = (m.group(1), m.group(2)) if m.group(1) else ('', m.group(2)) else: if len(line) - i < 3: # reduce m = pat2.match(text) if m: price, ratio = (m.group(1), m.group(2)) ratio = ratio[:-1] + '%' if ratio: ratioitem = line.pop(i) break if not ratio: numbers = sorted([i for i,d in enumerate(line) if re.match(r'([\dBG]+\.?[\dBG]{2})*', d['text'])], key=lambda x:line[x]['cx']-line[x]['w']/2) if len(numbers)>=3: i = numbers[-2] d = line[i] m = re.match(r'(\d{1,2})\D+', d['text']) # 1-2 number and !number char eg 11% if m: ratio = m.group(1) ratioitem = line.pop(i) if re.search(r'税$', ratio): tax = '***' else: if ratioitem: taxes = [l for l in line if l['cx'] > ratioitem['cx']] if len(taxes): tax = taxes[0]['text'] line.remove(taxes[0]) if not tax: x = 1000 for i,d in enumerate(line): if abs(d['cx'] + d['w'] / 2 - xmax) < x: x = abs(d['cx'] + d['w'] / 2 - xmax) idx = [i for i, d in enumerate(line) if abs(d['cx'] + d['w'] / 2 - xmax) < RIGHT_MARGIN] if len(idx): idx = idx[0] ln = line[idx] tax = ln['text'] line.pop(idx) if len(tax) > 2 and tax.find('.') == -1: tax = tax[:-2] + '.' + tax[-2:] if len(price) and not '.' in price: if tax and ratio: while float(price) > float(tax): prc = price[:-2] + '.' + price[-2:] f_tax = float(tax) f_ratio = float(ratio[:-1]) f_price = float(prc) if abs(f_price * f_ratio / 100.0 - f_tax) > 0.1 and f_ratio < 10: ratio = price[-1] + ratio price = price[:-1] else: price = prc break else: price = price[:-2] + '.' + price[-2:] if price and ratio and not tax: tax = str(round(float(price) * float(ratio[:-1]) / 100.0, 2)) return ratio, price, tax def get_tax(line, xmax, ratio): tax = '' if re.search(r'税$', ratio): tax = '***' idx = [i for i, d in enumerate(line) if abs(d['cx'] + d['w'] / 2 - xmax) < RIGHT_MARGIN] if len(idx): idx = idx[0] ln = line[idx] tax = ln['text'] line.pop(idx) if len(tax) > 2 and tax.find('.') == -1: tax = tax[:-2] + '.' + tax[-2:] return tax def get_ratio(line, xmax): ratio = '' price = '' pat = re.compile(r'(\-?[\dBG]+\.?[\dBG]{2})*(([\dBG]+[\%])|([\u4e00-\u9fa5]+税))$') for i in range(len(line)-1, -1, -1): text = line[i]['text'] m = pat.match(text) if m: price, ratio = (m.group(1), m.group(2)) if m.group(1) else ('', m.group(2)) if ratio: line.pop(i) break if not ratio: numbers = sorted([i for i,d in enumerate(line) if re.match(r'([\dBG]+\.?[\dBG]{2})*', d['text'])], key=lambda x:line[x]['cx']-line[x]['w']/2) if len(numbers)>=3: i = numbers[-2] d = line[i] m = re.match(r'(\d{1,2})\D+', d['text']) if m: ratio = m.group(1) + '%' line.pop(i) return ratio, price def get_numbers(line, price, ratio,tax): specs = '' amount = '' uprice = '' pattern = re.compile(r'\-?[\dBG:]+\.?[\dBG]*$') numbers = [] for d in line: if pattern.match(d['text']): d['text'] = d['text'].replace('B','8').replace('G', '6').replace(':','') numbers.append(d) if len(numbers): for n in numbers: line.remove(n) # preprocess_number(numbers) numbers = sorted(numbers, key=lambda x: x['cx'] - x['w'] / 2) if not ratio and re.match(r'^\d{2,3}$', numbers[-1]['text']): ratio = numbers[-1]['text'] ratio = ratio[:-1] + '%' numbers = numbers[0:-1] if not price: # print("*price:",price) # print("len:",len(numbers[-1]['text'])) if(len(numbers)): price = numbers[-1]['text'] m = re.match(r'(\d+\.\d{2})\d*(\d{2})$', price) if m and not ratio: price = m.group(1) ratio = m.group(2) + '%' numbers = numbers[0:-1] numlen = len(numbers) if numlen == 3: specs = numbers[0]['text'] amount = numbers[1]['text'] uprice = numbers[2]['text'] elif numlen == 2: num1 = numbers[0]['text'] num2 = numbers[1]['text'] if abs(float(num1) * float(num2) - float(price)) < 0.01: specs = '' amount = num1 uprice = num2 elif abs(float(num2) - float(price)) < 0.01: specs = num1 amount = '1' uprice = num2 else: specs, amount, uprice = get_amount_uprice(price, num2, num1) elif numlen == 1: specs = '' num = numbers[0]['text'] if abs(float(num) - float(price)) < 0.01: amount = '1' uprice = num else: specs, amount, uprice = get_amount_uprice(price, num) if not amount: if uprice: amount = str(int(float(price) / float(uprice) + 0.5)) else: amount = num if not ratio and price and tax: ratio = str(int(float(tax) * 100 / float(price) + 0.5)) + '%' return specs, amount, uprice, price, ratio def get_date(line, price, ratio): sdate = '' edate = '' pattern = re.compile(r'\-?[\dBG:]+\.?[\dBG]*$') numbers = [] for d in line: if pattern.match(d['text']): d['text'] = d['text'].replace('B','8').replace('G', '6').replace(':','') numbers.append(d) if len(numbers): for n in numbers: line.remove(n) # preprocess_number(numbers) numbers = sorted(numbers, key=lambda x: x['cx'] - x['w'] / 2) if not ratio and re.match(r'^\d{2,3}$', numbers[-1]['text']): ratio = numbers[-1]['text'] ratio = ratio[:-1] + '%' numbers = numbers[0:-1] if not price: price = numbers[-1]['text'] m = re.match(r'(\d+\.\d{2})\d*(\d{2})$', price) if m and not ratio: price = m.group(1) ratio = m.group(2) + '%' numbers = numbers[0:-1] numlen = len(numbers) if numlen == 2: sdate = numbers[0]['text'] edate = numbers[1]['text'] elif numlen == 1: edate = numbers[0]['text'] return sdate, edate, price, ratio def get_platenum_cartype(line, sdate, edate): platenum = '' cartype = '' pattern = re.compile(r'([\u4e00-\u9fa5]+)(\d{8,})$') if len(line) == 2: platenum = line[0]['text'] cartype = line[1]['text'] elif len(line) == 1: if not sdate: cartype = line[0]['text'] else: platenum = line[0]['text'] if cartype and not sdate: m = pattern.match(cartype) if m: cartype, sdate = m.group(1), m.group(2) if len(sdate) > 8 and not edate: edate = sdate[8:] sdate = sdate[:8] return platenum, cartype, sdate, edate def preprocess_number(numbers): number = [i for i,n in enumerate(numbers) if n['text'].find(':')>-1] adds = [] removes = [] for i in number: d = numbers[i] text = d['text'] splits = text.split(':') d1 = dict(d) d1['text'] = splits[0] d1['w'] = d['w'] * len(d1['text']) / len(text) d1['cx'] = d['cx'] - d['w'] / 2 + d1['w'] / 2 d2 = dict(d) d2['text'] = splits[1] d2['w'] = d['w'] * len(d2['text']) / len(text) d2['cx'] = d['cx'] + d['w'] / 2 - d2['w'] / 2 removes.append(d) adds.extend([d1, d2]) for d in removes: numbers.remove(d) numbers.extend(adds) def get_amount_uprice(price, upricecand, amtcand=None): price = float(price) specs = '' amount = '' uprice = '' copyprice = upricecand dotplace = upricecand.find('.') if dotplace > 0: upricecand = upricecand[:dotplace] + upricecand[dotplace + 1:] if amtcand: upr = str(math.trunc(float(price) / float(amtcand) * 100)) idx = upricecand.find(upr) if idx >= 0: amount = amtcand upricecand = upricecand[idx:] dot = len(upr[:-2]) uprice = upricecand[:dot] + '.' + upricecand[dot:] if not uprice: end = dotplace - 1 if dotplace else len(upricecand) - 2 for idx in range(2, end): amt = int(upricecand[:idx]) upr = upricecand[idx:] if not amt: break calcupr = price / amt if calcupr < 1: break dot = str(calcupr).find('.') if dot > len(upr): break upr = float(upr[0:dot] + '.' + upr[dot:]) if abs(upr - calcupr) < 1: amount = str(amt) uprice = str(upr) break if not uprice: m = re.match(r'(\d+0+)([1-9]\d*\.\d+)', copyprice) if m: amount = m.group(1) uprice = m.group(2) else: uprice = copyprice if amtcand: amount = amtcand else: if amtcand: specs = amtcand return specs,amount,uprice def get_specs_unit(line, specs): unit = '' linelen = len(line) if linelen == 2: specs = line[0]['text'] unit = line[1]['text'] if linelen == 1: text = line[0]['text'] if specs: unit = text else: if len(text) == 1: unit = text else: specs = text return specs,unit def is_wrapped_title(data, line, boundary): res = False xmin = boundary[0] dx = abs(data['cx'] - data['w'] / 2 - xmin) # 该data的左边与最左边的差的绝对值 text = data['text'] # if len(text) == 0: # 自己加的 return res if dx < LEFT_MARGIN and text[0] != '*': # 偏左并且开头不是* res = True return res def check_title(line, data, start, end, boundary): xmin = boundary[0] lf = min(line, key=lambda d:d['cx'] - d['w'] / 2) dx = abs(lf['cx'] - lf['w'] / 2 - xmin) if dx > LEFT_MARGIN: for d in data[start:end]: dx = abs(d['cx'] - d['w'] / 2 - xmin) if dx < LEFT_MARGIN: iou = [calc_axis_iou(d,l,1) for l in line] if np.mean(iou) > 0.3: line.append(d) data.remove(d) break def check_wrap_title(res, wraptitles, line=None): title = res[-1][0] wraplen = len(wraptitles) if wraplen: idx = 0 if not line: wrap = wraptitles[:] else: wrap = [] ref = min(line, key=lambda x:x['cx']-x['w']/2) for i,w in enumerate(wraptitles): if w['cy'] < ref['cy']: wrap.append(w) else: break if len(wrap): del wraptitles[0:len(wrap)] title = reduce(lambda a,b:a+b, [w['text'] for w in wrap], title) res[-1][0] = title def get_basic_boundary(data): indexes = [i for i, d in enumerate(data) if re.search(r'开.?日期|票日期|校.?码|20.?.?年?.?.?月', d['text'])] # print(data[71]) if len(indexes): end = max(indexes) # if end > 10 : # end = 10 else: end = 8 lt = min(data[:end+1]+data[-10:], key=lambda x:x['cx']-x['w']/2) rt = max(data[:end+1]+data[-10:], key=lambda x:x['cx']+x['w']/2) left = lt['cx'] - lt['w'] / 2 right = rt['cx'] + rt['w'] / 2 return (0, end, left, right) def get_basic_checkcode(basic): checkcode = '' candidates = [d for d in basic if re.search(r'^te校.?码*', d['text'])] if len(candidates): m = re.match(r'^校.?码.*?(\d+)', candidates[0]['text']) checkcode = m.group(1) if m else '' return checkcode def get_basic_checkcode2(date): checkcode = '' candidates = [d for d in date if re.search(r'^校.?码*', d['text'])] # 找到,切只能找到一个 if len(candidates) <=0: return '' # indexs = [idx for idx,d in enumerate(date) if re.search(r'^校.?码*', d['text'])] indexs = [i for i, d in enumerate(date) if re.search(r'^校.?码*', d['text'])] # 整体框的时候 if candidates[0]['text'].find(':') >= 0: checkcode = candidates[0]['text'].split(':')[1] if len(checkcode)==20: return checkcode if len(candidates) == 1: # 不是整体框的时候 r = indexs[0] + 5 l = max(indexs[0]-5,0) can = date[l:r] x = float(candidates[0]['cx']) + float(candidates[0]['w'])/2 y = float(candidates[0]['cy']) + float(candidates[0]['h'])/2 distance_min = 10000 index = 0 for i in range(0,len(can)): # 先找到一个最小的离验证码框 x_tem = float(can[i]['cx']) - float(can[i]['w'])/2 y_tem = float(can[i]['cy']) + float(can[i]['h'])/2 distance_tem = math.sqrt(math.pow((x - x_tem),2) + math.pow((y-y_tem),2)) if distance_tem < distance_min: distance_min = distance_tem index = i flags = [] flags.append(index) checkcode += can[index]['text'] for i in (0,4): if(len(checkcode)>=20): break x = float(can[index]['cx']) + float(can[index]['w']) / 2 y = float(can[index]['cy']) + float(can[index]['h']) / 2 distance_min = 10000 for j in range(0,len(can)): if j not in flags: x_tem = float(can[j]['cx']) - float(can[j]['w']) / 2 y_tem = float(can[j]['cy']) + float(can[j]['h']) / 2 distance_tem = math.sqrt(math.pow((x - x_tem), 2) + math.pow((y - y_tem), 2)) if distance_tem < distance_min: distance_min = distance_tem index = j if can[index]['text'].isdigit(): checkcode += can[index]['text'] flags.append(index) # zuihou yici jiancha : if checkcode.find(':') >= 0: checkcode = checkcode.split(':')[-1] # m = re.match(r'^校.?码.*?(\d+)', candidates[0]['text']) # checkcode = m.group(1) if m else '' return checkcode PROVINCE = ['河北','山西','辽宁','吉林','黑龙江','江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','海南','四川','贵州','云南','陕西'] def get_basic_type(basic): type = '' title = '' elec = '电子' if len([d for d in basic if re.search(r'发票代码', d['text'])])>0 else '' candidates = [d for d in basic if re.search(r'.*(专?用?|通)?发票', d['text'])] if len(candidates): text = candidates[0]['text'] if text.find('用') >= 0 or text.find('专') >= 0: type = elec + '专用发票' else: type = elec + '普通发票' suffix = '增值税' + type title = suffix # ---新加的 for p in PROVINCE: indexs = [d for d in basic if re.search(p, d['text'])] if len(indexs): title = p + suffix return type,title # ---- if text[:2] in PROVINCE: title = text[:2] + suffix elif text[:3] in PROVINCE: title = text[:3] + suffix else: titles = [d for d in basic if re.search(r'^.*增值?', d['text'])] if len(titles): title = titles[0]['text'] i = title.find('增') title = title[:i] + suffix else: i = basic.index(candidates[0]) titles = [basic[i-1], basic[i+1]] for t in titles: if re.match(r'[\u4e00-\u9fa5]{2,3}', t['text']): # duociyiju # title = t['text'] + suffix break else: for p in PROVINCE: indexs = [d for d in basic if re.search(p, d['text'])] if len(indexs): title = p + '增值税' + '发票' return type, title return type,title def get_basic_title(basic, type): title = '' elec = '电子' if len([d for d in basic if re.search(r'发票代码', d['text'])]) > 0 else '' candidates = [d for d in basic if re.search(r'^.*增值?', d['text'])] if len(candidates): title = candidates[0]['text'] i = title.find('增') title = title[:i] + '增值税' + elec + type return title def get_basic_date(basic): date = '' # candidates = [d for d in basic if re.search(r'开?票?日期', d['text'])] candidates = [d for d in basic if re.search(r'20?.?.?年?.?.?月', d['text'])] if len(candidates):# 原来的Pse wangluo shi zhengti kuangde date = candidates[0]['text'] date = re.sub(r'开?票?日期:?', '', date) return date def get_basic_code(basic): code = '' candidates = [d for d in basic if re.search(r'(发票代码:?\d+)|(^\d{10,12}$)', d['text'])] if len(candidates): code = max(candidates, key=lambda x:x['cx']+x['w']/2) m = re.match(r'.*?(\d+)$', code['text']) code = m.group(1) if m else '' return code def get_basic_sn(basic): sn = '' candidates = [d for d in basic if re.search(r'(发票号码:?\d+)|(^\d{8}$)', d['text'])] if len(candidates): code = max(candidates, key=lambda x: x['cx'] + x['w'] / 2) m = re.match('.*?(\d+)$', code['text']) sn = m.group(1) if m else '' return sn def get_basic_payee(data): payee = '' candidates = [d for d in data if re.search(r'收款人', d['text'])] if len(candidates): payee = max(candidates, key=lambda x: x['cy']) payee = re.sub(r'收款人:?', '', payee['text']) return payee def get_basic_reviewer(data): reviewer = '' candidates = [d for d in data if re.search(r'(复核|发校)', d['text'])] if len(candidates): reviewer = max(candidates, key=lambda x: x['cy']) reviewer = re.sub(r'(复核|发校):?', '', reviewer['text']) return reviewer def get_basic_drawer(data): drawer = '' candidates = [d for d in data if re.search(r'开票人', d['text'])] if len(candidates): drawer = max(candidates, key=lambda x: x['cy']) drawer = re.sub(r'开票人:?', '', drawer['text']) return drawer def parse_person(text): if text.find(':') >= 0: text = text.split(':')[1] else: text = re.sub(r'.*((开?票?人)|(复?核)|(复)|(收?款?人))', '', text) return text def get_basic_person(data, boundary): payee = '' reviewer = '' drawer = '' payee_text = '' reviewer_text = '' drawer_text = '' xmin = boundary[0] rear = data[-12:] #范围大一点,防止盖章和备注信息的影响 indexes = [i for i,d in enumerate(rear) if re.search(r'收?款|开票人|复?核|人:|复.:|校:', d['text'])] finded = len(indexes) if finded < 3: s = min(indexes) - 3 e = min(10, max(indexes)+3) for i in range(s,e): if i not in indexes: text = rear[i]['text'] l = len(text) if (text.find(':') > -1 and l < 8) or (text.find('钠售') < 0 and l < 4 and l > 1): indexes.append(i) candidates = [rear[i] for i in indexes] if len(candidates): candidates = sorted(candidates, key=lambda x:x['cx']-x['w']/2) left = candidates[0]['cx'] - candidates[0]['w'] / 2 - xmin if left < 25: payee = candidates[0] candidates.pop(0) s = max([i for i, d in enumerate(data) if re.search(r'\(?大写\)?', d['text'])],default=0) e = min([i for i, d in enumerate(data) if re.search(r'\(?小写\)?.*(¥|Y|羊)?\d+', d['text'])],default=0) ref = data[e] s, e = (e-1, s+2) if e < s else (s, e+1) refs = sorted([data[i] for i in range(s,e) if calc_axis_iou(ref, data[i], 1)>0.01], key=lambda x: x['cx']-x['w']/2) if len(refs) >= 3: idx = refs.index(ref) ref = refs[idx-1] rl = ref['cx'] - ref['w'] / 2 rr = ref['cx'] + ref['w'] / 2 for c in candidates: cl = c['cx'] - c['w'] / 2 cr = c['cx'] + c['w'] / 2 if cr > rr: drawer = c break elif rl < c['cx'] and rr > c['cx']: reviewer = c elif finded == 3: payee,reviewer,drawer = sorted([rear[i] for i in indexes],key=lambda x:x['cx']-x['w']/2) # payee_text = parse_person(payee['text']) payee_text = payee['text'] if len(payee_text)>4: payee_text = payee_text[4:] else: x = float(payee['cx']) + float(payee['w'])/2 y = float(payee['cy']) + float(payee['h'])/2 # 右下坐标 index =-1 distance_min = 100000 for i in range(len(data)-10,len(data)): tem_payee = data[i] x_tem = float(tem_payee['cx']) - float(tem_payee['w'])/2 y_tem = float(tem_payee['cy']) + float(tem_payee['h']) / 2 # 左下坐标 distance_tmp = math.sqrt(math.pow((x - x_tem), 2) + math.pow((y - y_tem), 2)) if distance_tmp < distance_min and len(tem_payee['text']) and distance_tmp <60: index = i distance_min = distance_tmp if index != -1: payee = data[index] payee_text = payee['text'] #-------------------------------------------- # reviewer_text = parse_person(reviewer['text']) reviewer_text = reviewer['text'] if len(reviewer_text) > 3: reviewer_text = reviewer_text[3:] else : x = float(reviewer['cx']) + float(reviewer['w'])/2 y = float(reviewer['cy']) + float(reviewer['h'])/2 index = -1 distance_min = 100000 for i in range(len(data)-10,len(data)): tem_reviewer = data[i] x_tem = float(tem_reviewer['cx']) - float(tem_reviewer['w'])/2 y_tem = float(tem_reviewer['cy']) + float(tem_reviewer['w'])/2 distance_tmp = math.sqrt(math.pow((x - x_tem),2) + math.pow((y - y_tem),2)) if distance_tmp < distance_min and len(tem_reviewer['text']) and distance_tmp <60: distance_min = distance_tmp index = i if index != -1: reviewer = data[index] reviewer_text = reviewer['text'] #-------------------------------------------------------- # drawer_text = parse_person(drawer['text']) drawer_text = drawer['text'] if len(drawer_text) > 4: drawer_text = drawer_text[4:] else: x = float(drawer['cx']) + float(drawer['w'])/2 y = float(drawer['cy']) + float(drawer['h'])/2 index = -1 distance_min = 100000 for i in range(len(data)-10,len(data)): tem_drawer = data[i] x_tem = float(tem_drawer['cx']) - float(tem_drawer['w'])/2 y_tem = float(tem_drawer['cy']) + float(tem_drawer['h'])/2 distance_tmp = math.sqrt(math.pow((x - x_tem),2) + math.pow((y - y_tem),2)) if distance_min > distance_tmp and len(tem_drawer['text']) and distance_tmp <60: distance_min = distance_tmp index = i if index != -1: drawer = data[index] drawer_text = drawer['text'] return payee_text,reviewer_text,drawer_text if payee: payee = parse_person(payee['text']) if reviewer: reviewer = parse_person(reviewer['text']) if drawer: drawer = parse_person(drawer['text']) return payee, reviewer, drawer def getBasics(data): s, e, left, right = get_basic_boundary(data) basic = data[s:e+1] # checkcode = get_basic_checkcode(basic) # checkcode = get_basic_checkcode2(data) # 只有电子发票有验证码 type, title = get_basic_type(basic) # title = basic_title(basic, checkcode, type) code = get_basic_code(basic) sn = get_basic_sn(basic) date = get_basic_date(basic) # payee = basic_payee(data[-10:]) # reviewer = basic_reviewer(data[-10:]) # drawer = basic_drawer(data[-10:]) payee, reviewer, drawer = get_basic_person(data, [left, right]) res = [[{'name': r'发票类型','value': type}, {'name': r'发票名称','value': title}, {'name': r'发票代码','value': code}, {'name': r'发票号码','value': sn}, {'name': r'开票日期','value': date}, {'name': r'校验码','value': checkcode}, {'name': r'收款人','value': payee}, {'name': r'复核','value': reviewer}, {'name': r'开票人','value': drawer}]] del data[:e-1] return res # return {"type":type, "title":title, "code":code, "sn":sn, "date":date, "checkcode":checkcode, "payee":payee, "reviewer":reviewer, "drawer":drawer} def get_buyer_boundary(data): indexes = [i for i, d in enumerate(data) if isTitle(d['text'])] end = min(indexes) # 为什么取最小 因为去tittle之前的 indexes = [i for i, d in enumerate(data) if i < end and re.search(r'(开票日期)|(校.?码)|(机器编号)|(20.?.?年.?.?月)', d['text'])] # print("len(indexes):",len(indexes)) start = max(indexes,default=0) + 1 # 取 上面日期范围中最大的 indexes = [i for i, d in enumerate(data[start:end]) if calc_axis_iou(data[start-1], d, 1) > 0.3] if len(indexes): start = start + max(indexes) + 1 return start, end def get_buyer_name(buyer): indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{6,}', d['text'])] # indexes = [i for i, d in enumerate(buyer) if re.search(r'^称:[\u4e00-\u9fa5]{6,}', d['text'])] if len(indexes): index = indexes[0] else: indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{6,}', d['text'])] index = indexes[0] name = buyer[index] text = name['text'] if text.find(':') >= 0: name = text.split(':')[-1] else: name = re.sub(r'^[^\u4e00-\u9fa5]+?', '', text) name = re.sub(r'^称', '', name) return name, index def get_buyer_taxnumber(buyer): indexes = [i for i, d in enumerate(buyer) if re.search(r'[0-9A-Z]{14,}', d['text'])] index = indexes[0] taxnumber = buyer[index] text = taxnumber['text'] if text.find(':') >= 0: taxnumber = text.split(':')[1] else: taxnumber = re.sub(r'^[^0-9A-Z]+?', '', text) return taxnumber, index def get_buyer_address(buyer): address = '' index = 0 indexes = [i for i, d in enumerate(buyer) if re.search(r'电话:[\u4e00-\u9fa5]{7,}', d['text'])] if not len(indexes): indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text'])] if len(indexes): index = indexes[0] address = buyer[index] text = address['text'] if text.find(':') >= 0: address_tem = text.split(':') address = '' for i in range(1,len(address_tem)): # print(address_tem[i]) address += str(address_tem[i]) else: address = text if not re.search(r'[0-9\-]{11,}$', address): # indexes = [i for i, d in enumerate(buyer) if re.match(r'\d+$', d['text']) and i > index] indexes = [i for i, d in enumerate(buyer) if re.match(r'[0-9\-]{6,}$', d['text'])] x = float(buyer[index]['cx']) + float(buyer[index]['w']/2) y = float(buyer[index]['cy']) + float(buyer[index]['h']/2) distance_min = 100000 for i in indexes: x_tem = float(buyer[i]['cx']) - float(buyer[i]['w'] / 2) y_tem = float(buyer[i]['cy']) + float(buyer[i]['h'] / 2) distance_tem = math.sqrt(math.pow((x-x_tem),2) + math.pow((y-y_tem),2)) if distance_min > distance_tem: index = i distance_min = distance_tem address += buyer[index]['text'] for prov in PROVINCE: idx = address.find(prov) if idx > 0: address = address[idx:] break return address, index def get_buyer_account(buyer): account = '' indexes = [i for i, d in enumerate(buyer) if re.search(r'账号:[\u4e00-\u9fa5]{7,}', d['text'])] if not len(indexes): indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text'])] if len(indexes): index = indexes[0] account = buyer[index] text = account['text'] if text.find(':') >= 0: account = text.split(':')[1] else: account = text if not re.search(r'\d{12,}$', account): # indexes = [i for i, d in enumerate(buyer) if re.match(r'\d{12,}$', d['text']) and i > index] indexes = [i for i, d in enumerate(buyer) if re.match(r'\d{12,}$', d['text'])] if len(indexes): index = indexes[0] account += buyer[index]['text'] idx = account.find(r'账号') if idx >= 0: account = account[idx+2:] return account def getBuyer(data): start, end = get_buyer_boundary(data) buyer = data[start:end] name, index = get_buyer_name(buyer) buyer = buyer[index+1:] taxnum, index = get_buyer_taxnumber(buyer) buyer = buyer[index+1:] address, index = get_buyer_address(buyer) buyer = buyer[index+1:] account = get_buyer_account(buyer) res = [[{'name':r'名称', 'value':name}, {'name':r'纳税人识别号', 'value':taxnum}, {'name':r'地址、电话', 'value':address}, {'name':r'开户行及账号','value':account}]] return res # return {"name":name, "taxnum":taxnum, "address":address, "account":account} def isVehicle(data): ret = False l = len(data) for d in data[:int(l/2)]: if re.search(r'项目|类型|车牌|通行日期', d['text']): ret = True break return ret def is_wrapped_title2(data, line, content, next, boundary) : """ :param data: ct :param line: one line have :param content: :param next: save as now data next index :param boundary: left and right :return: """ ret = False xmin = boundary[0] dx = abs(data['cx'] - data['w'] / 2 - xmin) text = data['text'] if dx < LEFT_MARGIN : if len(text) < 6 and len(line) : # len(tittle)==6 and ret = True else : if not re.search(r'\*[\u4e00-\u9fa5]', text) : # not *zhongwen if next == len(content) : # last one if (not len(line) or calc_axis_iou(data, line) > 0.2) : ret = True else : # is not last one end = min([next + 8, len(content)]) neighbor = None title = None for c in content[next :end] : if calc_axis_iou(c, data) > 0.2 : title = c else : if neighbor is None: if c['text'] != '': neighbor = c else : dx = c['cx'] - data['cx'] x = neighbor['cx'] - data['cx'] y = calc_axis_iou(c, neighbor,1) z = calc_axis_iou(c, neighbor) # must correct img_angle if (neighbor['cx'] - data['cx'] > dx > 0) and calc_axis_iou(c, neighbor,1) > 0.3 and calc_axis_iou(c, neighbor) < 0.1 : # now neighbor is more near than before in Y must be iou is not iou in X neighbor = c if neighbor is None : # have not neighbor ret = True else : y_iou = calc_axis_iou(neighbor, data, 1) if y_iou > 0.3 : # neighbor and data have big iou if len(line) and len(data) and len(neighbor): if calc_axis_iou(neighbor, line, 1) > 0.1 and calc_axis_iou(neighbor,line) < 0.1 and calc_axis_iou(data, line) > 0.1 : # neighbor and before line have iou in Y neighbor and before line have not iou in X data and before line have iou in X ret = True elif y_iou < 0.1 : # have little iou ret = True else : # have not iou in Y if title is not None : if calc_axis_iou(neighbor, title, 1) > 0.25 : ret = True else : if calc_axis_iou(data, line) > 0.2 : ret = True return ret def getContent(data): res = [] start,end,left,right = get_content_boundary(data) content = data[start+1:end] while len(content): left_tem = min(content, key = lambda x : x['cx'] - x['w'] / 2) if len(left_tem['text']) < 3 : content.remove(left_tem) else : break while len(content): right_tem = max(content, key = lambda x : x['cx'] + x['w'] / 2) if len(right_tem['text']) < 3 : content.remove(right_tem) else : break isvehicle = isVehicle(data) # 是否是私家车 # top = min(content, key=lambda x:float(x['cy'])-float(x['h']/2)) # bottom = max(content, key=lambda x: float(x['cy'])+float(x['h']/2)) # lh = (bottom['cy'] + bottom['h']/2 - top['cy'] + top['h']/2) / 8 lt = min(content, key=lambda x:float(x['cx'])-float(x['w']/2)) # 得到最左边的 rb = max(content, key=lambda x: float(x['cx'])+float(x['w']/2)) # 得到最右边的 # 下面这两行是根据中间的内容找的,不加就是根据 title 找的 left = float(lt['cx'])-float(lt['w']/2) # 得到最左边的边 right = float(rb['cx'])+float(rb['w']/2) # 得到最右边的边 line = [] wraptitle = [] # for idx,ct in enumerate(content): deal = False # iswrap = is_wrapped_title(ct, line, [left,right]) # ?? 可能是判断该行是不是之前的换行 True 是 上一行 iswrap = is_wrapped_title2(ct, line, content, idx + 1, [left, right]) if not iswrap and ct not in wraptitle: linelen = len(line) if linelen: y_ious = [] for l in line: x_iou = calc_axis_iou(l, ct) # l 是 dict,ct 是 dict y_iou = calc_axis_iou(l, ct, 1) y_ious.append(y_iou) if x_iou > 0.3: # 交叉部分大就跳出 deal = True break if not deal and np.mean(y_ious) < 0.05:# y的差距小 说明在一行 deal = True if deal == False: line.append(ct) else: # deal 为 true 已经跳出,说明当前的ct与之前的line里面的存在交叉 # 存前idx 总 check_title(line, content, idx+1, idx+4, [left,right]) if len(res): # 如果结果中已经有值,可以把判断为换行的tittle加到上一行 check_wrap_title(res, wraptitle, line) parsed = parseLine(line, [left, right], isvehicle) res.append(parsed) line = [ct] else: # 是换行 #--- <NAME> de neirong bei fencheng duoge bufen if ct not in wraptitle: wraptitle.append(ct) start_idx = idx+1 end_idx = idx + 3 if end_idx > len(content): end_idx = len(content) for i in range(start_idx,end_idx): y_iou = calc_axis_iou(content[i], ct, 1) if i != idx and calc_axis_iou(content[i], ct, 1) > 0.9: wraptitle.append(content[i]) #--- # flag = 0 if len(line) + len(wraptitle) >= 3: if len(res): check_wrap_title(res, wraptitle, line) if len(wraptitle): line.extend(wraptitle) parsed = parseLine(line, [left, right], isvehicle) res.append(parsed) ret = [] calcprice = 0 calctax = 0 for r in res: if isvehicle: title, platenum, type, sdate, edate, price, ratio, tax = r ret.append([{'name': r'项目名称', 'value': title}, {'name': r'车牌号', 'value': platenum}, {'name': r'类型', 'value': type}, {'name': r'通行日期起', 'value': sdate}, {'name': r'通行日期止', 'value': edate}, {'name': r'金额', 'value': price}, {'name': r'税率', 'value': ratio}, {'name': r'税额', 'value': tax}]) else: title, specs, unit, amount, uprice, price, ratio, tax = r ret.append([{'name': r'名称', 'value': title}, {'name': r'规格型号', 'value': specs}, {'name': r'单位', 'value': unit}, {'name': r'数量', 'value': amount}, {'name': r'单价', 'value': uprice}, {'name': r'金额', 'value': price}, {'name': r'税率', 'value': ratio}, {'name': r'税额', 'value': tax}]) # print("price:",price) if len(price): calcprice += float(price) calctax += float(tax) if is_number(tax) else 0 calctotal = '%.2f' % (calcprice + calctax) calcprice = '%.2f' % calcprice if calctax <= 0.001: calctax = '***' else: calctax = '%.2f' % calctax return ret, (calctotal, calcprice, calctax) def get_seller_boundary(data): s = max([i for i, d in enumerate(data) if re.search(r'\(?大写\)?|价税合?计?', d['text'])]) # e = min([i for i, d in enumerate(data[s-4:]) if re.search(r'\(?小写?\)?', d['text'])]) e = min([i for i, d in enumerate(data) if re.search(r'(¥|Y|羊)[0-9]+(.[0-9]{2})?$|\(?小写\)?', d['text'])]) # e = min([i for i, d in enumerate(data) if re.search(r'\(?小写\)?.*(¥|Y|羊)?\d+', d['text'])]) start = max([s,e]) + 1 # start = max([i for i, d in enumerate(data) if re.search(r'\(?小写\)?|\(?大写\)?|价税合?计?|¥[0-9]+(.[0-9]{2})?$|Y[0-9]+(.[0-9]{2})?$|羊[0-9]+(.[0-9]{2})?$', d['text'])]) + 1 # if abs(s-e) == 1: # start = start + 1 # 为什么 +1 end = len(data) - 2 benchmark = ['仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '圆', '角', '分','零','壹','贰','叁','肆','伍','陆','柒','捌','玖','拾','整'] text = data[start]['text'] i = 0 for t in text: if t in benchmark: i += 1 if i>2: return start + 1,end else: return start, end def get_seller_name(buyer): name = '' index = -1 # 匹配中文 indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{6,}', d['text'])] if len(indexes): index = indexes[0] name = buyer[index] text = name['text'] # ----- if len(text): benchmark = ['仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '圆', '角', '分','零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾','整'] flag = 0 for i in range(0,len(text)): if text[i] in benchmark: flag += 1 if flag > 3 and len(indexes) > 1: index = indexes[1] name = buyer[index] text = name['text'] # --- if text.find(':') >= 0: name = text.split(':')[1] else: name = re.sub(r'^[^\u4e00-\u9fa5]+?', '', text) name = re.sub(r'^称|你', '', name) return name, index def get_seller_taxnumber(buyer,RIGHT_MOST): taxnumber = '' index = -1 # 排除备注中的信息,以图片的中间为限 indexes = [i for i, d in enumerate(buyer) if float(d['cx']) - float(d['w'])/2 <= RIGHT_MOST/2 and re.search(r':[0-9A-Z]{16,}|^[0-9A-Z]{16,}', d['text'])] if len(indexes): index = indexes[0] taxnumber = buyer[index] text = taxnumber['text'] if text.find(':') >= 0: taxnumber_tem = text.split(':') taxnumber = '' for i in range(0,len(taxnumber_tem)): if re.search(r'^[0-9A-Z]{1,}',taxnumber_tem[i]): taxnumber += taxnumber_tem[i] else: taxnumber = re.sub(r'^[^0-9A-Z]+?', '', text) return taxnumber, index def get_seller_address(buyer,RIGHT_MOST): address = '' index = -1 # 匹配中文 indexes = [i for i, d in enumerate(buyer) if float(d['cx']) - float(d['w'])/2<= RIGHT_MOST/2 and re.search(r'[\u4e00-\u9fa5]{6,}', d['text']) and not re.search('识别号',d['text'])] index_add = sorted([d for i, d in enumerate(buyer) if re.search('地址|电话',d['text'])],key=lambda x: x['cx'] + x['w'] / 2,reverse=True) if len(index_add): index = buyer.index(index_add[0]) address = index_add[0] text = address['text'] if text.find(':') >= 0: address = text.split(':')[-1] else: address = '' address = re.sub(r'^地址、?电话', '', address) index_max = int(index) bre = 0 mark = 0 while True: # forbid seller address three part if not re.search(r'[0-9\-]{11,}$', address): #---- deal with 8 -> B rear_text = address.replace('B','8') if re.search(r'[0-9\-]{11,}$', rear_text): for i in range(len(address) - 1,-1,-1): if re.search(r'[\u4e00-\u9fa5]',address[i]): break if address[i] == 'B': address = address[:i] + '8' + address[i+1:] break #---- indexs = [i for i, d in enumerate(buyer)] if len(address) < 5 and mark == 0: index_tem = get_min_distance_index(buyer[index], indexes, buyer) mark = 1 else: indexes = indexs index_tem = get_min_distance_index(buyer[index], indexes, buyer) indexes = indexs address += buyer[index_tem]['text'] if index_tem > index_max: index_max = index_tem index = index_tem else: break bre += 1 if bre > 3: break # buyer.pop(index_tem) index = index_max for prov in PROVINCE: idx = address.find(prov) if idx > 0: address = address[idx:] break return address, index else: if len(indexes): index = indexes[0] address = buyer[index] text = address['text'] if text.find(':') >= 0: address = text.split(':')[1] else: address = text address = re.sub(r'^地址、?电话', '', address) index_max = int(index) bre = 0 while True: # forbid seller address three part if not re.search(r'[0-9\-]{11,}$',address): indexs = [i for i,d in enumerate(buyer)] index_tem = get_min_distance_index(buyer[index],indexs,buyer) address += buyer[index_tem]['text'] if index_tem >index_max: index_max = index_tem index = index_tem else: break bre += 1 if bre > 3: break index = index_max for prov in PROVINCE: idx = address.find(prov) if idx > 0: address = address[idx:] break return address, index def get_seller_account(buyer,RIGHT_MOST): account = '' indexes = [i for i, d in enumerate(buyer) if re.search(r'[\u4e00-\u9fa5]{7,}', d['text']) and d['cx'] < RIGHT_MOST / 2 ] # indexes = [i for i, d in enumerate(buyer) if re.search(r'行及账',d['text'])] if len(indexes): index = indexes[0] account = buyer[index] text = account['text'] if text.find(':') >= 0: splittxt = text.split(':') account = ''.join(splittxt[1:]) else: account = text if not re.search(r'\d{12,}$', account): # indexes = [i for i, d in enumerate(buyer) if re.match(r'[0-9]{13,}$', d['text'])] indexes = [i for i, d in enumerate(buyer) if re.search(r'[0-9]{13,}$', d['text'])] ii = get_min_distance_index(buyer[index],indexes,buyer) account += buyer[ii]['text'] idx = account.find(r'账号') if idx >= 0: account = account[idx+2:] return account def getSeller(data): RIGHT_MOST = get_right_marge(data) # 找最右边的边 start, end = get_seller_boundary(data) # 从大写/小写开始 到 倒数第二个结束 seller = data[start:end] name, index = get_seller_name(seller) seller = seller[index + 1:] taxnum, index = get_seller_taxnumber(seller,RIGHT_MOST) seller = seller[index + 1:] address, index = get_seller_address(seller,RIGHT_MOST) seller = seller[index + 1:] account = get_seller_account(seller,RIGHT_MOST) res = [[{'name': r'名称', 'value': name}, {'name': r'纳税人识别号', 'value': taxnum}, {'name': r'地址、电话', 'value': address}, {'name': r'开户行及账号', 'value': account}]] return res # return {"name": name, "taxnum": taxnum, "address": address, "account": account} def get_summation_boundary(data): summation = [i for i, d in enumerate(data) if re.search(r'\(?大写\)?', d['text'])] summation.extend([i for i, d in enumerate(data) if re.search(r'\(?小写\)?.*(¥|Y|羊)?[\d\.]+$', d['text'])]) summation.extend([i for i, d in enumerate(data) if re.search(r'(¥|Y|羊)[\d+\.]+$', d['text'])]) start = min(summation) - 1 end = max(summation) + 1 return start, end def check_price(price, calc): if price: price = re.sub(r'^\D+', '', price['text']) if re.search(r'[^\d\.]', price): price = calc else: idx = price.rfind(r'.') if idx <= 0: if len(price) > 2: price = price[:-2] + '.' + price[-2:] else: price = price[:idx].replace(r'.', '') + (price[idx:] if len(price[idx:]) <= 3 else price[idx:idx + 3]) if len(price) <= 2: price = calc else: price = calc return price def getSummation(data, calcsum): benchmark = ['仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '圆', '角', '分'] chinesedigit = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖','拾'] tax = '' price = '' total = '' capital = '' calctotal, calcprice, calctax = calcsum _,_,_,right = get_content_boundary(data) start, end = get_summation_boundary(data) summation = data[start:end] prices = [d for d in summation if re.search(r'(¥|Y|羊)?[\d\.]+$', d['text'])] #--- 处理盖章乱盖 and summation if len(prices) > 3: prices = sorted(prices, key=lambda x: x['cx'],reverse=True) for i in range(len(prices) - 1, -1, -1): if not re.search(r'(¥|Y|羊)[\d\.]+$', prices[i]['text']): prices.pop(i) else: # 如果匹配到就break break if len(prices)==3: break if len(prices) > 3: Y = [d for i,d in enumerate(prices) if re.search(r'(¥|Y|羊)[\d\.]+$', d['text'])] if len(Y): # 处理税额的影响 Y = sorted(Y,key=lambda x: x['cx'] + x['w'] / 2,reverse=True) tax_right = Y[0] if math.fabs(float(tax_right['cx']) + float(tax_right['w'])/2 - right) < RIGHT_MARGIN: for j in range(len(prices)-1, -1, -1): if tax_right != prices[j] and float(tax_right['cy'])>float(prices[j]['cy']): cha_rate = calc_axis_iou(tax_right, prices[j], axis=0) if calc_axis_iou(tax_right, prices[j], axis=0) > 0.5: prices.pop(j) if len(prices) == 3 : break if len(Y): # 处理金额的影响 Y = sorted(Y, key=lambda x: x['cx'] - x['w'] / 2) price_left = Y[0] if len(Y) > 1 and math.fabs(float(Y[-1]['cx']) + float(Y[-1]['w'])/2 - right) < RIGHT_MARGIN: for j in range(len(prices) - 1 ,-1,-1): if price_left != prices[j] and float(price_left['cy']) > float(prices[j]['cy']): if calc_axis_iou(price_left, prices[j]) > 0.5: prices.pop(j) if len(prices) == 3: break # 找一个条件说明是金额 #--- if len(prices): # 是不是该满足大于1 prices = sorted(prices, key=lambda x: x['cy'], reverse=True) # big -> small p = prices[0] ll = calc_axis_iou(p, prices[1:], 1) if calc_axis_iou(p, prices[1:], 1) < 0.11:# p 和 另外的数在y方向上都不存在交叉,说明 p 是 tatal total = p prices.remove(p) if len(prices): prices = sorted(prices, key=lambda x: x['cx'], reverse=True) p = prices[0] if abs(p['cx']+p['w']/2 - right) < RIGHT_MARGIN: # 最靠右的是tax tax = p prices.remove(p) if len(prices): price = prices[0] total = check_price(total, calctotal) price = check_price(price, calcprice) tax = check_price(tax, calctax) try: if total == calctotal and tax == calctax and math.fabs(float(calctax)+float(calcprice)-float(calctotal)) < 0.1: # 补丁 防止印章影响总的price price = calcprice except ValueError: print("float 转换类型出错,无影响") strtotal = re.sub(r'\.', '', total) bm = benchmark[-len(strtotal):] for (c, b) in zip(strtotal, bm): capital += chinesedigit[int(c)] + b if int(total[-2:]) == 0: capital = capital[:-4] + '整' capital = re.sub(r'零[仟佰拾角分]', '零', capital) capital = re.sub(r'零{2,}', '零', capital) capital = re.sub(r'零$', '', capital) capital = re.sub(r'零圆', '圆', capital) if capital[-1] != '整' and capital[-1] != '分': capital += '整' res = [[{'name': r'金额合计', 'value': price}, {'name': r'税额合计', 'value': tax}, {'name': r'价税合计(大写)', 'value': capital}, {'name': r'价税合计(小写)', 'value': total}]] return res def calc_axis_iou(a,b,axis=0): if isinstance(b, list): # b 是list类型时 if axis == 0: # x 方向的交叉率 # 左 右 左 右 ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] # else: # y fangxinag de jiaocha lv ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else: # a b 都不是 list类型 if axis == 0:# iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou def sort_result(data): data = sorted(data, key=lambda d: d['cy']) lines = [] line = [] for i in range(len(data)): d = data[i] if not len(line): line.append(d) else: iou_x = calc_axis_iou(d, line, 0) iou_y = calc_axis_iou(d, line, 1) if iou_y > 0.6 and iou_x < 0.1: line.append(d) else: line = sorted(line, key=lambda l:l['cx']-l['w']/2) lines.append(line) line = [d] if len(line): line = sorted(line, key=lambda l: l['cx'] - l['w'] / 2) lines.append(line) return lines def formatResult(data): basic = getBasics(data) buyer = getBuyer(data) content,calcsum = getContent(data) seller = getSeller(data) summation = getSummation(data, calcsum) res = [{'title':r'发票基本信息', 'items':basic}, {'title':r'购买方', 'items':buyer}, {'title':r'销售方', 'items':seller}, {'title':r'货物或应税劳务、服务', 'items':content}, {'title':r'合计', 'items':summation}] return res # return {"basic":basic, "buyer":buyer, "content":content, "seller":seller} if __name__ == '__main__': test() <file_sep># -*- coding:utf-8 -*- import math import util from apphelper.image import calc_iou from crnn import crnnRec # from angle import * # from eval.eval_business_license import evaluate def recognize(im=None, path=None): ret = None try: file = None if im: pass elif path: # 提取文件路径 # dir,base = os.path.split(path) # file,suffix = os.path.splitext(base) # dir = os.path.dirname(__file__) # tmpfile = os.path.join(dir, 'tmp/'+file+'-large'+suffix) # 修改图片大小和分辨率 im = Image.open(path) file = os.path.basename(path) if im: dir = '/home/share/gaoluoluo/complete_ocr/data/images/tmp/' file = file if file is not None else 'tmp.jpg' tmpfile = os.path.join(dir, file) im.save(tmpfile) data = test(tmpfile) if data: ret = data except Exception as e: print(e) return ret def get_min_distance_index(tem,indexes,near,maxRight = 100): x = float(tem['cx']) + float(tem['w']) / 2 y = float(tem['cy']) + float(tem['h']) / 2 distance_min = 100000 ii = -1 for i in range(0,len(near)): x_tem = float(near[i]['cx']) - float(near[i]['w']/2) y_tem = float(near[i]['cy']) + float(near[i]['h']/2) distance_tem = math.sqrt(math.pow((x-x_tem),2) + math.pow((y-y_tem),2)) if distance_tem < distance_min and near[i]['cx'] < maxRight and len(near[i]['text']) and calc_axis_iou(near[i],tem,1) > 0.3 and float(tem['cx']) < float(near[i]['cx']): ii = i distance_min = distance_tem # if distance_tem < 30 and re.search(r'[\u4e00-\u9fa5]{6,}',near[i]['text']): # return i return ii def write_result_as_txt(image_name, bboxes, path): filename = util.io.join_path(path, 'res_%s.txt' % (image_name)) lines = [] for b_idx, bbox in enumerate(bboxes): values = [int(v) for v in bbox] line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values) lines.append(line) util.io.write_lines(filename, lines) import os import sys import pathlib __dir__ = pathlib.Path(os.path.abspath(__file__)) sys.path.append(str(__dir__)) sys.path.append(str(__dir__.parent.parent)) import time import cv2 import torch from dbnet.data_loader import get_transforms from dbnet.models import build_model from dbnet.post_processing import get_post_processing def resize_image(img, short_size): height, width, _ = img.shape if height < width: new_height = short_size new_width = new_height / height * width else: new_width = short_size new_height = new_width / width * height new_height = int(round(new_height / 32) * 32) new_width = int(round(new_width / 32) * 32) resized_img = cv2.resize(img, (new_width, new_height)) return resized_img class Pytorch_model: def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): ''' 初始化pytorch模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) model_path='/home/share/gaoluoluo/dbnet/output/DBNet_resnet18_FPN_DBHead/checkpoint/model_latest.pth' :param gpu_id: 在哪一块gpu上运行 ''' self.gpu_id = gpu_id if self.gpu_id is not None and isinstance(self.gpu_id, int) and torch.cuda.is_available(): self.device = torch.device("cuda:%s" % self.gpu_id) else: self.device = torch.device("cpu") # print('device:', self.device) checkpoint = torch.load(model_path, map_location=self.device) # print("checkpoint:",checkpoint) config = checkpoint['config'] # print(checkpoint['config']) config['arch']['backbone']['pretrained'] = False self.model = build_model(config['arch']) self.post_process = get_post_processing(config['post_processing']) self.post_process.box_thresh = post_p_thre self.img_mode = config['dataset']['train']['dataset']['args']['img_mode'] self.model.load_state_dict(checkpoint['state_dict']) self.model.to(self.device) self.model.eval() self.transform = [] for t in config['dataset']['train']['dataset']['args']['transforms']: if t['type'] in ['ToTensor', 'Normalize']: self.transform.append(t) self.transform = get_transforms(self.transform) def predict(self, img, is_output_polygon=False, short_size: int = 1024): ''' 对传入的图像进行预测,支持图像地址,opecv 读取图片,偏慢 :param img_path: 图像地址 :param is_numpy: :return: ''' # assert os.path.exists(img_path), 'file is not exists' # img = cv2.imread(img_path, 1 if self.img_mode != 'GRAY' else 0) if self.img_mode == 'RGB': img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w = img.shape[:2] # 2550 3507 img = resize_image(img, short_size) # 将图片由(w,h)变为(1,img_channel,h,w) tensor = self.transform(img) tensor = tensor.unsqueeze_(0) tensor = tensor.to(self.device) batch = {'shape': [(h, w)]} with torch.no_grad(): if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) start = time.time() preds = self.model(tensor) if str(self.device).__contains__('cuda'): torch.cuda.synchronize(self.device) box_list, score_list = self.post_process(batch, preds, is_output_polygon=is_output_polygon) box_list, score_list = box_list[0], score_list[0] if len(box_list) > 0: if is_output_polygon: idx = [x.sum() > 0 for x in box_list] box_list = [box_list[i] for i, v in enumerate(idx) if v] score_list = [score_list[i] for i, v in enumerate(idx) if v] else: idx = box_list.reshape(box_list.shape[0], -1).sum(axis=1) > 0 # 去掉全为0的框 box_list, score_list = box_list[idx], score_list[idx] else: box_list, score_list = [], [] t = time.time() - start return preds[0, 0, :, :].detach().cpu().numpy(), box_list, score_list, t def init_args(): import argparse parser = argparse.ArgumentParser(description='DBNet.pytorch') # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/dbnet/output/DBNet_resnet50_FPN_DBHead/checkpoint/model_latest.pth', type=str) # parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/模型/model50_ch_epoch510_latest.pth', type=str) parser.add_argument('--model_path', default=r'/home/share/gaoluoluo/模型/model50_ch_epoch510_latest.pth', type=str) # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/invoices_gao_true/img/', type=str, help='img path for predict') parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_businessLicense/input/img/', type=str, help='img path for predict') parser.add_argument('--img_correct',default='/home/share/gaoluoluo/dbnet/test/test_corre_input/',type=str,help='img_correct path for predict') # parser.add_argument('--input_folder',default='/home/share/gaoluoluo/dbnet/test/test_corre_input', type=str, help='img path for predict') # parser.add_argument('--input_folder', default='/home/share/gaoluoluo/complete_ocr/data/images/tmp', type=str,help='img path for predict') parser.add_argument('--output_folder', default='/home/share/gaoluoluo/dbnet/test/test_output/', type=str, help='img path for output') # parser.add_argument('--output_folder', default='/home/share/gaoluoluo/invoices_gao_true/outputs/', type=str, help='img path for output') parser.add_argument('--gt_txt', default='/home/share/gaoluoluo/complete_businessLicense/input/gt/', type=str, help='img 对应的 txt') parser.add_argument('--thre', default=0.1, type=float, help='the thresh of post_processing') parser.add_argument('--polygon', action='store_true', help='output polygon or box') parser.add_argument('--show', action='store_true', help='show result') parser.add_argument('--save_result', action='store_true', help='save box and score to txt file') parser.add_argument('--evaluate', nargs='?', type=bool, default=False, help='evalution') args = parser.parse_args() return args def test(tmpfile): import pathlib from tqdm import tqdm import matplotlib.pyplot as plt from dbnet.utils.util import show_img, draw_bbox, save_result, get_file_list args = init_args() # print(args) os.environ['CUDA_VISIBLE_DEVICES'] = str('0') # 初始化网络 0.1 model = Pytorch_model(args.model_path, post_p_thre=args.thre, gpu_id=0) img_folder = pathlib.Path(args.input_folder) # dbnet/test/input/ # i = 0 total_frame = 0.0 total_time = [] precisions = [] names = [] idCode = [] names1 = [] sex = [] nation = [] address = [] brithday = [] dataOfFirstIssue = [] classType = [] validPerios = [] for ind in range(0,1): # img_path /home/share/gaoluoluo/dbnet/test/input/2018实验仪器发票.jpg # print("img_path:",img_path) /home/share/gaoluoluo/dbnet/test/input/2018实验仪器发票.jpg img_path = tmpfile print("\nimg_path:", img_path) # img_path = '/home/share/gaoluoluo/IDCard/corre_id/3.jpg' start_time = time.time() img = angle_corre(img_path)# 调整图片角度 wei调整 # img = cv2.imread(img_path) img_path = args.img_correct + img_path.split('/')[-1] # After correct angle img path names.append(img_path.split('/')[-1]) # names_tem.append(str(iii)+img_path.split('.')[-1]) # iii += 1 # print("img_path:",img_path) preds, boxes_list, score_list, t = model.predict(img, is_output_polygon=args.polygon) img_path1 = img_path boxes_list_save = boxes_list box = [] for i in range(0,len(boxes_list)): for j in range(0,len(boxes_list[0])): b = [] b.append(np.float32(boxes_list[i][j][0])) b.append(np.float32(boxes_list[i][j][1])) box.append(b) boxes_list = boxes_list.reshape(-1,2) boxes_list = box #---hekuang zhineng chuli yige kuang bei fencheng liangge bufen i = 4 points_kuang = [] remove_mark = [] max_X = -1 while(i<=len(boxes_list)): points = boxes_list[i-4:i] for _,p in enumerate(points): if p[0] > max_X: max_X = p[0] i = i+4 points = np.array(points) points_kuang.append(points) for i in range(0,len(points_kuang)):# 逆时针 1 -> 2 -> 3 -> 4 point3 = points_kuang[i][2] start_point = i - 3 end_point = i + 3 if start_point < 0: start_point = 0 if end_point > len(points_kuang): end_point = len(points_kuang) if i not in remove_mark: for j in range(start_point,end_point): point4 = points_kuang[j][3] min_dis = math.sqrt(math.pow((point3[0] - point4[0]),2) + math.pow((point3[1] - point4[1]),2)) Y_cha = math.fabs(point3[1] - point4[1]) if min_dis < 5 and Y_cha < 5 and j not in remove_mark and i != j : # 10 reasonable # if min_dis < 0: point1_1 = points_kuang[i][0] point1_2 = points_kuang[j][0] x_min = min(point1_1[0],point1_2[0]) y_min = min(point1_1[1],point1_2[1]) point3_2 = points_kuang[j][2] x_max = max(point3[0],point3_2[0]) y_max = max(point3[1],point3_2[1]) points_kuang[i][0,0] = x_min points_kuang[i][0,1] = y_min points_kuang[i][1,0] = x_max points_kuang[i][1,1] = y_min points_kuang[i][2,0] = x_max points_kuang[i][2,1] = y_max points_kuang[i][3,0] = x_min points_kuang[i][3,1] = y_max remove_mark.append(j) # print("i=",i," j=",j) # print('x:',point4[0]) break remove_mark = sorted(remove_mark,reverse=True) # print("---------------------------") for _,i in enumerate(remove_mark): # print('x:',points_kuang[i][3][0]) del points_kuang[i] boxes_list_save = points_kuang # 决定保存的画框图片是否是 合框之后的图片 #--- i = 0; rects = [] while(i<len(points_kuang)): points = points_kuang[i] rect = cv2.minAreaRect(points) # 4个点 -> d cx cy w h rec = [] rec.append(rect[-1]) rec.append(rect[1][1]) rec.append(rect[1][0]) rec.append(rect[0][0]) rec.append(rect[0][1]) rects.append(rec) i += 1 ori_img = cv2.imread(img_path1) # ori_img = cv2.imread('/home/share/gaoluoluo/IDCard/outputs/part_id/0.png') # print(img_path1) rects = reversed(rects) result = crnnRec(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) # result = crnnRec_tmp(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB), rects) # result = list(reversed(result)) # print("result:",result) dur = time.time() - start_time print("dur:",dur) # 保存画框图片--------- # img = draw_bbox(img(img_path)[:, :, ::-1], boxes_list_save) img = draw_bbox(cv2.imread(img_path)[:, :, ::-1], boxes_list_save) if args.show: show_img(preds) show_img(img, title=os.path.basename(img_path)) plt.show() # 保存结果到路径 os.makedirs(args.output_folder, exist_ok=True) img_path = pathlib.Path(img_path) output_path = os.path.join(args.output_folder, img_path.stem + '_result.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_result.jpg pred_path = os.path.join(args.output_folder,img_path.stem + '_pred.jpg') # /home/share/gaoluoluo/dbnet/test/output/2018实验仪器发票_pred.jpg cv2.imwrite(output_path, img[:, :, ::-1]) cv2.imwrite(pred_path, preds * 255) save_result(output_path.replace('_result.jpg', '.txt'), boxes_list_save, score_list, args.polygon) # -------- total_frame += 1 total_time.append(dur) # print("--------------") # print("-------------------11") result = formatResult(result) return result; import re def calc_axis_iou(a,b,axis=0): if isinstance(b, list): # b 是list类型时 if axis == 0: # x 方向的交叉率 # 左 右 左 右 ious = [calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2]) for x in b] # else: # y 方向的交叉类 ious = [calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2]) for x in b] iou = max(ious) elif isinstance(a, list): if axis == 0: ious = [calc_iou([x['cx'] - x['w'] / 2, x['cx'] + x['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) for x in a] else: ious = [calc_iou([x['cy'] - x['h'] / 2, x['cy'] + x['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) for x in a] iou = max(ious) else: # a b 都不是 list类型 if axis == 0:# iou = calc_iou([a['cx'] - a['w'] / 2, a['cx'] + a['w'] / 2], [b['cx'] - b['w'] / 2, b['cx'] + b['w'] / 2]) else: iou = calc_iou([a['cy'] - a['h'] / 2, a['cy'] + a['h'] / 2], [b['cy'] - b['h'] / 2, b['cy'] + b['h'] / 2]) return iou # ------------------------------------------------------------------------------------ def getValidPeriod(data): start_time = '' end_time = '' candidates = [d for d in data if re.search(r'\d{4}-|^(19|20|28)|-..-|.?..-..', d['text']) and len(d['text']) <= 13] if len(candidates): candidates = sorted(candidates, key=lambda d: d['cx'] - d['w'] / 2) start_time = candidates[0]['text'] if start_time.find('至') != -1 and len(start_time) > 13: start_time, end_time = start_time.split('至') else: # del candidates[:1] if len(candidates) > 1: end_time = candidates[1]['text'] if len(end_time) < 5: tmp_index = get_min_distance_index(candidates[-1],None,candidates) if end_time[-1] == '-' or candidates[tmp_index]['text'][0] == '-': end_time += candidates[tmp_index]['text'] else: end_time += '-' + candidates[tmp_index]['text'] start_time = re.sub(r'Z','2',start_time) start_time = re.sub(r'Q', '0', start_time) start_time = re.sub(r'T', '1', start_time) end_time = re.sub(r'Z','2',end_time) end_time = re.sub(r'Q', '0', end_time) end_time = re.sub(r'T', '1', end_time) start_time = re.sub('至','',start_time) end_time = re.sub('至','',end_time) # date1 = start_time.split('-') # date2 = end_time.split('-') if len(start_time.split('-')) == 3 and len(end_time.split('-') )== 3: # 6/10/forever # year------ date1 = start_time.split('-') date2 = end_time.split('-') year1 = date1[0] year2 = date2[0] else: year1 = start_time[:4] year2 = end_time[:4] if year1[1] == '8' or year1[1] == '6': year1 = year1[0] + '0' + year1[2:] if year2[1] == '8' or year2[1] == '6': year2 = year2[0] + '0' + year2[2:] if year1[2] == '7': year1 = year1[:2] + '1' +year1[3:] if year1[2] == '8' and year1[:2] == '20': year1 = '200' + year1[-1] if year2[2] == '8' and year2[:2] == '20': year2 = '200' + year2[-1] if year1[-1] == '8': # 最后一位矫正不了 if int(year2) - int(year1) == 6 or int(year2) - int(year1) == 10: pass else: year1 = year1[:3] + '0' # ---------- # month----- if len(start_time.split('-')) == 3: month = start_time.split('-')[1] day = start_time.split('-')[2] if len(end_time.split('-')) == 3: month = end_time.split('-')[1] day = end_time.split('-')[2] # month = date1[1] if len(month) != 2: month = date2[1] if month[0] == '8' or month[0] == '6': month = '0' + month[1] if month[1] == '8' or month[1] == '6': if month[0] != '0': month = month[0] + '0' # ---------- # day------- 最后一位矫正不了 # day = date1[2] if len(day) != 2: day = date2[2] if day[0] == '8': day ='0' + day[1] # ---------- start_time = year1 + '-' + month + '-' + day end_time = year2 + '-' + month + '-' +day return start_time, end_time def getDateOfFirstIssue(data): dateFirstIssue = '' try : candidates = [d for d in data if re.search(r'\d{4}-|^(19|20|28)|-..-|.?..-..|初|次|领|证', d['text']) and len(d['text']) <= 13] if len(candidates): candidates = sorted(candidates, key=lambda d: d['cy'] - d['h'] / 2) tmp_candidate = candidates[0] number_list = [] for i in range(0,len(candidates)): tmp = calc_axis_iou(tmp_candidate,candidates[i],1) if calc_axis_iou(tmp_candidate,candidates[i],1) > 0.3: number_list.append(candidates[i]) candidates = [d for d in number_list if re.search(r'\d{4}-|^(19|20|28)|-..-|.?..-..|-..', d['text']) and len(d['text']) <= 13] if len(candidates): candidates = sorted(candidates, key=lambda d:d['cx'] - d['w'] / 2) for i in range(0,len(candidates)): dateFirstIssue += candidates[i]['text'] year = dateFirstIssue[:4] if year[1] == '8': year = year[0] + '0' + year[2:] if year[2] == '8': if year[:2] != '19': year = year[:2] + '0' + year[-1] dateFirstIssue = year + dateFirstIssue[4:] except Exception as e: print("getDateOfFirstIssue flase ") return dateFirstIssue def getMaxRight(data): maxRight = -1 for i in range(0,len(data)): if data[i]['cx'] + data[i]['w'] / 2 > maxRight: maxRight = data[i]['cx'] + data[i]['w'] / 2 return maxRight def getCreditCode(data): creditCode = '' index = 0 indexes = [i+2 for i, d in enumerate(data[2:]) if re.search(r'[0-9A-Z]{13,}', d['text'])] if len(indexes): index = indexes[0] creditCode = data[indexes[0]]['text'] creditCode = creditCode.split('号')[-1] creditCode = creditCode.split('码')[-1] return creditCode,index def getName(data,index): name = '' tmp_index = index + 1 indexes = [i + tmp_index for i, r in enumerate(data[index+1:]) if re.search(r'(名|称)', r['text'])] if len(indexes): index = indexes[0] candidates = [] candidates.append(data[index]) for i in range(0,len(data)): if calc_axis_iou(data[i],data[index],1) > 0.3 and data[i] not in candidates: candidates.append(data[i]) candidates = sorted(candidates, key=lambda d:len(d['text'])) name = candidates[-1]['text'] tmp_index = data.index(candidates[-1]) return name, tmp_index def getType(data, index): ty = '' tmp_index = index + 1 """ 有限责任公司 股份有限责任公司 个人独资企业 合伙企业 个体工商户 """ indexes = [i + tmp_index for i, r in enumerate(data[index+1:]) if re.search(r'(有限|责?任|公司|独资?企业|合伙企业|个体工商户)', r['text'])] if len(indexes): ty = data[indexes[0]]['text'] tmp_index = indexes[0] else: candidates = [d for i,d in enumerate(data[index+1:]) if re.search(r'类|型',d['text'])][:2] if len(candidates): candidates = sorted(candidates,key=lambda d:d['cx']) for i in range(0,len(data)): if calc_axis_iou(data[i],candidates[-1],1) > 0.3 and data[i]['cx'] > candidates[-1]['cx']: ty = data[i] break tmp_index = data.index(ty) ty = ty['text'] return ty, tmp_index def getAddress(data,index): addr = '' tmp_index = index + 1 indexes = [i + tmp_index for i, d in enumerate(data[index + 1:]) if re.search(r'[\u4e00-\u9fa5]{6,}', d['text'])] if len(indexes): addr = data[indexes[0]]['text'] tmp_index = indexes[0] for i in range(tmp_index,len(data)): if math.fabs((data[indexes[0]]['cy'] + data[indexes[0]]['h'] / 2) - (data[i]['cy'] - data[i]['h'] / 2)) < 10 and math.fabs((data[indexes[0]]['cx'] + data[indexes[0]]['w'] / 2) - (data[i]['cx'] - data[i]['w'] / 2)) < 10: addr += data[i]['text'] tmp_index = i break return addr, tmp_index def getLegalPerson(data,index): legalPerson = '' tmp_index = index + 1 indexes = [i + tmp_index for i, r in enumerate(data[index+1:]) if re.search(r'(法定|代表人)', r['text'])] if len(indexes): candidate = [] for i in range(0,len(data)): x_cha = (data[i]['cx'] - data[i]['w'] / 2) - (data[indexes[0]]['cx'] + data[indexes[0]]['w'] / 2) if i != indexes[0] and calc_axis_iou(data[i],data[indexes[0]],1) > 0.4 and (data[i]['cx'] - data[i]['w'] / 2) - (data[indexes[0]]['cx'] + data[indexes[0]]['w'] / 2) < 200: candidate.append(data[i]) candidate = sorted(candidate,key=lambda d: d['cx']) legalPerson = candidate[-1]['text'] tmp_index = data.index(candidate[-1]) return legalPerson, tmp_index def getRegisterCapital(data,index): registerCapital = '' tmp_index = index + 1 indexes = [i + tmp_index for i, r in enumerate(data[index + 1:]) if re.search(r'注册|资本|出资总额', r['text'])] if len(indexes): candidate = [] for i in range(0, len(data)): if calc_axis_iou(data[i], data[indexes[0]], 1) > 0.3: candidate.append(data[i]) candidate = sorted(candidate, key=lambda d: d['cx']) registerCapital = candidate[-1]['text'] tmp_index = data.index(candidate[-1]) return registerCapital, tmp_index def getEstDate(data,index): estdate = '' tmp_index = index + 1 candidates = [d for d in data[index+1:] if re.search(r'\d{4}-|^(19|20|28)|年.?.?月.?.?日', d['text'])] if len(candidates): estdate = candidates[0]['text'] tmp_index = data.index(candidates[0]) return estdate, tmp_index def getBusiTerm(data,index): busiTerm = '' indexes = [i+index+1 for i, r in enumerate(data[index + 1:]) if re.search(r'\d{4}-|^(19|20|28)|(年.?.?月.?.?日)$', r['text']) and len(r['text']) > 5] if len(indexes): start_time = '' end_time = '' candidates = [] for i in range(0,len(data)): if i in indexes: candidates.append(data[i]) if len(candidates): candidates = sorted(candidates, key=lambda d: d['cy'])[:2] candidates = sorted(candidates, key=lambda d: d['cx']) start_time = candidates[0]['text'] if start_time.find('至') != -1 and len(start_time) > 13: start_time, end_time = start_time.split('至') else: # del candidates[:1] if len(candidates) > 1: end_time = candidates[-1]['text'] if len(end_time) < 5: tmp_index = get_min_distance_index(candidates[-1], None, candidates) if end_time[-1] == '-' or candidates[tmp_index]['text'][0] == '-': end_time += candidates[tmp_index]['text'] else: end_time += '-' + candidates[tmp_index]['text'] start_time = re.sub('至','',start_time) end_time = re.sub('至','',end_time) busiTerm = start_time + ' 至 ' + end_time else: candidates = [d for i,d in enumerate(data[index + 1:]) if re.search(r'长期',d['text'])] if len(candidates): busiTerm = '长期' return busiTerm def getBusiScope(data,index): busiScope = '' candidates = [d for i, d in enumerate(data[index+1:]) if re.search(r'范|围', d['text'])][:2] if len(candidates): scopes = [] candidates = sorted(candidates, key=lambda d:d['cx'],reverse=True) for i in range(index + 1,len(data)): if calc_axis_iou(candidates[0],data[i],1) > 0.2 and data[i]['cx'] > candidates[0]['cx']: scopes.append(data[i]) scopes = sorted(scopes,key=lambda d: math.pow((d['cx'] - d['w'] / 2),2) + math.pow((d['cy'] - d['h'] / 2),2)) while True: scp = scopes[0] scopes = [] scopes.append(scp) index = data.index(scp) for i in range(index-4,len(data)): if calc_axis_iou(data[i],scp,1) > 0.3 and data[i]['cx'] >= scp['cx'] and data[i] not in scopes: scopes.append(data[i]) if len(scopes) == 0: break scopes = sorted(scopes, key=lambda d: d['cx']) for i in range(0,len(scopes)): busiScope += scopes[i]['text'] scp = scopes[0] scopes = [] index = data.index(scp) for i in range(index+1,len(data)): if calc_axis_iou(scp,data[i]) > 0.01 and math.fabs(data[i]['cy'] - scp['cy']) < 70: scopes.append(data[i]) if len(scopes) == 0: break scopes = sorted(scopes, key=lambda d: math.pow((d['cx'] - d['w'] / 2),2) + math.pow((d['cy'] - d['h'] / 2),2)) return busiScope def formatResult(data): maxRight = getMaxRight(data) creditCode,index = getCreditCode(data) name, index = getName(data,index) ty, index = getType(data,index) addr, index = getAddress(data,index) legalPerson, index = getLegalPerson(data,index) registerCapital, index = getRegisterCapital(data,index) estdate,index = getEstDate(data,index) busiTerm = getBusiTerm(data,index) busiScope = getBusiScope(data,index) res = [{'title': r'营业执照信息', 'items': [[{'name': r'统一社会信用代码', 'value': creditCode}, {'name': r'名称', 'value': name}, {'name': r'注册资本', 'value': registerCapital}, {'name': r'类型', 'value': ty}, {'name': r'成立日期', 'value': estdate}, {'name': r'法定代表人', 'value': legalPerson}, {'name': r'营业期限', 'value': busiTerm}, {'name': r'经营范围', 'value': busiScope}, {'name': r'住所', 'value': addr} ]] }] return res if __name__ == '__main__': test()
4f5c6d5824325008e15199545e1a44cd21b6fbd5
[ "Markdown", "Python" ]
21
Python
gaoshangle/complet_OCR
e3641313a9e289a923c1f0a6dd2c0ca880798b6d
99a8fdce1d9af41abacdfaf4beb84fade56b4f08
refs/heads/master
<file_sep>package statistics import ( "encoding/json" "errors" "fmt" "sort" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/compliance" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/holdings" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" "github.com/idoall/gocryptotrader/backtester/eventtypes/signal" gctcommon "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/convert" gctmath "github.com/idoall/gocryptotrader/common/math" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/log" "github.com/shopspring/decimal" ) // Reset returns the struct to defaults func (s *Statistic) Reset() { *s = Statistic{} } // SetupEventForTime sets up the big map for to store important data at each time interval func (s *Statistic) SetupEventForTime(ev common.DataEventHandler) error { if ev == nil { return common.ErrNilEvent } ex := ev.GetExchange() a := ev.GetAssetType() p := ev.Pair() s.setupMap(ex, a) lookup := s.ExchangeAssetPairStatistics[ex][a][p] if lookup == nil { lookup = &CurrencyPairStatistic{} } for i := range lookup.Events { if lookup.Events[i].DataEvent.GetTime().Equal(ev.GetTime()) && lookup.Events[i].DataEvent.GetExchange() == ev.GetExchange() && lookup.Events[i].DataEvent.GetAssetType() == ev.GetAssetType() && lookup.Events[i].DataEvent.Pair().Equal(ev.Pair()) && lookup.Events[i].DataEvent.GetOffset() == ev.GetOffset() { return ErrAlreadyProcessed } } lookup.Events = append(lookup.Events, EventStore{ DataEvent: ev, }, ) s.ExchangeAssetPairStatistics[ex][a][p] = lookup return nil } func (s *Statistic) setupMap(ex string, a asset.Item) { if s.ExchangeAssetPairStatistics == nil { s.ExchangeAssetPairStatistics = make(map[string]map[asset.Item]map[currency.Pair]*CurrencyPairStatistic) } if s.ExchangeAssetPairStatistics[ex] == nil { s.ExchangeAssetPairStatistics[ex] = make(map[asset.Item]map[currency.Pair]*CurrencyPairStatistic) } if s.ExchangeAssetPairStatistics[ex][a] == nil { s.ExchangeAssetPairStatistics[ex][a] = make(map[currency.Pair]*CurrencyPairStatistic) } } // SetEventForOffset sets the event for the time period in the event func (s *Statistic) SetEventForOffset(ev common.EventHandler) error { if ev == nil { return common.ErrNilEvent } if s.ExchangeAssetPairStatistics == nil { return errExchangeAssetPairStatsUnset } exch := ev.GetExchange() a := ev.GetAssetType() p := ev.Pair() offset := ev.GetOffset() lookup := s.ExchangeAssetPairStatistics[exch][a][p] if lookup == nil { return fmt.Errorf("%w for %v %v %v to set signal event", errCurrencyStatisticsUnset, exch, a, p) } for i := len(lookup.Events) - 1; i >= 0; i-- { if lookup.Events[i].DataEvent.GetOffset() == offset { return applyEventAtOffset(ev, lookup, i) } } return nil } func applyEventAtOffset(ev common.EventHandler, lookup *CurrencyPairStatistic, i int) error { switch t := ev.(type) { case common.DataEventHandler: lookup.Events[i].DataEvent = t case signal.Event: lookup.Events[i].SignalEvent = t case order.Event: lookup.Events[i].OrderEvent = t case fill.Event: lookup.Events[i].FillEvent = t default: return fmt.Errorf("unknown event type received: %v", ev) } return nil } // AddHoldingsForTime adds all holdings to the statistics at the time period func (s *Statistic) AddHoldingsForTime(h *holdings.Holding) error { if s.ExchangeAssetPairStatistics == nil { return errExchangeAssetPairStatsUnset } lookup := s.ExchangeAssetPairStatistics[h.Exchange][h.Asset][h.Pair] if lookup == nil { return fmt.Errorf("%w for %v %v %v to set holding event", errCurrencyStatisticsUnset, h.Exchange, h.Asset, h.Pair) } for i := len(lookup.Events) - 1; i >= 0; i-- { if lookup.Events[i].DataEvent.GetOffset() == h.Offset { lookup.Events[i].Holdings = *h break } } return nil } // AddComplianceSnapshotForTime adds the compliance snapshot to the statistics at the time period func (s *Statistic) AddComplianceSnapshotForTime(c compliance.Snapshot, e fill.Event) error { if e == nil { return common.ErrNilEvent } if s.ExchangeAssetPairStatistics == nil { return errExchangeAssetPairStatsUnset } exch := e.GetExchange() a := e.GetAssetType() p := e.Pair() lookup := s.ExchangeAssetPairStatistics[exch][a][p] if lookup == nil { return fmt.Errorf("%w for %v %v %v to set compliance snapshot", errCurrencyStatisticsUnset, exch, a, p) } for i := len(lookup.Events) - 1; i >= 0; i-- { if lookup.Events[i].DataEvent.GetOffset() == e.GetOffset() { lookup.Events[i].Transactions = c break } } return nil } // CalculateAllResults calculates the statistics of all exchange asset pair holdings, // orders, ratios and drawdowns func (s *Statistic) CalculateAllResults() error { log.Info(log.BackTester, "calculating backtesting results") s.PrintAllEventsChronologically() currCount := 0 var finalResults []FinalResultsHolder var err error for exchangeName, exchangeMap := range s.ExchangeAssetPairStatistics { for assetItem, assetMap := range exchangeMap { for pair, stats := range assetMap { currCount++ last := stats.Events[len(stats.Events)-1] err = stats.CalculateResults(s.RiskFreeRate) if err != nil { log.Error(log.BackTester, err) } stats.PrintResults(exchangeName, assetItem, pair, s.FundManager.IsUsingExchangeLevelFunding()) stats.FinalHoldings = last.Holdings stats.InitialHoldings = stats.Events[0].Holdings stats.FinalOrders = last.Transactions s.StartDate = stats.Events[0].DataEvent.GetTime() s.EndDate = last.DataEvent.GetTime() finalResults = append(finalResults, FinalResultsHolder{ Exchange: exchangeName, Asset: assetItem, Pair: pair, MaxDrawdown: stats.MaxDrawdown, MarketMovement: stats.MarketMovement, StrategyMovement: stats.StrategyMovement, }) s.TotalBuyOrders += stats.BuyOrders s.TotalSellOrders += stats.SellOrders if stats.ShowMissingDataWarning { s.WasAnyDataMissing = true } } } } s.FundingStatistics, err = CalculateFundingStatistics(s.FundManager, s.ExchangeAssetPairStatistics, s.RiskFreeRate, s.CandleInterval) if err != nil { return err } err = s.FundingStatistics.PrintResults(s.WasAnyDataMissing) if err != nil { return err } s.TotalOrders = s.TotalBuyOrders + s.TotalSellOrders if currCount > 1 { s.BiggestDrawdown = s.GetTheBiggestDrawdownAcrossCurrencies(finalResults) s.BestMarketMovement = s.GetBestMarketPerformer(finalResults) s.BestStrategyResults = s.GetBestStrategyPerformer(finalResults) s.PrintTotalResults() } return nil } // PrintTotalResults outputs all results to the CMD func (s *Statistic) PrintTotalResults() { log.Info(log.BackTester, "------------------Strategy-----------------------------------") log.Infof(log.BackTester, "Strategy Name: %v", s.StrategyName) log.Infof(log.BackTester, "Strategy Nickname: %v", s.StrategyNickname) log.Infof(log.BackTester, "Strategy Goal: %v\n\n", s.StrategyGoal) log.Info(log.BackTester, "------------------Total Results------------------------------") log.Info(log.BackTester, "------------------Orders-------------------------------------") log.Infof(log.BackTester, "Total buy orders: %v", convert.IntToHumanFriendlyString(s.TotalBuyOrders, ",")) log.Infof(log.BackTester, "Total sell orders: %v", convert.IntToHumanFriendlyString(s.TotalSellOrders, ",")) log.Infof(log.BackTester, "Total orders: %v\n\n", convert.IntToHumanFriendlyString(s.TotalOrders, ",")) if s.BiggestDrawdown != nil { log.Info(log.BackTester, "------------------Biggest Drawdown-----------------------") log.Infof(log.BackTester, "Exchange: %v Asset: %v Currency: %v", s.BiggestDrawdown.Exchange, s.BiggestDrawdown.Asset, s.BiggestDrawdown.Pair) log.Infof(log.BackTester, "Highest Price: %s", convert.DecimalToHumanFriendlyString(s.BiggestDrawdown.MaxDrawdown.Highest.Value, 8, ".", ",")) log.Infof(log.BackTester, "Highest Price Time: %v", s.BiggestDrawdown.MaxDrawdown.Highest.Time) log.Infof(log.BackTester, "Lowest Price: %s", convert.DecimalToHumanFriendlyString(s.BiggestDrawdown.MaxDrawdown.Lowest.Value, 8, ".", ",")) log.Infof(log.BackTester, "Lowest Price Time: %v", s.BiggestDrawdown.MaxDrawdown.Lowest.Time) log.Infof(log.BackTester, "Calculated Drawdown: %s%%", convert.DecimalToHumanFriendlyString(s.BiggestDrawdown.MaxDrawdown.DrawdownPercent, 2, ".", ",")) log.Infof(log.BackTester, "Difference: %s", convert.DecimalToHumanFriendlyString(s.BiggestDrawdown.MaxDrawdown.Highest.Value.Sub(s.BiggestDrawdown.MaxDrawdown.Lowest.Value), 8, ".", ",")) log.Infof(log.BackTester, "Drawdown length: %v\n\n", convert.IntToHumanFriendlyString(s.BiggestDrawdown.MaxDrawdown.IntervalDuration, ",")) } if s.BestMarketMovement != nil && s.BestStrategyResults != nil { log.Info(log.BackTester, "------------------Orders----------------------------------") log.Infof(log.BackTester, "Best performing market movement: %v %v %v %v%%", s.BestMarketMovement.Exchange, s.BestMarketMovement.Asset, s.BestMarketMovement.Pair, convert.DecimalToHumanFriendlyString(s.BestMarketMovement.MarketMovement, 2, ".", ",")) log.Infof(log.BackTester, "Best performing strategy movement: %v %v %v %v%%\n\n", s.BestStrategyResults.Exchange, s.BestStrategyResults.Asset, s.BestStrategyResults.Pair, convert.DecimalToHumanFriendlyString(s.BestStrategyResults.StrategyMovement, 2, ".", ",")) } } // GetBestMarketPerformer returns the best final market movement func (s *Statistic) GetBestMarketPerformer(results []FinalResultsHolder) *FinalResultsHolder { result := &FinalResultsHolder{} for i := range results { if results[i].MarketMovement.GreaterThan(result.MarketMovement) || result.MarketMovement.IsZero() { result = &results[i] break } } return result } // GetBestStrategyPerformer returns the best performing strategy result func (s *Statistic) GetBestStrategyPerformer(results []FinalResultsHolder) *FinalResultsHolder { result := &FinalResultsHolder{} for i := range results { if results[i].StrategyMovement.GreaterThan(result.StrategyMovement) || result.StrategyMovement.IsZero() { result = &results[i] } } return result } // GetTheBiggestDrawdownAcrossCurrencies returns the biggest drawdown across all currencies in a backtesting run func (s *Statistic) GetTheBiggestDrawdownAcrossCurrencies(results []FinalResultsHolder) *FinalResultsHolder { result := &FinalResultsHolder{} for i := range results { if results[i].MaxDrawdown.DrawdownPercent.GreaterThan(result.MaxDrawdown.DrawdownPercent) || result.MaxDrawdown.DrawdownPercent.IsZero() { result = &results[i] } } return result } func addEventOutputToTime(events []eventOutputHolder, t time.Time, message string) []eventOutputHolder { for i := range events { if events[i].Time.Equal(t) { events[i].Events = append(events[i].Events, message) return events } } events = append(events, eventOutputHolder{Time: t, Events: []string{message}}) return events } // PrintAllEventsChronologically outputs all event details in the CMD // rather than separated by exchange, asset and currency pair, it's // grouped by time to allow a clearer picture of events func (s *Statistic) PrintAllEventsChronologically() { var results []eventOutputHolder log.Info(log.BackTester, "------------------Events-------------------------------------") var errs gctcommon.Errors for exch, x := range s.ExchangeAssetPairStatistics { for a, y := range x { for pair, currencyStatistic := range y { for i := range currencyStatistic.Events { switch { case currencyStatistic.Events[i].FillEvent != nil: direction := currencyStatistic.Events[i].FillEvent.GetDirection() if direction == common.CouldNotBuy || direction == common.CouldNotSell || direction == common.DoNothing || direction == common.MissingData || direction == common.TransferredFunds || direction == "" { results = addEventOutputToTime(results, currencyStatistic.Events[i].FillEvent.GetTime(), fmt.Sprintf("%v %v %v %v | Price: $%v - Direction: %v - Reason: %s", currencyStatistic.Events[i].FillEvent.GetTime().Format(gctcommon.SimpleTimeFormat), currencyStatistic.Events[i].FillEvent.GetExchange(), currencyStatistic.Events[i].FillEvent.GetAssetType(), currencyStatistic.Events[i].FillEvent.Pair(), currencyStatistic.Events[i].FillEvent.GetClosePrice().Round(8), currencyStatistic.Events[i].FillEvent.GetDirection(), currencyStatistic.Events[i].FillEvent.GetReason())) } else { results = addEventOutputToTime(results, currencyStatistic.Events[i].FillEvent.GetTime(), fmt.Sprintf("%v %v %v %v | Price: $%v - Amount: %v - Fee: $%v - Total: $%v - Direction %v - Reason: %s", currencyStatistic.Events[i].FillEvent.GetTime().Format(gctcommon.SimpleTimeFormat), currencyStatistic.Events[i].FillEvent.GetExchange(), currencyStatistic.Events[i].FillEvent.GetAssetType(), currencyStatistic.Events[i].FillEvent.Pair(), currencyStatistic.Events[i].FillEvent.GetPurchasePrice().Round(8), currencyStatistic.Events[i].FillEvent.GetAmount().Round(8), currencyStatistic.Events[i].FillEvent.GetExchangeFee().Round(8), currencyStatistic.Events[i].FillEvent.GetTotal().Round(8), currencyStatistic.Events[i].FillEvent.GetDirection(), currencyStatistic.Events[i].FillEvent.GetReason(), )) } case currencyStatistic.Events[i].SignalEvent != nil: results = addEventOutputToTime(results, currencyStatistic.Events[i].SignalEvent.GetTime(), fmt.Sprintf("%v %v %v %v | Price: $%v - Reason: %v", currencyStatistic.Events[i].SignalEvent.GetTime().Format(gctcommon.SimpleTimeFormat), currencyStatistic.Events[i].SignalEvent.GetExchange(), currencyStatistic.Events[i].SignalEvent.GetAssetType(), currencyStatistic.Events[i].SignalEvent.Pair(), currencyStatistic.Events[i].SignalEvent.GetPrice().Round(8), currencyStatistic.Events[i].SignalEvent.GetReason())) case currencyStatistic.Events[i].DataEvent != nil: results = addEventOutputToTime(results, currencyStatistic.Events[i].DataEvent.GetTime(), fmt.Sprintf("%v %v %v %v | Price: $%v - Reason: %v", currencyStatistic.Events[i].DataEvent.GetTime().Format(gctcommon.SimpleTimeFormat), currencyStatistic.Events[i].DataEvent.GetExchange(), currencyStatistic.Events[i].DataEvent.GetAssetType(), currencyStatistic.Events[i].DataEvent.Pair(), currencyStatistic.Events[i].DataEvent.GetClosePrice().Round(8), currencyStatistic.Events[i].DataEvent.GetReason())) default: errs = append(errs, fmt.Errorf("%v %v %v unexpected data received %+v", exch, a, pair, currencyStatistic.Events[i])) } } } } } sort.Slice(results, func(i, j int) bool { b1 := results[i] b2 := results[j] return b1.Time.Before(b2.Time) }) for i := range results { for j := range results[i].Events { log.Info(log.BackTester, results[i].Events[j]) } } if len(errs) > 0 { log.Info(log.BackTester, "------------------Errors-------------------------------------") for i := range errs { log.Error(log.BackTester, errs[i].Error()) } } } // SetStrategyName sets the name for statistical identification func (s *Statistic) SetStrategyName(name string) { s.StrategyName = name } // Serialise outputs the Statistic struct in json func (s *Statistic) Serialise() (string, error) { resp, err := json.MarshalIndent(s, "", " ") if err != nil { return "", err } return string(resp), nil } // CalculateRatios creates arithmetic and geometric ratios from funding or currency pair data func CalculateRatios(benchmarkRates, returnsPerCandle []decimal.Decimal, riskFreeRatePerCandle decimal.Decimal, maxDrawdown *Swing, logMessage string) (arithmeticStats, geometricStats *Ratios, err error) { var arithmeticBenchmarkAverage, geometricBenchmarkAverage decimal.Decimal arithmeticBenchmarkAverage, err = gctmath.DecimalArithmeticMean(benchmarkRates) if err != nil { return nil, nil, err } geometricBenchmarkAverage, err = gctmath.DecimalFinancialGeometricMean(benchmarkRates) if err != nil { return nil, nil, err } riskFreeRateForPeriod := riskFreeRatePerCandle.Mul(decimal.NewFromInt(int64(len(benchmarkRates)))) var arithmeticReturnsPerCandle, geometricReturnsPerCandle, arithmeticSharpe, arithmeticSortino, arithmeticInformation, arithmeticCalmar, geomSharpe, geomSortino, geomInformation, geomCalmar decimal.Decimal arithmeticReturnsPerCandle, err = gctmath.DecimalArithmeticMean(returnsPerCandle) if err != nil { return nil, nil, err } geometricReturnsPerCandle, err = gctmath.DecimalFinancialGeometricMean(returnsPerCandle) if err != nil { return nil, nil, err } arithmeticSharpe, err = gctmath.DecimalSharpeRatio(returnsPerCandle, riskFreeRatePerCandle, arithmeticReturnsPerCandle) if err != nil { return nil, nil, err } arithmeticSortino, err = gctmath.DecimalSortinoRatio(returnsPerCandle, riskFreeRatePerCandle, arithmeticReturnsPerCandle) if err != nil && !errors.Is(err, gctmath.ErrNoNegativeResults) { if errors.Is(err, gctmath.ErrInexactConversion) { log.Warnf(log.BackTester, "%s funding arithmetic sortino ratio %v", logMessage, err) } else { return nil, nil, err } } arithmeticInformation, err = gctmath.DecimalInformationRatio(returnsPerCandle, benchmarkRates, arithmeticReturnsPerCandle, arithmeticBenchmarkAverage) if err != nil { return nil, nil, err } arithmeticCalmar, err = gctmath.DecimalCalmarRatio(maxDrawdown.Highest.Value, maxDrawdown.Lowest.Value, arithmeticReturnsPerCandle, riskFreeRateForPeriod) if err != nil { return nil, nil, err } arithmeticStats = &Ratios{} if !arithmeticSharpe.IsZero() { arithmeticStats.SharpeRatio = arithmeticSharpe } if !arithmeticSortino.IsZero() { arithmeticStats.SortinoRatio = arithmeticSortino } if !arithmeticInformation.IsZero() { arithmeticStats.InformationRatio = arithmeticInformation } if !arithmeticCalmar.IsZero() { arithmeticStats.CalmarRatio = arithmeticCalmar } geomSharpe, err = gctmath.DecimalSharpeRatio(returnsPerCandle, riskFreeRatePerCandle, geometricReturnsPerCandle) if err != nil { return nil, nil, err } geomSortino, err = gctmath.DecimalSortinoRatio(returnsPerCandle, riskFreeRatePerCandle, geometricReturnsPerCandle) if err != nil && !errors.Is(err, gctmath.ErrNoNegativeResults) { if errors.Is(err, gctmath.ErrInexactConversion) { log.Warnf(log.BackTester, "%s geometric sortino ratio %v", logMessage, err) } else { return nil, nil, err } } geomInformation, err = gctmath.DecimalInformationRatio(returnsPerCandle, benchmarkRates, geometricReturnsPerCandle, geometricBenchmarkAverage) if err != nil { return nil, nil, err } geomCalmar, err = gctmath.DecimalCalmarRatio(maxDrawdown.Highest.Value, maxDrawdown.Lowest.Value, geometricReturnsPerCandle, riskFreeRateForPeriod) if err != nil { return nil, nil, err } geometricStats = &Ratios{} if !arithmeticSharpe.IsZero() { geometricStats.SharpeRatio = geomSharpe } if !arithmeticSortino.IsZero() { geometricStats.SortinoRatio = geomSortino } if !arithmeticInformation.IsZero() { geometricStats.InformationRatio = geomInformation } if !arithmeticCalmar.IsZero() { geometricStats.CalmarRatio = geomCalmar } return arithmeticStats, geometricStats, nil } <file_sep>package statistics import ( "fmt" "sort" "time" "github.com/idoall/gocryptotrader/backtester/common" gctcommon "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/convert" gctmath "github.com/idoall/gocryptotrader/common/math" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/log" "github.com/shopspring/decimal" ) // CalculateResults calculates all statistics for the exchange, asset, currency pair func (c *CurrencyPairStatistic) CalculateResults(riskFreeRate decimal.Decimal) error { var errs gctcommon.Errors var err error first := c.Events[0] sep := fmt.Sprintf("%v %v %v |\t", first.DataEvent.GetExchange(), first.DataEvent.GetAssetType(), first.DataEvent.Pair()) firstPrice := first.DataEvent.GetClosePrice() last := c.Events[len(c.Events)-1] lastPrice := last.DataEvent.GetClosePrice() for i := range last.Transactions.Orders { if last.Transactions.Orders[i].Side == gctorder.Buy { c.BuyOrders++ } else if last.Transactions.Orders[i].Side == gctorder.Sell { c.SellOrders++ } } for i := range c.Events { price := c.Events[i].DataEvent.GetClosePrice() if c.LowestClosePrice.IsZero() || price.LessThan(c.LowestClosePrice) { c.LowestClosePrice = price } if price.GreaterThan(c.HighestClosePrice) { c.HighestClosePrice = price } } oneHundred := decimal.NewFromInt(100) if !firstPrice.IsZero() { c.MarketMovement = lastPrice.Sub(firstPrice).Div(firstPrice).Mul(oneHundred) } if first.Holdings.TotalValue.GreaterThan(decimal.Zero) { c.StrategyMovement = last.Holdings.TotalValue.Sub(first.Holdings.TotalValue).Div(first.Holdings.TotalValue).Mul(oneHundred) } c.calculateHighestCommittedFunds() returnsPerCandle := make([]decimal.Decimal, len(c.Events)) benchmarkRates := make([]decimal.Decimal, len(c.Events)) var allDataEvents []common.DataEventHandler for i := range c.Events { returnsPerCandle[i] = c.Events[i].Holdings.ChangeInTotalValuePercent allDataEvents = append(allDataEvents, c.Events[i].DataEvent) if i == 0 { continue } if c.Events[i].SignalEvent != nil && c.Events[i].SignalEvent.GetDirection() == common.MissingData { c.ShowMissingDataWarning = true } if c.Events[i].DataEvent.GetClosePrice().IsZero() || c.Events[i-1].DataEvent.GetClosePrice().IsZero() { // closing price for the current candle or previous candle is zero, use the previous // benchmark rate to allow some consistency c.ShowMissingDataWarning = true benchmarkRates[i] = benchmarkRates[i-1] continue } benchmarkRates[i] = c.Events[i].DataEvent.GetClosePrice().Sub( c.Events[i-1].DataEvent.GetClosePrice()).Div( c.Events[i-1].DataEvent.GetClosePrice()) } // remove the first entry as its zero and impacts // ratio calculations as no movement has been made benchmarkRates = benchmarkRates[1:] returnsPerCandle = returnsPerCandle[1:] c.MaxDrawdown, err = CalculateBiggestEventDrawdown(allDataEvents) if err != nil { errs = append(errs, err) } interval := first.DataEvent.GetInterval() intervalsPerYear := interval.IntervalsPerYear() riskFreeRatePerCandle := riskFreeRate.Div(decimal.NewFromFloat(intervalsPerYear)) c.ArithmeticRatios, c.GeometricRatios, err = CalculateRatios(benchmarkRates, returnsPerCandle, riskFreeRatePerCandle, &c.MaxDrawdown, sep) if err != nil { return err } if last.Holdings.QuoteInitialFunds.GreaterThan(decimal.Zero) { cagr, err := gctmath.DecimalCompoundAnnualGrowthRate( last.Holdings.QuoteInitialFunds, last.Holdings.TotalValue, decimal.NewFromFloat(intervalsPerYear), decimal.NewFromInt(int64(len(c.Events))), ) if err != nil { errs = append(errs, err) } if !cagr.IsZero() { c.CompoundAnnualGrowthRate = cagr } } c.IsStrategyProfitable = last.Holdings.TotalValue.GreaterThan(first.Holdings.TotalValue) c.DoesPerformanceBeatTheMarket = c.StrategyMovement.GreaterThan(c.MarketMovement) c.TotalFees = last.Holdings.TotalFees.Round(8) c.TotalValueLostToVolumeSizing = last.Holdings.TotalValueLostToVolumeSizing.Round(2) c.TotalValueLost = last.Holdings.TotalValueLost.Round(2) c.TotalValueLostToSlippage = last.Holdings.TotalValueLostToSlippage.Round(2) c.TotalAssetValue = last.Holdings.BaseValue.Round(8) if len(errs) > 0 { return errs } return nil } // PrintResults outputs all calculated statistics to the command line func (c *CurrencyPairStatistic) PrintResults(e string, a asset.Item, p currency.Pair, usingExchangeLevelFunding bool) { var errs gctcommon.Errors sort.Slice(c.Events, func(i, j int) bool { return c.Events[i].DataEvent.GetTime().Before(c.Events[j].DataEvent.GetTime()) }) last := c.Events[len(c.Events)-1] first := c.Events[0] c.StartingClosePrice = first.DataEvent.GetClosePrice() c.EndingClosePrice = last.DataEvent.GetClosePrice() c.TotalOrders = c.BuyOrders + c.SellOrders last.Holdings.TotalValueLost = last.Holdings.TotalValueLostToSlippage.Add(last.Holdings.TotalValueLostToVolumeSizing) sep := fmt.Sprintf("%v %v %v |\t", e, a, p) currStr := fmt.Sprintf("------------------Stats for %v %v %v------------------------------------------", e, a, p) log.Infof(log.BackTester, currStr[:61]) log.Infof(log.BackTester, "%s Highest committed funds: %s at %v", sep, convert.DecimalToHumanFriendlyString(c.HighestCommittedFunds.Value, 8, ".", ","), c.HighestCommittedFunds.Time) log.Infof(log.BackTester, "%s Buy orders: %s", sep, convert.IntToHumanFriendlyString(c.BuyOrders, ",")) log.Infof(log.BackTester, "%s Buy value: %s", sep, convert.DecimalToHumanFriendlyString(last.Holdings.BoughtValue, 8, ".", ",")) log.Infof(log.BackTester, "%s Buy amount: %s %s", sep, convert.DecimalToHumanFriendlyString(last.Holdings.BoughtAmount, 8, ".", ","), last.Holdings.Pair.Base) log.Infof(log.BackTester, "%s Sell orders: %s", sep, convert.IntToHumanFriendlyString(c.SellOrders, ",")) log.Infof(log.BackTester, "%s Sell value: %s", sep, convert.DecimalToHumanFriendlyString(last.Holdings.SoldValue, 8, ".", ",")) log.Infof(log.BackTester, "%s Sell amount: %s", sep, convert.DecimalToHumanFriendlyString(last.Holdings.SoldAmount, 8, ".", ",")) log.Infof(log.BackTester, "%s Total orders: %s\n\n", sep, convert.IntToHumanFriendlyString(c.TotalOrders, ",")) log.Info(log.BackTester, "------------------Max Drawdown-------------------------------") log.Infof(log.BackTester, "%s Highest Price of drawdown: %s at %v", sep, convert.DecimalToHumanFriendlyString(c.MaxDrawdown.Highest.Value, 8, ".", ","), c.MaxDrawdown.Highest.Time) log.Infof(log.BackTester, "%s Lowest Price of drawdown: %s at %v", sep, convert.DecimalToHumanFriendlyString(c.MaxDrawdown.Lowest.Value, 8, ".", ","), c.MaxDrawdown.Lowest.Time) log.Infof(log.BackTester, "%s Calculated Drawdown: %s%%", sep, convert.DecimalToHumanFriendlyString(c.MaxDrawdown.DrawdownPercent, 8, ".", ",")) log.Infof(log.BackTester, "%s Difference: %s", sep, convert.DecimalToHumanFriendlyString(c.MaxDrawdown.Highest.Value.Sub(c.MaxDrawdown.Lowest.Value), 2, ".", ",")) log.Infof(log.BackTester, "%s Drawdown length: %s\n\n", sep, convert.IntToHumanFriendlyString(c.MaxDrawdown.IntervalDuration, ",")) if !usingExchangeLevelFunding { log.Info(log.BackTester, "------------------Ratios------------------------------------------------") log.Info(log.BackTester, "------------------Rates-------------------------------------------------") log.Infof(log.BackTester, "%s Compound Annual Growth Rate: %s", sep, convert.DecimalToHumanFriendlyString(c.CompoundAnnualGrowthRate, 2, ".", ",")) log.Info(log.BackTester, "------------------Arithmetic--------------------------------------------") if c.ShowMissingDataWarning { log.Infoln(log.BackTester, "Missing data was detected during this backtesting run") log.Infoln(log.BackTester, "Ratio calculations will be skewed") } log.Infof(log.BackTester, "%s Sharpe ratio: %v", sep, c.ArithmeticRatios.SharpeRatio.Round(4)) log.Infof(log.BackTester, "%s Sortino ratio: %v", sep, c.ArithmeticRatios.SortinoRatio.Round(4)) log.Infof(log.BackTester, "%s Information ratio: %v", sep, c.ArithmeticRatios.InformationRatio.Round(4)) log.Infof(log.BackTester, "%s Calmar ratio: %v", sep, c.ArithmeticRatios.CalmarRatio.Round(4)) log.Info(log.BackTester, "------------------Geometric--------------------------------------------") if c.ShowMissingDataWarning { log.Infoln(log.BackTester, "Missing data was detected during this backtesting run") log.Infoln(log.BackTester, "Ratio calculations will be skewed") } log.Infof(log.BackTester, "%s Sharpe ratio: %v", sep, c.GeometricRatios.SharpeRatio.Round(4)) log.Infof(log.BackTester, "%s Sortino ratio: %v", sep, c.GeometricRatios.SortinoRatio.Round(4)) log.Infof(log.BackTester, "%s Information ratio: %v", sep, c.GeometricRatios.InformationRatio.Round(4)) log.Infof(log.BackTester, "%s Calmar ratio: %v\n\n", sep, c.GeometricRatios.CalmarRatio.Round(4)) } log.Info(log.BackTester, "------------------Results------------------------------------") log.Infof(log.BackTester, "%s Starting Close Price: %s", sep, convert.DecimalToHumanFriendlyString(c.StartingClosePrice, 8, ".", ",")) log.Infof(log.BackTester, "%s Finishing Close Price: %s", sep, convert.DecimalToHumanFriendlyString(c.EndingClosePrice, 8, ".", ",")) log.Infof(log.BackTester, "%s Lowest Close Price: %s", sep, convert.DecimalToHumanFriendlyString(c.LowestClosePrice, 8, ".", ",")) log.Infof(log.BackTester, "%s Highest Close Price: %s", sep, convert.DecimalToHumanFriendlyString(c.HighestClosePrice, 8, ".", ",")) log.Infof(log.BackTester, "%s Market movement: %s%%", sep, convert.DecimalToHumanFriendlyString(c.MarketMovement, 2, ".", ",")) if !usingExchangeLevelFunding { log.Infof(log.BackTester, "%s Strategy movement: %s%%", sep, convert.DecimalToHumanFriendlyString(c.StrategyMovement, 2, ".", ",")) log.Infof(log.BackTester, "%s Did it beat the market: %v", sep, c.StrategyMovement.GreaterThan(c.MarketMovement)) } log.Infof(log.BackTester, "%s Value lost to volume sizing: %s", sep, convert.DecimalToHumanFriendlyString(c.TotalValueLostToVolumeSizing, 2, ".", ",")) log.Infof(log.BackTester, "%s Value lost to slippage: %s", sep, convert.DecimalToHumanFriendlyString(c.TotalValueLostToSlippage, 2, ".", ",")) log.Infof(log.BackTester, "%s Total Value lost: %s", sep, convert.DecimalToHumanFriendlyString(c.TotalValueLost, 2, ".", ",")) log.Infof(log.BackTester, "%s Total Fees: %s\n\n", sep, convert.DecimalToHumanFriendlyString(c.TotalFees, 8, ".", ",")) log.Infof(log.BackTester, "%s Final holdings value: %s", sep, convert.DecimalToHumanFriendlyString(c.TotalAssetValue, 8, ".", ",")) if !usingExchangeLevelFunding { // the following have no direct translation to individual exchange level funds as they // combine base and quote values log.Infof(log.BackTester, "%s Final funds: %s", sep, convert.DecimalToHumanFriendlyString(last.Holdings.QuoteSize, 8, ".", ",")) log.Infof(log.BackTester, "%s Final holdings: %s", sep, convert.DecimalToHumanFriendlyString(last.Holdings.BaseSize, 8, ".", ",")) log.Infof(log.BackTester, "%s Final total value: %s\n\n", sep, convert.DecimalToHumanFriendlyString(last.Holdings.TotalValue, 8, ".", ",")) } if len(errs) > 0 { log.Info(log.BackTester, "------------------Errors-------------------------------------") for i := range errs { log.Error(log.BackTester, errs[i].Error()) } } } // CalculateBiggestEventDrawdown calculates the biggest drawdown using a slice of DataEvents func CalculateBiggestEventDrawdown(closePrices []common.DataEventHandler) (Swing, error) { if len(closePrices) == 0 { return Swing{}, fmt.Errorf("%w to calculate drawdowns", errReceivedNoData) } var swings []Swing lowestPrice := closePrices[0].GetLowPrice() highestPrice := closePrices[0].GetHighPrice() lowestTime := closePrices[0].GetTime() highestTime := closePrices[0].GetTime() interval := closePrices[0].GetInterval() for i := range closePrices { currHigh := closePrices[i].GetHighPrice() currLow := closePrices[i].GetLowPrice() currTime := closePrices[i].GetTime() if lowestPrice.GreaterThan(currLow) && !currLow.IsZero() { lowestPrice = currLow lowestTime = currTime } if highestPrice.LessThan(currHigh) { if lowestTime.Equal(highestTime) { // create distinction if the greatest drawdown occurs within the same candle lowestTime = lowestTime.Add(interval.Duration() - time.Nanosecond) } intervals, err := gctkline.CalculateCandleDateRanges(highestTime, lowestTime, closePrices[i].GetInterval(), 0) if err != nil { log.Error(log.BackTester, err) continue } if highestPrice.IsPositive() && lowestPrice.IsPositive() { swings = append(swings, Swing{ Highest: ValueAtTime{ Time: highestTime, Value: highestPrice, }, Lowest: ValueAtTime{ Time: lowestTime, Value: lowestPrice, }, DrawdownPercent: lowestPrice.Sub(highestPrice).Div(highestPrice).Mul(decimal.NewFromInt(100)), IntervalDuration: int64(len(intervals.Ranges[0].Intervals)), }) } // reset the drawdown highestPrice = currHigh highestTime = currTime lowestPrice = currLow lowestTime = currTime } } if (len(swings) > 0 && swings[len(swings)-1].Lowest.Value != closePrices[len(closePrices)-1].GetLowPrice()) || swings == nil { // need to close out the final drawdown if lowestTime.Equal(highestTime) { // create distinction if the greatest drawdown occurs within the same candle lowestTime = lowestTime.Add(interval.Duration() - time.Nanosecond) } intervals, err := gctkline.CalculateCandleDateRanges(highestTime, lowestTime, closePrices[0].GetInterval(), 0) if err != nil { return Swing{}, err } drawdownPercent := decimal.Zero if highestPrice.GreaterThan(decimal.Zero) { drawdownPercent = lowestPrice.Sub(highestPrice).Div(highestPrice).Mul(decimal.NewFromInt(100)) } if lowestTime.Equal(highestTime) { // create distinction if the greatest drawdown occurs within the same candle lowestTime = lowestTime.Add(interval.Duration() - time.Nanosecond) } swings = append(swings, Swing{ Highest: ValueAtTime{ Time: highestTime, Value: highestPrice, }, Lowest: ValueAtTime{ Time: lowestTime, Value: lowestPrice, }, DrawdownPercent: drawdownPercent, IntervalDuration: int64(len(intervals.Ranges[0].Intervals)), }) } var maxDrawdown Swing if len(swings) > 0 { maxDrawdown = swings[0] } for i := range swings { if swings[i].DrawdownPercent.LessThan(maxDrawdown.DrawdownPercent) { maxDrawdown = swings[i] } } return maxDrawdown, nil } func (c *CurrencyPairStatistic) calculateHighestCommittedFunds() { for i := range c.Events { if c.Events[i].Holdings.BaseSize.Mul(c.Events[i].DataEvent.GetClosePrice()).GreaterThan(c.HighestCommittedFunds.Value) { c.HighestCommittedFunds.Value = c.Events[i].Holdings.BaseSize.Mul(c.Events[i].DataEvent.GetClosePrice()) c.HighestCommittedFunds.Time = c.Events[i].Holdings.Timestamp } } } // CalculateBiggestValueAtTimeDrawdown calculates the biggest drawdown using a slice of ValueAtTimes func CalculateBiggestValueAtTimeDrawdown(closePrices []ValueAtTime, interval gctkline.Interval) (Swing, error) { if len(closePrices) == 0 { return Swing{}, fmt.Errorf("%w to calculate drawdowns", errReceivedNoData) } var swings []Swing lowestPrice := closePrices[0].Value highestPrice := closePrices[0].Value lowestTime := closePrices[0].Time highestTime := closePrices[0].Time for i := range closePrices { currHigh := closePrices[i].Value currLow := closePrices[i].Value currTime := closePrices[i].Time if lowestPrice.GreaterThan(currLow) && !currLow.IsZero() { lowestPrice = currLow lowestTime = currTime } if highestPrice.LessThan(currHigh) && highestPrice.IsPositive() { if lowestTime.Equal(highestTime) { // create distinction if the greatest drawdown occurs within the same candle lowestTime = lowestTime.Add(interval.Duration() - time.Nanosecond) } intervals, err := gctkline.CalculateCandleDateRanges(highestTime, lowestTime, interval, 0) if err != nil { return Swing{}, err } swings = append(swings, Swing{ Highest: ValueAtTime{ Time: highestTime, Value: highestPrice, }, Lowest: ValueAtTime{ Time: lowestTime, Value: lowestPrice, }, DrawdownPercent: lowestPrice.Sub(highestPrice).Div(highestPrice).Mul(decimal.NewFromInt(100)), IntervalDuration: int64(len(intervals.Ranges[0].Intervals)), }) // reset the drawdown highestPrice = currHigh highestTime = currTime lowestPrice = currLow lowestTime = currTime } } if (len(swings) > 0 && !swings[len(swings)-1].Lowest.Value.Equal(closePrices[len(closePrices)-1].Value)) || swings == nil { // need to close out the final drawdown if lowestTime.Equal(highestTime) { // create distinction if the greatest drawdown occurs within the same candle lowestTime = lowestTime.Add(interval.Duration() - time.Nanosecond) } intervals, err := gctkline.CalculateCandleDateRanges(highestTime, lowestTime, interval, 0) if err != nil { log.Error(log.BackTester, err) } drawdownPercent := decimal.Zero if highestPrice.GreaterThan(decimal.Zero) { drawdownPercent = lowestPrice.Sub(highestPrice).Div(highestPrice).Mul(decimal.NewFromInt(100)) } if lowestTime.Equal(highestTime) { // create distinction if the greatest drawdown occurs within the same candle lowestTime = lowestTime.Add(interval.Duration() - time.Nanosecond) } swings = append(swings, Swing{ Highest: ValueAtTime{ Time: highestTime, Value: highestPrice, }, Lowest: ValueAtTime{ Time: lowestTime, Value: lowestPrice, }, DrawdownPercent: drawdownPercent, IntervalDuration: int64(len(intervals.Ranges[0].Intervals)), }) } var maxDrawdown Swing if len(swings) > 0 { maxDrawdown = swings[0] } for i := range swings { if swings[i].DrawdownPercent.LessThan(maxDrawdown.DrawdownPercent) { maxDrawdown = swings[i] } } return maxDrawdown, nil } <file_sep>package ftx import ( "context" "errors" "fmt" "sort" "strconv" "strings" "sync" "time" "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/config" "github.com/idoall/gocryptotrader/currency" exchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/account" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/deposit" "github.com/idoall/gocryptotrader/exchanges/kline" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/exchanges/orderbook" "github.com/idoall/gocryptotrader/exchanges/protocol" "github.com/idoall/gocryptotrader/exchanges/request" "github.com/idoall/gocryptotrader/exchanges/stream" "github.com/idoall/gocryptotrader/exchanges/ticker" "github.com/idoall/gocryptotrader/exchanges/trade" "github.com/idoall/gocryptotrader/log" "github.com/idoall/gocryptotrader/portfolio/withdraw" ) // GetDefaultConfig returns a default exchange config func (f *FTX) GetDefaultConfig() (*config.Exchange, error) { f.SetDefaults() exchCfg := new(config.Exchange) exchCfg.Name = f.Name exchCfg.HTTPTimeout = exchange.DefaultHTTPTimeout exchCfg.BaseCurrencies = f.BaseCurrencies err := f.SetupDefaults(exchCfg) if err != nil { return nil, err } if f.Features.Supports.RESTCapabilities.AutoPairUpdates { err = f.UpdateTradablePairs(context.TODO(), true) if err != nil { return nil, err } } return exchCfg, nil } // SetDefaults sets the basic defaults for FTX func (f *FTX) SetDefaults() { f.Name = "FTX" f.Enabled = true f.Verbose = true f.API.CredentialsValidator.RequiresKey = true f.API.CredentialsValidator.RequiresSecret = true spot := currency.PairStore{ RequestFormat: &currency.PairFormat{ Uppercase: true, Delimiter: "/", }, ConfigFormat: &currency.PairFormat{ Uppercase: true, Delimiter: "/", }, } futures := currency.PairStore{ RequestFormat: &currency.PairFormat{ Uppercase: true, Delimiter: "-", }, ConfigFormat: &currency.PairFormat{ Uppercase: true, Delimiter: "-", }, } err := f.StoreAssetPairFormat(asset.Spot, spot) if err != nil { log.Errorln(log.ExchangeSys, err) } err = f.StoreAssetPairFormat(asset.Futures, futures) if err != nil { log.Errorln(log.ExchangeSys, err) } f.Features = exchange.Features{ Supports: exchange.FeaturesSupported{ REST: true, Websocket: true, RESTCapabilities: protocol.Features{ TickerFetching: true, TickerBatching: true, KlineFetching: true, TradeFetching: true, OrderbookFetching: true, AutoPairUpdates: true, AccountInfo: true, GetOrder: true, GetOrders: true, CancelOrders: true, CancelOrder: true, SubmitOrder: true, TradeFee: true, FiatDepositFee: true, FiatWithdrawalFee: true, CryptoWithdrawalFee: true, CryptoDeposit: true, CryptoWithdrawal: true, MultiChainDeposits: true, MultiChainWithdrawals: true, }, WebsocketCapabilities: protocol.Features{ OrderbookFetching: true, TradeFetching: true, Subscribe: true, Unsubscribe: true, GetOrders: true, GetOrder: true, }, WithdrawPermissions: exchange.AutoWithdrawCrypto, Kline: kline.ExchangeCapabilitiesSupported{ DateRanges: true, Intervals: true, }, }, Enabled: exchange.FeaturesEnabled{ AutoPairUpdates: true, Kline: kline.ExchangeCapabilitiesEnabled{ Intervals: map[string]bool{ kline.FifteenSecond.Word(): true, kline.OneMin.Word(): true, kline.FiveMin.Word(): true, kline.FifteenMin.Word(): true, kline.OneHour.Word(): true, kline.FourHour.Word(): true, kline.OneDay.Word(): true, }, ResultLimit: 5000, }, }, } f.Requester = request.New(f.Name, common.NewHTTPClientWithTimeout(exchange.DefaultHTTPTimeout), request.WithLimiter(request.NewBasicRateLimit(ratePeriod, rateLimit))) f.API.Endpoints = f.NewEndpoints() err = f.API.Endpoints.SetDefaultEndpoints(map[exchange.URL]string{ exchange.RestSpot: ftxAPIURL, exchange.WebsocketSpot: ftxWSURL, }) if err != nil { log.Errorln(log.ExchangeSys, err) } f.Websocket = stream.New() f.WebsocketResponseMaxLimit = exchange.DefaultWebsocketResponseMaxLimit f.WebsocketResponseCheckTimeout = exchange.DefaultWebsocketResponseCheckTimeout f.WebsocketOrderbookBufferLimit = exchange.DefaultWebsocketOrderbookBufferLimit } // Setup takes in the supplied exchange configuration details and sets params func (f *FTX) Setup(exch *config.Exchange) error { err := exch.Validate() if err != nil { return err } if !exch.Enabled { f.SetEnabled(false) return nil } err = f.SetupDefaults(exch) if err != nil { return err } wsEndpoint, err := f.API.Endpoints.GetURL(exchange.WebsocketSpot) if err != nil { return err } err = f.Websocket.Setup(&stream.WebsocketSetup{ ExchangeConfig: exch, DefaultURL: ftxWSURL, RunningURL: wsEndpoint, Connector: f.WsConnect, Subscriber: f.Subscribe, Unsubscriber: f.Unsubscribe, GenerateSubscriptions: f.GenerateDefaultSubscriptions, Features: &f.Features.Supports.WebsocketCapabilities, TradeFeed: f.Features.Enabled.TradeFeed, FillsFeed: f.Features.Enabled.FillsFeed, }) if err != nil { return err } return f.Websocket.SetupNewConnection(stream.ConnectionSetup{ ResponseCheckTimeout: exch.WebsocketResponseCheckTimeout, ResponseMaxLimit: exch.WebsocketResponseMaxLimit, }) } // Start starts the FTX go routine func (f *FTX) Start(wg *sync.WaitGroup) error { if wg == nil { return fmt.Errorf("%T %w", wg, common.ErrNilPointer) } wg.Add(1) go func() { f.Run() wg.Done() }() return nil } // Run implements the FTX wrapper func (f *FTX) Run() { if f.Verbose { log.Debugf(log.ExchangeSys, "%s Websocket: %s.", f.Name, common.IsEnabled(f.Websocket.IsEnabled())) f.PrintEnabledPairs() } err := f.UpdateOrderExecutionLimits(context.TODO(), "") if err != nil { log.Errorf(log.ExchangeSys, "%s failed to set exchange order execution limits. Err: %v", f.Name, err) } if !f.GetEnabledFeatures().AutoPairUpdates { return } err = f.UpdateTradablePairs(context.TODO(), false) if err != nil { log.Errorf(log.ExchangeSys, "%s failed to update tradable pairs. Err: %s", f.Name, err) } } // FetchTradablePairs returns a list of the exchanges tradable pairs func (f *FTX) FetchTradablePairs(ctx context.Context, a asset.Item) ([]string, error) { if !f.SupportsAsset(a) { return nil, fmt.Errorf("asset type of %s is not supported by %s", a, f.Name) } markets, err := f.GetMarkets(ctx) if err != nil { return nil, err } format, err := f.GetPairFormat(a, false) if err != nil { return nil, err } var pairs []string switch a { case asset.Spot: for x := range markets { if markets[x].MarketType == spotString { curr, err := currency.NewPairFromString(markets[x].Name) if err != nil { return nil, err } pairs = append(pairs, format.Format(curr)) } } case asset.Futures: for x := range markets { if markets[x].MarketType == futuresString { curr, err := currency.NewPairFromString(markets[x].Name) if err != nil { return nil, err } pairs = append(pairs, format.Format(curr)) } } } return pairs, nil } // UpdateTradablePairs updates the exchanges available pairs and stores // them in the exchanges config func (f *FTX) UpdateTradablePairs(ctx context.Context, forceUpdate bool) error { assets := f.GetAssetTypes(false) for x := range assets { pairs, err := f.FetchTradablePairs(ctx, assets[x]) if err != nil { return err } p, err := currency.NewPairsFromStrings(pairs) if err != nil { return err } err = f.UpdatePairs(p, assets[x], false, forceUpdate) if err != nil { return err } } return nil } // UpdateTickers updates the ticker for all currency pairs of a given asset type func (f *FTX) UpdateTickers(ctx context.Context, a asset.Item) error { allPairs, err := f.GetEnabledPairs(a) if err != nil { return err } markets, err := f.GetMarkets(ctx) if err != nil { return err } for p := range allPairs { formattedPair, err := f.FormatExchangeCurrency(allPairs[p], a) if err != nil { return err } for x := range markets { if markets[x].Name != formattedPair.String() { continue } var resp ticker.Price resp.Pair, err = currency.NewPairFromString(markets[x].Name) if err != nil { return err } resp.Last = markets[x].Last resp.Bid = markets[x].Bid resp.Ask = markets[x].Ask resp.LastUpdated = time.Now() resp.AssetType = a resp.ExchangeName = f.Name err = ticker.ProcessTicker(&resp) if err != nil { return err } } } return nil } // UpdateTicker updates and returns the ticker for a currency pair func (f *FTX) UpdateTicker(ctx context.Context, p currency.Pair, a asset.Item) (*ticker.Price, error) { formattedPair, err := f.FormatExchangeCurrency(p, a) if err != nil { return nil, err } market, err := f.GetMarket(ctx, formattedPair.String()) if err != nil { return nil, err } var resp ticker.Price resp.Pair, err = currency.NewPairFromString(market.Name) if err != nil { return nil, err } resp.Last = market.Last resp.Bid = market.Bid resp.Ask = market.Ask resp.LastUpdated = time.Now() resp.AssetType = a resp.ExchangeName = f.Name err = ticker.ProcessTicker(&resp) if err != nil { return nil, err } return ticker.GetTicker(f.Name, p, a) } // FetchTicker returns the ticker for a currency pair func (f *FTX) FetchTicker(ctx context.Context, p currency.Pair, assetType asset.Item) (*ticker.Price, error) { tickerNew, err := ticker.GetTicker(f.Name, p, assetType) if err != nil { return f.UpdateTicker(ctx, p, assetType) } return tickerNew, nil } // FetchOrderbook returns orderbook base on the currency pair func (f *FTX) FetchOrderbook(ctx context.Context, c currency.Pair, assetType asset.Item) (*orderbook.Base, error) { ob, err := orderbook.Get(f.Name, c, assetType) if err != nil { return f.UpdateOrderbook(ctx, c, assetType) } return ob, nil } // UpdateOrderbook updates and returns the orderbook for a currency pair func (f *FTX) UpdateOrderbook(ctx context.Context, p currency.Pair, assetType asset.Item) (*orderbook.Base, error) { book := &orderbook.Base{ Exchange: f.Name, Pair: p, Asset: assetType, VerifyOrderbook: f.CanVerifyOrderbook, } formattedPair, err := f.FormatExchangeCurrency(p, assetType) if err != nil { return book, err } tempResp, err := f.GetOrderbook(ctx, formattedPair.String(), 100) if err != nil { return book, err } for x := range tempResp.Bids { book.Bids = append(book.Bids, orderbook.Item{ Amount: tempResp.Bids[x].Size, Price: tempResp.Bids[x].Price}) } for y := range tempResp.Asks { book.Asks = append(book.Asks, orderbook.Item{ Amount: tempResp.Asks[y].Size, Price: tempResp.Asks[y].Price}) } err = book.Process() if err != nil { return book, err } return orderbook.Get(f.Name, p, assetType) } // UpdateAccountInfo retrieves balances for all enabled currencies func (f *FTX) UpdateAccountInfo(ctx context.Context, a asset.Item) (account.Holdings, error) { var resp account.Holdings var data AllWalletBalances if f.API.Credentials.Subaccount != "" { balances, err := f.GetBalances(ctx) if err != nil { return resp, err } data = make(AllWalletBalances) data[f.API.Credentials.Subaccount] = balances } else { // Get all wallet balances used so we can transfer between accounts if // needed. var err error data, err = f.GetAllWalletBalances(ctx) if err != nil { return resp, err } } for subName, balances := range data { // "main" defines the main account in the sub account list var acc = account.SubAccount{ID: subName, AssetType: a} for x := range balances { c := currency.NewCode(balances[x].Coin) hold := balances[x].Total - balances[x].Free acc.Currencies = append(acc.Currencies, account.Balance{CurrencyName: c, TotalValue: balances[x].Total, Hold: hold}) } resp.Accounts = append(resp.Accounts, acc) } resp.Exchange = f.Name if err := account.Process(&resp); err != nil { return account.Holdings{}, err } return resp, nil } // FetchAccountInfo retrieves balances for all enabled currencies func (f *FTX) FetchAccountInfo(ctx context.Context, assetType asset.Item) (account.Holdings, error) { acc, err := account.GetHoldings(f.Name, assetType) if err != nil { return f.UpdateAccountInfo(ctx, assetType) } return acc, nil } // GetFundingHistory returns funding history, deposits and // withdrawals func (f *FTX) GetFundingHistory(ctx context.Context) ([]exchange.FundHistory, error) { var resp []exchange.FundHistory depositData, err := f.FetchDepositHistory(ctx) if err != nil { return resp, err } for x := range depositData { var tempData exchange.FundHistory tempData.Fee = depositData[x].Fee tempData.Timestamp = depositData[x].Time tempData.ExchangeName = f.Name tempData.CryptoToAddress = depositData[x].Address.Address tempData.CryptoTxID = depositData[x].TxID tempData.CryptoChain = depositData[x].Address.Method tempData.Status = depositData[x].Status tempData.Amount = depositData[x].Size tempData.Currency = depositData[x].Coin tempData.TransferID = strconv.FormatInt(depositData[x].ID, 10) resp = append(resp, tempData) } withdrawalData, err := f.FetchWithdrawalHistory(ctx) if err != nil { return resp, err } for y := range withdrawalData { var tempData exchange.FundHistory tempData.Fee = withdrawalData[y].Fee tempData.Timestamp = withdrawalData[y].Time tempData.ExchangeName = f.Name tempData.CryptoToAddress = withdrawalData[y].Address tempData.CryptoTxID = withdrawalData[y].TXID tempData.CryptoChain = withdrawalData[y].Method tempData.Status = withdrawalData[y].Status tempData.Amount = withdrawalData[y].Size tempData.Currency = withdrawalData[y].Coin tempData.TransferID = strconv.FormatInt(withdrawalData[y].ID, 10) resp = append(resp, tempData) } return resp, nil } // GetWithdrawalsHistory returns previous withdrawals data func (f *FTX) GetWithdrawalsHistory(ctx context.Context, c currency.Code) (resp []exchange.WithdrawalHistory, err error) { return nil, common.ErrNotYetImplemented } // GetRecentTrades returns the most recent trades for a currency and asset func (f *FTX) GetRecentTrades(ctx context.Context, p currency.Pair, assetType asset.Item) ([]trade.Data, error) { return f.GetHistoricTrades(ctx, p, assetType, time.Now().Add(-time.Minute*15), time.Now()) } // GetHistoricTrades returns historic trade data within the timeframe provided // FTX returns trades from the end date and iterates towards the start date func (f *FTX) GetHistoricTrades(ctx context.Context, p currency.Pair, assetType asset.Item, timestampStart, timestampEnd time.Time) ([]trade.Data, error) { if err := common.StartEndTimeCheck(timestampStart, timestampEnd); err != nil { return nil, fmt.Errorf("invalid time range supplied. Start: %v End %v %w", timestampStart, timestampEnd, err) } var err error p, err = f.FormatExchangeCurrency(p, assetType) if err != nil { return nil, err } endTime := timestampEnd var resp []trade.Data allTrades: for { var trades []TradeData trades, err = f.GetTrades(ctx, p.String(), timestampStart.Unix(), endTime.Unix(), 0) if err != nil { if errors.Is(err, errStartTimeCannotBeAfterEndTime) { break } return nil, err } if len(trades) == 0 { break } for i := 0; i < len(trades); i++ { if timestampStart.Equal(trades[i].Time) || trades[i].Time.Before(timestampStart) { // reached end of trades to crawl break allTrades } if trades[i].Time.After(endTime) { continue } var side order.Side side, err = order.StringToOrderSide(trades[i].Side) if err != nil { return nil, err } resp = append(resp, trade.Data{ TID: strconv.FormatInt(trades[i].ID, 10), Exchange: f.Name, CurrencyPair: p, AssetType: assetType, Side: side, Price: trades[i].Price, Amount: trades[i].Size, Timestamp: trades[i].Time, }) } endTime = trades[len(trades)-1].Time } err = f.AddTradesToBuffer(resp...) if err != nil { return nil, err } sort.Sort(trade.ByDate(resp)) return trade.FilterTradesByTime(resp, timestampStart, timestampEnd), nil } // SubmitOrder submits a new order func (f *FTX) SubmitOrder(ctx context.Context, s *order.Submit) (order.SubmitResponse, error) { var resp order.SubmitResponse if err := s.Validate(); err != nil { return resp, err } if s.Side == order.Ask { s.Side = order.Sell } if s.Side == order.Bid { s.Side = order.Buy } fPair, err := f.FormatExchangeCurrency(s.Pair, s.AssetType) if err != nil { return resp, err } tempResp, err := f.Order(ctx, fPair.String(), s.Side.Lower(), s.Type.Lower(), s.ReduceOnly, s.ImmediateOrCancel, s.PostOnly, s.ClientOrderID, s.Price, s.Amount) if err != nil { return resp, err } resp.IsOrderPlaced = true resp.OrderID = strconv.FormatInt(tempResp.ID, 10) return resp, nil } // ModifyOrder will allow of changing orderbook placement and limit to // market conversion func (f *FTX) ModifyOrder(ctx context.Context, action *order.Modify) (order.Modify, error) { if err := action.Validate(); err != nil { return order.Modify{}, err } if action.TriggerPrice != 0 { a, err := f.ModifyTriggerOrder(ctx, action.ID, action.Type.String(), action.Amount, action.TriggerPrice, action.Price, 0) if err != nil { return order.Modify{}, err } return order.Modify{ Exchange: action.Exchange, AssetType: action.AssetType, Pair: action.Pair, ID: strconv.FormatInt(a.ID, 10), Price: action.Price, Amount: action.Amount, TriggerPrice: action.TriggerPrice, Type: action.Type, }, err } var o OrderData var err error if action.ID == "" { o, err = f.ModifyOrderByClientID(ctx, action.ClientOrderID, action.ClientOrderID, action.Price, action.Amount) if err != nil { return order.Modify{}, err } } else { o, err = f.ModifyPlacedOrder(ctx, action.ID, action.ClientOrderID, action.Price, action.Amount) if err != nil { return order.Modify{}, err } } return order.Modify{ Exchange: action.Exchange, AssetType: action.AssetType, Pair: action.Pair, ID: strconv.FormatInt(o.ID, 10), Price: action.Price, Amount: action.Amount, }, err } // CancelOrder cancels an order by its corresponding ID number func (f *FTX) CancelOrder(ctx context.Context, o *order.Cancel) error { if err := o.Validate(o.StandardCancel()); err != nil { return err } if o.ClientOrderID != "" { _, err := f.DeleteOrderByClientID(ctx, o.ClientOrderID) return err } _, err := f.DeleteOrder(ctx, o.ID) return err } // CancelBatchOrders cancels an orders by their corresponding ID numbers func (f *FTX) CancelBatchOrders(ctx context.Context, o []order.Cancel) (order.CancelBatchResponse, error) { return order.CancelBatchResponse{}, common.ErrNotYetImplemented } // CancelAllOrders cancels all orders associated with a currency pair func (f *FTX) CancelAllOrders(ctx context.Context, orderCancellation *order.Cancel) (order.CancelAllResponse, error) { if err := orderCancellation.Validate(); err != nil { return order.CancelAllResponse{}, err } var resp order.CancelAllResponse formattedPair, err := f.FormatExchangeCurrency(orderCancellation.Pair, orderCancellation.AssetType) if err != nil { return resp, err } orders, err := f.GetOpenOrders(ctx, formattedPair.String()) if err != nil { return resp, err } tempMap := make(map[string]string) for x := range orders { _, err := f.DeleteOrder(ctx, strconv.FormatInt(orders[x].ID, 10)) if err != nil { tempMap[strconv.FormatInt(orders[x].ID, 10)] = "Cancellation Failed" continue } tempMap[strconv.FormatInt(orders[x].ID, 10)] = "Success" } resp.Status = tempMap return resp, nil } // GetCompatible gets compatible variables for order vars func (s *OrderData) GetCompatible(ctx context.Context, f *FTX) (OrderVars, error) { var resp OrderVars switch s.Side { case order.Buy.Lower(): resp.Side = order.Buy case order.Sell.Lower(): resp.Side = order.Sell default: resp.Side = order.UnknownSide } switch s.Status { case strings.ToLower(order.New.String()): resp.Status = order.New case strings.ToLower(order.Open.String()): resp.Status = order.Open case closedStatus: if s.FilledSize != 0 && s.FilledSize != s.Size { resp.Status = order.PartiallyCancelled } if s.FilledSize == 0 { resp.Status = order.Cancelled } if s.FilledSize == s.Size { resp.Status = order.Filled } default: resp.Status = order.AnyStatus } var feeBuilder exchange.FeeBuilder feeBuilder.PurchasePrice = s.AvgFillPrice feeBuilder.Amount = s.Size resp.OrderType = order.Market if strings.EqualFold(s.OrderType, order.Limit.String()) { resp.OrderType = order.Limit feeBuilder.IsMaker = true } fee, err := f.GetFee(ctx, &feeBuilder) if err != nil { return resp, err } resp.Fee = fee return resp, nil } // GetOrderInfo returns order information based on order ID func (f *FTX) GetOrderInfo(ctx context.Context, orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) { var resp order.Detail orderData, err := f.GetOrderStatus(ctx, orderID) if err != nil { return resp, err } p, err := currency.NewPairFromString(orderData.Market) if err != nil { return resp, err } orderAssetType, err := f.GetPairAssetType(p) if err != nil { return resp, err } resp.ID = strconv.FormatInt(orderData.ID, 10) resp.Amount = orderData.Size resp.ClientOrderID = orderData.ClientID resp.Date = orderData.CreatedAt resp.Exchange = f.Name resp.ExecutedAmount = orderData.Size - orderData.RemainingSize resp.Pair = p resp.AssetType = orderAssetType if orderData.Price == 0.0 { resp.Price = orderData.AvgFillPrice } else { resp.Price = orderData.Price } resp.RemainingAmount = orderData.RemainingSize orderVars, err := orderData.GetCompatible(ctx, f) if err != nil { return resp, err } resp.Status = orderVars.Status resp.Side = orderVars.Side resp.Type = orderVars.OrderType resp.Fee = orderVars.Fee return resp, nil } // GetDepositAddress returns a deposit address for a specified currency func (f *FTX) GetDepositAddress(ctx context.Context, cryptocurrency currency.Code, _, chain string) (*deposit.Address, error) { a, err := f.FetchDepositAddress(ctx, cryptocurrency, chain) if err != nil { return nil, err } return &deposit.Address{ Address: a.Address, Tag: a.Tag, }, nil } // WithdrawCryptocurrencyFunds returns a withdrawal ID when a withdrawal is // submitted func (f *FTX) WithdrawCryptocurrencyFunds(ctx context.Context, withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error) { if err := withdrawRequest.Validate(); err != nil { return nil, err } resp, err := f.Withdraw(ctx, withdrawRequest.Currency, withdrawRequest.Crypto.Address, withdrawRequest.Crypto.AddressTag, withdrawRequest.TradePassword, withdrawRequest.Crypto.Chain, strconv.FormatInt(withdrawRequest.OneTimePassword, 10), withdrawRequest.Amount) if err != nil { return nil, err } return &withdraw.ExchangeResponse{ ID: strconv.FormatInt(resp.ID, 10), Status: resp.Status, }, nil } // WithdrawFiatFunds returns a withdrawal ID when a withdrawal is // submitted func (f *FTX) WithdrawFiatFunds(_ context.Context, _ *withdraw.Request) (*withdraw.ExchangeResponse, error) { return nil, common.ErrFunctionNotSupported } // WithdrawFiatFundsToInternationalBank returns a withdrawal ID when a // withdrawal is submitted func (f *FTX) WithdrawFiatFundsToInternationalBank(_ context.Context, _ *withdraw.Request) (*withdraw.ExchangeResponse, error) { return nil, common.ErrFunctionNotSupported } // GetWebsocket returns a pointer to the exchange websocket func (f *FTX) GetWebsocket() (*stream.Websocket, error) { return f.Websocket, nil } // GetActiveOrders retrieves any orders that are active/open func (f *FTX) GetActiveOrders(ctx context.Context, getOrdersRequest *order.GetOrdersRequest) ([]order.Detail, error) { if err := getOrdersRequest.Validate(); err != nil { return nil, err } var resp []order.Detail for x := range getOrdersRequest.Pairs { assetType, err := f.GetPairAssetType(getOrdersRequest.Pairs[x]) if err != nil { return resp, err } formattedPair, err := f.FormatExchangeCurrency(getOrdersRequest.Pairs[x], assetType) if err != nil { return nil, err } var tempResp order.Detail orderData, err := f.GetOpenOrders(ctx, formattedPair.String()) if err != nil { return resp, err } for y := range orderData { var p currency.Pair p, err = currency.NewPairFromString(orderData[y].Market) if err != nil { return nil, err } tempResp.ID = strconv.FormatInt(orderData[y].ID, 10) tempResp.Amount = orderData[y].Size tempResp.AssetType = assetType tempResp.ClientOrderID = orderData[y].ClientID tempResp.Date = orderData[y].CreatedAt tempResp.Exchange = f.Name tempResp.ExecutedAmount = orderData[y].Size - orderData[y].RemainingSize tempResp.Pair = p tempResp.Price = orderData[y].Price tempResp.RemainingAmount = orderData[y].RemainingSize var orderVars OrderVars orderVars, err = f.compatibleOrderVars(ctx, orderData[y].Side, orderData[y].Status, orderData[y].OrderType, orderData[y].Size, orderData[y].FilledSize, orderData[y].AvgFillPrice) if err != nil { return resp, err } tempResp.Status = orderVars.Status tempResp.Side = orderVars.Side tempResp.Type = orderVars.OrderType tempResp.Fee = orderVars.Fee resp = append(resp, tempResp) } triggerOrderData, err := f.GetOpenTriggerOrders(ctx, formattedPair.String(), getOrdersRequest.Type.String()) if err != nil { return resp, err } for z := range triggerOrderData { var p currency.Pair p, err = currency.NewPairFromString(triggerOrderData[z].Market) if err != nil { return nil, err } tempResp.ID = strconv.FormatInt(triggerOrderData[z].ID, 10) tempResp.Amount = triggerOrderData[z].Size tempResp.AssetType = assetType tempResp.Date = triggerOrderData[z].CreatedAt tempResp.Exchange = f.Name tempResp.ExecutedAmount = triggerOrderData[z].FilledSize tempResp.Pair = p tempResp.Price = triggerOrderData[z].AvgFillPrice tempResp.RemainingAmount = triggerOrderData[z].Size - triggerOrderData[z].FilledSize tempResp.TriggerPrice = triggerOrderData[z].TriggerPrice orderVars, err := f.compatibleOrderVars(ctx, triggerOrderData[z].Side, triggerOrderData[z].Status, triggerOrderData[z].OrderType, triggerOrderData[z].Size, triggerOrderData[z].FilledSize, triggerOrderData[z].AvgFillPrice) if err != nil { return resp, err } tempResp.Status = orderVars.Status tempResp.Side = orderVars.Side tempResp.Type = orderVars.OrderType tempResp.Fee = orderVars.Fee resp = append(resp, tempResp) } } return resp, nil } // GetOrderHistory retrieves account order information // Can Limit response to specific order status func (f *FTX) GetOrderHistory(ctx context.Context, getOrdersRequest *order.GetOrdersRequest) ([]order.Detail, error) { if err := getOrdersRequest.Validate(); err != nil { return nil, err } var resp []order.Detail for x := range getOrdersRequest.Pairs { var tempResp order.Detail assetType, err := f.GetPairAssetType(getOrdersRequest.Pairs[x]) if err != nil { return resp, err } formattedPair, err := f.FormatExchangeCurrency(getOrdersRequest.Pairs[x], assetType) if err != nil { return nil, err } orderData, err := f.FetchOrderHistory(ctx, formattedPair.String(), getOrdersRequest.StartTime, getOrdersRequest.EndTime, "") if err != nil { return resp, err } for y := range orderData { var p currency.Pair p, err = currency.NewPairFromString(orderData[y].Market) if err != nil { return nil, err } tempResp.ID = strconv.FormatInt(orderData[y].ID, 10) tempResp.Amount = orderData[y].Size tempResp.AssetType = assetType tempResp.AverageExecutedPrice = orderData[y].AvgFillPrice tempResp.ClientOrderID = orderData[y].ClientID tempResp.Date = orderData[y].CreatedAt tempResp.Exchange = f.Name tempResp.ExecutedAmount = orderData[y].Size - orderData[y].RemainingSize tempResp.Pair = p tempResp.Price = orderData[y].Price tempResp.RemainingAmount = orderData[y].RemainingSize var orderVars OrderVars orderVars, err = f.compatibleOrderVars(ctx, orderData[y].Side, orderData[y].Status, orderData[y].OrderType, orderData[y].Size, orderData[y].FilledSize, orderData[y].AvgFillPrice) if err != nil { return resp, err } tempResp.Status = orderVars.Status tempResp.Side = orderVars.Side tempResp.Type = orderVars.OrderType tempResp.Fee = orderVars.Fee resp = append(resp, tempResp) } triggerOrderData, err := f.GetTriggerOrderHistory(ctx, formattedPair.String(), getOrdersRequest.StartTime, getOrdersRequest.EndTime, strings.ToLower(getOrdersRequest.Side.String()), strings.ToLower(getOrdersRequest.Type.String()), "") if err != nil { return resp, err } for z := range triggerOrderData { var p currency.Pair p, err = currency.NewPairFromString(triggerOrderData[z].Market) if err != nil { return nil, err } tempResp.ID = strconv.FormatInt(triggerOrderData[z].ID, 10) tempResp.Amount = triggerOrderData[z].Size tempResp.AssetType = assetType tempResp.Date = triggerOrderData[z].CreatedAt tempResp.Exchange = f.Name tempResp.ExecutedAmount = triggerOrderData[z].FilledSize tempResp.Pair = p tempResp.Price = triggerOrderData[z].AvgFillPrice tempResp.RemainingAmount = triggerOrderData[z].Size - triggerOrderData[z].FilledSize tempResp.TriggerPrice = triggerOrderData[z].TriggerPrice orderVars, err := f.compatibleOrderVars(ctx, triggerOrderData[z].Side, triggerOrderData[z].Status, triggerOrderData[z].OrderType, triggerOrderData[z].Size, triggerOrderData[z].FilledSize, triggerOrderData[z].AvgFillPrice) if err != nil { return resp, err } tempResp.Status = orderVars.Status tempResp.Side = orderVars.Side tempResp.Type = orderVars.OrderType tempResp.Fee = orderVars.Fee tempResp.InferCostsAndTimes() resp = append(resp, tempResp) } } return resp, nil } // GetFeeByType returns an estimate of fee based on the type of transaction func (f *FTX) GetFeeByType(ctx context.Context, feeBuilder *exchange.FeeBuilder) (float64, error) { if feeBuilder == nil { return 0, fmt.Errorf("%T %w", feeBuilder, common.ErrNilPointer) } return f.GetFee(ctx, feeBuilder) } // SubscribeToWebsocketChannels appends to ChannelsToSubscribe // which lets websocket.manageSubscriptions handle subscribing func (f *FTX) SubscribeToWebsocketChannels(channels []stream.ChannelSubscription) error { return f.Websocket.SubscribeToChannels(channels) } // UnsubscribeToWebsocketChannels removes from ChannelsToSubscribe // which lets websocket.manageSubscriptions handle unsubscribing func (f *FTX) UnsubscribeToWebsocketChannels(channels []stream.ChannelSubscription) error { return f.Websocket.UnsubscribeChannels(channels) } // AuthenticateWebsocket sends an authentication message to the websocket func (f *FTX) AuthenticateWebsocket(_ context.Context) error { return f.WsAuth() } // ValidateCredentials validates current credentials used for wrapper // functionality func (f *FTX) ValidateCredentials(ctx context.Context, assetType asset.Item) error { _, err := f.UpdateAccountInfo(ctx, assetType) return f.CheckTransientError(err) } // GetHistoricCandles returns candles between a time period for a set time interval func (f *FTX) GetHistoricCandles(ctx context.Context, p currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) { if err := f.ValidateKline(p, a, interval); err != nil { return kline.Item{}, err } formattedPair, err := f.FormatExchangeCurrency(p, a) if err != nil { return kline.Item{}, err } ohlcData, err := f.GetHistoricalData(ctx, formattedPair.String(), int64(interval.Duration().Seconds()), int64(f.Features.Enabled.Kline.ResultLimit), start, end) if err != nil { return kline.Item{}, err } ret := kline.Item{ Exchange: f.Name, Pair: p, Asset: a, Interval: interval, } for x := range ohlcData { ret.Candles = append(ret.Candles, kline.Candle{ Time: ohlcData[x].StartTime, Open: ohlcData[x].Open, High: ohlcData[x].High, Low: ohlcData[x].Low, Close: ohlcData[x].Close, Volume: ohlcData[x].Volume, }) } return ret, nil } // GetHistoricCandlesExtended returns candles between a time period for a set time interval func (f *FTX) GetHistoricCandlesExtended(ctx context.Context, p currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) { if err := f.ValidateKline(p, a, interval); err != nil { return kline.Item{}, err } ret := kline.Item{ Exchange: f.Name, Pair: p, Asset: a, Interval: interval, } dates, err := kline.CalculateCandleDateRanges(start, end, interval, f.Features.Enabled.Kline.ResultLimit) if err != nil { return kline.Item{}, err } formattedPair, err := f.FormatExchangeCurrency(p, a) if err != nil { return kline.Item{}, err } for x := range dates.Ranges { var ohlcData []OHLCVData ohlcData, err = f.GetHistoricalData(ctx, formattedPair.String(), int64(interval.Duration().Seconds()), int64(f.Features.Enabled.Kline.ResultLimit), dates.Ranges[x].Start.Time, dates.Ranges[x].End.Time) if err != nil { return kline.Item{}, err } for i := range ohlcData { ret.Candles = append(ret.Candles, kline.Candle{ Time: ohlcData[i].StartTime, Open: ohlcData[i].Open, High: ohlcData[i].High, Low: ohlcData[i].Low, Close: ohlcData[i].Close, Volume: ohlcData[i].Volume, }) } } dates.SetHasDataFromCandles(ret.Candles) summary := dates.DataSummary(false) if len(summary) > 0 { log.Warnf(log.ExchangeSys, "%v - %v", f.Name, summary) } ret.RemoveDuplicates() ret.RemoveOutsideRange(start, end) ret.SortCandlesByTimestamp(false) return ret, nil } // UpdateOrderExecutionLimits sets exchange executions for a required asset type func (f *FTX) UpdateOrderExecutionLimits(ctx context.Context, _ asset.Item) error { limits, err := f.FetchExchangeLimits(ctx) if err != nil { return fmt.Errorf("cannot update exchange execution limits: %w", err) } return f.LoadLimits(limits) } // GetAvailableTransferChains returns the available transfer blockchains for the specific // cryptocurrency func (f *FTX) GetAvailableTransferChains(ctx context.Context, cryptocurrency currency.Code) ([]string, error) { coins, err := f.GetCoins(ctx) if err != nil { return nil, err } var availableChains []string for x := range coins { if strings.EqualFold(coins[x].ID, cryptocurrency.String()) { for y := range coins[x].Methods { availableChains = append(availableChains, coins[x].Methods[y]) } } } return availableChains, nil } <file_sep>package account import ( "sync" "testing" "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/dispatch" "github.com/idoall/gocryptotrader/exchanges/asset" ) func TestHoldings(t *testing.T) { err := dispatch.Start(dispatch.DefaultMaxWorkers, dispatch.DefaultJobsLimit) if err != nil { t.Fatal(err) } err = Process(nil) if err == nil { t.Error("error cannot be nil") } err = Process(&Holdings{}) if err == nil { t.Error("error cannot be nil") } holdings := Holdings{ Exchange: "Test", } err = Process(&holdings) if err != nil { t.Error(err) } err = Process(&Holdings{ Exchange: "Test", Accounts: []SubAccount{{ AssetType: asset.Spot, ID: "1337", Currencies: []Balance{ { CurrencyName: currency.BTC, TotalValue: 100, Hold: 20, }, }, }}, }) if err != nil { t.Error(err) } _, err = GetHoldings("", asset.Spot) if err == nil { t.Error("error cannot be nil") } _, err = GetHoldings("bla", asset.Spot) if err == nil { t.Error("error cannot be nil") } _, err = GetHoldings("bla", asset.Item("hi")) if err == nil { t.Error("error cannot be nil since an invalid asset type is provided") } u, err := GetHoldings("Test", asset.Spot) if err != nil { t.Error(err) } if u.Accounts[0].ID != "1337" { t.Errorf("expecting 1337 but received %s", u.Accounts[0].ID) } if u.Accounts[0].Currencies[0].CurrencyName != currency.BTC { t.Errorf("expecting BTC but received %s", u.Accounts[0].Currencies[0].CurrencyName) } if u.Accounts[0].Currencies[0].TotalValue != 100 { t.Errorf("expecting 100 but received %f", u.Accounts[0].Currencies[0].TotalValue) } if u.Accounts[0].Currencies[0].Hold != 20 { t.Errorf("expecting 20 but received %f", u.Accounts[0].Currencies[0].Hold) } _, err = SubscribeToExchangeAccount("nonsense") if err == nil { t.Fatal("error cannot be nil") } p, err := SubscribeToExchangeAccount("Test") if err != nil { t.Fatal(err) } var wg sync.WaitGroup wg.Add(1) go func(p dispatch.Pipe, wg *sync.WaitGroup) { for i := 0; i < 2; i++ { c := time.NewTimer(time.Second) select { case <-p.C: case <-c.C: } } wg.Done() }(p, &wg) err = Process(&Holdings{ Exchange: "Test", Accounts: []SubAccount{{ ID: "1337", Currencies: []Balance{ { CurrencyName: currency.BTC, TotalValue: 100000, Hold: 20, }, }, }}, }) if err != nil { t.Error(err) } wg.Wait() } func TestBalance_Available(t *testing.T) { t.Parallel() b := Balance{ CurrencyName: currency.BTC, TotalValue: 16, Hold: 0, } if have := b.Available(); have != 16 { t.Errorf("have %f, want 16", have) } b.Hold = 8 if have := b.Available(); have != 8 { t.Errorf("have %f, want 8", have) } b.Hold = 16 if have := b.Available(); have != 0 { t.Errorf("have %f, want 0", have) } } <file_sep>package signal import ( "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) // Event handler is used for getting trade signal details // Example Amount and Price of current candle tick type Event interface { common.EventHandler common.Directioner GetPrice() decimal.Decimal IsSignal() bool GetSellLimit() decimal.Decimal GetBuyLimit() decimal.Decimal } // Signal contains everything needed for a strategy to raise a signal event type Signal struct { event.Base OpenPrice decimal.Decimal HighPrice decimal.Decimal LowPrice decimal.Decimal ClosePrice decimal.Decimal Volume decimal.Decimal BuyLimit decimal.Decimal SellLimit decimal.Decimal Direction order.Side } <file_sep>package signal import ( "testing" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) func TestIsSignal(t *testing.T) { t.Parallel() s := Signal{} if !s.IsSignal() { t.Error("expected true") } } func TestSetDirection(t *testing.T) { t.Parallel() s := Signal{Direction: gctorder.Sell} s.SetDirection(gctorder.Buy) if s.GetDirection() != gctorder.Buy { t.Error("expected buy") } } func TestSetPrice(t *testing.T) { t.Parallel() s := Signal{ ClosePrice: decimal.NewFromInt(1), } s.SetPrice(decimal.NewFromInt(1337)) if !s.GetPrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestSetBuyLimit(t *testing.T) { t.Parallel() s := Signal{ BuyLimit: decimal.NewFromInt(10), } s.SetBuyLimit(decimal.NewFromInt(20)) if !s.GetBuyLimit().Equal(decimal.NewFromInt(20)) { t.Errorf("expected 20, received %v", s.GetBuyLimit()) } } func TestSetSellLimit(t *testing.T) { t.Parallel() s := Signal{ SellLimit: decimal.NewFromInt(10), } s.SetSellLimit(decimal.NewFromInt(20)) if !s.GetSellLimit().Equal(decimal.NewFromInt(20)) { t.Errorf("expected 20, received %v", s.GetSellLimit()) } } <file_sep>package hitbtc import ( "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/exchanges/kline" ) // GetKlines checks and returns a requested kline if it exists func (b *HitBTC) GetKlines(arg interface{}) ([]*kline.Kline, error) { var klines []*kline.Kline return klines, common.ErrFunctionNotSupported } <file_sep>package currency import ( "encoding/json" "errors" "fmt" "io/ioutil" "path/filepath" "time" "github.com/idoall/gocryptotrader/common/file" "github.com/idoall/gocryptotrader/currency/coinmarketcap" "github.com/idoall/gocryptotrader/currency/forexprovider" "github.com/idoall/gocryptotrader/currency/forexprovider/base" "github.com/idoall/gocryptotrader/log" ) func init() { storage.SetDefaults() } // SetDefaults sets storage defaults for basic package functionality func (s *Storage) SetDefaults() { s.defaultBaseCurrency = USD s.baseCurrency = s.defaultBaseCurrency var fiatCurrencies []Code for item := range symbols { if item == USDT.Item { continue } fiatCurrencies = append(fiatCurrencies, Code{Item: item, UpperCase: true}) } err := s.SetDefaultFiatCurrencies(fiatCurrencies...) if err != nil { log.Errorf(log.Global, "Currency Storage: Setting default fiat currencies error: %s", err) } err = s.SetDefaultCryptocurrencies(BTC, LTC, ETH, DOGE, DASH, XRP, XMR, USDT, UST) if err != nil { log.Errorf(log.Global, "Currency Storage: Setting default cryptocurrencies error: %s", err) } s.SetupConversionRates() s.fiatExchangeMarkets = forexprovider.NewDefaultFXProvider() } // RunUpdater runs the foreign exchange updater service. This will set up a JSON // dump file and keep foreign exchange rates updated as fast as possible without // triggering rate limiters, it will also run a full cryptocurrency check // through coin market cap and expose analytics for exchange services func (s *Storage) RunUpdater(overrides BotOverrides, settings *MainConfiguration, filePath string) error { s.mtx.Lock() s.shutdown = make(chan struct{}) // 判断是否有数据 if !settings.Cryptocurrencies.HasData() { s.mtx.Unlock() return errors.New("currency storage error, no cryptocurrencies loaded") } // 获取配置文件中的 s.cryptocurrencies = settings.Cryptocurrencies // 判断是否设置了法币 if settings.FiatDisplayCurrency.IsEmpty() { s.mtx.Unlock() return errors.New("currency storage error, no fiat display currency set in config") } s.baseCurrency = settings.FiatDisplayCurrency log.Debugf(log.Global, "Fiat display currency: %s.\n", s.baseCurrency) if settings.CryptocurrencyProvider.Enabled { log.Debugln(log.Global, "Setting up currency analysis system with Coinmarketcap...") c := &coinmarketcap.Coinmarketcap{} // 设置 CoinMarketCap 的基本信息 c.SetDefaults() // 根据传入的配置,再次设置 CoinMarketCap 配置 err := c.Setup(coinmarketcap.Settings{ Name: settings.CryptocurrencyProvider.Name, Enabled: settings.CryptocurrencyProvider.Enabled, AccountPlan: settings.CryptocurrencyProvider.AccountPlan, APIkey: settings.CryptocurrencyProvider.APIkey, Verbose: settings.CryptocurrencyProvider.Verbose, }) if err != nil { log.Errorf(log.Global, "Unable to setup CoinMarketCap analysis. Error: %s", err) settings.CryptocurrencyProvider.Enabled = false } else { s.currencyAnalysis = c } } if filePath == "" { s.mtx.Unlock() return errors.New("currency package runUpdater error filepath not set") } s.path = filepath.Join(filePath, DefaultStorageFile) if settings.CurrencyDelay.Nanoseconds() == 0 { s.currencyFileUpdateDelay = DefaultCurrencyFileDelay } else { s.currencyFileUpdateDelay = settings.CurrencyDelay } if settings.FxRateDelay.Nanoseconds() == 0 { s.foreignExchangeUpdateDelay = DefaultForeignExchangeDelay } else { s.foreignExchangeUpdateDelay = settings.FxRateDelay } var fxSettings []base.Settings for i := range settings.ForexProviders { switch settings.ForexProviders[i].Name { case "CurrencyConverter": if overrides.FxCurrencyConverter || settings.ForexProviders[i].Enabled { settings.ForexProviders[i].Enabled = true fxSettings = append(fxSettings, base.Settings(settings.ForexProviders[i])) } case "CurrencyLayer": if overrides.FxCurrencyLayer || settings.ForexProviders[i].Enabled { settings.ForexProviders[i].Enabled = true fxSettings = append(fxSettings, base.Settings(settings.ForexProviders[i])) } case "Fixer": if overrides.FxFixer || settings.ForexProviders[i].Enabled { settings.ForexProviders[i].Enabled = true fxSettings = append(fxSettings, base.Settings(settings.ForexProviders[i])) } case "OpenExchangeRates": if overrides.FxOpenExchangeRates || settings.ForexProviders[i].Enabled { settings.ForexProviders[i].Enabled = true fxSettings = append(fxSettings, base.Settings(settings.ForexProviders[i])) } case "ExchangeRates": // TODO ADD OVERRIDE if settings.ForexProviders[i].Enabled { settings.ForexProviders[i].Enabled = true fxSettings = append(fxSettings, base.Settings(settings.ForexProviders[i])) } case "ExchangeRateHost": if overrides.FxExchangeRateHost || settings.ForexProviders[i].Enabled { settings.ForexProviders[i].Enabled = true fxSettings = append(fxSettings, base.Settings(settings.ForexProviders[i])) } } } if len(fxSettings) != 0 { var err error s.fiatExchangeMarkets, err = forexprovider.StartFXService(fxSettings) if err != nil { s.mtx.Unlock() return err } log.Debugf(log.Global, "Primary foreign exchange conversion provider %s enabled\n", s.fiatExchangeMarkets.Primary.Provider.GetName()) for i := range s.fiatExchangeMarkets.Support { log.Debugf(log.Global, "Support forex conversion provider %s enabled\n", s.fiatExchangeMarkets.Support[i].Provider.GetName()) } // Mutex present in this go routine to lock down retrieving rate data // until this system initially updates go s.ForeignExchangeUpdater() } else { log.Warnln(log.Global, "No foreign exchange providers enabled in config.json") s.mtx.Unlock() } return nil } // SetupConversionRates sets default conversion rate values func (s *Storage) SetupConversionRates() { s.fxRates = ConversionRates{ m: make(map[*Item]map[*Item]*float64), } } // SetDefaultFiatCurrencies assigns the default fiat currency list and adds it // to the running list func (s *Storage) SetDefaultFiatCurrencies(c ...Code) error { for i := range c { err := s.currencyCodes.UpdateCurrency("", c[i].String(), "", 0, Fiat) if err != nil { return err } } s.defaultFiatCurrencies = append(s.defaultFiatCurrencies, c...) s.fiatCurrencies = append(s.fiatCurrencies, c...) return nil } // SetDefaultCryptocurrencies assigns the default cryptocurrency list and adds // it to the running list func (s *Storage) SetDefaultCryptocurrencies(c ...Code) error { for i := range c { err := s.currencyCodes.UpdateCurrency("", c[i].String(), "", 0, Cryptocurrency) if err != nil { return err } } s.defaultCryptoCurrencies = append(s.defaultCryptoCurrencies, c...) s.cryptocurrencies = append(s.cryptocurrencies, c...) return nil } // SetupForexProviders sets up a new instance of the forex providers func (s *Storage) SetupForexProviders(setting ...base.Settings) error { addr, err := forexprovider.StartFXService(setting) if err != nil { return err } s.fiatExchangeMarkets = addr return nil } // ForeignExchangeUpdater is a routine that seeds foreign exchange rate and keeps // updated as fast as possible func (s *Storage) ForeignExchangeUpdater() { log.Debugln(log.Global, "Foreign exchange updater started, seeding FX rate list..") s.wg.Add(1) defer s.wg.Done() err := s.SeedCurrencyAnalysisData() if err != nil { log.Errorln(log.Global, err) } err = s.SeedForeignExchangeRates() if err != nil { log.Errorln(log.Global, err) } // Unlock main rate retrieval mutex so all routines waiting can get access // to data s.mtx.Unlock() // Set tickers to client defined rates or defaults SeedForeignExchangeTick := time.NewTicker(s.foreignExchangeUpdateDelay) SeedCurrencyAnalysisTick := time.NewTicker(s.currencyFileUpdateDelay) defer SeedForeignExchangeTick.Stop() defer SeedCurrencyAnalysisTick.Stop() for { select { case <-s.shutdown: return case <-SeedForeignExchangeTick.C: go func() { err := s.SeedForeignExchangeRates() if err != nil { log.Errorln(log.Global, err) } }() case <-SeedCurrencyAnalysisTick.C: go func() { err := s.SeedCurrencyAnalysisData() if err != nil { log.Errorln(log.Global, err) } }() } } } // SeedCurrencyAnalysisData sets a new instance of a coinmarketcap data. func (s *Storage) SeedCurrencyAnalysisData() error { if s.currencyCodes.LastMainUpdate.IsZero() { b, err := ioutil.ReadFile(s.path) if err != nil { return s.FetchCurrencyAnalysisData() } var f *File err = json.Unmarshal(b, &f) if err != nil { return err } err = s.LoadFileCurrencyData(f) if err != nil { return err } } // Based on update delay update the file if time.Now().After(s.currencyCodes.LastMainUpdate.Add(s.currencyFileUpdateDelay)) || s.currencyCodes.LastMainUpdate.IsZero() { err := s.FetchCurrencyAnalysisData() if err != nil { return err } } return nil } // FetchCurrencyAnalysisData fetches a new fresh batch of currency data and // loads it into memory func (s *Storage) FetchCurrencyAnalysisData() error { if s.currencyAnalysis == nil { log.Warnln(log.Global, "Currency analysis system offline, please set api keys for coinmarketcap if you wish to use this feature.") return errors.New("currency analysis system offline") } return s.UpdateCurrencies() } // WriteCurrencyDataToFile writes the full currency data to a designated file func (s *Storage) WriteCurrencyDataToFile(path string, mainUpdate bool) error { data, err := s.currencyCodes.GetFullCurrencyData() if err != nil { return err } if mainUpdate { t := time.Now() data.LastMainUpdate = t.Unix() s.currencyCodes.LastMainUpdate = t } var encoded []byte encoded, err = json.MarshalIndent(data, "", " ") if err != nil { return err } return file.Write(path, encoded) } // LoadFileCurrencyData loads currencies into the currency codes func (s *Storage) LoadFileCurrencyData(f *File) error { for i := range f.Contracts { contract := f.Contracts[i] contract.Role = Contract err := s.currencyCodes.LoadItem(&contract) if err != nil { return err } } for i := range f.Cryptocurrency { crypto := f.Cryptocurrency[i] crypto.Role = Cryptocurrency err := s.currencyCodes.LoadItem(&crypto) if err != nil { return err } } for i := range f.Token { token := f.Token[i] token.Role = Token err := s.currencyCodes.LoadItem(&token) if err != nil { return err } } for i := range f.FiatCurrency { fiat := f.FiatCurrency[i] fiat.Role = Fiat err := s.currencyCodes.LoadItem(&fiat) if err != nil { return err } } for i := range f.UnsetCurrency { unset := f.UnsetCurrency[i] unset.Role = Unset err := s.currencyCodes.LoadItem(&unset) if err != nil { return err } } switch t := f.LastMainUpdate.(type) { case string: parseT, err := time.Parse(time.RFC3339Nano, t) if err != nil { return err } s.currencyCodes.LastMainUpdate = parseT case float64: s.currencyCodes.LastMainUpdate = time.Unix(int64(t), 0) default: return errors.New("unhandled type conversion for LastMainUpdate time") } return nil } // UpdateCurrencies updates currency role and information using coin market cap func (s *Storage) UpdateCurrencies() error { m, err := s.currencyAnalysis.GetCryptocurrencyIDMap() if err != nil { return err } for x := range m { if m[x].IsActive != 1 { continue } if m[x].Platform.Symbol != "" { err = s.currencyCodes.UpdateCurrency(m[x].Name, m[x].Symbol, m[x].Platform.Symbol, m[x].ID, Token) if err != nil { return err } continue } err = s.currencyCodes.UpdateCurrency(m[x].Name, m[x].Symbol, "", m[x].ID, Cryptocurrency) if err != nil { return err } } return nil } // SeedForeignExchangeRatesByCurrencies seeds the foreign exchange rates by // currencies supplied func (s *Storage) SeedForeignExchangeRatesByCurrencies(c Currencies) error { s.fxRates.mtx.Lock() defer s.fxRates.mtx.Unlock() rates, err := s.fiatExchangeMarkets.GetCurrencyData(s.baseCurrency.String(), c.Strings()) if err != nil { return err } return s.updateExchangeRates(rates) } // SeedForeignExchangeRate returns a singular exchange rate func (s *Storage) SeedForeignExchangeRate(from, to Code) (map[string]float64, error) { return s.fiatExchangeMarkets.GetCurrencyData(from.String(), []string{to.String()}) } // GetDefaultForeignExchangeRates returns foreign exchange rates based off // default fiat currencies. func (s *Storage) GetDefaultForeignExchangeRates() (Conversions, error) { if !s.updaterRunning { err := s.SeedDefaultForeignExchangeRates() if err != nil { return nil, err } } return s.fxRates.GetFullRates(), nil } // SeedDefaultForeignExchangeRates seeds the default foreign exchange rates func (s *Storage) SeedDefaultForeignExchangeRates() error { s.fxRates.mtx.Lock() defer s.fxRates.mtx.Unlock() rates, err := s.fiatExchangeMarkets.GetCurrencyData( s.defaultBaseCurrency.String(), s.defaultFiatCurrencies.Strings()) if err != nil { return err } return s.updateExchangeRates(rates) } // GetExchangeRates returns storage seeded exchange rates func (s *Storage) GetExchangeRates() (Conversions, error) { if !s.updaterRunning { err := s.SeedForeignExchangeRates() if err != nil { return nil, err } } return s.fxRates.GetFullRates(), nil } // SeedForeignExchangeRates seeds the foreign exchange rates from storage config // currencies func (s *Storage) SeedForeignExchangeRates() error { s.fxRates.mtx.Lock() defer s.fxRates.mtx.Unlock() rates, err := s.fiatExchangeMarkets.GetCurrencyData(s.baseCurrency.String(), s.fiatCurrencies.Strings()) if err != nil { return err } return s.updateExchangeRates(rates) } // UpdateForeignExchangeRates sets exchange rates on the FX map func (s *Storage) updateExchangeRates(m map[string]float64) error { return s.fxRates.Update(m) } // SetupCryptoProvider sets congiguration parameters and starts a new instance // of the currency analyser func (s *Storage) SetupCryptoProvider(settings coinmarketcap.Settings) error { if settings.APIkey == "" || settings.APIkey == "key" || settings.AccountPlan == "" || settings.AccountPlan == "accountPlan" { return errors.New("currencyprovider error api key or plan not set in config.json") } s.currencyAnalysis = new(coinmarketcap.Coinmarketcap) s.currencyAnalysis.SetDefaults() return s.currencyAnalysis.Setup(settings) } // GetTotalMarketCryptocurrencies returns the total seeded market // cryptocurrencies func (s *Storage) GetTotalMarketCryptocurrencies() (Currencies, error) { if !s.currencyCodes.HasData() { return nil, errors.New("market currency codes not populated") } return s.currencyCodes.GetCurrencies(), nil } // IsDefaultCurrency returns if a currency is a default currency func (s *Storage) IsDefaultCurrency(c Code) bool { for i := range s.defaultFiatCurrencies { if s.defaultFiatCurrencies[i].Match(c) || s.defaultFiatCurrencies[i].Match(GetTranslation(c)) { return true } } return false } // IsDefaultCryptocurrency returns if a cryptocurrency is a default // cryptocurrency func (s *Storage) IsDefaultCryptocurrency(c Code) bool { for i := range s.defaultCryptoCurrencies { if s.defaultCryptoCurrencies[i].Match(c) || s.defaultCryptoCurrencies[i].Match(GetTranslation(c)) { return true } } return false } // IsFiatCurrency returns if a currency is part of the enabled fiat currency // list func (s *Storage) IsFiatCurrency(c Code) bool { if c.Item.Role != Unset { return c.Item.Role == Fiat } if c == USDT { return false } for i := range s.fiatCurrencies { if s.fiatCurrencies[i].Match(c) || s.fiatCurrencies[i].Match(GetTranslation(c)) { return true } } return false } // IsCryptocurrency returns if a cryptocurrency is part of the enabled // cryptocurrency list func (s *Storage) IsCryptocurrency(c Code) bool { if c.Item.Role != Unset { return c.Item.Role == Cryptocurrency } if c == USD { return false } for i := range s.cryptocurrencies { if s.cryptocurrencies[i].Match(c) || s.cryptocurrencies[i].Match(GetTranslation(c)) { return true } } return false } // ValidateCode validates string against currency list and returns a currency // code func (s *Storage) ValidateCode(newCode string) Code { return s.currencyCodes.Register(newCode) } // ValidateFiatCode validates a fiat currency string and returns a currency // code func (s *Storage) ValidateFiatCode(newCode string) Code { c := s.currencyCodes.RegisterFiat(newCode) if !s.fiatCurrencies.Contains(c) { s.fiatCurrencies = append(s.fiatCurrencies, c) } return c } // ValidateCryptoCode validates a cryptocurrency string and returns a currency // code // TODO: Update and add in RegisterCrypto member func func (s *Storage) ValidateCryptoCode(newCode string) Code { c := s.currencyCodes.Register(newCode) if !s.cryptocurrencies.Contains(c) { s.cryptocurrencies = append(s.cryptocurrencies, c) } return c } // UpdateBaseCurrency changes base currency func (s *Storage) UpdateBaseCurrency(c Code) error { if c.IsFiatCurrency() { s.baseCurrency = c return nil } return fmt.Errorf("currency %s not fiat failed to set currency", c) } // GetCryptocurrencies returns the cryptocurrency list func (s *Storage) GetCryptocurrencies() Currencies { return s.cryptocurrencies } // GetDefaultCryptocurrencies returns a list of default cryptocurrencies func (s *Storage) GetDefaultCryptocurrencies() Currencies { return s.defaultCryptoCurrencies } // GetFiatCurrencies returns the fiat currencies list func (s *Storage) GetFiatCurrencies() Currencies { return s.fiatCurrencies } // GetDefaultFiatCurrencies returns the default fiat currencies list func (s *Storage) GetDefaultFiatCurrencies() Currencies { return s.defaultFiatCurrencies } // GetDefaultBaseCurrency returns the default base currency func (s *Storage) GetDefaultBaseCurrency() Code { return s.defaultBaseCurrency } // GetBaseCurrency returns the current storage base currency func (s *Storage) GetBaseCurrency() Code { return s.baseCurrency } // UpdateEnabledCryptoCurrencies appends new cryptocurrencies to the enabled // currency list func (s *Storage) UpdateEnabledCryptoCurrencies(c Currencies) { for i := range c { if !s.cryptocurrencies.Contains(c[i]) { s.cryptocurrencies = append(s.cryptocurrencies, c[i]) } } } // UpdateEnabledFiatCurrencies appends new fiat currencies to the enabled // currency list func (s *Storage) UpdateEnabledFiatCurrencies(c Currencies) { for i := range c { if !s.fiatCurrencies.Contains(c[i]) && !s.cryptocurrencies.Contains(c[i]) { s.fiatCurrencies = append(s.fiatCurrencies, c[i]) } } } // ConvertCurrency for example converts $1 USD to the equivalent Japanese Yen // or vice versa. func (s *Storage) ConvertCurrency(amount float64, from, to Code) (float64, error) { s.mtx.Lock() defer s.mtx.Unlock() if !s.fxRates.HasData() { err := s.SeedDefaultForeignExchangeRates() if err != nil { return 0, err } } r, err := s.fxRates.GetRate(from, to) if err != nil { return 0, err } return r * amount, nil } // GetStorageRate returns the rate of the conversion value func (s *Storage) GetStorageRate(from, to Code) (float64, error) { s.mtx.Lock() defer s.mtx.Unlock() if !s.fxRates.HasData() { err := s.SeedDefaultForeignExchangeRates() if err != nil { return 0, err } } return s.fxRates.GetRate(from, to) } // NewConversion returns a new conversion object that has a pointer to a related // rate with its inversion. func (s *Storage) NewConversion(from, to Code) (Conversion, error) { s.mtx.Lock() defer s.mtx.Unlock() if !s.fxRates.HasData() { err := storage.SeedDefaultForeignExchangeRates() if err != nil { return Conversion{}, err } } return s.fxRates.Register(from, to) } // IsVerbose returns if the storage is in verbose mode func (s *Storage) IsVerbose() bool { return s.Verbose } // Shutdown shuts down the currency storage system and saves to currency.json func (s *Storage) Shutdown() error { s.mtx.Lock() defer s.mtx.Unlock() close(s.shutdown) s.wg.Wait() return s.WriteCurrencyDataToFile(s.path, true) } <file_sep>package signal import ( "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) // IsSignal returns whether the event is a signal type func (s *Signal) IsSignal() bool { return true } // SetDirection sets the direction func (s *Signal) SetDirection(st order.Side) { s.Direction = st } // GetDirection returns the direction func (s *Signal) GetDirection() order.Side { return s.Direction } // SetBuyLimit sets the buy limit func (s *Signal) SetBuyLimit(f decimal.Decimal) { s.BuyLimit = f } // GetBuyLimit returns the buy limit func (s *Signal) GetBuyLimit() decimal.Decimal { return s.BuyLimit } // SetSellLimit sets the sell limit func (s *Signal) SetSellLimit(f decimal.Decimal) { s.SellLimit = f } // GetSellLimit returns the sell limit func (s *Signal) GetSellLimit() decimal.Decimal { return s.SellLimit } // Pair returns the currency pair func (s *Signal) Pair() currency.Pair { return s.CurrencyPair } // GetPrice returns the price func (s *Signal) GetPrice() decimal.Decimal { return s.ClosePrice } // SetPrice sets the price func (s *Signal) SetPrice(f decimal.Decimal) { s.ClosePrice = f } <file_sep>package order import ( "errors" "fmt" "sort" "strings" "time" "github.com/gofrs/uuid" "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/validate" ) // Validate checks the supplied data and returns whether or not it's valid func (s *Submit) Validate(opt ...validate.Checker) error { if s == nil { return ErrSubmissionIsNil } if s.Pair.IsEmpty() { return ErrPairIsEmpty } if s.AssetType == "" { return ErrAssetNotSet } if s.Side != Buy && s.Side != Sell && s.Side != Bid && s.Side != Ask { return ErrSideIsInvalid } if s.Type != Market && s.Type != Limit { return ErrTypeIsInvalid } if s.Amount <= 0 { return fmt.Errorf("submit validation error %w, suppled: %.8f", ErrAmountIsInvalid, s.Amount) } if s.Type == Limit && s.Price <= 0 { return ErrPriceMustBeSetIfLimitOrder } for _, o := range opt { err := o.Check() if err != nil { return err } } return nil } // UpdateOrderFromDetail Will update an order detail (used in order management) // by comparing passed in and existing values func (d *Detail) UpdateOrderFromDetail(m *Detail) { var updated bool if d.ImmediateOrCancel != m.ImmediateOrCancel { d.ImmediateOrCancel = m.ImmediateOrCancel updated = true } if d.HiddenOrder != m.HiddenOrder { d.HiddenOrder = m.HiddenOrder updated = true } if d.FillOrKill != m.FillOrKill { d.FillOrKill = m.FillOrKill updated = true } if m.Price > 0 && m.Price != d.Price { d.Price = m.Price updated = true } if m.Amount > 0 && m.Amount != d.Amount { d.Amount = m.Amount updated = true } if m.LimitPriceUpper > 0 && m.LimitPriceUpper != d.LimitPriceUpper { d.LimitPriceUpper = m.LimitPriceUpper updated = true } if m.LimitPriceLower > 0 && m.LimitPriceLower != d.LimitPriceLower { d.LimitPriceLower = m.LimitPriceLower updated = true } if m.TriggerPrice > 0 && m.TriggerPrice != d.TriggerPrice { d.TriggerPrice = m.TriggerPrice updated = true } if m.TargetAmount > 0 && m.TargetAmount != d.TargetAmount { d.TargetAmount = m.TargetAmount updated = true } if m.ExecutedAmount > 0 && m.ExecutedAmount != d.ExecutedAmount { d.ExecutedAmount = m.ExecutedAmount updated = true } if m.Fee > 0 && m.Fee != d.Fee { d.Fee = m.Fee updated = true } if m.AccountID != "" && m.AccountID != d.AccountID { d.AccountID = m.AccountID updated = true } if m.PostOnly != d.PostOnly { d.PostOnly = m.PostOnly updated = true } if !m.Pair.IsEmpty() && m.Pair != d.Pair { d.Pair = m.Pair updated = true } if m.Leverage != 0 && m.Leverage != d.Leverage { d.Leverage = m.Leverage updated = true } if m.ClientID != "" && m.ClientID != d.ClientID { d.ClientID = m.ClientID updated = true } if m.WalletAddress != "" && m.WalletAddress != d.WalletAddress { d.WalletAddress = m.WalletAddress updated = true } if m.Type != "" && m.Type != d.Type { d.Type = m.Type updated = true } if m.Side != "" && m.Side != d.Side { d.Side = m.Side updated = true } if m.Status != "" && m.Status != d.Status { d.Status = m.Status updated = true } if m.AssetType != "" && m.AssetType != d.AssetType { d.AssetType = m.AssetType updated = true } if m.Trades != nil { for x := range m.Trades { var found bool for y := range d.Trades { if d.Trades[y].TID != m.Trades[x].TID { continue } found = true if d.Trades[y].Fee != m.Trades[x].Fee { d.Trades[y].Fee = m.Trades[x].Fee updated = true } if m.Trades[x].Price != 0 && d.Trades[y].Price != m.Trades[x].Price { d.Trades[y].Price = m.Trades[x].Price updated = true } if d.Trades[y].Side != m.Trades[x].Side { d.Trades[y].Side = m.Trades[x].Side updated = true } if d.Trades[y].Type != m.Trades[x].Type { d.Trades[y].Type = m.Trades[x].Type updated = true } if d.Trades[y].Description != m.Trades[x].Description { d.Trades[y].Description = m.Trades[x].Description updated = true } if m.Trades[x].Amount != 0 && d.Trades[y].Amount != m.Trades[x].Amount { d.Trades[y].Amount = m.Trades[x].Amount updated = true } if d.Trades[y].Timestamp != m.Trades[x].Timestamp { d.Trades[y].Timestamp = m.Trades[x].Timestamp updated = true } if d.Trades[y].IsMaker != m.Trades[x].IsMaker { d.Trades[y].IsMaker = m.Trades[x].IsMaker updated = true } } if !found { d.Trades = append(d.Trades, m.Trades[x]) updated = true } m.RemainingAmount -= m.Trades[x].Amount } } if m.RemainingAmount > 0 && m.RemainingAmount != d.RemainingAmount { d.RemainingAmount = m.RemainingAmount updated = true } if updated { if d.LastUpdated.Equal(m.LastUpdated) { d.LastUpdated = time.Now() } else { d.LastUpdated = m.LastUpdated } } if d.Exchange == "" { d.Exchange = m.Exchange } if d.ID == "" { d.ID = m.ID } if d.InternalOrderID == "" { d.InternalOrderID = m.InternalOrderID } } // UpdateOrderFromModify Will update an order detail (used in order management) // by comparing passed in and existing values func (d *Detail) UpdateOrderFromModify(m *Modify) { var updated bool if m.ID != "" && d.ID != m.ID { d.ID = m.ID updated = true } if d.ImmediateOrCancel != m.ImmediateOrCancel { d.ImmediateOrCancel = m.ImmediateOrCancel updated = true } if d.HiddenOrder != m.HiddenOrder { d.HiddenOrder = m.HiddenOrder updated = true } if d.FillOrKill != m.FillOrKill { d.FillOrKill = m.FillOrKill updated = true } if m.Price > 0 && m.Price != d.Price { d.Price = m.Price updated = true } if m.Amount > 0 && m.Amount != d.Amount { d.Amount = m.Amount updated = true } if m.LimitPriceUpper > 0 && m.LimitPriceUpper != d.LimitPriceUpper { d.LimitPriceUpper = m.LimitPriceUpper updated = true } if m.LimitPriceLower > 0 && m.LimitPriceLower != d.LimitPriceLower { d.LimitPriceLower = m.LimitPriceLower updated = true } if m.TriggerPrice > 0 && m.TriggerPrice != d.TriggerPrice { d.TriggerPrice = m.TriggerPrice updated = true } if m.TargetAmount > 0 && m.TargetAmount != d.TargetAmount { d.TargetAmount = m.TargetAmount updated = true } if m.ExecutedAmount > 0 && m.ExecutedAmount != d.ExecutedAmount { d.ExecutedAmount = m.ExecutedAmount updated = true } if m.Fee > 0 && m.Fee != d.Fee { d.Fee = m.Fee updated = true } if m.AccountID != "" && m.AccountID != d.AccountID { d.AccountID = m.AccountID updated = true } if m.PostOnly != d.PostOnly { d.PostOnly = m.PostOnly updated = true } if !m.Pair.IsEmpty() && m.Pair != d.Pair { d.Pair = m.Pair updated = true } if m.Leverage != 0 && m.Leverage != d.Leverage { d.Leverage = m.Leverage updated = true } if m.ClientID != "" && m.ClientID != d.ClientID { d.ClientID = m.ClientID updated = true } if m.WalletAddress != "" && m.WalletAddress != d.WalletAddress { d.WalletAddress = m.WalletAddress updated = true } if m.Type != "" && m.Type != d.Type { d.Type = m.Type updated = true } if m.Side != "" && m.Side != d.Side { d.Side = m.Side updated = true } if m.Status != "" && m.Status != d.Status { d.Status = m.Status updated = true } if m.AssetType != "" && m.AssetType != d.AssetType { d.AssetType = m.AssetType updated = true } if m.Trades != nil { for x := range m.Trades { var found bool for y := range d.Trades { if d.Trades[y].TID != m.Trades[x].TID { continue } found = true if d.Trades[y].Fee != m.Trades[x].Fee { d.Trades[y].Fee = m.Trades[x].Fee updated = true } if m.Trades[x].Price != 0 && d.Trades[y].Price != m.Trades[x].Price { d.Trades[y].Price = m.Trades[x].Price updated = true } if d.Trades[y].Side != m.Trades[x].Side { d.Trades[y].Side = m.Trades[x].Side updated = true } if d.Trades[y].Type != m.Trades[x].Type { d.Trades[y].Type = m.Trades[x].Type updated = true } if d.Trades[y].Description != m.Trades[x].Description { d.Trades[y].Description = m.Trades[x].Description updated = true } if m.Trades[x].Amount != 0 && d.Trades[y].Amount != m.Trades[x].Amount { d.Trades[y].Amount = m.Trades[x].Amount updated = true } if d.Trades[y].Timestamp != m.Trades[x].Timestamp { d.Trades[y].Timestamp = m.Trades[x].Timestamp updated = true } if d.Trades[y].IsMaker != m.Trades[x].IsMaker { d.Trades[y].IsMaker = m.Trades[x].IsMaker updated = true } } if !found { d.Trades = append(d.Trades, m.Trades[x]) updated = true } m.RemainingAmount -= m.Trades[x].Amount } } if m.RemainingAmount > 0 && m.RemainingAmount != d.RemainingAmount { d.RemainingAmount = m.RemainingAmount updated = true } if updated { if d.LastUpdated.Equal(m.LastUpdated) { d.LastUpdated = time.Now() } else { d.LastUpdated = m.LastUpdated } } } // MatchFilter will return true if a detail matches the filter criteria // empty elements are ignored func (d *Detail) MatchFilter(f *Filter) bool { if f.Exchange != "" && !strings.EqualFold(d.Exchange, f.Exchange) { return false } if f.AssetType != "" && d.AssetType != f.AssetType { return false } if !f.Pair.IsEmpty() && !d.Pair.Equal(f.Pair) { return false } if f.ID != "" && d.ID != f.ID { return false } if f.Type != "" && f.Type != AnyType && d.Type != f.Type { return false } if f.Side != "" && f.Side != AnySide && d.Side != f.Side { return false } if f.Status != "" && f.Status != AnyStatus && d.Status != f.Status { return false } if f.ClientOrderID != "" && d.ClientOrderID != f.ClientOrderID { return false } if f.ClientID != "" && d.ClientID != f.ClientID { return false } if f.InternalOrderID != "" && d.InternalOrderID != f.InternalOrderID { return false } if f.AccountID != "" && d.AccountID != f.AccountID { return false } if f.WalletAddress != "" && d.WalletAddress != f.WalletAddress { return false } return true } // IsActive returns true if an order has a status that indicates it is // currently available on the exchange func (d *Detail) IsActive() bool { if d.Amount <= 0 || d.Amount <= d.ExecutedAmount { return false } return d.Status == Active || d.Status == Open || d.Status == PartiallyFilled || d.Status == New || d.Status == AnyStatus || d.Status == PendingCancel || d.Status == Hidden || d.Status == UnknownStatus || d.Status == AutoDeleverage || d.Status == Pending } // IsInactive returns true if an order has a status that indicates it is // currently not available on the exchange func (d *Detail) IsInactive() bool { if d.Amount <= 0 || d.Amount <= d.ExecutedAmount { return true } return d.Status == Filled || d.Status == Cancelled || d.Status == InsufficientBalance || d.Status == MarketUnavailable || d.Status == Rejected || d.Status == PartiallyCancelled || d.Status == Expired || d.Status == Closed } // GenerateInternalOrderID sets a new V4 order ID or a V5 order ID if // the V4 function returns an error func (d *Detail) GenerateInternalOrderID() { if d.InternalOrderID == "" { var id uuid.UUID id, err := uuid.NewV4() if err != nil { id = uuid.NewV5(uuid.UUID{}, d.ID) } d.InternalOrderID = id.String() } } // Copy will return a copy of Detail func (d *Detail) Copy() Detail { c := *d if len(d.Trades) > 0 { c.Trades = make([]TradeHistory, len(d.Trades)) copy(c.Trades, d.Trades) } return c } // String implements the stringer interface func (t Type) String() string { return string(t) } // Lower returns the type lower case string func (t Type) Lower() string { return strings.ToLower(string(t)) } // Title returns the type titleized, eg "Limit" func (t Type) Title() string { return strings.Title(strings.ToLower(string(t))) } // String implements the stringer interface func (s Side) String() string { return string(s) } // Lower returns the side lower case string func (s Side) Lower() string { return strings.ToLower(string(s)) } // Title returns the side titleized, eg "Buy" func (s Side) Title() string { return strings.Title(strings.ToLower(string(s))) } // String implements the stringer interface func (s Status) String() string { return string(s) } // InferCostsAndTimes infer order costs using execution information and times when available func (d *Detail) InferCostsAndTimes() { if d.CostAsset.IsEmpty() { d.CostAsset = d.Pair.Quote } if d.LastUpdated.IsZero() { if d.CloseTime.IsZero() { d.LastUpdated = d.Date } else { d.LastUpdated = d.CloseTime } } if d.ExecutedAmount <= 0 { return } if d.AverageExecutedPrice == 0 { if d.Cost != 0 { d.AverageExecutedPrice = d.Cost / d.ExecutedAmount } else { d.AverageExecutedPrice = d.Price } } if d.Cost == 0 { d.Cost = d.AverageExecutedPrice * d.ExecutedAmount } } // FilterOrdersBySide removes any order details that don't match the // order status provided func FilterOrdersBySide(orders *[]Detail, side Side) { if side == "" || side == AnySide { return } var filteredOrders []Detail for i := range *orders { if strings.EqualFold(string((*orders)[i].Side), string(side)) { filteredOrders = append(filteredOrders, (*orders)[i]) } } *orders = filteredOrders } // FilterOrdersByType removes any order details that don't match the order type // provided func FilterOrdersByType(orders *[]Detail, orderType Type) { if orderType == "" || orderType == AnyType { return } var filteredOrders []Detail for i := range *orders { if strings.EqualFold(string((*orders)[i].Type), string(orderType)) { filteredOrders = append(filteredOrders, (*orders)[i]) } } *orders = filteredOrders } // FilterOrdersByTimeRange removes any OrderDetails outside of the time range func FilterOrdersByTimeRange(orders *[]Detail, startTime, endTime time.Time) { if startTime.IsZero() || endTime.IsZero() || startTime.Unix() == 0 || endTime.Unix() == 0 || endTime.Before(startTime) { return } var filteredOrders []Detail for i := range *orders { if ((*orders)[i].Date.Unix() >= startTime.Unix() && (*orders)[i].Date.Unix() <= endTime.Unix()) || (*orders)[i].Date.IsZero() { filteredOrders = append(filteredOrders, (*orders)[i]) } } *orders = filteredOrders } // FilterOrdersByCurrencies removes any order details that do not match the // provided currency list. It is forgiving in that the provided currencies can // match quote or base currencies func FilterOrdersByCurrencies(orders *[]Detail, currencies []currency.Pair) { if len(currencies) == 0 { return } if len(currencies) == 1 && currencies[0].IsEmpty() { return } var filteredOrders []Detail for i := range *orders { for _, c := range currencies { if (*orders)[i].Pair.EqualIncludeReciprocal(c) { filteredOrders = append(filteredOrders, (*orders)[i]) break } } } *orders = filteredOrders } func (b ByPrice) Len() int { return len(b) } func (b ByPrice) Less(i, j int) bool { return b[i].Price < b[j].Price } func (b ByPrice) Swap(i, j int) { b[i], b[j] = b[j], b[i] } // SortOrdersByPrice the caller function to sort orders func SortOrdersByPrice(orders *[]Detail, reverse bool) { if reverse { sort.Sort(sort.Reverse(ByPrice(*orders))) } else { sort.Sort(ByPrice(*orders)) } } func (b ByOrderType) Len() int { return len(b) } func (b ByOrderType) Less(i, j int) bool { return b[i].Type.String() < b[j].Type.String() } func (b ByOrderType) Swap(i, j int) { b[i], b[j] = b[j], b[i] } // SortOrdersByType the caller function to sort orders func SortOrdersByType(orders *[]Detail, reverse bool) { if reverse { sort.Sort(sort.Reverse(ByOrderType(*orders))) } else { sort.Sort(ByOrderType(*orders)) } } func (b ByCurrency) Len() int { return len(b) } func (b ByCurrency) Less(i, j int) bool { return b[i].Pair.String() < b[j].Pair.String() } func (b ByCurrency) Swap(i, j int) { b[i], b[j] = b[j], b[i] } // SortOrdersByCurrency the caller function to sort orders func SortOrdersByCurrency(orders *[]Detail, reverse bool) { if reverse { sort.Sort(sort.Reverse(ByCurrency(*orders))) } else { sort.Sort(ByCurrency(*orders)) } } func (b ByDate) Len() int { return len(b) } func (b ByDate) Less(i, j int) bool { return b[i].Date.Unix() < b[j].Date.Unix() } func (b ByDate) Swap(i, j int) { b[i], b[j] = b[j], b[i] } // SortOrdersByDate the caller function to sort orders func SortOrdersByDate(orders *[]Detail, reverse bool) { if reverse { sort.Sort(sort.Reverse(ByDate(*orders))) } else { sort.Sort(ByDate(*orders)) } } func (b ByOrderSide) Len() int { return len(b) } func (b ByOrderSide) Less(i, j int) bool { return b[i].Side.String() < b[j].Side.String() } func (b ByOrderSide) Swap(i, j int) { b[i], b[j] = b[j], b[i] } // SortOrdersBySide the caller function to sort orders func SortOrdersBySide(orders *[]Detail, reverse bool) { if reverse { sort.Sort(sort.Reverse(ByOrderSide(*orders))) } else { sort.Sort(ByOrderSide(*orders)) } } // StringToOrderSide for converting case insensitive order side // and returning a real Side func StringToOrderSide(side string) (Side, error) { switch { case strings.EqualFold(side, Buy.String()): return Buy, nil case strings.EqualFold(side, Sell.String()): return Sell, nil case strings.EqualFold(side, Bid.String()): return Bid, nil case strings.EqualFold(side, Ask.String()): return Ask, nil case strings.EqualFold(side, AnySide.String()): return AnySide, nil default: return UnknownSide, errors.New(side + " not recognised as order side") } } // StringToOrderType for converting case insensitive order type // and returning a real Type func StringToOrderType(oType string) (Type, error) { switch { case strings.EqualFold(oType, Limit.String()), strings.EqualFold(oType, "EXCHANGE LIMIT"): return Limit, nil case strings.EqualFold(oType, Market.String()), strings.EqualFold(oType, "EXCHANGE MARKET"): return Market, nil case strings.EqualFold(oType, ImmediateOrCancel.String()), strings.EqualFold(oType, "immediate or cancel"), strings.EqualFold(oType, "IOC"), strings.EqualFold(oType, "EXCHANGE IOC"): return ImmediateOrCancel, nil case strings.EqualFold(oType, Stop.String()), strings.EqualFold(oType, "stop loss"), strings.EqualFold(oType, "stop_loss"), strings.EqualFold(oType, "EXCHANGE STOP"): return Stop, nil case strings.EqualFold(oType, StopLimit.String()), strings.EqualFold(oType, "EXCHANGE STOP LIMIT"): return StopLimit, nil case strings.EqualFold(oType, TrailingStop.String()), strings.EqualFold(oType, "trailing stop"), strings.EqualFold(oType, "EXCHANGE TRAILING STOP"): return TrailingStop, nil case strings.EqualFold(oType, FillOrKill.String()), strings.EqualFold(oType, "EXCHANGE FOK"): return FillOrKill, nil case strings.EqualFold(oType, IOS.String()): return IOS, nil case strings.EqualFold(oType, PostOnly.String()): return PostOnly, nil case strings.EqualFold(oType, AnyType.String()): return AnyType, nil case strings.EqualFold(oType, Trigger.String()): return Trigger, nil default: return UnknownType, errors.New(oType + " not recognised as order type") } } // StringToOrderStatus for converting case insensitive order status // and returning a real Status func StringToOrderStatus(status string) (Status, error) { switch { case strings.EqualFold(status, AnyStatus.String()): return AnyStatus, nil case strings.EqualFold(status, New.String()), strings.EqualFold(status, "placed"): return New, nil case strings.EqualFold(status, Active.String()), strings.EqualFold(status, "STATUS_ACTIVE"): // BTSE case return Active, nil case strings.EqualFold(status, PartiallyFilled.String()), strings.EqualFold(status, "partially matched"), strings.EqualFold(status, "partially filled"): return PartiallyFilled, nil case strings.EqualFold(status, Filled.String()), strings.EqualFold(status, "fully matched"), strings.EqualFold(status, "fully filled"), strings.EqualFold(status, "ORDER_FULLY_TRANSACTED"): // BTSE case return Filled, nil case strings.EqualFold(status, PartiallyCancelled.String()), strings.EqualFold(status, "partially cancelled"), strings.EqualFold(status, "ORDER_PARTIALLY_TRANSACTED"): // BTSE case return PartiallyCancelled, nil case strings.EqualFold(status, Open.String()): return Open, nil case strings.EqualFold(status, Closed.String()): return Closed, nil case strings.EqualFold(status, Cancelled.String()), strings.EqualFold(status, "CANCELED"), // Binance and Kraken case strings.EqualFold(status, "ORDER_CANCELLED"): // BTSE case return Cancelled, nil case strings.EqualFold(status, PendingCancel.String()), strings.EqualFold(status, "pending cancel"), strings.EqualFold(status, "pending cancellation"): return PendingCancel, nil case strings.EqualFold(status, Rejected.String()): return Rejected, nil case strings.EqualFold(status, Expired.String()): return Expired, nil case strings.EqualFold(status, Hidden.String()): return Hidden, nil case strings.EqualFold(status, InsufficientBalance.String()): return InsufficientBalance, nil case strings.EqualFold(status, MarketUnavailable.String()): return MarketUnavailable, nil default: return UnknownStatus, errors.New(status + " not recognised as order status") } } func (o *ClassificationError) Error() string { if o.OrderID != "" { return fmt.Sprintf("%s - OrderID: %s classification error: %v", o.Exchange, o.OrderID, o.Err) } return fmt.Sprintf("%s - classification error: %v", o.Exchange, o.Err) } // StandardCancel defines an option in the validator to make sure an ID is set // for a standard cancel func (c *Cancel) StandardCancel() validate.Checker { return validate.Check(func() error { if c.ID == "" { return errors.New("ID not set") } return nil }) } // PairAssetRequired is a validation check for when a cancel request // requires an asset type and currency pair to be present func (c *Cancel) PairAssetRequired() validate.Checker { return validate.Check(func() error { if c.Pair.IsEmpty() { return ErrPairIsEmpty } if c.AssetType == "" { return ErrAssetNotSet } return nil }) } // Validate checks internal struct requirements func (c *Cancel) Validate(opt ...validate.Checker) error { if c == nil { return ErrCancelOrderIsNil } var errs common.Errors for _, o := range opt { err := o.Check() if err != nil { errs = append(errs, err) } } if errs != nil { return errs } return nil } // Validate checks internal struct requirements func (g *GetOrdersRequest) Validate(opt ...validate.Checker) error { if g == nil { return ErrGetOrdersRequestIsNil } if !g.AssetType.IsValid() { return fmt.Errorf("assetType %v not supported", g.AssetType) } var errs common.Errors for _, o := range opt { err := o.Check() if err != nil { errs = append(errs, err) } } if errs != nil { return errs } return nil } // Validate checks internal struct requirements func (m *Modify) Validate(opt ...validate.Checker) error { if m == nil { return ErrModifyOrderIsNil } if m.Pair.IsEmpty() { return ErrPairIsEmpty } if m.AssetType.String() == "" { return ErrAssetNotSet } var errs common.Errors for _, o := range opt { err := o.Check() if err != nil { errs = append(errs, err) } } if errs != nil { return errs } if m.ClientOrderID == "" && m.ID == "" { return ErrOrderIDNotSet } return nil } <file_sep>package order import ( "testing" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/currency" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) func TestIsOrder(t *testing.T) { t.Parallel() o := Order{} if !o.IsOrder() { t.Error("expected true") } } func TestSetDirection(t *testing.T) { t.Parallel() o := Order{ Direction: gctorder.Sell, } o.SetDirection(gctorder.Buy) if o.GetDirection() != gctorder.Buy { t.Error("expected buy") } } func TestSetAmount(t *testing.T) { t.Parallel() o := Order{ Amount: decimal.NewFromInt(1), } o.SetAmount(decimal.NewFromInt(1337)) if !o.GetAmount().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestPair(t *testing.T) { t.Parallel() o := Order{ Base: event.Base{ CurrencyPair: currency.NewPair(currency.BTC, currency.USDT), }, } y := o.CurrencyPair if y.IsEmpty() { t.Error("expected btc-usdt") } } func TestSetID(t *testing.T) { t.Parallel() o := Order{ ID: "decimal.NewFromInt(1337)", } o.SetID("1338") if o.GetID() != "1338" { t.Error("expected 1338") } } func TestLeverage(t *testing.T) { t.Parallel() o := Order{ Leverage: decimal.NewFromInt(1), } o.SetLeverage(decimal.NewFromInt(1337)) if !o.GetLeverage().Equal(decimal.NewFromInt(1337)) || !o.IsLeveraged() { t.Error("expected leverage") } } func TestGetFunds(t *testing.T) { t.Parallel() o := Order{ AllocatedFunds: decimal.NewFromInt(1337), } funds := o.GetAllocatedFunds() if !funds.Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } <file_sep>package buffer import ( "sync" "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/orderbook" ) // Orderbook defines a local cache of orderbooks for amending, appending // and deleting changes and updates the main store for a stream type Orderbook struct { ob map[currency.Code]map[currency.Code]map[asset.Item]*orderbookHolder obBufferLimit int bufferEnabled bool sortBuffer bool sortBufferByUpdateIDs bool // When timestamps aren't provided, an id can help sort updateEntriesByID bool // Use the update IDs to match ob entries exchangeName string dataHandler chan interface{} verbose bool publishPeriod time.Duration m sync.Mutex } // orderbookHolder defines a store of pending updates and a pointer to the // orderbook depth type orderbookHolder struct { ob *orderbook.Depth buffer *[]Update // Reduces the amount of outbound alerts to the data handler for example // coinbasepro can have up too 100 updates per second introducing overhead. // The sync agent only requires an alert every 15 seconds for a specific // currency. ticker *time.Ticker } // Update stores orderbook updates and dictates what features to use when processing type Update struct { UpdateID int64 // Used when no time is provided UpdateTime time.Time Asset asset.Item Action Bids []orderbook.Item Asks []orderbook.Item Pair currency.Pair // Determines if there is a max depth of orderbooks and after an append we // should remove any items that are outside of this scope. Kraken is the // only exchange utilising this field. MaxDepth int } // Action defines a set of differing states required to implement an incoming // orderbook update used in conjunction with UpdateEntriesByID type Action string const ( // Amend applies amount adjustment by ID Amend Action = "update" // Delete removes price level from book by ID Delete Action = "delete" // Insert adds price level to book Insert Action = "insert" // UpdateInsert on conflict applies amount adjustment or appends new amount // to book UpdateInsert Action = "update/insert" ) <file_sep>package fill import ( "testing" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) func TestSetDirection(t *testing.T) { t.Parallel() f := Fill{ Direction: gctorder.Sell, } f.SetDirection(gctorder.Buy) if f.GetDirection() != gctorder.Buy { t.Error("expected buy") } } func TestSetAmount(t *testing.T) { t.Parallel() f := Fill{ Amount: decimal.NewFromInt(1), } f.SetAmount(decimal.NewFromInt(1337)) if !f.GetAmount().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestGetClosePrice(t *testing.T) { t.Parallel() f := Fill{ ClosePrice: decimal.NewFromInt(1337), } if !f.GetClosePrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestGetVolumeAdjustedPrice(t *testing.T) { t.Parallel() f := Fill{ VolumeAdjustedPrice: decimal.NewFromInt(1337), } if !f.GetVolumeAdjustedPrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestGetPurchasePrice(t *testing.T) { t.Parallel() f := Fill{ PurchasePrice: decimal.NewFromInt(1337), } if !f.GetPurchasePrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestSetExchangeFee(t *testing.T) { t.Parallel() f := Fill{ ExchangeFee: decimal.NewFromInt(1), } f.SetExchangeFee(decimal.NewFromInt(1337)) if !f.GetExchangeFee().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestGetOrder(t *testing.T) { t.Parallel() f := Fill{ Order: &gctorder.Detail{}, } if f.GetOrder() == nil { t.Error("expected not nil") } } func TestGetSlippageRate(t *testing.T) { t.Parallel() f := Fill{ Slippage: decimal.NewFromInt(1), } if !f.GetSlippageRate().Equal(decimal.NewFromInt(1)) { t.Error("expected 1") } } <file_sep>package bitfinex import ( "encoding/json" "errors" "fmt" "hash/crc32" "net/http" "sort" "strconv" "strings" "sync" "time" "github.com/gorilla/websocket" "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/convert" "github.com/idoall/gocryptotrader/common/crypto" "github.com/idoall/gocryptotrader/currency" exchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/exchanges/orderbook" "github.com/idoall/gocryptotrader/exchanges/stream" "github.com/idoall/gocryptotrader/exchanges/stream/buffer" "github.com/idoall/gocryptotrader/exchanges/ticker" "github.com/idoall/gocryptotrader/exchanges/trade" "github.com/idoall/gocryptotrader/log" ) var comms = make(chan stream.Response) type checksum struct { Token int Sequence int64 } // checksumStore quick global for now var checksumStore = make(map[int]*checksum) var cMtx sync.Mutex // WsConnect starts a new websocket connection func (b *Bitfinex) WsConnect() error { if !b.Websocket.IsEnabled() || !b.IsEnabled() { return errors.New(stream.WebsocketNotEnabled) } var dialer websocket.Dialer err := b.Websocket.Conn.Dial(&dialer, http.Header{}) if err != nil { return fmt.Errorf("%v unable to connect to Websocket. Error: %s", b.Name, err) } b.Websocket.Wg.Add(1) go b.wsReadData(b.Websocket.Conn) if b.Websocket.CanUseAuthenticatedEndpoints() { err = b.Websocket.AuthConn.Dial(&dialer, http.Header{}) if err != nil { log.Errorf(log.ExchangeSys, "%v unable to connect to authenticated Websocket. Error: %s", b.Name, err) b.Websocket.SetCanUseAuthenticatedEndpoints(false) } b.Websocket.Wg.Add(1) go b.wsReadData(b.Websocket.AuthConn) err = b.WsSendAuth() if err != nil { log.Errorf(log.ExchangeSys, "%v - authentication failed: %v\n", b.Name, err) b.Websocket.SetCanUseAuthenticatedEndpoints(false) } } b.Websocket.Wg.Add(1) go b.WsDataHandler() return nil } // wsReadData receives and passes on websocket messages for processing func (b *Bitfinex) wsReadData(ws stream.Connection) { defer b.Websocket.Wg.Done() for { resp := ws.ReadMessage() if resp.Raw == nil { return } comms <- resp } } // WsDataHandler handles data from wsReadData func (b *Bitfinex) WsDataHandler() { defer b.Websocket.Wg.Done() for { select { case <-b.Websocket.ShutdownC: select { case resp := <-comms: err := b.wsHandleData(resp.Raw) if err != nil { select { case b.Websocket.DataHandler <- err: default: log.Errorf(log.WebsocketMgr, "%s websocket handle data error: %v", b.Name, err) } } default: } return case resp := <-comms: if resp.Type != websocket.TextMessage { continue } err := b.wsHandleData(resp.Raw) if err != nil { b.Websocket.DataHandler <- err } } } } func (b *Bitfinex) wsHandleData(respRaw []byte) error { var result interface{} err := json.Unmarshal(respRaw, &result) if err != nil { return err } switch d := result.(type) { case map[string]interface{}: event := d["event"] switch event { case "subscribed": if symbol, ok := d["symbol"].(string); ok { b.WsAddSubscriptionChannel(int(d["chanId"].(float64)), d["channel"].(string), symbol, ) } else if key, ok := d["key"].(string); ok { // Capture trading subscriptions contents := strings.Split(d["key"].(string), ":") if len(contents) > 3 { // Edge case to parse margin strings. // map[chanId:139136 channel:candles event:subscribed key:trade:1m:tXAUTF0:USTF0] if contents[2][0] == 't' { key = contents[2] + ":" + contents[3] } } b.WsAddSubscriptionChannel(int(d["chanId"].(float64)), d["channel"].(string), key, ) } case "auth": status, ok := d["status"].(string) if !ok { return errors.New("unable to type assert status") } if status == "OK" { b.Websocket.DataHandler <- d b.WsAddSubscriptionChannel(0, "account", "N/A") } else if status == "fail" { return fmt.Errorf("websocket unable to AUTH. Error code: %s", d["code"].(string)) } } case []interface{}: chanF, ok := d[0].(float64) if !ok { return errors.New("channel ID type assertion failure") } chanID := int(chanF) var datum string if datum, ok = d[1].(string); ok { // Capturing heart beat if datum == "hb" { return nil } // Capturing checksum and storing value if datum == "cs" { var tokenF float64 tokenF, ok = d[2].(float64) if !ok { return errors.New("checksum token type assertion failure") } var seqNoF float64 seqNoF, ok = d[3].(float64) if !ok { return errors.New("sequence number type assertion failure") } cMtx.Lock() checksumStore[chanID] = &checksum{ Token: int(tokenF), Sequence: int64(seqNoF), } cMtx.Unlock() return nil } } chanInfo, ok := b.WebsocketSubdChannels[chanID] if !ok && chanID != 0 { return fmt.Errorf("unable to locate chanID: %d", chanID) } var chanAsset = asset.Spot var pair currency.Pair pairInfo := strings.Split(chanInfo.Pair, ":") switch { case len(pairInfo) >= 3: newPair := pairInfo[2] if newPair[0] == 'f' { chanAsset = asset.MarginFunding } pair, err = currency.NewPairFromString(newPair[1:]) if err != nil { return err } case len(pairInfo) == 1: newPair := pairInfo[0] if newPair[0] == 'f' { chanAsset = asset.MarginFunding } pair, err = currency.NewPairFromString(newPair[1:]) if err != nil { return err } case chanInfo.Pair != "": if strings.Contains(chanInfo.Pair, ":") { chanAsset = asset.Margin } pair, err = currency.NewPairFromString(chanInfo.Pair[1:]) if err != nil { return err } } switch chanInfo.Channel { case wsBook: var newOrderbook []WebsocketBook obSnapBundle, ok := d[1].([]interface{}) if !ok { return errors.New("orderbook interface cast failed") } if len(obSnapBundle) == 0 { return errors.New("no data within orderbook snapshot") } sequenceNo, ok := d[2].(float64) if !ok { return errors.New("type assertion failure") } var fundingRate bool switch id := obSnapBundle[0].(type) { case []interface{}: for i := range obSnapBundle { data, ok := obSnapBundle[i].([]interface{}) if !ok { return errors.New("type assertion failed for orderbok item data") } id, okAssert := data[0].(float64) if !okAssert { return errors.New("type assertion failed for orderbook id data") } pricePeriod, okAssert := data[1].(float64) if !okAssert { return errors.New("type assertion failed for orderbook price data") } rateAmount, okAssert := data[2].(float64) if !okAssert { return errors.New("type assertion failed for orderbook rate data") } if len(data) == 4 { fundingRate = true amount, okFunding := data[3].(float64) if !okFunding { return errors.New("type assertion failed for orderbook funding data") } newOrderbook = append(newOrderbook, WebsocketBook{ ID: int64(id), Period: int64(pricePeriod), Price: rateAmount, Amount: amount}) } else { newOrderbook = append(newOrderbook, WebsocketBook{ ID: int64(id), Price: pricePeriod, Amount: rateAmount}) } } if err = b.WsInsertSnapshot(pair, chanAsset, newOrderbook, fundingRate); err != nil { return fmt.Errorf("inserting snapshot error: %s", err) } case float64: pricePeriod, okSnap := obSnapBundle[1].(float64) if !okSnap { return errors.New("type assertion failed for orderbook price snapshot data") } amountRate, okSnap := obSnapBundle[2].(float64) if !okSnap { return errors.New("type assertion failed for orderbook amount snapshot data") } if len(obSnapBundle) == 4 { fundingRate = true var amount float64 amount, okSnap = obSnapBundle[3].(float64) if !okSnap { return errors.New("type assertion failed for orderbook amount snapshot data") } newOrderbook = append(newOrderbook, WebsocketBook{ ID: int64(id), Period: int64(pricePeriod), Price: amountRate, Amount: amount}) } else { newOrderbook = append(newOrderbook, WebsocketBook{ ID: int64(id), Price: pricePeriod, Amount: amountRate}) } if err = b.WsUpdateOrderbook(pair, chanAsset, newOrderbook, chanID, int64(sequenceNo), fundingRate); err != nil { return fmt.Errorf("updating orderbook error: %s", err) } } return nil case wsCandles: if candleBundle, ok := d[1].([]interface{}); ok { if len(candleBundle) == 0 { return nil } switch candleData := candleBundle[0].(type) { case []interface{}: for i := range candleBundle { var element []interface{} element, ok = candleBundle[i].([]interface{}) if !ok { return errors.New("type assertion for element data") } if len(element) < 6 { return errors.New("invalid candleBundle length") } var klineData stream.KlineData if klineData.Timestamp, err = convert.TimeFromUnixTimestampFloat(element[0]); err != nil { return fmt.Errorf("unable to convert timestamp: %w", err) } if klineData.OpenPrice, ok = element[1].(float64); !ok { return errors.New("unable to type assert OpenPrice") } if klineData.ClosePrice, ok = element[2].(float64); !ok { return errors.New("unable to type assert ClosePrice") } if klineData.HighPrice, ok = element[3].(float64); !ok { return errors.New("unable to type assert HighPrice") } if klineData.LowPrice, ok = element[4].(float64); !ok { return errors.New("unable to type assert LowPrice") } if klineData.Volume, ok = element[5].(float64); !ok { return errors.New("unable to type assert volume") } klineData.Exchange = b.Name klineData.AssetType = chanAsset klineData.Pair = pair b.Websocket.DataHandler <- klineData } case float64: if len(candleBundle) < 6 { return errors.New("invalid candleBundle length") } var klineData stream.KlineData if klineData.Timestamp, err = convert.TimeFromUnixTimestampFloat(candleData); err != nil { return fmt.Errorf("unable to convert timestamp: %w", err) } if klineData.OpenPrice, ok = candleBundle[1].(float64); !ok { return errors.New("unable to type assert OpenPrice") } if klineData.ClosePrice, ok = candleBundle[2].(float64); !ok { return errors.New("unable to type assert ClosePrice") } if klineData.HighPrice, ok = candleBundle[3].(float64); !ok { return errors.New("unable to type assert HighPrice") } if klineData.LowPrice, ok = candleBundle[4].(float64); !ok { return errors.New("unable to type assert LowPrice") } if klineData.Volume, ok = candleBundle[5].(float64); !ok { return errors.New("unable to type assert volume") } klineData.Exchange = b.Name klineData.AssetType = chanAsset klineData.Pair = pair b.Websocket.DataHandler <- klineData } } return nil case wsTicker: tickerData, ok := d[1].([]interface{}) if !ok { return errors.New("type assertion for tickerData") } if len(tickerData) == 10 { b.Websocket.DataHandler <- &ticker.Price{ ExchangeName: b.Name, Bid: tickerData[0].(float64), Ask: tickerData[2].(float64), Last: tickerData[6].(float64), Volume: tickerData[7].(float64), High: tickerData[8].(float64), Low: tickerData[9].(float64), AssetType: chanAsset, Pair: pair, } } else { b.Websocket.DataHandler <- &ticker.Price{ ExchangeName: b.Name, FlashReturnRate: tickerData[0].(float64), Bid: tickerData[1].(float64), BidPeriod: tickerData[2].(float64), BidSize: tickerData[3].(float64), Ask: tickerData[4].(float64), AskPeriod: tickerData[5].(float64), AskSize: tickerData[6].(float64), Last: tickerData[9].(float64), Volume: tickerData[10].(float64), High: tickerData[11].(float64), Low: tickerData[12].(float64), FlashReturnRateAmount: tickerData[15].(float64), AssetType: chanAsset, Pair: pair, } } return nil case wsTrades: if !b.IsSaveTradeDataEnabled() { return nil } if chanAsset == asset.MarginFunding { return nil } var tradeHolder []WebsocketTrade switch len(d) { case 2: snapshot, ok := d[1].([]interface{}) if !ok { return errors.New("unable to type assert snapshot data") } for i := range snapshot { elem, ok := snapshot[i].([]interface{}) if !ok { return errors.New("unable to type assert snapshot element data") } if len(elem) == 5 { tradeHolder = append(tradeHolder, WebsocketTrade{ ID: int64(elem[0].(float64)), Timestamp: int64(elem[1].(float64)), Amount: elem[2].(float64), Rate: elem[3].(float64), Period: int64(elem[4].(float64)), }) } else { tradeHolder = append(tradeHolder, WebsocketTrade{ ID: int64(elem[0].(float64)), Timestamp: int64(elem[1].(float64)), Amount: elem[2].(float64), Price: elem[3].(float64), }) } } case 3: if d[1].(string) != wsFundingTradeUpdate && d[1].(string) != wsTradeExecutionUpdate { return nil } data, ok := d[2].([]interface{}) if !ok { return errors.New("data type assertion error") } if len(data) == 5 { tradeHolder = append(tradeHolder, WebsocketTrade{ ID: int64(data[0].(float64)), Timestamp: int64(data[1].(float64)), Amount: data[2].(float64), Rate: data[3].(float64), Period: int64(data[4].(float64)), }) } else { tradeHolder = append(tradeHolder, WebsocketTrade{ ID: int64(data[0].(float64)), Timestamp: int64(data[1].(float64)), Amount: data[2].(float64), Price: data[3].(float64), }) } } var trades []trade.Data for i := range tradeHolder { side := order.Buy newAmount := tradeHolder[i].Amount if newAmount < 0 { side = order.Sell newAmount *= -1 } price := tradeHolder[i].Price if price == 0 && tradeHolder[i].Rate > 0 { price = tradeHolder[i].Rate } trades = append(trades, trade.Data{ TID: strconv.FormatInt(tradeHolder[i].ID, 10), CurrencyPair: pair, Timestamp: time.UnixMilli(tradeHolder[i].Timestamp), Price: price, Amount: newAmount, Exchange: b.Name, AssetType: chanAsset, Side: side, }) } return b.AddTradesToBuffer(trades...) } if authResp, ok := d[1].(string); ok { switch authResp { case wsHeartbeat, pong: return nil case wsNotification: notification, ok := d[2].([]interface{}) if !ok { return errors.New("unable to type assert notification data") } if data, ok := notification[4].([]interface{}); ok { channelName, ok := notification[1].(string) if !ok { return errors.New("unable to type assert channelName") } switch { case strings.Contains(channelName, wsFundingOrderNewRequest), strings.Contains(channelName, wsFundingOrderUpdateRequest), strings.Contains(channelName, wsFundingOrderCancelRequest): if data[0] != nil && data[0].(float64) > 0 { id := int64(data[0].(float64)) if b.Websocket.Match.IncomingWithData(id, respRaw) { return nil } b.wsHandleFundingOffer(data) } case strings.Contains(channelName, wsOrderNewRequest), strings.Contains(channelName, wsOrderUpdateRequest), strings.Contains(channelName, wsOrderCancelRequest): if data[2] != nil && data[2].(float64) > 0 { id := int64(data[2].(float64)) if b.Websocket.Match.IncomingWithData(id, respRaw) { return nil } b.wsHandleOrder(data) } default: return fmt.Errorf("%s - Unexpected data returned %s", b.Name, respRaw) } } if notification[5] != nil { if wsErr, ok := notification[5].(string); ok { if strings.EqualFold(wsErr, wsError) { if errMsg, ok := notification[6].(string); ok { return fmt.Errorf("%s - Error %s", b.Name, errMsg) } return fmt.Errorf("%s - unhandled error message: %v", b.Name, notification[6]) } } } case wsOrderSnapshot: if snapBundle, ok := d[2].([]interface{}); ok && len(snapBundle) > 0 { if _, ok := snapBundle[0].([]interface{}); ok { for i := range snapBundle { if positionData, ok := snapBundle[i].([]interface{}); ok { b.wsHandleOrder(positionData) } } } } case wsOrderCancel, wsOrderNew, wsOrderUpdate: if oData, ok := d[2].([]interface{}); ok && len(oData) > 0 { b.wsHandleOrder(oData) } case wsPositionSnapshot: var snapshot []WebsocketPosition if snapBundle, ok := d[2].([]interface{}); ok && len(snapBundle) > 0 { if _, ok := snapBundle[0].([]interface{}); ok { for i := range snapBundle { positionData, ok := snapBundle[i].([]interface{}) if !ok { return errors.New("unable to type assert wsPositionSnapshot positionData") } position := WebsocketPosition{ Pair: positionData[0].(string), Status: positionData[1].(string), Amount: positionData[2].(float64), Price: positionData[3].(float64), MarginFunding: positionData[4].(float64), MarginFundingType: int64(positionData[5].(float64)), ProfitLoss: positionData[6].(float64), ProfitLossPercent: positionData[7].(float64), LiquidationPrice: positionData[8].(float64), Leverage: positionData[9].(float64), } snapshot = append(snapshot, position) } b.Websocket.DataHandler <- snapshot } } case wsPositionNew, wsPositionUpdate, wsPositionClose: if positionData, ok := d[2].([]interface{}); ok && len(positionData) > 0 { position := WebsocketPosition{ Pair: positionData[0].(string), Status: positionData[1].(string), Amount: positionData[2].(float64), Price: positionData[3].(float64), MarginFunding: positionData[4].(float64), MarginFundingType: int64(positionData[5].(float64)), ProfitLoss: positionData[6].(float64), ProfitLossPercent: positionData[7].(float64), LiquidationPrice: positionData[8].(float64), Leverage: positionData[9].(float64), } b.Websocket.DataHandler <- position } case wsTradeExecuted, wsTradeExecutionUpdate: if tradeData, ok := d[2].([]interface{}); ok && len(tradeData) > 4 { b.Websocket.DataHandler <- WebsocketTradeData{ TradeID: int64(tradeData[0].(float64)), Pair: tradeData[1].(string), Timestamp: int64(tradeData[2].(float64)), OrderID: int64(tradeData[3].(float64)), AmountExecuted: tradeData[4].(float64), PriceExecuted: tradeData[5].(float64), OrderType: tradeData[6].(string), OrderPrice: tradeData[7].(float64), Maker: tradeData[8].(float64) == 1, Fee: tradeData[9].(float64), FeeCurrency: tradeData[10].(string), } } case wsFundingOrderSnapshot: var snapshot []WsFundingOffer if snapBundle, ok := d[2].([]interface{}); ok && len(snapBundle) > 0 { if _, ok := snapBundle[0].([]interface{}); ok { for i := range snapBundle { data, ok := snapBundle[i].([]interface{}) if !ok { return errors.New("unable to type assert wsFundingOrderSnapshot snapBundle data") } offer := WsFundingOffer{ ID: int64(data[0].(float64)), Symbol: data[1].(string), Created: int64(data[2].(float64)), Updated: int64(data[3].(float64)), Amount: data[4].(float64), OriginalAmount: data[5].(float64), Type: data[6].(string), Flags: data[9].(float64), Status: data[10].(string), Rate: data[14].(float64), Period: int64(data[15].(float64)), Notify: data[16].(float64) == 1, Hidden: data[17].(float64) == 1, Insure: data[18].(float64) == 1, Renew: data[19].(float64) == 1, RateReal: data[20].(float64), } snapshot = append(snapshot, offer) } b.Websocket.DataHandler <- snapshot } } case wsFundingOrderNew, wsFundingOrderUpdate, wsFundingOrderCancel: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { b.wsHandleFundingOffer(data) } case wsFundingCreditSnapshot: var snapshot []WsCredit if snapBundle, ok := d[2].([]interface{}); ok && len(snapBundle) > 0 { if _, ok := snapBundle[0].([]interface{}); ok { for i := range snapBundle { data, ok := snapBundle[i].([]interface{}) if !ok { return errors.New("unable to type assert wsFundingCreditSnapshot snapBundle data") } credit := WsCredit{ ID: int64(data[0].(float64)), Symbol: data[1].(string), Side: data[2].(string), Created: int64(data[3].(float64)), Updated: int64(data[4].(float64)), Amount: data[5].(float64), Flags: data[6].(string), Status: data[7].(string), Rate: data[11].(float64), Period: int64(data[12].(float64)), Opened: int64(data[13].(float64)), LastPayout: int64(data[14].(float64)), Notify: data[15].(float64) == 1, Hidden: data[16].(float64) == 1, Insure: data[17].(float64) == 1, Renew: data[18].(float64) == 1, RateReal: data[19].(float64), NoClose: data[20].(float64) == 1, PositionPair: data[21].(string), } snapshot = append(snapshot, credit) } b.Websocket.DataHandler <- snapshot } } case wsFundingCreditNew, wsFundingCreditUpdate, wsFundingCreditCancel: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { b.Websocket.DataHandler <- WsCredit{ ID: int64(data[0].(float64)), Symbol: data[1].(string), Side: data[2].(string), Created: int64(data[3].(float64)), Updated: int64(data[4].(float64)), Amount: data[5].(float64), Flags: data[6].(string), Status: data[7].(string), Rate: data[11].(float64), Period: int64(data[12].(float64)), Opened: int64(data[13].(float64)), LastPayout: int64(data[14].(float64)), Notify: data[15].(float64) == 1, Hidden: data[16].(float64) == 1, Insure: data[17].(float64) == 1, Renew: data[18].(float64) == 1, RateReal: data[19].(float64), NoClose: data[20].(float64) == 1, PositionPair: data[21].(string), } } case wsFundingLoanSnapshot: var snapshot []WsCredit if snapBundle, ok := d[2].([]interface{}); ok && len(snapBundle) > 0 { if _, ok := snapBundle[0].([]interface{}); ok { for i := range snapBundle { data, ok := snapBundle[i].([]interface{}) if !ok { return errors.New("unable to type assert wsFundingLoanSnapshot snapBundle data") } credit := WsCredit{ ID: int64(data[0].(float64)), Symbol: data[1].(string), Side: data[2].(string), Created: int64(data[3].(float64)), Updated: int64(data[4].(float64)), Amount: data[5].(float64), Flags: data[6].(string), Status: data[7].(string), Rate: data[11].(float64), Period: int64(data[12].(float64)), Opened: int64(data[13].(float64)), LastPayout: int64(data[14].(float64)), Notify: data[15].(float64) == 1, Hidden: data[16].(float64) == 1, Insure: data[17].(float64) == 1, Renew: data[18].(float64) == 1, RateReal: data[19].(float64), NoClose: data[20].(float64) == 1, } snapshot = append(snapshot, credit) } b.Websocket.DataHandler <- snapshot } } case wsFundingLoanNew, wsFundingLoanUpdate, wsFundingLoanCancel: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { b.Websocket.DataHandler <- WsCredit{ ID: int64(data[0].(float64)), Symbol: data[1].(string), Side: data[2].(string), Created: int64(data[3].(float64)), Updated: int64(data[4].(float64)), Amount: data[5].(float64), Flags: data[6].(string), Status: data[7].(string), Rate: data[11].(float64), Period: int64(data[12].(float64)), Opened: int64(data[13].(float64)), LastPayout: int64(data[14].(float64)), Notify: data[15].(float64) == 1, Hidden: data[16].(float64) == 1, Insure: data[17].(float64) == 1, Renew: data[18].(float64) == 1, RateReal: data[19].(float64), NoClose: data[20].(float64) == 1, } } case wsWalletSnapshot: var snapshot []WsWallet if snapBundle, ok := d[2].([]interface{}); ok && len(snapBundle) > 0 { if _, ok := snapBundle[0].([]interface{}); ok { for i := range snapBundle { data, ok := snapBundle[i].([]interface{}) if !ok { return errors.New("unable to type assert wsWalletSnapshot snapBundle data") } var balanceAvailable float64 if v, ok := data[4].(float64); ok { balanceAvailable = v } wallet := WsWallet{ Type: data[0].(string), Currency: data[1].(string), Balance: data[2].(float64), UnsettledInterest: data[3].(float64), BalanceAvailable: balanceAvailable, } snapshot = append(snapshot, wallet) } b.Websocket.DataHandler <- snapshot } } case wsWalletUpdate: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { var balanceAvailable float64 if v, ok := data[4].(float64); ok { balanceAvailable = v } b.Websocket.DataHandler <- WsWallet{ Type: data[0].(string), Currency: data[1].(string), Balance: data[2].(float64), UnsettledInterest: data[3].(float64), BalanceAvailable: balanceAvailable, } } case wsBalanceUpdate: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { b.Websocket.DataHandler <- WsBalanceInfo{ TotalAssetsUnderManagement: data[0].(float64), NetAssetsUnderManagement: data[1].(float64), } } case wsMarginInfoUpdate: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { if data[0].(string) == "base" { if infoBase, ok := d[2].([]interface{}); ok && len(infoBase) > 0 { baseData, ok := data[1].([]interface{}) if !ok { return errors.New("unable to type assert wsMarginInfoUpdate baseData") } b.Websocket.DataHandler <- WsMarginInfoBase{ UserProfitLoss: baseData[0].(float64), UserSwaps: baseData[1].(float64), MarginBalance: baseData[2].(float64), MarginNet: baseData[3].(float64), } } } } case wsFundingInfoUpdate: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { if data[0].(string) == "sym" { symbolData, ok := data[1].([]interface{}) if !ok { return errors.New("unable to type assert wsFundingInfoUpdate symbolData") } b.Websocket.DataHandler <- WsFundingInfo{ YieldLoan: symbolData[0].(float64), YieldLend: symbolData[1].(float64), DurationLoan: symbolData[2].(float64), DurationLend: symbolData[3].(float64), } } } case wsFundingTradeExecuted, wsFundingTradeUpdate: if data, ok := d[2].([]interface{}); ok && len(data) > 0 { b.Websocket.DataHandler <- WsFundingTrade{ ID: int64(data[0].(float64)), Symbol: data[1].(string), MTSCreated: int64(data[2].(float64)), OfferID: int64(data[3].(float64)), Amount: data[4].(float64), Rate: data[5].(float64), Period: int64(data[6].(float64)), Maker: data[7].(float64) == 1, } } default: b.Websocket.DataHandler <- stream.UnhandledMessageWarning{ Message: b.Name + stream.UnhandledMessage + string(respRaw), } return nil } } } return nil } func (b *Bitfinex) wsHandleFundingOffer(data []interface{}) { var fo WsFundingOffer if data[0] != nil { if id, ok := data[0].(float64); ok { fo.ID = int64(id) } } if data[1] != nil { if sym, ok := data[1].(string); ok { fo.Symbol = sym[1:] } } if data[2] != nil { if created, ok := data[2].(float64); ok { fo.Created = int64(created) } } if data[3] != nil { if updated, ok := data[3].(float64); ok { fo.Updated = int64(updated) } } if data[15] != nil { if period, ok := data[15].(float64); ok { fo.Period = int64(period) } } if data[4] != nil { if amount, ok := data[4].(float64); ok { fo.Amount = amount } } if data[5] != nil { if origAmount, ok := data[5].(float64); ok { fo.OriginalAmount = origAmount } } if data[6] != nil { if fType, ok := data[6].(string); ok { fo.Type = fType } } if data[9] != nil { if flags, ok := data[9].(float64); ok { fo.Flags = flags } } if data[9] != nil && data[10] != nil { if status, ok := data[10].(string); ok { fo.Status = status } } if data[9] != nil && data[14] != nil { if rate, ok := data[14].(float64); ok { fo.Rate = rate } } if data[16] != nil { if notify, ok := data[16].(float64); ok { fo.Notify = notify == 1 } } if data[17] != nil { if hidden, ok := data[17].(float64); ok { fo.Hidden = hidden == 1 } } if data[18] != nil { if insure, ok := data[18].(float64); ok { fo.Insure = insure == 1 } } if data[19] != nil { if renew, ok := data[19].(float64); ok { fo.Renew = renew == 1 } } if data[20] != nil { if rateReal, ok := data[20].(float64); ok { fo.RateReal = rateReal } } b.Websocket.DataHandler <- fo } func (b *Bitfinex) wsHandleOrder(data []interface{}) { var od order.Detail var err error od.Exchange = b.Name if data[0] != nil { if id, ok := data[0].(float64); ok { od.ID = strconv.FormatFloat(id, 'f', -1, 64) } } if data[16] != nil { if price, ok := data[16].(float64); ok { od.Price = price } } if data[7] != nil { if amount, ok := data[7].(float64); ok { od.Amount = amount } } if data[6] != nil { if remainingAmount, ok := data[6].(float64); ok { od.RemainingAmount = remainingAmount } } if data[7] != nil && data[6] != nil { if executedAmount, ok := data[7].(float64); ok { od.ExecutedAmount = executedAmount - od.RemainingAmount } } if data[4] != nil { if date, ok := data[4].(float64); ok { od.Date = time.Unix(int64(date)*1000, 0) } } if data[5] != nil { if lastUpdated, ok := data[5].(float64); ok { od.LastUpdated = time.Unix(int64(lastUpdated)*1000, 0) } } if data[2] != nil { if p, ok := data[3].(string); ok { od.Pair, od.AssetType, err = b.GetRequestFormattedPairAndAssetType(p[1:]) if err != nil { b.Websocket.DataHandler <- err return } } } if data[8] != nil { if ordType, ok := data[8].(string); ok { oType, err := order.StringToOrderType(ordType) if err != nil { b.Websocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: od.ID, Err: err, } } od.Type = oType } } if data[13] != nil { if ordStatus, ok := data[13].(string); ok { oStatus, err := order.StringToOrderStatus(ordStatus) if err != nil { b.Websocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: od.ID, Err: err, } } od.Status = oStatus } } b.Websocket.DataHandler <- &od } // WsInsertSnapshot add the initial orderbook snapshot when subscribed to a // channel func (b *Bitfinex) WsInsertSnapshot(p currency.Pair, assetType asset.Item, books []WebsocketBook, fundingRate bool) error { if len(books) == 0 { return errors.New("no orderbooks submitted") } var book orderbook.Base for i := range books { item := orderbook.Item{ ID: books[i].ID, Amount: books[i].Amount, Price: books[i].Price, Period: books[i].Period, } if fundingRate { if item.Amount < 0 { item.Amount *= -1 book.Bids = append(book.Bids, item) } else { book.Asks = append(book.Asks, item) } } else { if books[i].Amount > 0 { book.Bids = append(book.Bids, item) } else { item.Amount *= -1 book.Asks = append(book.Asks, item) } } } book.Asset = assetType book.Pair = p book.Exchange = b.Name book.PriceDuplication = true book.IsFundingRate = fundingRate book.VerifyOrderbook = b.CanVerifyOrderbook return b.Websocket.Orderbook.LoadSnapshot(&book) } // WsUpdateOrderbook updates the orderbook list, removing and adding to the // orderbook sides func (b *Bitfinex) WsUpdateOrderbook(p currency.Pair, assetType asset.Item, book []WebsocketBook, channelID int, sequenceNo int64, fundingRate bool) error { orderbookUpdate := buffer.Update{Asset: assetType, Pair: p} for i := range book { item := orderbook.Item{ ID: book[i].ID, Amount: book[i].Amount, Price: book[i].Price, Period: book[i].Period, } if book[i].Price > 0 { orderbookUpdate.Action = buffer.UpdateInsert if fundingRate { if book[i].Amount < 0 { item.Amount *= -1 orderbookUpdate.Bids = append(orderbookUpdate.Bids, item) } else { orderbookUpdate.Asks = append(orderbookUpdate.Asks, item) } } else { if book[i].Amount > 0 { orderbookUpdate.Bids = append(orderbookUpdate.Bids, item) } else { item.Amount *= -1 orderbookUpdate.Asks = append(orderbookUpdate.Asks, item) } } } else { orderbookUpdate.Action = buffer.Delete if fundingRate { if book[i].Amount == 1 { // delete bid orderbookUpdate.Asks = append(orderbookUpdate.Asks, item) } else { // delete ask orderbookUpdate.Bids = append(orderbookUpdate.Bids, item) } } else { if book[i].Amount == 1 { // delete bid orderbookUpdate.Bids = append(orderbookUpdate.Bids, item) } else { // delete ask orderbookUpdate.Asks = append(orderbookUpdate.Asks, item) } } } } cMtx.Lock() checkme := checksumStore[channelID] if checkme == nil { cMtx.Unlock() return b.Websocket.Orderbook.Update(&orderbookUpdate) } checksumStore[channelID] = nil cMtx.Unlock() if checkme.Sequence+1 == sequenceNo { // Sequence numbers get dropped, if checksum is not in line with // sequence, do not check. ob, err := b.Websocket.Orderbook.GetOrderbook(p, assetType) if err != nil { return fmt.Errorf("cannot calculate websocket checksum: book not found for %s %s %w", p, assetType, err) } err = validateCRC32(ob, checkme.Token) if err != nil { return err } } return b.Websocket.Orderbook.Update(&orderbookUpdate) } // GenerateDefaultSubscriptions Adds default subscriptions to websocket to be handled by ManageSubscriptions() func (b *Bitfinex) GenerateDefaultSubscriptions() ([]stream.ChannelSubscription, error) { var channels = []string{ wsBook, wsTrades, wsTicker, wsCandles, } var subscriptions []stream.ChannelSubscription assets := b.GetAssetTypes(true) for i := range assets { enabledPairs, err := b.GetEnabledPairs(assets[i]) if err != nil { return nil, err } for j := range channels { for k := range enabledPairs { params := make(map[string]interface{}) if channels[j] == wsBook { params["prec"] = "R0" params["len"] = "100" } if channels[j] == wsCandles { // TODO: Add ability to select timescale && funding period var fundingPeriod string prefix := "t" if assets[i] == asset.MarginFunding { prefix = "f" fundingPeriod = ":p30" } params["key"] = "trade:1m:" + prefix + enabledPairs[k].String() + fundingPeriod } else { params["symbol"] = enabledPairs[k].String() } subscriptions = append(subscriptions, stream.ChannelSubscription{ Channel: channels[j], Currency: enabledPairs[k], Params: params, Asset: assets[i], }) } } } return subscriptions, nil } // Subscribe sends a websocket message to receive data from the channel func (b *Bitfinex) Subscribe(channelsToSubscribe []stream.ChannelSubscription) error { var errs common.Errors checksum := make(map[string]interface{}) checksum["event"] = "conf" checksum["flags"] = bitfinexChecksumFlag + bitfinexWsSequenceFlag err := b.Websocket.Conn.SendJSONMessage(checksum) if err != nil { return err } for i := range channelsToSubscribe { req := make(map[string]interface{}) req["event"] = "subscribe" req["channel"] = channelsToSubscribe[i].Channel for k, v := range channelsToSubscribe[i].Params { req[k] = v } err := b.Websocket.Conn.SendJSONMessage(req) if err != nil { errs = append(errs, err) continue } b.Websocket.AddSuccessfulSubscriptions(channelsToSubscribe[i]) } if errs != nil { return errs } return nil } // Unsubscribe sends a websocket message to stop receiving data from the channel func (b *Bitfinex) Unsubscribe(channelsToUnsubscribe []stream.ChannelSubscription) error { var errs common.Errors for i := range channelsToUnsubscribe { req := make(map[string]interface{}) req["event"] = "unsubscribe" req["channel"] = channelsToUnsubscribe[i].Channel for k, v := range channelsToUnsubscribe[i].Params { req[k] = v } err := b.Websocket.Conn.SendJSONMessage(req) if err != nil { errs = append(errs, err) continue } b.Websocket.RemoveSuccessfulUnsubscriptions(channelsToUnsubscribe[i]) } if errs != nil { return errs } return nil } // WsSendAuth sends a autheticated event payload func (b *Bitfinex) WsSendAuth() error { if !b.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) { return fmt.Errorf("%v AuthenticatedWebsocketAPISupport not enabled", b.Name) } nonce := strconv.FormatInt(time.Now().Unix(), 10) payload := "AUTH" + nonce hmac, err := crypto.GetHMAC(crypto.HashSHA512_384, []byte(payload), []byte(b.API.Credentials.Secret)) if err != nil { return err } request := WsAuthRequest{ Event: "auth", APIKey: b.API.Credentials.Key, AuthPayload: payload, AuthSig: crypto.HexEncodeToString(hmac), AuthNonce: nonce, DeadManSwitch: 0, } err = b.Websocket.AuthConn.SendJSONMessage(request) if err != nil { b.Websocket.SetCanUseAuthenticatedEndpoints(false) return err } return nil } // WsAddSubscriptionChannel adds a new subscription channel to the // WebsocketSubdChannels map in bitfinex.go (Bitfinex struct) func (b *Bitfinex) WsAddSubscriptionChannel(chanID int, channel, pair string) { chanInfo := WebsocketChanInfo{Pair: pair, Channel: channel} b.WebsocketSubdChannels[chanID] = chanInfo if b.Verbose { log.Debugf(log.ExchangeSys, "%s Subscribed to Channel: %s Pair: %s ChannelID: %d\n", b.Name, channel, pair, chanID) } } // WsNewOrder authenticated new order request func (b *Bitfinex) WsNewOrder(data *WsNewOrderRequest) (string, error) { data.CustomID = b.Websocket.AuthConn.GenerateMessageID(false) request := makeRequestInterface(wsOrderNew, data) resp, err := b.Websocket.AuthConn.SendMessageReturnResponse(data.CustomID, request) if err != nil { return "", err } if resp == nil { return "", errors.New(b.Name + " - Order message not returned") } var respData []interface{} err = json.Unmarshal(resp, &respData) if err != nil { return "", err } if len(respData) < 3 { return "", errors.New("unexpected respData length") } responseDataDetail, ok := respData[2].([]interface{}) if !ok { return "", errors.New("unable to type assert respData") } if len(responseDataDetail) < 4 { return "", errors.New("invalid responseDataDetail length") } responseOrderDetail, ok := responseDataDetail[4].([]interface{}) if !ok { return "", errors.New("unable to type assert responseOrderDetail") } var orderID string if responseOrderDetail[0] != nil { if ordID, ordOK := responseOrderDetail[0].(float64); ordOK && ordID > 0 { orderID = strconv.FormatFloat(ordID, 'f', -1, 64) } } var errorMessage, errCode string if len(responseDataDetail) > 6 { errCode, ok = responseDataDetail[6].(string) if !ok { return "", errors.New("unable to type assert errCode") } } if len(responseDataDetail) > 7 { errorMessage, ok = responseDataDetail[7].(string) if !ok { return "", errors.New("unable to type assert errorMessage") } } if strings.EqualFold(errCode, wsError) { return orderID, errors.New(b.Name + " - " + errCode + ": " + errorMessage) } return orderID, nil } // WsModifyOrder authenticated modify order request func (b *Bitfinex) WsModifyOrder(data *WsUpdateOrderRequest) error { request := makeRequestInterface(wsOrderUpdate, data) resp, err := b.Websocket.AuthConn.SendMessageReturnResponse(data.OrderID, request) if err != nil { return err } if resp == nil { return errors.New(b.Name + " - Order message not returned") } var responseData []interface{} err = json.Unmarshal(resp, &responseData) if err != nil { return err } if len(responseData) < 3 { return errors.New("unexpected responseData length") } responseOrderData, ok := responseData[2].([]interface{}) if !ok { return errors.New("unable to type assert responseOrderData") } var errorMessage, errCode string if len(responseOrderData) > 6 { errCode, ok = responseOrderData[6].(string) if !ok { return errors.New("unable to type assert errCode") } } if len(responseOrderData) > 7 { errorMessage, ok = responseOrderData[7].(string) if !ok { return errors.New("unable to type assert errorMessage") } } if strings.EqualFold(errCode, wsError) { return errors.New(b.Name + " - " + errCode + ": " + errorMessage) } return nil } // WsCancelMultiOrders authenticated cancel multi order request func (b *Bitfinex) WsCancelMultiOrders(orderIDs []int64) error { cancel := WsCancelGroupOrdersRequest{ OrderID: orderIDs, } request := makeRequestInterface(wsCancelMultipleOrders, cancel) return b.Websocket.AuthConn.SendJSONMessage(request) } // WsCancelOrder authenticated cancel order request func (b *Bitfinex) WsCancelOrder(orderID int64) error { cancel := WsCancelOrderRequest{ OrderID: orderID, } request := makeRequestInterface(wsOrderCancel, cancel) resp, err := b.Websocket.AuthConn.SendMessageReturnResponse(orderID, request) if err != nil { return err } if resp == nil { return fmt.Errorf("%v - Order %v failed to cancel", b.Name, orderID) } var responseData []interface{} err = json.Unmarshal(resp, &responseData) if err != nil { return err } if len(responseData) < 3 { return errors.New("unexpected responseData length") } responseOrderData, ok := responseData[2].([]interface{}) if !ok { return errors.New("unable to type assert responseOrderData") } var errorMessage, errCode string if len(responseOrderData) > 6 { errCode, ok = responseOrderData[6].(string) if !ok { return errors.New("unable to type assert errCode") } } if len(responseOrderData) > 7 { errorMessage, ok = responseOrderData[7].(string) if !ok { return errors.New("unable to type assert errorMessage") } } if strings.EqualFold(errCode, wsError) { return errors.New(b.Name + " - " + errCode + ": " + errorMessage) } return nil } // WsCancelAllOrders authenticated cancel all orders request func (b *Bitfinex) WsCancelAllOrders() error { cancelAll := WsCancelAllOrdersRequest{All: 1} request := makeRequestInterface(wsCancelMultipleOrders, cancelAll) return b.Websocket.AuthConn.SendJSONMessage(request) } // WsNewOffer authenticated new offer request func (b *Bitfinex) WsNewOffer(data *WsNewOfferRequest) error { request := makeRequestInterface(wsFundingOrderNew, data) return b.Websocket.AuthConn.SendJSONMessage(request) } // WsCancelOffer authenticated cancel offer request func (b *Bitfinex) WsCancelOffer(orderID int64) error { cancel := WsCancelOrderRequest{ OrderID: orderID, } request := makeRequestInterface(wsFundingOrderCancel, cancel) resp, err := b.Websocket.AuthConn.SendMessageReturnResponse(orderID, request) if err != nil { return err } if resp == nil { return fmt.Errorf("%v - Order %v failed to cancel", b.Name, orderID) } var responseData []interface{} err = json.Unmarshal(resp, &responseData) if err != nil { return err } if len(responseData) < 3 { return errors.New("unexpected responseData length") } responseOrderData, ok := responseData[2].([]interface{}) if !ok { return errors.New("unable to type assert responseOrderData") } var errorMessage, errCode string if len(responseOrderData) > 6 { errCode, ok = responseOrderData[6].(string) if !ok { return errors.New("unable to type assert errCode") } } if len(responseOrderData) > 7 { errorMessage, ok = responseOrderData[7].(string) if !ok { return errors.New("unable to type assert errorMessage") } } if strings.EqualFold(errCode, wsError) { return errors.New(b.Name + " - " + errCode + ": " + errorMessage) } return nil } func makeRequestInterface(channelName string, data interface{}) []interface{} { return []interface{}{0, channelName, nil, data} } func validateCRC32(book *orderbook.Base, token int) error { // Order ID's need to be sub-sorted in ascending order, this needs to be // done on the main book to ensure that we do not cut price levels out below reOrderByID(book.Bids) reOrderByID(book.Asks) // RO precision calculation is based on order ID's and amount values var bids, asks []orderbook.Item for i := 0; i < 25; i++ { if i < len(book.Bids) { bids = append(bids, book.Bids[i]) } if i < len(book.Asks) { asks = append(asks, book.Asks[i]) } } // ensure '-' (negative amount) is passed back to string buffer as // this is needed for calcs - These get swapped if funding rate bidmod := float64(1) if book.IsFundingRate { bidmod = -1 } askMod := float64(-1) if book.IsFundingRate { askMod = 1 } var check strings.Builder for i := 0; i < 25; i++ { if i < len(bids) { check.WriteString(strconv.FormatInt(bids[i].ID, 10)) check.WriteString(":") check.WriteString(strconv.FormatFloat(bidmod*bids[i].Amount, 'f', -1, 64)) check.WriteString(":") } if i < len(asks) { check.WriteString(strconv.FormatInt(asks[i].ID, 10)) check.WriteString(":") check.WriteString(strconv.FormatFloat(askMod*asks[i].Amount, 'f', -1, 64)) check.WriteString(":") } } checksumStr := strings.TrimSuffix(check.String(), ":") checksum := crc32.ChecksumIEEE([]byte(checksumStr)) if checksum == uint32(token) { return nil } return fmt.Errorf("invalid checksum for %s %s: calculated [%d] does not match [%d]", book.Asset, book.Pair, checksum, uint32(token)) } // reOrderByID sub sorts orderbook items by its corresponding ID when price // levels are the same. TODO: Deprecate and shift to buffer level insertion // based off ascending ID. func reOrderByID(depth []orderbook.Item) { subSort: for x := 0; x < len(depth); { var subset []orderbook.Item // Traverse forward elements for y := x + 1; y < len(depth); y++ { if depth[x].Price == depth[y].Price && // Period matching is for funding rates, this was undocumented // but these need to be matched with price for the correct ID // alignment depth[x].Period == depth[y].Period { // Append element to subset when price match occurs subset = append(subset, depth[y]) // Traverse next continue } if len(subset) != 0 { // Append root element subset = append(subset, depth[x]) // Sort IDs by ascending sort.Slice(subset, func(i, j int) bool { return subset[i].ID < subset[j].ID }) // Re-align elements with sorted ID subset for z := range subset { depth[x+z] = subset[z] } } // When price is not matching change checked element to root x = y continue subSort } break } } <file_sep>package binance import ( "context" "fmt" "net/http" "net/url" "strconv" "strings" exchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/request" ) // GetContractBalance 获取合约余额 // [uFuture]UAccountBalanceV2 [cFuture]GetFuturesAccountBalance // func (b *Binance) GetContractBalance(assetType asset.Item) ([]*ContractBalanceResponse, error) { // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, biananceContractbalance) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, biananceContractbalance) // } else { // return nil, fmt.Errorf("Error assetType") // } // // params := url.Values{} // var resp []*ContractBalanceResponse // var err error // if err = b.SendAuthHTTPRequest(http.MethodGet, path, nil, limitOrder, &resp); err != nil { // return nil, err // } // return resp, nil // } // Transfer 用户万向划转 func (b *Binance) Transfer(ctx context.Context, transferType TransferType, symbolBase string, amount float64) (tranId int64, err error) { path := defaultTransfer params := url.Values{} params.Set("type", string(transferType)) params.Set("asset", symbolBase) params.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64)) type response struct { TranId int64 } var resp response if err = b.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, path, params, spotDefaultRate, &resp); err != nil { return 0, err } return resp.TranId, err } // GetContractTradeFee 获取合约手续费 func (b *Binance) GetContractTradeFee(ctx context.Context, assetType asset.Item, symbol string) (*ContractTradeFeeResponse, error) { var path string var ePath exchange.URL var f request.EndpointLimit if assetType == asset.USDTMarginedFutures { // U本位合约 path = ufuturesTradeFree ePath = exchange.RestUSDTMargined f = uFuturesDefaultRate } else if assetType == asset.CoinMarginedFutures { // 币本位合约 path = cfuturesTradeFree ePath = exchange.RestCoinMargined f = cFuturesDefaultRate } else { return nil, fmt.Errorf("Error assetType") } params := url.Values{} params.Set("symbol", symbol) var resp ContractTradeFeeResponse var err error if err = b.SendAuthHTTPRequest(ctx, ePath, http.MethodGet, path, params, f, &resp); err != nil { return nil, err } return &resp, nil } // GetSpotTradeFee 查询现货手续费 (USER_DATA) func (b *Binance) GetSpotTradeFee(ctx context.Context, symbol string) ([]SpotTradeFeeResponse, error) { params := url.Values{} if symbol != "" { params.Set("symbol", symbol) } var resp []SpotTradeFeeResponse if err := b.SendAuthHTTPRequest(ctx, exchange.RestSpotSupplementary, http.MethodGet, spotTradeFee, params, spotDefaultRate, &resp); err != nil { return resp, err } return resp, nil } // DualQuery 查询持仓模式(USER_DATA) // "true": 双向持仓模式;"false": 单向持仓模式 func (b *Binance) DualQuery(ctx context.Context, assetType asset.Item) (flag bool, err error) { var path string var ePath exchange.URL var f request.EndpointLimit if assetType == asset.USDTMarginedFutures { // U本位合约 path = ufuturesDualQuery ePath = exchange.RestUSDTMargined f = uFuturesDefaultRate } else if assetType == asset.CoinMarginedFutures { // 币本位合约 path = cfuturesDualQuery ePath = exchange.RestCoinMargined f = cFuturesDefaultRate } else { return false, fmt.Errorf("Error assetType") } type response struct { DualSidePosition bool `json:'dualSidePosition'` } var resp response if err = b.SendAuthHTTPRequest(ctx, ePath, http.MethodGet, path, url.Values{}, f, &resp); err != nil { return false, err } return resp.DualSidePosition, err } // Dual 更改持仓模式(TRADE) // 变换用户在 所有symbol 合约上的持仓模式:双向持仓或单向持仓。"true": 双向持仓模式;"false": 单向持仓模式 func (b *Binance) Dual(ctx context.Context, assetType asset.Item, dualSide bool) (flag bool, err error) { params := url.Values{} if dualSide { params.Set("dualSidePosition", "true") } else { params.Set("dualSidePosition", "false") } var path string var ePath exchange.URL var f request.EndpointLimit if assetType == asset.USDTMarginedFutures { // U本位合约 path = ufuturesDualQuery ePath = exchange.RestUSDTMargined f = uFuturesDefaultRate } else if assetType == asset.CoinMarginedFutures { // 币本位合约 path = cfuturesDualQuery ePath = exchange.RestCoinMargined f = cFuturesDefaultRate } else { return false, fmt.Errorf("Error assetType") } type response struct { Code int `json:"code"` Msg string `json:"msg"` } var resp response err = b.SendAuthHTTPRequest(ctx, ePath, http.MethodPost, path, params, f, &resp) if strings.Index(err.Error(), "{\"code\":-4059,\"msg\":\"No need to change position side.\"}") != -1 { return true, nil } else if !strings.EqualFold(err.Error(), "success") { return false, err } return true, nil } // Ping 测试服务器连通性 func (b *Binance) Ping(ctx context.Context, assetType asset.Item) (ping bool, err error) { var path string var ePath exchange.URL var f request.EndpointLimit if assetType == asset.Spot { path = spotPingServer ePath = exchange.RestSpot f = spotDefaultRate } else if assetType == asset.USDTMarginedFutures { // U本位合约 path = ufuturesPingServer ePath = exchange.RestUSDTMargined f = uFuturesDefaultRate } else if assetType == asset.CoinMarginedFutures { // 币本位合约 path = cfuturesPingServer ePath = exchange.RestCoinMargined f = cFuturesDefaultRate } else { return false, fmt.Errorf("Error assetType") } if err = b.SendHTTPRequest(ctx, ePath, path, f, nil); err != nil { return false, err } return true, nil } // GetPrice 最新价格------> [Spot]GetLatestSpotPrice [uFuture]USymbolPriceTicker [cFuture]GetFuturesSymbolPriceTicker // func (b *Binance) GetPrice(assetType asset.Item, pair currency.Pair) (price float64, err error) { // params := url.Values{} // type response struct { // Symbol string `json:"symbol"` // Price string `json:"price"` // } // var resp response // var path string // if assetType == asset.Spot { // 现货 // params.Set("symbol", pair.Base.String()+pair.Quote.String()) // path = fmt.Sprintf("%s/%s/v%s/ticker/%s?%s", b.API.Endpoints.URL, binanceSpotRESTBasePath, binanceAPIVersion3, binancePrice, params.Encode()) // if err = b.SendHTTPRequest(path, limitDefault, &resp); err != nil { // return price, err // } // if price, err = strconv.ParseFloat(resp.Price, 64); err != nil { // return price, err // } // return price, nil // } else if assetType == asset.Future { // U本位合约 // params.Set("symbol", pair.String()) // path = fmt.Sprintf("%s/%s/v%s/ticker/%s?%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binancePrice, params.Encode()) // if err = b.SendHTTPRequest(path, limitDefault, &resp); err != nil { // return price, err // } // if price, err = strconv.ParseFloat(resp.Price, 64); err != nil { // return price, err // } // return price, nil // } else if assetType == asset.PerpetualContract { // 币本位合约 // type response struct { // Symbol string `json:"symbol"` // Pair string `json:"ps"` // Price string `json:"price"` // Time int64 `json:"time"` // } // var resp []response // params.Set("symbol", pair.String()) // path = fmt.Sprintf("%s/%s/v%s/ticker/%s?%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binancePrice, params.Encode()) // if err = b.SendHTTPRequest(path, limitDefault, &resp); err != nil { // return price, err // } // if price, err = strconv.ParseFloat(resp[0].Price, 64); err != nil { // return price, err // } // return price, nil // } else { // return price, fmt.Errorf("Error assetType") // } // } // SpotSubmitOrder submits a new order 可以用 SubmitOrder 替代 // func (b *Binance) SpotSubmitOrder(ctx context.Context,s *SpotSubmit) (order.SubmitResponse, error) { // var submitOrderResponse order.SubmitResponse // var sideType string // if s.Side == order.Buy { // sideType = order.Buy.String() // } else { // sideType = order.Sell.String() // } // timeInForce := s.TimeInForce // var requestParamsOrderType RequestParamsOrderType // switch s.Type { // case order.Market: // timeInForce = "" // requestParamsOrderType = BinanceRequestParamsOrderMarket // case order.Limit: // requestParamsOrderType = BinanceRequestParamsOrderLimit // default: // submitOrderResponse.IsOrderPlaced = false // return submitOrderResponse, errors.New("unsupported order type") // } // // fPair, err := b.FormatExchangeCurrency(s.Symbol, s.AssetType) // // if err != nil { // // return submitOrderResponse, err // // } // var orderRequest = NewOrderRequest{ // Symbol: s.Symbol, // Side: sideType, // Price: s.Price, // Quantity: s.Quantity, // QuoteOrderQty: s.QuoteOrderQty, // TradeType: requestParamsOrderType, // TimeInForce: timeInForce, // NewClientOrderID: s.NewClientOrderId, // StopPrice: s.StopPrice, // IcebergQty: s.IcebergQty, // } // response, err := b.NewOrder(&orderRequest) // if err != nil { // return submitOrderResponse, err // } // if response.OrderID > 0 { // submitOrderResponse.OrderID = strconv.FormatInt(response.OrderID, 10) // } // if response.ExecutedQty == response.OrigQty { // submitOrderResponse.FullyMatched = true // } // submitOrderResponse.IsOrderPlaced = true // for i := range response.Fills { // submitOrderResponse.Trades = append(submitOrderResponse.Trades, order.TradeHistory{ // Price: response.Fills[i].Price, // Amount: response.Fills[i].Qty, // Fee: response.Fills[i].Commission, // FeeAsset: response.Fills[i].CommissionAsset, // }) // } // return submitOrderResponse, nil // } // ExchangeInfo returns exchange information. Check binance_types for more // information spot[GetExchangeInfo] ufuture[UExchangeInfo] cfuture[FuturesExchangeInfo] // func (b *Binance) ExchangeInfo(assetType asset.Item) (ExchangeInfo, error) { // var resp ExchangeInfo // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractExchangeInfo) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractExchangeInfo) // } else { // return resp, fmt.Errorf("Error assetType") // } // return resp, b.SendHTTPRequest(path, limitDefault, &resp) // } // Account 账户信息V2 (USER_DATA) // [spot]GetAccount ufuture[UAccountInformationV2] [cfuture]GetFuturesAccountInfo // func (b *Binance) Account(assetType asset.Item) (*AccountInfoFuture, error) { // params := url.Values{} // var resp AccountInfoFuture // var err error // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion2, binanceContractAccount) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractAccount) // } else { // return &resp, fmt.Errorf("Error assetType") // } // if err = b.SendAuthHTTPRequest(http.MethodGet, path, params, limitOrder, &resp); err != nil { // return nil, err // } // return &resp, nil // } // ADLQuantile 持仓ADL队列估算 // [ufuture]UPositionsADLEstimate [cfuture]FuturesPositionsADLEstimate // func (b *Binance) ADLQuantile(assetType asset.Item, symbol currency.Pair) (*AdlQuantileResponse, error) { // var result *AdlQuantileResponse // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractAdlQuantile) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractAdlQuantile) // } else { // return result, fmt.Errorf("Error assetType") // } // params := url.Values{} // params.Set("symbol", symbol.String()) // var resp interface{} // var err error // if err = b.SendAuthHTTPRequest(http.MethodGet, path, params, limitOrder, &resp); err != nil { // return result, err // } // p := &AdlQuantileResponse{} // mapObj := resp.(map[string]interface{}) // if mapObj["symbol"] == nil { // return nil, nil // } // p.Symbol = mapObj["symbol"].(string) // adlObj := mapObj["adlQuantile"].(map[string]interface{}) // p.AdlQuantile.LONG = adlObj["LONG"].(float64) // p.AdlQuantile.SHORT = adlObj["SHORT"].(float64) // if adlObj["HEDGE"] != nil { // p.AdlQuantile.HEDGE = adlObj["HEDGE"].(float64) // } // if mapObj["BOTH"] != nil { // p.AdlQuantile.BOTH = adlObj["BOTH"].(float64) // } // return p, nil // } // Income 获取账户损益资金流水 // [ufutures]UAccountIncomeHistory [cfutures]FuturesIncomeHistory // func (b *Binance) Income(assetType asset.Item, req IncomeRequest) ([]IncomeResponse, error) { // params := url.Values{} // if req.Symbol != "" { // params.Set("symbol", strings.ToUpper(req.Symbol)) // } // if req.IncomeType != IncomeType_ALL { // params.Set("incomeType", string(req.IncomeType)) // } // if req.StartTime != 0 { // params.Set("startTime", strconv.FormatInt(req.StartTime, 10)) // } // if req.EndTime != 0 { // params.Set("endTime", strconv.FormatInt(req.EndTime, 10)) // } // if req.Limit != 0 { // params.Set("limit", strconv.FormatInt(req.Limit, 10)) // } // var result []IncomeResponse // var resp []interface{} // var err error // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractIncome) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractIncome) // } else { // return result, fmt.Errorf("Error assetType") // } // if err = b.SendAuthHTTPRequest(http.MethodGet, path, params, limitOrder, &resp); err != nil { // return result, err // } // for _, v := range resp { // p := IncomeResponse{} // mapObj := v.(map[string]interface{}) // p.Symbol = mapObj["symbol"].(string) // p.IncomeType = IncomeType(mapObj["incomeType"].(string)) // if p.Income, err = strconv.ParseFloat(mapObj["income"].(string), 64); err != nil { // return nil, err // } // p.Asset = mapObj["asset"].(string) // p.Info = mapObj["info"].(string) // p.Time = time.Unix(0, int64(mapObj["time"].(float64))*int64(time.Millisecond)) // if mapObj["tranId"] == nil { // p.TranId = 0 // } else { // p.TranId = int64(mapObj["tranId"].(float64)) // } // if mapObj["tradeId"].(string) == "" { // p.TradeId = 0 // } else { // if p.TradeId, err = strconv.ParseInt(mapObj["tradeId"].(string), 10, 64); err != nil { // return nil, err // } // } // result = append(result, p) // } // return result, nil // } // Leverage 调整开仓杠杆 // [uFuture]UChangeInitialLeverageRequest [cFuture]FuturesChangeInitialLeverage // func (b *Binance) Leverage(assetType asset.Item, symbol string, leverage int) (*FutureLeverageResponse, error) { // params := url.Values{} // params.Set("symbol", symbol) // params.Set("leverage", strconv.FormatInt(int64(leverage), 10)) // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceLeverage) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceLeverage) // } else { // return nil, fmt.Errorf("Error assetType") // } // var resp interface{} // err := b.SendAuthHTTPRequest(http.MethodPost, path, params, limitOrder, &resp) // if err != nil { // return nil, err // } // mapObj := resp.(map[string]interface{}) // result := &FutureLeverageResponse{} // result.Symbol = mapObj["symbol"].(string) // result.Leverage = int(mapObj["leverage"].(float64)) // if mapObj["maxNotionalValue"] != nil { // if result.MaxNotionalValue, err = strconv.ParseInt(mapObj["maxNotionalValue"].(string), 10, 64); err != nil { // return nil, err // } // } // return result, err // } // OpenOrdersContract Current open orders. Get all open orders on a symbol. // Careful when accessing this with no symbol: The number of requests counted against the rate limiter // is significantly higher // [uFuture]UAllAccountOpenOrders [cFuture]GetFuturesAllOpenOrders // func (b *Binance) OpenOrdersContract(assetType asset.Item, symbol string) ([]FutureQueryOrderData, error) { // type Response struct { // AvgPrice float64 `json:"avgPrice,string"` // 平均成交价 // ClientOrderID string `json:"clientOrderId"` // 用户自定义的订单号 // CumQuote float64 `json:"cumQuote,string"` //成交金额 // ExecutedQty float64 `json:"executedQty,string"` //成交量 // OrderID int64 `json:"orderId"` // OrigQty float64 `json:"origQty,string"` // 原始委托数量 // OrigType string `json:"origType"` // Price float64 `json:"price,string"` // ReduceOnly bool `json:"reduceOnly"` // 是否仅减仓 // Side order.Side `json:"side"` // PositionSide PositionSide `json:"positionSide"` // 持仓方向 // Status order.Status `json:"status"` // StopPrice float64 `json:"stopPrice,string"` // 触发价,对`TRAILING_STOP_MARKET`无效 // ClosePosition bool `json:"closePosition"` // 是否条件全平仓 // Symbol string `json:"symbol"` // Time float64 `json:"time"` // 订单时间 // TimeInForce RequestParamsTimeForceType `json:"timeInForce"` // 有效方法 // Type string `json:"type"` //订单类型 // ActivatePrice float64 `json:"activatePrice,string"` // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 // PriceRate float64 `json:"priceRate,string"` // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 // UpdateTime int64 `json:"updateTime"` // WorkingType WorkingType `json:"workingType"` // 条件价格触发类型 // PriceProtect bool `json:"priceProtect"` // 是否开启条件单触发保护 // } // var respList []Response // var result []FutureQueryOrderData // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractOpenOrders) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractOpenOrders) // } else { // return nil, fmt.Errorf("Error assetType") // } // params := url.Values{} // if symbol != "" { // params.Set("symbol", strings.ToUpper(symbol)) // } // if err := b.SendAuthHTTPRequest(http.MethodGet, path, params, openOrdersLimit(symbol), &respList); err != nil { // return result, err // } // for _, resp := range respList { // result = append(result, FutureQueryOrderData{ // AvgPrice: resp.AvgPrice, // ClientOrderID: resp.ClientOrderID, // CumQuote: resp.CumQuote, // ExecutedQty: resp.ExecutedQty, // OrderID: resp.OrderID, // OrigQty: resp.OrigQty, // OrigType: resp.OrigType, // Price: resp.Price, // ReduceOnly: resp.ReduceOnly, // Side: resp.Side, // PositionSide: resp.PositionSide, // Status: resp.Status, // StopPrice: resp.StopPrice, // ClosePosition: resp.ClosePosition, // Symbol: resp.Symbol, // TimeInForce: resp.TimeInForce, // Type: resp.Type, // ActivatePrice: resp.ActivatePrice, // PriceRate: resp.PriceRate, // WorkingType: resp.WorkingType, // PriceProtect: resp.PriceProtect, // Time: time.Unix(0, int64(resp.Time)*int64(time.Millisecond)), // UpdateTime: time.Unix(0, resp.UpdateTime*int64(time.Millisecond)), // }) // } // return result, nil // } // ForceOrders 用户强平单历史 (USER_DATA) // [uFuture]UAccountForcedOrders [cFuture]FuturesForceOrders // func (b *Binance) ForceOrders(assetType asset.Item, symbol string, startTime, endTime, limit int64) ([]FutureQueryOrderData, error) { // type Response struct { // OrderID int64 `json:"orderId"` // Symbol string `json:"symbol"` // Status order.Status `json:"status"` // ClientOrderID string `json:"clientOrderId"` // 用户自定义的订单号 // Price float64 `json:"price,string"` // AvgPrice float64 `json:"avgPrice,string"` // 平均成交价 // OrigQty float64 `json:"origQty,string"` // 原始委托数量 // ExecutedQty float64 `json:"executedQty,string"` //成交量 // CumQuote float64 `json:"cumQuote,string"` //成交金额 // TimeInForce RequestParamsTimeForceType `json:"timeInForce"` // 有效方法 // OrderType string `json:"origType"` // ReduceOnly bool `json:"reduceOnly"` // 是否仅减仓 // ClosePosition bool `json:"closePosition"` // 是否条件全平仓 // Side order.Side `json:"side"` // PositionSide PositionSide `json:"positionSide"` // 持仓方向 // StopPrice float64 `json:"stopPrice,string"` // 触发价,对`TRAILING_STOP_MARKET`无效 // WorkingType WorkingType `json:"workingType"` // 条件价格触发类型 // Time float64 `json:"time"` // 订单时间 // UpdateTime int64 `json:"updateTime"` // } // var respList []Response // var result []FutureQueryOrderData // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractForceOrder) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractForceOrder) // } else { // return nil, fmt.Errorf("Error assetType") // } // params := url.Values{} // if symbol != "" { // params.Set("symbol", strings.ToUpper(symbol)) // } // if startTime != 0 { // params.Set("startTime", strconv.FormatInt(startTime, 10)) // } // if endTime != 0 { // params.Set("endTime", strconv.FormatInt(startTime, 10)) // } // if limit != 0 { // params.Set("limit", strconv.FormatInt(limit, 10)) // } // if err := b.SendAuthHTTPRequest(http.MethodGet, path, params, openOrdersLimit(symbol), &respList); err != nil { // return result, err // } // for _, resp := range respList { // result = append(result, FutureQueryOrderData{ // AvgPrice: resp.AvgPrice, // ClientOrderID: resp.ClientOrderID, // CumQuote: resp.CumQuote, // ExecutedQty: resp.ExecutedQty, // OrderID: resp.OrderID, // OrigQty: resp.OrigQty, // OrigType: resp.OrderType, // Price: resp.Price, // ReduceOnly: resp.ReduceOnly, // Side: resp.Side, // PositionSide: resp.PositionSide, // Status: resp.Status, // StopPrice: resp.StopPrice, // ClosePosition: resp.ClosePosition, // Symbol: resp.Symbol, // TimeInForce: resp.TimeInForce, // WorkingType: resp.WorkingType, // Time: time.Unix(0, int64(resp.Time)*int64(time.Millisecond)), // UpdateTime: time.Unix(0, resp.UpdateTime*int64(time.Millisecond)), // }) // } // return result, nil // } // // NewFutureOrder sends a new order to Binance // func (b *Binance) NewOrderFuture(o *NewOrderContractRequest) (resp *FutureNewOrderResponse, err error) { // if resp, err = b.newOrderFuture(o); err != nil { // return resp, err // } // return resp, nil // } // NewOrderContract sends a new order to Binance // [uFuture]SubmitOrder [cFuture]SubmitOrder // func (b *Binance) NewOrderContract(assetType asset.Item, o *NewOrderContractRequest) (result *NewOrderContractResponse, err error) { // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractNewOrder) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractNewOrder) // } else { // return nil, fmt.Errorf("Error assetType") // } // params := url.Values{} // params.Set("symbol", o.Symbol) // params.Set("side", string(o.Side)) // params.Set("type", string(o.Type)) // params.Set("positionSide", string(o.PositionSide)) // params.Set("quantity", strconv.FormatFloat(o.Quantity, 'f', -1, 64)) // if o.Type == BinanceRequestParamsOrderLimit { // params.Set("price", strconv.FormatFloat(o.Price, 'f', -1, 64)) // } // if o.TimeInForce != "" { // params.Set("timeInForce", string(o.TimeInForce)) // } // if o.NewClientOrderID != "" { // params.Set("newClientOrderID", o.NewClientOrderID) // } // if o.StopPrice != 0 { // params.Set("stopPrice", strconv.FormatFloat(o.StopPrice, 'f', -1, 64)) // } // if o.NewOrderRespType != "" { // params.Set("newOrderRespType", o.NewOrderRespType) // } // type Response struct { // Symbol string `json:"symbol"` //交易对 // OrderID int64 `json:"orderId"` // ClientOrderID string `json:"clientOrderId"` // AvgPrice string `json:"avgPrice, string"` //平均成交价 // Price float64 `json:"price,string"` //委托价格 // OrigQty float64 `json:"origQty,string"` //原始委托数量 // CumQty float64 `json:"cumQty,string"` // CumQuote float64 `json:"cumQuote,string"` //成交金额 // // The cumulative amount of the quote that has been spent (with a BUY order) or received (with a SELL order). // ExecutedQty float64 `json:"executedQty,string"` //成交量 // Status order.Status `json:"status"` //订单状态 // TimeInForce RequestParamsTimeForceType `json:"timeInForce"` //有效方法 // Type order.Type `json:"type"` //订单类型 // Side order.Side `json:"side"` //买卖方向 // PositionSide string `json:"positionSide"` //持仓方向 // StopPrice string `json:"stopPrice"` //触发价,对`TRAILING_STOP_MARKET`无效 // ClosePosition bool `json:"closePosition"` //是否条件全平仓 // OrigType string `json:"origType"` //触发前订单类型 // ActivatePrice string `json:"activatePrice"` //跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 // PriceRate string `json:"priceRate"` //跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 // UpdateTime int64 `json:"updateTime"` // 更新时间 // WorkingType WorkingType `json:"workingType"` // 条件价格触发类型 // PriceProtect bool `json:"priceProtect"` // 是否开启条件单触发保护 // } // var resp Response // if err = b.SendAuthHTTPRequest(http.MethodPost, path, params, limitOrder, &resp); err != nil { // return result, err // } // result = &NewOrderContractResponse{ // Symbol: resp.Symbol, // OrderID: resp.OrderID, // ClientOrderID: resp.ClientOrderID, // Price: resp.Price, // OrigQty: resp.OrigQty, // CumQty: resp.CumQty, // CumQuote: resp.CumQuote, // ExecutedQty: resp.ExecutedQty, // Status: resp.Status, // TimeInForce: resp.TimeInForce, // Type: resp.Type, // Side: resp.Side, // PositionSide: resp.PositionSide, // StopPrice: resp.StopPrice, // ClosePosition: resp.ClosePosition, // OrigType: resp.OrigType, // ActivatePrice: resp.ActivatePrice, // PriceRate: resp.PriceRate, // UpdateTime: time.Unix(0, resp.UpdateTime*int64(time.Millisecond)), // } // if result.AvgPrice, err = strconv.ParseFloat(resp.AvgPrice, 64); err != nil { // return nil, err // } // return result, nil // } // QueryOrderContract returns information on a past order // [uFuture]UGetOrderData [cFuture]FuturesGetOrderData // func (b *Binance) QueryOrderContract(assetType asset.Item, symbol string, orderID int64, origClientOrderID string) (FutureQueryOrderData, error) { // type Response struct { // AvgPrice float64 `json:"avgPrice,string"` // 平均成交价 // ClientOrderID string `json:"clientOrderId"` // 用户自定义的订单号 // CumBase float64 `json:"cumBase,string"` //成交额(标的数量) // CumQuote float64 `json:"cumQuote,string"` //成交金额 // ExecutedQty float64 `json:"executedQty,string"` //成交量 // OrderID int64 `json:"orderId"` // OrigQty float64 `json:"origQty,string"` // 原始委托数量 // OrigType string `json:"origType"` // Price float64 `json:"price,string"` // ReduceOnly bool `json:"reduceOnly"` // 是否仅减仓 // Side order.Side `json:"side"` // PositionSide PositionSide `json:"positionSide"` // 持仓方向 // Status order.Status `json:"status"` // StopPrice float64 `json:"stopPrice,string"` // 触发价,对`TRAILING_STOP_MARKET`无效 // ClosePosition bool `json:"closePosition"` // 是否条件全平仓 // Symbol string `json:"symbol"` // Time float64 `json:"time"` // 订单时间 // TimeInForce RequestParamsTimeForceType `json:"timeInForce"` // 有效方法 // Type string `json:"type"` //订单类型 // ActivatePrice float64 `json:"activatePrice,string"` // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 // PriceRate float64 `json:"priceRate,string"` // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 // UpdateTime int64 `json:"updateTime"` // WorkingType WorkingType `json:"workingType"` // 条件价格触发类型 // PriceProtect bool `json:"priceProtect"` // 是否开启条件单触发保护 // } // var resp Response // var result FutureQueryOrderData // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractQueryOrder) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractQueryOrder) // } else { // return result, fmt.Errorf("Error assetType") // } // params := url.Values{} // params.Set("symbol", strings.ToUpper(symbol)) // if origClientOrderID != "" { // params.Set("origClientOrderId", origClientOrderID) // } // if orderID != 0 { // params.Set("orderId", strconv.FormatInt(orderID, 10)) // } // if err := b.SendAuthHTTPRequest(http.MethodGet, path, params, limitOrder, &resp); err != nil { // return result, err // } // result = FutureQueryOrderData{ // AvgPrice: resp.AvgPrice, // ClientOrderID: resp.ClientOrderID, // CumBase: resp.CumBase, // CumQuote: resp.CumQuote, // ExecutedQty: resp.ExecutedQty, // OrderID: resp.OrderID, // OrigQty: resp.OrigQty, // OrigType: resp.OrigType, // Price: resp.Price, // ReduceOnly: resp.ReduceOnly, // Side: resp.Side, // PositionSide: resp.PositionSide, // Status: resp.Status, // StopPrice: resp.StopPrice, // ClosePosition: resp.ClosePosition, // Symbol: resp.Symbol, // TimeInForce: resp.TimeInForce, // Type: resp.Type, // ActivatePrice: resp.ActivatePrice, // PriceRate: resp.PriceRate, // WorkingType: resp.WorkingType, // PriceProtect: resp.PriceProtect, // Time: time.Unix(0, int64(resp.Time)*int64(time.Millisecond)), // UpdateTime: time.Unix(0, resp.UpdateTime*int64(time.Millisecond)), // } // return result, nil // } // CancelExistingOrderContract sends a cancel order to Binance // 取消订单 // [uFuture]UCancelOrder [cFuture]FuturesCancelOrder // func (b *Binance) CancelExistingOrderContract(assetType asset.Item, symbol string, orderID int64, origClientOrderID string) (CancelOrderResponse, error) { // var resp CancelOrderResponse // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceCancelOrder) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceCancelOrder) // } else { // return resp, fmt.Errorf("Error assetType") // } // params := url.Values{} // params.Set("symbol", symbol) // if orderID != 0 { // params.Set("orderId", strconv.FormatInt(orderID, 10)) // } // if origClientOrderID != "" { // params.Set("origClientOrderId", origClientOrderID) // } // return resp, b.SendAuthHTTPRequest(http.MethodDelete, path, params, limitOrder, &resp) // } // GetPremiumIndex 最新标记价格和资金费率 // [uFuture]UGetMarkPrice [cFuture]GetIndexAndMarkPrice // func (b *Binance) GetPremiumIndex(assetType asset.Item, symbol currency.Pair) (*PreminuIndexResponse, error) { // params := url.Values{} // params.Set("symbol", symbol.String()) // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s?%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractPreminuIndex, params.Encode()) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s?%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractPreminuIndex, params.Encode()) // } else { // return nil, fmt.Errorf("Error assetType") // } // var resp interface{} // var err error // if err = b.SendHTTPRequest(path, limitDefault, &resp); err != nil { // return nil, err // } // p := new(PreminuIndexResponse) // if assetType == asset.Future { // mapObj := resp.(map[string]interface{}) // if p.MarkPrice, err = strconv.ParseFloat(mapObj["markPrice"].(string), 64); err != nil { // return nil, err // } // if p.IndexPrice, err = strconv.ParseFloat(mapObj["indexPrice"].(string), 64); err != nil { // return nil, err // } // if p.LastFundingRate, err = strconv.ParseFloat(mapObj["lastFundingRate"].(string), 64); err != nil { // return nil, err // } // if p.InterestRate, err = strconv.ParseFloat(mapObj["interestRate"].(string), 64); err != nil { // return nil, err // } // p.NextFundingTime = time.Unix(0, int64(mapObj["nextFundingTime"].(float64))*int64(time.Millisecond)) // p.Time = time.Unix(0, int64(mapObj["time"].(float64))*int64(time.Millisecond)) // } else if assetType == asset.PerpetualContract { // mapObjArr := resp.([]interface{}) // mapObj := mapObjArr[0].(map[string]interface{}) // if p.MarkPrice, err = strconv.ParseFloat(mapObj["markPrice"].(string), 64); err != nil { // return nil, err // } // if p.IndexPrice, err = strconv.ParseFloat(mapObj["indexPrice"].(string), 64); err != nil { // return nil, err // } // if p.LastFundingRate, err = strconv.ParseFloat(mapObj["lastFundingRate"].(string), 64); err != nil { // return nil, err // } // if p.InterestRate, err = strconv.ParseFloat(mapObj["interestRate"].(string), 64); err != nil { // return nil, err // } // p.NextFundingTime = time.Unix(0, int64(mapObj["nextFundingTime"].(float64))*int64(time.Millisecond)) // p.Time = time.Unix(0, int64(mapObj["time"].(float64))*int64(time.Millisecond)) // } // return p, nil // } // GetFundingRate 查询资金费率历史 // [uFuture]UGetFundingHistory [cFuture]FuturesGetFundingHistory // func (b *Binance) GetFundingRate(assetType asset.Item, req FundingRateRequest) ([]FundingRateResponeItem, error) { // params := url.Values{} // if req.Symbol.String() != "" { // params.Set("symbol", req.Symbol.String()) // } // if req.Limit != 0 { // params.Set("limit", strconv.FormatInt(req.Limit, 10)) // } // if req.StartTime != 0 { // params.Set("startTime", strconv.FormatInt(req.StartTime, 10)) // } // if req.EndTime != 0 { // params.Set("endTime", strconv.FormatInt(req.EndTime, 10)) // } // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s?%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceContractFundingRate, params.Encode()) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s?%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceContractFundingRate, params.Encode()) // } else { // return nil, fmt.Errorf("Error assetType") // } // var resp []interface{} // var err error // if err = b.SendHTTPRequest(path, limitDefault, &resp); err != nil { // return nil, err // } // var result []FundingRateResponeItem // for _, v := range resp { // p := FundingRateResponeItem{} // mapObj := v.(map[string]interface{}) // p.Symbol = mapObj["symbol"].(string) // if p.FundingRate, err = strconv.ParseFloat(mapObj["fundingRate"].(string), 64); err != nil { // return nil, err // } // p.FundingTime = time.Unix(0, int64(mapObj["fundingTime"].(float64))*int64(time.Millisecond)) // result = append(result, p) // } // return result, nil // } // PositionRisk 用户持仓风险V2 (USER_DATA) // [uFuture]UPositionsInfoV2 [cFuture]FuturesPositionsInfo // func (b *Binance) PositionRisk(assetType asset.Item, symbol string) ([]PositionRiskResponse, error) { // params := url.Values{} // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion2, binancePositionRisk) // params.Set("symbol", strings.ToUpper(symbol)) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binancePositionRisk) // params.Set("pair", strings.ToUpper(symbol)) // } else { // return nil, fmt.Errorf("Error assetType") // } // var result []PositionRiskResponse // var resp []interface{} // var err error // if err = b.SendAuthHTTPRequest(http.MethodGet, path, params, limitOrder, &resp); err != nil { // return result, err // } // for _, v := range resp { // p := PositionRiskResponse{} // mapObj := v.(map[string]interface{}) // p.Symbol = mapObj["symbol"].(string) // if p.PositionAmt, err = strconv.ParseFloat(mapObj["positionAmt"].(string), 64); err != nil { // return nil, err // } // if p.UnRealizedProfit, err = strconv.ParseFloat(mapObj["unRealizedProfit"].(string), 64); err != nil { // return nil, err // } // if p.EntryPrice, err = strconv.ParseFloat(mapObj["entryPrice"].(string), 64); err != nil { // return nil, err // } // if p.MarkPrice, err = strconv.ParseFloat(mapObj["markPrice"].(string), 64); err != nil { // return nil, err // } // if p.LiquidationPrice, err = strconv.ParseFloat(mapObj["liquidationPrice"].(string), 64); err != nil { // return nil, err // } // if p.Leverage, err = strconv.ParseInt(mapObj["leverage"].(string), 10, 64); err != nil { // return nil, err // } // if mapObj["maxNotionalValue"] != nil { // // if p.MaxNotionalValue, err = strconv.ParseInt(mapObj["maxNotionalValue"].(string), 10, 64); err != nil { // // return nil, err // // } // if p.MaxNotionalValue, err = strconv.ParseFloat(mapObj["maxNotionalValue"].(string), 64); err != nil { // return nil, err // } // } // if strings.EqualFold(mapObj["marginType"].(string), "cross") { // p.MarginType = MarginType_CROSSED // } // if p.IsolatedMargin, err = strconv.ParseFloat(mapObj["isolatedMargin"].(string), 64); err != nil { // return nil, err // } // if p.IsAutoAddMargin, err = strconv.ParseBool(mapObj["isAutoAddMargin"].(string)); err != nil { // return nil, err // } // p.PositionSide = PositionSide(mapObj["positionSide"].(string)) // result = append(result, p) // } // return result, nil // } // MarginType 变换逐全仓模式 // [uFuture]UChangeInitialMarginType [cFuture]FuturesChangeMarginType // func (b *Binance) MarginType(assetType asset.Item, symbol currency.Pair, marginType MarginType) (flag bool, err error) { // params := url.Values{} // params.Set("symbol", symbol.String()) // params.Set("marginType", string(marginType)) // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceMarginType) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceMarginType) // } else { // return false, fmt.Errorf("Error assetType") // } // type response struct { // Code int `json:"code"` // Msg string `json:"msg"` // } // var resp response // err = b.SendAuthHTTPRequest(http.MethodPost, path, params, limitOrder, &resp) // if strings.Index(err.Error(), "{\"code\":-4046,\"msg\":\"No need to change margin type.\"}") != -1 { // return true, nil // } else if !strings.EqualFold(err.Error(), "success") { // return false, err // } // return true, nil // } // PositionMargin 调整逐仓保证金 // [uFuture]UModifyIsolatedPositionMarginReq [uFuture]ModifyIsolatedPositionMargin // func (b *Binance) PositionMargin(assetType asset.Item, req PositionMarginRequest) (bool, error) { // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binancePositionMargin) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binancePositionMargin) // } else { // return false, fmt.Errorf("Error assetType") // } // params := url.Values{} // params.Set("symbol", req.Symbol.String()) // params.Set("amount", strconv.FormatFloat(req.Amount, 'f', -1, 64)) // params.Set("type", strconv.FormatInt(int64(req.Type), 10)) // params.Set("positionSide", string(req.PositionSide)) // var resp interface{} // err := b.SendAuthHTTPRequest(http.MethodPost, path, params, limitOrder, &resp) // if strings.EqualFold(err.Error(), "Successfully modify position margin.") { // return true, nil // } // return false, err // } // PositionMarginHistory 逐仓保证金变动历史 (TRADE) // [uFuture]UPositionMarginChangeHistory [cFuture]FuturesMarginChangeHistory // func (b *Binance) PositionMarginHistory(assetType asset.Item, req PositionMarginHistoryRequest) ([]PositionMarginHistoryResponse, error) { // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binancePositionMarginHistory) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binancePositionMarginHistory) // } else { // return nil, fmt.Errorf("Error assetType") // } // params := url.Values{} // params.Set("symbol", req.Symbol.String()) // if req.Type != 0 { // params.Set("type", strconv.FormatInt(int64(req.Type), 10)) // } // if req.StartTime != 0 { // params.Set("startTime", strconv.FormatInt(req.StartTime, 10)) // } // if req.EndTime != 0 { // params.Set("endTime", strconv.FormatInt(req.EndTime, 10)) // } // if req.Limit != 0 { // params.Set("limit", strconv.FormatInt(req.Limit, 10)) // } // var result []PositionMarginHistoryResponse // var resp []interface{} // var err error // if err = b.SendAuthHTTPRequest(http.MethodGet, path, params, limitOrder, &resp); err != nil { // return result, err // } // for _, v := range resp { // p := PositionMarginHistoryResponse{} // mapObj := v.(map[string]interface{}) // p.Asset = mapObj["asset"].(string) // p.Symbol = mapObj["symbol"].(string) // if p.Amount, err = strconv.ParseFloat(mapObj["amount"].(string), 64); err != nil { // return nil, err // } // p.Type = PositionMarginType(int(mapObj["type"].(float64))) // p.PositionSide = PositionSide(mapObj["positionSide"].(string)) // p.Time = time.Unix(0, int64(mapObj["time"].(float64))*int64(time.Millisecond)) // result = append(result, p) // } // return result, nil // } // GetSpotKlineFuture returns candle stick data // 获取 K 线数据 // symbol: // limit: // interval // [uFuture]UKlineData [cFuture]GetFuturesKlineData // func (b *Binance) GetContractKline(assetType asset.Item, pair currency.Pair, contractType ContractType, startTime, endTime, limit int64, interval kline.Interval) (kline.Item, error) { // ret := kline.Item{ // Exchange: b.Name, // Pair: pair, // Asset: assetType, // Interval: interval, // } // params := url.Values{} // params.Set("symbol", pair.String()) // params.Set("interval", b.FormatExchangeKlineInterval(interval)) // if limit != 0 { // params.Set("limit", strconv.FormatInt(limit, 10)) // } // if startTime != 0 { // params.Set("startTime", strconv.FormatInt(startTime, 10)) // } // if endTime != 0 { // params.Set("endTime", strconv.FormatInt(endTime, 10)) // } // var path string // if assetType == asset.Future { // U本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s?%s", futureApiURL, binanceFutureRESTBasePath, binanceAPIVersion, binanceKlines, params.Encode()) // } else if assetType == asset.PerpetualContract { // 币本位合约 // path = fmt.Sprintf("%s/%s/v%s/%s?%s", perpetualApiURL, binancePerpetualRESTBasePath, binanceAPIVersion, binanceKlines, params.Encode()) // } else { // return ret, fmt.Errorf("Error assetType") // } // var resp interface{} // if err := b.SendHTTPRequest(path, limitDefault, &resp); err != nil { // return ret, err // } // for _, responseData := range resp.([]interface{}) { // var candle CandleStick // for i, individualData := range responseData.([]interface{}) { // switch i { // case 0: // tempTime := individualData.(float64) // var err error // candle.OpenTime, err = convert.TimeFromUnixTimestampFloat(tempTime) // if err != nil { // return ret, err // } // case 1: // candle.Open, _ = strconv.ParseFloat(individualData.(string), 64) // case 2: // candle.High, _ = strconv.ParseFloat(individualData.(string), 64) // case 3: // candle.Low, _ = strconv.ParseFloat(individualData.(string), 64) // case 4: // candle.Close, _ = strconv.ParseFloat(individualData.(string), 64) // case 5: // candle.Volume, _ = strconv.ParseFloat(individualData.(string), 64) // case 6: // tempTime := individualData.(float64) // var err error // candle.CloseTime, err = convert.TimeFromUnixTimestampFloat(tempTime) // if err != nil { // return ret, err // } // case 7: // candle.QuoteAssetVolume, _ = strconv.ParseFloat(individualData.(string), 64) // case 8: // candle.TradeCount = individualData.(float64) // case 9: // candle.TakerBuyAssetVolume, _ = strconv.ParseFloat(individualData.(string), 64) // case 10: // candle.TakerBuyQuoteAssetVolume, _ = strconv.ParseFloat(individualData.(string), 64) // } // } // ret.Candles = append(ret.Candles, kline.Candle{ // Time: candle.OpenTime, // Open: candle.Open, // Close: candle.Close, // Low: candle.Low, // High: candle.High, // Volume: candle.Volume, // }) // } // ret.SortCandlesByTimestamp(false) // return ret, nil // } <file_sep>package account import ( "errors" "fmt" "strings" "github.com/gofrs/uuid" "github.com/idoall/gocryptotrader/dispatch" "github.com/idoall/gocryptotrader/exchanges/asset" ) func init() { service = new(Service) service.accounts = make(map[string]*Account) service.mux = dispatch.GetNewMux() } // SubscribeToExchangeAccount subcribes to your exchange account func SubscribeToExchangeAccount(exchange string) (dispatch.Pipe, error) { exchange = strings.ToLower(exchange) service.Lock() acc, ok := service.accounts[exchange] if !ok { service.Unlock() return dispatch.Pipe{}, fmt.Errorf("%s exchange account holdings not found", exchange) } defer service.Unlock() return service.mux.Subscribe(acc.ID) } // Process processes new account holdings updates func Process(h *Holdings) error { if h == nil { return errors.New("cannot be nil") } if h.Exchange == "" { return errors.New("exchange name unset") } return service.Update(h) } // GetHoldings returns full holdings for an exchange func GetHoldings(exch string, assetType asset.Item) (Holdings, error) { if exch == "" { return Holdings{}, errors.New("exchange name unset") } exch = strings.ToLower(exch) if !assetType.IsValid() { return Holdings{}, fmt.Errorf("assetType %v is invalid", assetType) } service.Lock() defer service.Unlock() h, ok := service.accounts[exch] if !ok { return Holdings{}, errors.New("exchange account holdings not found") } for y := range h.h.Accounts { if h.h.Accounts[y].AssetType == assetType { return *h.h, nil } } return Holdings{}, fmt.Errorf("%v holdings data not found for %s", assetType, exch) } // Update updates holdings with new account info func (s *Service) Update(a *Holdings) error { exch := strings.ToLower(a.Exchange) s.Lock() acc, ok := s.accounts[exch] if !ok { id, err := s.mux.GetID() if err != nil { s.Unlock() return err } s.accounts[exch] = &Account{h: a, ID: id} s.Unlock() return nil } acc.h.Accounts = a.Accounts defer s.Unlock() return s.mux.Publish([]uuid.UUID{acc.ID}, acc.h) } // Available returns the amount you can use immediately. E.g. if you have $100, but $20 // are held (locked) because of a limit buy order, your available balance is $80. func (b Balance) Available() float64 { return b.TotalValue - b.Hold } <file_sep>package alert import ( "log" "sync" "testing" "time" ) func TestWait(t *testing.T) { wait := Notice{} var wg sync.WaitGroup // standard alert wg.Add(100) for x := 0; x < 100; x++ { go func() { w := wait.Wait(nil) wg.Done() if <-w { log.Fatal("incorrect routine wait response for alert expecting false") } wg.Done() }() } wg.Wait() wg.Add(100) isLeaky(t, &wait, nil) wait.Alert() wg.Wait() isLeaky(t, &wait, nil) // use kick ch := make(chan struct{}) wg.Add(100) for x := 0; x < 100; x++ { go func() { w := wait.Wait(ch) wg.Done() if !<-w { log.Fatal("incorrect routine wait response for kick expecting true") } wg.Done() }() } wg.Wait() wg.Add(100) isLeaky(t, &wait, ch) close(ch) wg.Wait() ch = make(chan struct{}) isLeaky(t, &wait, ch) // late receivers wg.Add(100) for x := 0; x < 100; x++ { go func(x int) { bb := wait.Wait(ch) wg.Done() if x%2 == 0 { time.Sleep(time.Millisecond * 5) } b := <-bb if b { log.Fatal("incorrect routine wait response since we call alert below; expecting false") } wg.Done() }(x) } wg.Wait() wg.Add(100) isLeaky(t, &wait, ch) wait.Alert() wg.Wait() isLeaky(t, &wait, ch) } // isLeaky tests to see if the wait functionality is returning an abnormal // channel that is operational when it shouldn't be. func isLeaky(t *testing.T, a *Notice, ch chan struct{}) { t.Helper() check := a.Wait(ch) time.Sleep(time.Millisecond * 5) // When we call wait a routine for hold is // spawned, so for a test we need to add in a time for goschedular to allow // routine to actually wait on the forAlert and kick channels select { case <-check: t.Fatal("leaky waiter") default: } } <file_sep>package order import ( "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) // Order contains all details for an order event type Order struct { event.Base ID string Direction order.Side Status order.Status Price decimal.Decimal Amount decimal.Decimal OrderType order.Type Leverage decimal.Decimal AllocatedFunds decimal.Decimal BuyLimit decimal.Decimal SellLimit decimal.Decimal } // Event inherits common event interfaces along with extra functions related to handling orders type Event interface { common.EventHandler common.Directioner GetBuyLimit() decimal.Decimal GetSellLimit() decimal.Decimal SetAmount(decimal.Decimal) GetAmount() decimal.Decimal IsOrder() bool GetStatus() order.Status SetID(id string) GetID() string IsLeveraged() bool GetAllocatedFunds() decimal.Decimal } <file_sep>package currency import ( "encoding/json" "testing" ) func TestRoleString(t *testing.T) { if Unset.String() != UnsetRoleString { t.Errorf("Role String() error expected %s but received %s", UnsetRoleString, Unset) } if Fiat.String() != FiatCurrencyString { t.Errorf("Role String() error expected %s but received %s", FiatCurrencyString, Fiat) } if Cryptocurrency.String() != CryptocurrencyString { t.Errorf("Role String() error expected %s but received %s", CryptocurrencyString, Cryptocurrency) } if Token.String() != TokenString { t.Errorf("Role String() error expected %s but received %s", TokenString, Token) } if Contract.String() != ContractString { t.Errorf("Role String() error expected %s but received %s", ContractString, Contract) } var random Role = 1 << 7 if random.String() != "UNKNOWN" { t.Errorf("Role String() error expected %s but received %s", "UNKNOWN", random) } } func TestRoleMarshalJSON(t *testing.T) { d, err := json.Marshal(Fiat) if err != nil { t.Error("Role MarshalJSON() error", err) } if expected := `"fiatCurrency"`; string(d) != expected { t.Errorf("Role MarshalJSON() error expected %s but received %s", expected, string(d)) } } // TestRoleUnmarshalJSON logic test func TestRoleUnmarshalJSON(t *testing.T) { type AllTheRoles struct { RoleOne Role `json:"RoleOne"` RoleTwo Role `json:"RoleTwo"` RoleThree Role `json:"RoleThree"` RoleFour Role `json:"RoleFour"` RoleFive Role `json:"RoleFive"` RoleUnknown Role `json:"RoleUnknown"` } var outgoing = AllTheRoles{ RoleOne: Unset, RoleTwo: Cryptocurrency, RoleThree: Fiat, RoleFour: Token, RoleFive: Contract, } e, err := json.Marshal(1337) if err != nil { t.Fatal("Role UnmarshalJSON() error", err) } var incoming AllTheRoles err = json.Unmarshal(e, &incoming) if err == nil { t.Fatal("Role UnmarshalJSON() Expected error") } e, err = json.Marshal(outgoing) if err != nil { t.Fatal("Role UnmarshalJSON() error", err) } err = json.Unmarshal(e, &incoming) if err != nil { t.Fatal("Role UnmarshalJSON() error", err) } if incoming.RoleOne != Unset { t.Errorf("Role String() error expected %s but received %s", Unset, incoming.RoleOne) } if incoming.RoleTwo != Cryptocurrency { t.Errorf("Role String() error expected %s but received %s", Cryptocurrency, incoming.RoleTwo) } if incoming.RoleThree != Fiat { t.Errorf("Role String() error expected %s but received %s", Fiat, incoming.RoleThree) } if incoming.RoleFour != Token { t.Errorf("Role String() error expected %s but received %s", Token, incoming.RoleFour) } if incoming.RoleFive != Contract { t.Errorf("Role String() error expected %s but received %s", Contract, incoming.RoleFive) } if incoming.RoleUnknown != Unset { t.Errorf("Role String() error expected %s but received %s", incoming.RoleFive, incoming.RoleUnknown) } var unhandled Role err = unhandled.UnmarshalJSON([]byte("\"ThisIsntReal\"")) if err == nil { t.Error("Expected unmarshall error") } } func TestBaseCode(t *testing.T) { var main BaseCodes if main.HasData() { t.Errorf("BaseCode HasData() error expected false but received %v", main.HasData()) } catsCode := main.Register("CATS") if !main.HasData() { t.Errorf("BaseCode HasData() error expected true but received %v", main.HasData()) } if !main.Register("CATS").Match(catsCode) { t.Errorf("BaseCode Match() error expected true but received %v", false) } if main.Register("DOGS").Match(catsCode) { t.Errorf("BaseCode Match() error expected false but received %v", true) } loadedCurrencies := main.GetCurrencies() if loadedCurrencies.Contains(main.Register("OWLS")) { t.Errorf("BaseCode Contains() error expected false but received %v", true) } if !loadedCurrencies.Contains(catsCode) { t.Errorf("BaseCode Contains() error expected true but received %v", false) } main.Register("XBTUSD") err := main.UpdateCurrency("Bitcoin Perpetual", "XBTUSD", "", 0, Contract) if err != nil { t.Fatal(err) } main.Register("BTC") err = main.UpdateCurrency("Bitcoin", "BTC", "", 1337, Cryptocurrency) if err != nil { t.Fatal(err) } main.Register("AUD") err = main.UpdateCurrency("Unreal Dollar", "AUD", "", 1111, Fiat) if err != nil { t.Fatal(err) } if main.Items[5].FullName != "Unreal Dollar" { t.Error("Expected fullname to update for AUD") } err = main.UpdateCurrency("Australian Dollar", "AUD", "", 1336, Fiat) if err != nil { t.Fatal(err) } main.Items[5].Role = Unset err = main.UpdateCurrency("Australian Dollar", "AUD", "", 1336, Fiat) if err != nil { t.Fatal(err) } if main.Items[5].Role != Fiat { t.Error("Expected role to change to Fiat") } main.Register("PPT") err = main.UpdateCurrency("Populous", "PPT", "ETH", 1335, Token) if err != nil { t.Fatal(err) } contract := main.Register("XBTUSD") if contract.IsFiatCurrency() { t.Errorf("BaseCode IsFiatCurrency() error expected false but received %v", true) } if contract.IsCryptocurrency() { t.Errorf("BaseCode IsFiatCurrency() error expected false but received %v", true) } if contract.IsDefaultFiatCurrency() { t.Errorf("BaseCode IsDefaultFiatCurrency() error expected false but received %v", true) } if contract.IsDefaultFiatCurrency() { t.Errorf("BaseCode IsFiatCurrency() error expected false but received %v", true) } err = main.LoadItem(&Item{ ID: 0, FullName: "Cardano", Role: Cryptocurrency, Symbol: "ADA", }) if err != nil { t.Fatal(err) } full, err := main.GetFullCurrencyData() if err != nil { t.Error("BaseCode GetFullCurrencyData error", err) } if len(full.Contracts) != 1 { t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.Contracts)) } if len(full.Cryptocurrency) != 2 { t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.Cryptocurrency)) } if len(full.FiatCurrency) != 1 { t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.FiatCurrency)) } if len(full.Token) != 1 { t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.Token)) } if len(full.UnsetCurrency) != 3 { t.Errorf("BaseCode GetFullCurrencyData() error expected 3 but received %v", len(full.UnsetCurrency)) } if full.LastMainUpdate.(int64) != -62135596800 { t.Errorf("BaseCode GetFullCurrencyData() error expected -62135596800 but received %d", full.LastMainUpdate) } err = main.LoadItem(&Item{ ID: 0, FullName: "Cardano", Role: Role(99), Symbol: "ADA", }) if err != nil { t.Error("BaseCode LoadItem() error", err) } _, err = main.GetFullCurrencyData() if err == nil { t.Error("Expected 'Role undefined'") } main.Items[0].FullName = "Hello" err = main.UpdateCurrency("MEWOW", "CATS", "", 1338, Cryptocurrency) if err != nil { t.Fatal(err) } if main.Items[0].FullName != "MEWOW" { t.Error("Fullname not updated") } err = main.UpdateCurrency("MEWOW", "CATS", "", 1338, Cryptocurrency) if err != nil { t.Fatal(err) } err = main.UpdateCurrency("WOWCATS", "CATS", "", 3, Token) if err != nil { t.Fatal(err) } // Creates a new item under a different currency role if main.Items[9].ID != 3 { t.Error("ID not updated") } main.Items[0].Role = Unset err = main.UpdateCurrency("MEWOW", "CATS", "", 1338, Cryptocurrency) if err != nil { t.Fatal(err) } if main.Items[0].ID != 1338 { t.Error("ID not updated") } } func TestCodeString(t *testing.T) { if cc, expected := NewCode("TEST"), "TEST"; cc.String() != expected { t.Errorf("Currency Code String() error expected %s but received %s", expected, cc) } } func TestCodeLower(t *testing.T) { if cc, expected := NewCode("TEST"), "test"; cc.Lower().String() != expected { t.Errorf("Currency Code Lower() error expected %s but received %s", expected, cc.Lower()) } } func TestCodeUpper(t *testing.T) { if cc, expected := NewCode("test"), "TEST"; cc.Upper().String() != expected { t.Errorf("Currency Code Upper() error expected %s but received %s", expected, cc.Upper()) } } func TestCodeUnmarshalJSON(t *testing.T) { var unmarshalHere Code expected := "BRO" encoded, err := json.Marshal(expected) if err != nil { t.Fatal("Currency Code UnmarshalJSON error", err) } err = json.Unmarshal(encoded, &unmarshalHere) if err != nil { t.Fatal("Currency Code UnmarshalJSON error", err) } err = json.Unmarshal(encoded, &unmarshalHere) if err != nil { t.Fatal("Currency Code UnmarshalJSON error", err) } if unmarshalHere.String() != expected { t.Errorf("Currency Code Upper() error expected %s but received %s", expected, unmarshalHere) } } func TestCodeMarshalJSON(t *testing.T) { quickstruct := struct { Codey Code `json:"sweetCodes"` }{ Codey: NewCode("BRO"), } expectedJSON := `{"sweetCodes":"BRO"}` encoded, err := json.Marshal(quickstruct) if err != nil { t.Fatal("Currency Code UnmarshalJSON error", err) } if string(encoded) != expectedJSON { t.Errorf("Currency Code Upper() error expected %s but received %s", expectedJSON, string(encoded)) } quickstruct = struct { Codey Code `json:"sweetCodes"` }{ Codey: Code{}, // nil code } encoded, err = json.Marshal(quickstruct) if err != nil { t.Fatal("Currency Code UnmarshalJSON error", err) } newExpectedJSON := `{"sweetCodes":""}` if string(encoded) != newExpectedJSON { t.Errorf("Currency Code Upper() error expected %s but received %s", newExpectedJSON, string(encoded)) } } func TestIsDefaultCurrency(t *testing.T) { if !USD.IsDefaultFiatCurrency() { t.Errorf("TestIsDefaultCurrency Cannot match currency %s.", USD) } if !AUD.IsDefaultFiatCurrency() { t.Errorf("TestIsDefaultCurrency Cannot match currency, %s.", AUD) } if LTC.IsDefaultFiatCurrency() { t.Errorf("TestIsDefaultCurrency Function return is incorrect with, %s.", LTC) } } func TestIsDefaultCryptocurrency(t *testing.T) { if !BTC.IsDefaultCryptocurrency() { t.Errorf("TestIsDefaultCryptocurrency cannot match currency, %s.", BTC) } if !LTC.IsDefaultCryptocurrency() { t.Errorf("TestIsDefaultCryptocurrency cannot match currency, %s.", LTC) } if AUD.IsDefaultCryptocurrency() { t.Errorf("TestIsDefaultCryptocurrency function return is incorrect with, %s.", AUD) } } func TestIsFiatCurrency(t *testing.T) { if !USD.IsFiatCurrency() { t.Errorf( "TestIsFiatCurrency cannot match currency, %s.", USD) } if !CNY.IsFiatCurrency() { t.Errorf( "TestIsFiatCurrency cannot match currency, %s.", CNY) } if LINO.IsFiatCurrency() { t.Errorf( "TestIsFiatCurrency cannot match currency, %s.", LINO, ) } } func TestIsCryptocurrency(t *testing.T) { if !BTC.IsCryptocurrency() { t.Errorf("TestIsFiatCurrency cannot match currency, %s.", BTC) } if !LTC.IsCryptocurrency() { t.Errorf("TestIsFiatCurrency cannot match currency, %s.", LTC) } if AUD.IsCryptocurrency() { t.Errorf("TestIsFiatCurrency cannot match currency, %s.", AUD) } } func TestItemString(t *testing.T) { expected := "Hello,World" newItem := Item{ FullName: expected, } if newItem.String() != expected { t.Errorf("Currency String() error expected %s but received %s", expected, &newItem) } } <file_sep>package okgroup import ( "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "time" ) // WebsocketResponsePosition defines type WebsocketResponsePosition struct { Timestamp time.Time Pair currency.Pair AssetType asset.Item ExchangeName string Holding []WebsocketResponsePositionHoldingData `json:"holding,omitempty"` } // WebsocketResponsePositionHoldingData contains formatted data for user position holding data type WebsocketResponsePositionHoldingData struct { InstrumentID string `json:"instrument_id"` AvailablePosition float64 `json:"avail_position,string,omitempty"` AverageCost float64 `json:"avg_cost,string,omitempty"` Leverage float64 `json:"leverage,string,omitempty"` LiquidationPrice float64 `json:"liquidation_price,string,omitempty"` Margin float64 `json:"margin,string,omitempty"` Position float64 `json:"position,string,omitempty"` RealizedPnl float64 `json:"realized_pnl,string,omitempty"` SettlementPrice float64 `json:"settlement_price,string,omitempty"` Side string `json:"side,omitempty"` Timestamp time.Time `json:"timestamp,omitempty"` } // WebsocketResponseMarkPrice defines type WebsocketResponseMarkPrice struct { Timestamp time.Time Pair currency.Pair AssetType asset.Item ExchangeName string Price float64 } type WebsocketResponseOrders struct { Timestamp time.Time Pair currency.Pair AssetType asset.Item ExchangeName string OrderInfo []WebsocketResponseOrdersData `json:"order_info"` } type WebsocketResponseUserSwapFutureAccounts struct { Timestamp time.Time Pair currency.Pair AssetType asset.Item ExchangeName string Data []WebsocketResponseUserSwapFutureAccountsData } type WebsocketResponseUserSwapFutureAccountsData struct { Equity float64 `json:"equity,string"` InstrumentID string `json:"instrument_id,string"` Margin float64 `json:"margin,string"` MarginFrozen float64 `json:"margin_frozen,string"` MarginRatio float64 `json:"margin_ratio,string"` RealizedPnl float64 `json:"realized_pnl,string"` Timestamp time.Time `json:"timestamp,string"` TotalAvailBalance float64 `json:"total_avail_balance,string"` UnrealizedPnl float64 `json:"unrealized_pnl,string"` FixedBalance float64 `json:"fixed_balance,string"` MaintMarginRatio float64 `json:"maint_margin_ratio,string"` MarginForUnfilled float64 `json:"margin_for_unfilled,string"`//交割合约独有 AvailableQty float64 `json:"available_qty,string"` // 可用保证金 LiquiMode string `json:"liqui_mode,string"` //交割合约独有 MarginMode string `json:"margin_mode,string"` ShortOpenMax int64 `json:"short_open_max,string"` LongOpenMax int64 `json:"long_open_max,string"` } // GetSwapOrderListResponseData individual order data from GetSwapOrderList type WebsocketResponseOrdersData struct { ContractVal float64 `json:"contract_val,string"` Fee float64 `json:"fee,string"` FilledQty float64 `json:"filled_qty,string"` InstrumentID string `json:"instrument_id"` Leverage float64 `json:"leverage,string"` // Leverage value:10\20 default:10 OrderID int64 `json:"order_id,string"` Price float64 `json:"price,string"` PriceAvg float64 `json:"price_avg,string"` Size float64 `json:"size,string"` Status int64 `json:"status,string"` // Order Status (-1 canceled; 0: pending, 1: partially filled, 2: fully filled) Timestamp time.Time `json:"timestamp"` Type int64 `json:"type,string"` // Type (1: open long 2: open short 3: close long 4: close short) }<file_sep>echo "GoCryptoTrader: Generating gRPC, proxy and swagger files." # You may need to include the go mod package for the annotations file: # $GOPATH/pkg/mod/github.com/grpc-ecosystem/grpc-gateway/v2@v2.0.1/third_party/googleapis export GOPATH=$(go env GOPATH) protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=paths=source_relative:. rpc.proto protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go-grpc_out=paths=source_relative:. rpc.proto protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=paths=source_relative,logtostderr=true:. rpc.proto protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --openapiv2_out=logtostderr=true:. rpc.proto <file_sep>package dispatch import ( "fmt" "os" "sync" "testing" "github.com/gofrs/uuid" ) var mux *Mux func TestMain(m *testing.M) { err := Start(DefaultMaxWorkers, 0) if err != nil { fmt.Println(err) os.Exit(1) } cpyDispatch = dispatcher mux = GetNewMux() cpyMux = mux os.Exit(m.Run()) } var cpyDispatch *Dispatcher var cpyMux *Mux func TestDispatcher(t *testing.T) { dispatcher = nil err := Stop() if err == nil { t.Error("error cannot be nil") } err = Start(10, 0) if err == nil { t.Error("error cannot be nil") } if IsRunning() { t.Error("should be false") } err = DropWorker() if err == nil { t.Error("error cannot be nil") } err = SpawnWorker() if err == nil { t.Error("error cannot be nil") } dispatcher = cpyDispatch if !IsRunning() { t.Error("should be true") } err = Start(10, 0) if err == nil { t.Error("error cannot be nil") } err = DropWorker() if err != nil { t.Error(err) } err = DropWorker() if err != nil { t.Error(err) } err = SpawnWorker() if err != nil { t.Error(err) } err = SpawnWorker() if err != nil { t.Error(err) } err = SpawnWorker() if err == nil { t.Error("error cannot be nil") } err = Stop() if err != nil { t.Error(err) } err = Stop() if err == nil { t.Error("error cannot be nil") } err = Start(0, 20) if err != nil { t.Error(err) } if cap(dispatcher.jobs) != 20 { t.Errorf("Expected jobs limit to be %v, is %v", 20, cap(dispatcher.jobs)) } payload := "something" err = dispatcher.publish(uuid.UUID{}, &payload) if err == nil { t.Error("error cannot be nil") } err = dispatcher.publish(uuid.UUID{}, nil) if err == nil { t.Error("error cannot be nil") } id, err := dispatcher.getNewID() if err != nil { t.Error(err) } err = dispatcher.publish(id, &payload) if err != nil { t.Error(err) } err = dispatcher.stop() if err != nil { t.Error(err) } err = dispatcher.publish(id, &payload) if err != nil { t.Error(err) } _, err = dispatcher.subscribe(id) if err == nil { t.Error("error cannot be nil") } err = dispatcher.start(10, -1) if err != nil { t.Error(err) } if cap(dispatcher.jobs) != DefaultJobsLimit { t.Errorf("Expected jobs limit to be %v, is %v", DefaultJobsLimit, cap(dispatcher.jobs)) } someID, err := uuid.NewV4() if err != nil { t.Error(err) } _, err = dispatcher.subscribe(someID) if err == nil { t.Error("error cannot be nil") } randomChan := make(chan interface{}) err = dispatcher.unsubscribe(someID, randomChan) if err == nil { t.Error("Expected error") } err = dispatcher.unsubscribe(id, randomChan) if err == nil { t.Error("Expected error") } close(randomChan) err = dispatcher.unsubscribe(id, randomChan) if err == nil { t.Error("Expected error") } } func TestMux(t *testing.T) { mux = nil _, err := mux.Subscribe(uuid.UUID{}) if err == nil { t.Error("error cannot be nil") } err = mux.Unsubscribe(uuid.UUID{}, nil) if err == nil { t.Error("error cannot be nil") } err = mux.Publish(nil, nil) if err == nil { t.Error("error cannot be nil") } _, err = mux.GetID() if err == nil { t.Error("error cannot be nil") } mux = cpyMux err = mux.Publish(nil, nil) if err == nil { t.Error("error cannot be nil") } payload := "string" id, err := uuid.NewV4() if err != nil { t.Error(err) } err = mux.Publish([]uuid.UUID{id}, &payload) if err != nil { t.Error(err) } _, err = mux.Subscribe(uuid.UUID{}) if err == nil { t.Error("error cannot be nil") } _, err = mux.Subscribe(id) if err == nil { t.Error("error cannot be nil") } } func TestSubscribe(t *testing.T) { itemID, err := mux.GetID() if err != nil { t.Fatal(err) } var pipes []Pipe for i := 0; i < 1000; i++ { newPipe, err := mux.Subscribe(itemID) if err != nil { t.Error(err) } pipes = append(pipes, newPipe) } for i := range pipes { err := pipes[i].Release() if err != nil { t.Error(err) } } } func TestPublish(t *testing.T) { itemID, err := mux.GetID() if err != nil { t.Fatal(err) } pipe, err := mux.Subscribe(itemID) if err != nil { t.Error(err) } var wg sync.WaitGroup wg.Add(1) go func(wg *sync.WaitGroup) { wg.Done() for { _, ok := <-pipe.C if !ok { pErr := pipe.Release() if pErr != nil { t.Error(pErr) } wg.Done() return } } }(&wg) wg.Wait() wg.Add(1) mainPayload := "PAYLOAD" for i := 0; i < 100; i++ { errMux := mux.Publish([]uuid.UUID{itemID}, &mainPayload) if errMux != nil { t.Error(errMux) } } // Shut down dispatch system err = Stop() if err != nil { t.Fatal(err) } wg.Wait() } func BenchmarkSubscribe(b *testing.B) { newID, err := mux.GetID() if err != nil { b.Error(err) } for n := 0; n < b.N; n++ { _, err := mux.Subscribe(newID) if err != nil { b.Error(err) } } } <file_sep>package buffer import ( "errors" "fmt" "sort" "time" "github.com/idoall/gocryptotrader/config" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/orderbook" "github.com/idoall/gocryptotrader/log" ) const packageError = "websocket orderbook buffer error: %w" var ( errExchangeConfigNil = errors.New("exchange config is nil") errUnsetDataHandler = errors.New("datahandler unset") errIssueBufferEnabledButNoLimit = errors.New("buffer enabled but no limit set") errUpdateIsNil = errors.New("update is nil") errUpdateNoTargets = errors.New("update bid/ask targets cannot be nil") errDepthNotFound = errors.New("orderbook depth not found") errRESTOverwrite = errors.New("orderbook has been overwritten by REST protocol") ) // Setup sets private variables func (w *Orderbook) Setup(cfg *config.Exchange, sortBuffer, sortBufferByUpdateIDs, updateEntriesByID bool, dataHandler chan interface{}) error { if cfg == nil { // exchange config fields are checked in stream package // prior to calling this, so further checks are not needed. return fmt.Errorf(packageError, errExchangeConfigNil) } if dataHandler == nil { return fmt.Errorf(packageError, errUnsetDataHandler) } if cfg.Orderbook.WebsocketBufferEnabled && cfg.Orderbook.WebsocketBufferLimit < 1 { return fmt.Errorf(packageError, errIssueBufferEnabledButNoLimit) } w.bufferEnabled = cfg.Orderbook.WebsocketBufferEnabled w.obBufferLimit = cfg.Orderbook.WebsocketBufferLimit w.sortBuffer = sortBuffer w.sortBufferByUpdateIDs = sortBufferByUpdateIDs w.updateEntriesByID = updateEntriesByID w.exchangeName = cfg.Name w.dataHandler = dataHandler w.ob = make(map[currency.Code]map[currency.Code]map[asset.Item]*orderbookHolder) w.verbose = cfg.Verbose // set default publish period if missing orderbookPublishPeriod := config.DefaultOrderbookPublishPeriod if cfg.Orderbook.PublishPeriod != nil { orderbookPublishPeriod = *cfg.Orderbook.PublishPeriod } w.publishPeriod = orderbookPublishPeriod return nil } // validate validates update against setup values func (w *Orderbook) validate(u *Update) error { if u == nil { return fmt.Errorf(packageError, errUpdateIsNil) } if len(u.Bids) == 0 && len(u.Asks) == 0 { return fmt.Errorf(packageError, errUpdateNoTargets) } return nil } // Update updates a stored pointer to an orderbook.Depth struct containing a // linked list, this switches between the usage of a buffered update func (w *Orderbook) Update(u *Update) error { if err := w.validate(u); err != nil { return err } w.m.Lock() defer w.m.Unlock() book, ok := w.ob[u.Pair.Base][u.Pair.Quote][u.Asset] if !ok { return fmt.Errorf("%w for Exchange %s CurrencyPair: %s AssetType: %s", errDepthNotFound, w.exchangeName, u.Pair, u.Asset) } // Checks for when the rest protocol overwrites a streaming dominated book // will stop updating book via incremental updates. This occurs because our // sync manager (engine/sync.go) timer has elapsed for streaming. Usually // because the book is highly illiquid. TODO: Book resubscribe on websocket. if book.ob.IsRestSnapshot() { if w.verbose { log.Warnf(log.WebsocketMgr, "%s for Exchange %s CurrencyPair: %s AssetType: %s consider extending synctimeoutwebsocket", errRESTOverwrite, w.exchangeName, u.Pair, u.Asset) } return fmt.Errorf("%w for Exchange %s CurrencyPair: %s AssetType: %s", errRESTOverwrite, w.exchangeName, u.Pair, u.Asset) } if w.bufferEnabled { processed, err := w.processBufferUpdate(book, u) if err != nil { return err } if !processed { return nil } } else { err := w.processObUpdate(book, u) if err != nil { return err } } if book.ob.VerifyOrderbook { // This is used here so as to not retrieve // book if verification is off. // On every update, this will retrieve and verify orderbook depths err := book.ob.Retrieve().Verify() if err != nil { return err } } // a nil ticker means that a zero publish period has been requested, // this means publish now whatever was received with no throttling if book.ticker == nil { go func() { w.dataHandler <- book.ob.Retrieve() book.ob.Publish() }() return nil } select { case <-book.ticker.C: // Opted to wait for receiver because we are limiting here and the sync // manager requires update go func() { w.dataHandler <- book.ob.Retrieve() book.ob.Publish() }() default: // We do not need to send an update to the sync manager within this time // window unless verbose is turned on if w.verbose { w.dataHandler <- book.ob.Retrieve() book.ob.Publish() } } return nil } // processBufferUpdate stores update into buffer, when buffer at capacity as // defined by w.obBufferLimit it well then sort and apply updates. func (w *Orderbook) processBufferUpdate(o *orderbookHolder, u *Update) (bool, error) { *o.buffer = append(*o.buffer, *u) if len(*o.buffer) < w.obBufferLimit { return false, nil } if w.sortBuffer { // sort by last updated to ensure each update is in order if w.sortBufferByUpdateIDs { sort.Slice(*o.buffer, func(i, j int) bool { return (*o.buffer)[i].UpdateID < (*o.buffer)[j].UpdateID }) } else { sort.Slice(*o.buffer, func(i, j int) bool { return (*o.buffer)[i].UpdateTime.Before((*o.buffer)[j].UpdateTime) }) } } for i := range *o.buffer { err := w.processObUpdate(o, &(*o.buffer)[i]) if err != nil { return false, err } } // clear buffer of old updates *o.buffer = nil return true, nil } // processObUpdate processes updates either by its corresponding id or by // price level func (w *Orderbook) processObUpdate(o *orderbookHolder, u *Update) error { if w.updateEntriesByID { return o.updateByIDAndAction(u) } o.updateByPrice(u) return nil } // updateByPrice ammends amount if match occurs by price, deletes if amount is // zero or less and inserts if not found. func (o *orderbookHolder) updateByPrice(updts *Update) { o.ob.UpdateBidAskByPrice(updts.Bids, updts.Asks, updts.MaxDepth, updts.UpdateID, updts.UpdateTime) } // updateByIDAndAction will receive an action to execute against the orderbook // it will then match by IDs instead of price to perform the action func (o *orderbookHolder) updateByIDAndAction(updts *Update) error { switch updts.Action { case Amend: return o.ob.UpdateBidAskByID(updts.Bids, updts.Asks, updts.UpdateID, updts.UpdateTime) case Delete: // edge case for Bitfinex as their streaming endpoint duplicates deletes bypassErr := o.ob.GetName() == "Bitfinex" && o.ob.IsFundingRate() return o.ob.DeleteBidAskByID(updts.Bids, updts.Asks, bypassErr, updts.UpdateID, updts.UpdateTime) case Insert: return o.ob.InsertBidAskByID(updts.Bids, updts.Asks, updts.UpdateID, updts.UpdateTime) case UpdateInsert: return o.ob.UpdateInsertByID(updts.Bids, updts.Asks, updts.UpdateID, updts.UpdateTime) default: return fmt.Errorf("invalid action [%s]", updts.Action) } } // LoadSnapshot loads initial snapshot of orderbook data from websocket func (w *Orderbook) LoadSnapshot(book *orderbook.Base) error { w.m.Lock() defer w.m.Unlock() m1, ok := w.ob[book.Pair.Base] if !ok { m1 = make(map[currency.Code]map[asset.Item]*orderbookHolder) w.ob[book.Pair.Base] = m1 } m2, ok := m1[book.Pair.Quote] if !ok { m2 = make(map[asset.Item]*orderbookHolder) m1[book.Pair.Quote] = m2 } holder, ok := m2[book.Asset] if !ok { // Associate orderbook pointer with local exchange depth map depth, err := orderbook.DeployDepth(book.Exchange, book.Pair, book.Asset) if err != nil { return err } depth.AssignOptions(book) buffer := make([]Update, w.obBufferLimit) var ticker *time.Ticker if w.publishPeriod != 0 { ticker = time.NewTicker(w.publishPeriod) } holder = &orderbookHolder{ ob: depth, buffer: &buffer, ticker: ticker, } m2[book.Asset] = holder } // Checks if book can deploy to linked list err := book.Verify() if err != nil { return err } holder.ob.LoadSnapshot( book.Bids, book.Asks, book.LastUpdateID, book.LastUpdated, false, ) if holder.ob.VerifyOrderbook { // This is used here so as to not retrieve // book if verification is off. // Checks to see if orderbook snapshot that was deployed has not been // altered in any way err = holder.ob.Retrieve().Verify() if err != nil { return err } } w.dataHandler <- holder.ob.Retrieve() holder.ob.Publish() return nil } // GetOrderbook returns an orderbook copy as orderbook.Base func (w *Orderbook) GetOrderbook(p currency.Pair, a asset.Item) (*orderbook.Base, error) { w.m.Lock() defer w.m.Unlock() book, ok := w.ob[p.Base][p.Quote][a] if !ok { return nil, fmt.Errorf("%s %s %s %w", w.exchangeName, p, a, errDepthNotFound) } return book.ob.Retrieve(), nil } // FlushBuffer flushes w.ob data to be garbage collected and refreshed when a // connection is lost and reconnected func (w *Orderbook) FlushBuffer() { w.m.Lock() w.ob = make(map[currency.Code]map[currency.Code]map[asset.Item]*orderbookHolder) w.m.Unlock() } // FlushOrderbook flushes independent orderbook func (w *Orderbook) FlushOrderbook(p currency.Pair, a asset.Item) error { w.m.Lock() defer w.m.Unlock() book, ok := w.ob[p.Base][p.Quote][a] if !ok { return fmt.Errorf("cannot flush orderbook %s %s %s %w", w.exchangeName, p, a, errDepthNotFound) } book.ob.Flush() return nil } <file_sep>package gctscript import ( "github.com/idoall/gocryptotrader/gctscript/modules" "github.com/idoall/gocryptotrader/gctscript/wrappers/gct" ) // Setup configures the wrapper interface to use func Setup() { modules.SetModuleWrapper(gct.Setup()) } <file_sep>package asset import ( "errors" "fmt" "strings" ) var ( // ErrNotSupported is an error for an unsupported asset type ErrNotSupported = errors.New("received unsupported asset type") ) // Item stores the asset type type Item string // Items stores a list of assets types type Items []Item // Const vars for asset package const ( Spot = Item("spot") Margin = Item("margin") MarginFunding = Item("marginfunding") Index = Item("index") Binary = Item("binary") PerpetualContract = Item("perpetualcontract") PerpetualSwap = Item("perpetualswap") Futures = Item("futures") Future = Item("future") UpsideProfitContract = Item("upsideprofitcontract") DownsideProfitContract = Item("downsideprofitcontract") CoinMarginedFutures = Item("coinmarginedfutures") USDTMarginedFutures = Item("usdtmarginedfutures") ) var supported = Items{ Spot, Margin, MarginFunding, Index, Binary, PerpetualContract, PerpetualSwap, Futures, UpsideProfitContract, DownsideProfitContract, CoinMarginedFutures, USDTMarginedFutures, } // Supported returns a list of supported asset types func Supported() Items { return supported } // returns an Item to string func (a Item) String() string { return string(a) } // Strings converts an asset type array to a string array func (a Items) Strings() []string { var assets []string for x := range a { assets = append(assets, string(a[x])) } return assets } // Contains returns whether or not the supplied asset exists // in the list of Items func (a Items) Contains(i Item) bool { if !i.IsValid() { return false } for x := range a { if a[x].String() == i.String() { return true } } return false } // JoinToString joins an asset type array and converts it to a string // with the supplied separator func (a Items) JoinToString(separator string) string { return strings.Join(a.Strings(), separator) } // IsValid returns whether or not the supplied asset type is valid or // not func (a Item) IsValid() bool { for x := range supported { if supported[x].String() == a.String() { return true } } return false } // New takes an input matches to relevant package assets func New(input string) (Item, error) { input = strings.ToLower(input) for i := range supported { if string(supported[i]) == input { return supported[i], nil } } return "", fmt.Errorf("%w %v, only supports %v", ErrNotSupported, input, supported) } // UseDefault returns default asset type func UseDefault() Item { return Spot } <file_sep>package main import ( "flag" "fmt" "log" "os" "runtime" "time" "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/config" "github.com/idoall/gocryptotrader/core" "github.com/idoall/gocryptotrader/dispatch" "github.com/idoall/gocryptotrader/engine" "github.com/idoall/gocryptotrader/exchanges/request" "github.com/idoall/gocryptotrader/exchanges/trade" "github.com/idoall/gocryptotrader/gctscript" gctscriptVM "github.com/idoall/gocryptotrader/gctscript/vm" gctlog "github.com/idoall/gocryptotrader/log" "github.com/idoall/gocryptotrader/portfolio/withdraw" "github.com/idoall/gocryptotrader/signaler" ) func main() { // Handle flags var settings engine.Settings versionFlag := flag.Bool("version", false, "retrieves current GoCryptoTrader version") // Core settings flag.StringVar(&settings.ConfigFile, "config", config.DefaultFilePath(), "config file to load") flag.StringVar(&settings.DataDir, "datadir", common.GetDefaultDataDir(runtime.GOOS), "default data directory for GoCryptoTrader files") flag.IntVar(&settings.GoMaxProcs, "gomaxprocs", runtime.GOMAXPROCS(-1), "sets the runtime GOMAXPROCS value") flag.BoolVar(&settings.EnableDryRun, "dryrun", false, "dry runs bot, doesn't save config file") flag.BoolVar(&settings.EnableAllExchanges, "enableallexchanges", false, "enables all exchanges") flag.BoolVar(&settings.EnableAllPairs, "enableallpairs", false, "enables all pairs for enabled exchanges") flag.BoolVar(&settings.EnablePortfolioManager, "portfoliomanager", true, "enables the portfolio manager") flag.BoolVar(&settings.EnableDataHistoryManager, "datahistorymanager", false, "enables the data history manager") flag.DurationVar(&settings.PortfolioManagerDelay, "portfoliomanagerdelay", time.Duration(0), "sets the portfolio managers sleep delay between updates") flag.BoolVar(&settings.EnableGRPC, "grpc", true, "enables the grpc server") flag.BoolVar(&settings.EnableGRPCProxy, "grpcproxy", false, "enables the grpc proxy server") flag.BoolVar(&settings.EnableWebsocketRPC, "websocketrpc", true, "enables the websocket RPC server") flag.BoolVar(&settings.EnableDeprecatedRPC, "deprecatedrpc", true, "enables the deprecated RPC server") flag.BoolVar(&settings.EnableCommsRelayer, "enablecommsrelayer", true, "enables available communications relayer") flag.BoolVar(&settings.Verbose, "verbose", false, "increases logging verbosity for GoCryptoTrader") flag.BoolVar(&settings.EnableExchangeSyncManager, "syncmanager", true, "enables to exchange sync manager") flag.BoolVar(&settings.EnableWebsocketRoutine, "websocketroutine", true, "enables the websocket routine for all loaded exchanges") flag.BoolVar(&settings.EnableCoinmarketcapAnalysis, "coinmarketcap", false, "overrides config and runs currency analysis") flag.BoolVar(&settings.EnableEventManager, "eventmanager", true, "enables the event manager") flag.BoolVar(&settings.EnableOrderManager, "ordermanager", true, "enables the order manager") flag.BoolVar(&settings.EnableDepositAddressManager, "depositaddressmanager", true, "enables the deposit address manager") flag.BoolVar(&settings.EnableConnectivityMonitor, "connectivitymonitor", true, "enables the connectivity monitor") flag.BoolVar(&settings.EnableDatabaseManager, "databasemanager", true, "enables database manager") flag.BoolVar(&settings.EnableGCTScriptManager, "gctscriptmanager", true, "enables gctscript manager") flag.DurationVar(&settings.EventManagerDelay, "eventmanagerdelay", time.Duration(0), "sets the event managers sleep delay between event checking") flag.BoolVar(&settings.EnableNTPClient, "ntpclient", true, "enables the NTP client to check system clock drift") flag.BoolVar(&settings.EnableDispatcher, "dispatch", true, "enables the dispatch system") flag.BoolVar(&settings.EnableCurrencyStateManager, "currencystatemanager", true, "enables the currency state manager") flag.IntVar(&settings.DispatchMaxWorkerAmount, "dispatchworkers", dispatch.DefaultMaxWorkers, "sets the dispatch package max worker generation limit") flag.IntVar(&settings.DispatchJobsLimit, "dispatchjobslimit", dispatch.DefaultJobsLimit, "sets the dispatch package max jobs limit") // Exchange syncer settings flag.BoolVar(&settings.EnableTickerSyncing, "tickersync", true, "enables ticker syncing for all enabled exchanges") flag.BoolVar(&settings.EnableOrderbookSyncing, "orderbooksync", true, "enables orderbook syncing for all enabled exchanges") flag.BoolVar(&settings.EnableTradeSyncing, "tradesync", false, "enables trade syncing for all enabled exchanges") flag.IntVar(&settings.SyncWorkers, "syncworkers", engine.DefaultSyncerWorkers, "the amount of workers (goroutines) to use for syncing exchange data") flag.BoolVar(&settings.SyncContinuously, "synccontinuously", true, "whether to sync exchange data continuously (ticker, orderbook and trade history info") flag.DurationVar(&settings.SyncTimeoutREST, "synctimeoutrest", engine.DefaultSyncerTimeoutREST, "the amount of time before the syncer will switch from rest protocol to the streaming protocol (e.g. from REST to websocket)") flag.DurationVar(&settings.SyncTimeoutWebsocket, "synctimeoutwebsocket", engine.DefaultSyncerTimeoutWebsocket, "the amount of time before the syncer will switch from the websocket protocol to REST protocol (e.g. from websocket to REST)") // Forex provider settings flag.BoolVar(&settings.EnableCurrencyConverter, "currencyconverter", false, "overrides config and sets up foreign exchange Currency Converter") flag.BoolVar(&settings.EnableCurrencyLayer, "currencylayer", false, "overrides config and sets up foreign exchange Currency Layer") flag.BoolVar(&settings.EnableFixer, "fixer", false, "overrides config and sets up foreign exchange Fixer.io") flag.BoolVar(&settings.EnableOpenExchangeRates, "openexchangerates", false, "overrides config and sets up foreign exchange Open Exchange Rates") flag.BoolVar(&settings.EnableExchangeRateHost, "exchangeratehost", false, "overrides config and sets up foreign exchange ExchangeRate.host") // Exchange tuning settings flag.BoolVar(&settings.EnableExchangeAutoPairUpdates, "exchangeautopairupdates", false, "enables automatic available currency pair updates for supported exchanges") flag.BoolVar(&settings.DisableExchangeAutoPairUpdates, "exchangedisableautopairupdates", false, "disables exchange auto pair updates") flag.BoolVar(&settings.EnableExchangeWebsocketSupport, "exchangewebsocketsupport", false, "enables Websocket support for exchanges") flag.BoolVar(&settings.EnableExchangeRESTSupport, "exchangerestsupport", true, "enables REST support for exchanges") flag.BoolVar(&settings.EnableExchangeVerbose, "exchangeverbose", false, "increases exchange logging verbosity") flag.BoolVar(&settings.ExchangePurgeCredentials, "exchangepurgecredentials", false, "purges the stored exchange API credentials") flag.BoolVar(&settings.EnableExchangeHTTPRateLimiter, "ratelimiter", true, "enables the rate limiter for HTTP requests") flag.IntVar(&settings.MaxHTTPRequestJobsLimit, "requestjobslimit", int(request.DefaultMaxRequestJobs), "sets the max amount of jobs the HTTP request package stores") flag.IntVar(&settings.RequestMaxRetryAttempts, "httpmaxretryattempts", request.DefaultMaxRetryAttempts, "sets the number of retry attempts after a retryable HTTP failure") flag.DurationVar(&settings.HTTPTimeout, "httptimeout", time.Duration(0), "sets the HTTP timeout value for HTTP requests") flag.StringVar(&settings.HTTPUserAgent, "httpuseragent", "", "sets the HTTP user agent") flag.StringVar(&settings.HTTPProxy, "httpproxy", "", "sets the HTTP proxy server") flag.BoolVar(&settings.EnableExchangeHTTPDebugging, "exchangehttpdebugging", false, "sets the exchanges HTTP debugging") flag.DurationVar(&settings.TradeBufferProcessingInterval, "tradeprocessinginterval", trade.DefaultProcessorIntervalTime, "sets the interval to save trade buffer data to the database") // Common tuning settings flag.DurationVar(&settings.GlobalHTTPTimeout, "globalhttptimeout", time.Duration(0), "sets common HTTP timeout value for HTTP requests") flag.StringVar(&settings.GlobalHTTPUserAgent, "globalhttpuseragent", "", "sets the common HTTP client's user agent") flag.StringVar(&settings.GlobalHTTPProxy, "globalhttpproxy", "", "sets the common HTTP client's proxy server") // GCTScript tuning settings flag.UintVar(&settings.MaxVirtualMachines, "maxvirtualmachines", uint(gctscriptVM.DefaultMaxVirtualMachines), "set max virtual machines that can load") // Withdraw Cache tuning settings flag.Uint64Var(&settings.WithdrawCacheSize, "withdrawcachesize", withdraw.CacheSize, "set cache size for withdrawal requests") flag.Parse() if *versionFlag { fmt.Print(core.Version(true)) os.Exit(0) } fmt.Println(core.Banner) fmt.Println(core.Version(false)) var err error settings.CheckParamInteraction = true // collect flags flagSet := make(map[string]bool) // Stores the set flags flag.Visit(func(f *flag.Flag) { flagSet[f.Name] = true }) if !flagSet["config"] { // If config file is not explicitly set, fall back to default path resolution settings.ConfigFile = "" } engine.Bot, err = engine.NewFromSettings(&settings, flagSet) if engine.Bot == nil || err != nil { log.Fatalf("Unable to initialise bot engine. Error: %s\n", err) } config.Cfg = *engine.Bot.Config // { // -------Gateio // var exch gateio.Gateio // exch.SetDefaults() // //获取交易所 -- 测试不需要使用 engine,直接使用 实例 ,也可以访问 // exchCfg, _ := engine.Bot.Config.GetExchangeConfig("GateIO") // exchCfg.Verbose = true // exchCfg.Features.Enabled.Websocket = true // exchCfg.AuthenticatedWebsocketAPISupport = &exchCfg.Features.Enabled.Websocket // exch.API.AuthenticatedSupport = true // exch.API.AuthenticatedWebsocketSupport = true // exch.SkipAuthCheck = true // exch.Verbose = true // logCfg := gctlog.GenDefaultSettings() // gctlog.GlobalLogConfig = &logCfg // exch.Setup(exchCfg) // // // // exch.WebsocketFuture.SetCanUseAuthenticatedEndpoints(true) // // //------- 测试 GateIO WebSocket Spot 开始 // go func() { // assetType := asset.Spot // symbolPair, _ := currency.NewPairFromStrings("cqt", "usdt") // symbolPair.Delimiter = "_" // exch.CurrencyPairs.Pairs[assetType].Available = exch.CurrencyPairs.Pairs[assetType].Available.Add(symbolPair) // if !exch.CurrencyPairs.Pairs[assetType].Enabled.Contains(symbolPair, true) { // err = exch.CurrencyPairs.EnablePair(assetType, symbolPair) // if err != nil { // panic(err) // } // } // err = exch.WsConnect() // if err != nil { // panic(err) // } // }() // go func() { // for { // select { // case data := <-exch.Websocket.DataHandler: // switch d := data.(type) { // case *ticker.Price: // fmt.Printf("[%s]ticker.Price\t%+v", d.Pair, d) // default: // } // } // } // }() // interruptxx := signaler.WaitForInterrupt() // gctlog.Infof(gctlog.Global, "Captured %v, shutdown requested.\n", interruptxx) // return // ------- 测试 GateIO WebSocket Spot 结束 //-------火币 // var exch huobi.HUOBI // exch.SetDefaults() // //获取交易所 -- 测试不需要使用 engine,直接使用 实例 ,也可以访问 // exchCfg, _ := engine.Bot.Config.GetExchangeConfig("Huobi") // exchCfg.Verbose = true // exchCfg.Features.Enabled.Websocket = true // exchCfg.AuthenticatedWebsocketAPISupport = &exchCfg.Features.Enabled.Websocket // exch.API.AuthenticatedSupport = true // exch.API.AuthenticatedWebsocketSupport = true // exch.SkipAuthCheck = true // exch.Verbose = true // logCfg := gctlog.GenDefaultSettings() // gctlog.GlobalLogConfig = &logCfg // exch.Setup(exchCfg) // symbol := currency.NewPair(currency.NewCode("BTC"), currency.NewCode("USD")) // symbol.Delimiter = "-" // if klineItems, err := exch.HistoricalFundingRate(asset.PerpetualContract, huobi.HistoricalFundingRateRequest{ // Symbol: symbol, // PageIndex: 1, // }); err != nil { // fmt.Printf("Error:%+v\n", err) // } else { // for _, v := range klineItems.Data.Data { // fmt.Printf("%+v\n", v) // } // fmt.Println(klineItems.Data.TotalPage) // } // return // =================== 币安 =================== // var exch binance.Binance // exch.SetDefaults() // //获取交易所 -- 测试不需要使用 engine,直接使用 实例 ,也可以访问 // exchCfg, _ := engine.Bot.Config.GetExchangeConfig("Binance") // exchCfg.Verbose = true // // exchCfg.ProxyAddress = "http://10.0.0.10:18080" // exchCfg.Features.Enabled.Websocket = true // exchCfg.AuthenticatedWebsocketAPISupport = &exchCfg.Features.Enabled.Websocket // exch.API.AuthenticatedSupport = true // exch.API.AuthenticatedWebsocketSupport = true // exch.API.Credentials.Key = "" // exch.API.Credentials.Secret = "" // exch.SkipAuthCheck = true // exch.Verbose = true // gctlog.GlobalLogConfig = gctlog.GenDefaultSettings() // exch.Setup(exchCfg) // // // // exch.WebsocketFuture.SetCanUseAuthenticatedEndpoints(true) // // ctx := context.Background() // // //------- 测试WebSocket Spot 开始 // //---通用日志 // logName := fmt.Sprintf("access-%s.log", "web") // logErrName := fmt.Sprintf("access-%s.error.log", "web") // loggerInstance := logger.New() // loggerInstance.InfoFileName = logName // loggerInstance.ErrorFileName = logErrName // loggerInstance.LevelSeparate = true // loggerInstance.JSONFormat = false // loggerInstance.SetDivision(logger.DivisionTime) // loggerInstance.MaxSize = 10 // loggerInstance.InitLogger(false) // //--- WS文件日志 // // --- 设置原交易所WebSocket的日志目录 // // 获取当前工作目录 // workPath, err := os.Getwd() // if err != nil { // panic(err) // } // // 设置 logs 输出文件目录 // logFolderPath := filepath.Join(workPath, "logs") // // 如果目录不存在,则创建 // if !commonutils.PathExists(logFolderPath) { // if err = os.Mkdir(logFolderPath, os.ModePerm); err != nil { // panic(err) // } // } // // 拼接日志目录文件 // baseLogPath := filepath.Join(logFolderPath, "Websocket-Source.%F.log") // hook, err := rotatelogs.New( // baseLogPath, // rotatelogs.WithLinkName(baseLogPath), // rotatelogs.WithMaxAge(time.Duration(int64(24*time.Hour)*int64(7))), // rotatelogs.WithRotationTime(time.Hour*24), // rotatelogs.WithClock(rotatelogs.Local), // ) // gctlog.WebsocketMgr.SetOutput(hook) // go func() { // assetType := asset.Spot // symbolPair, _ := currency.NewPairFromStrings("BTC", "USDT") // symbolPair.Delimiter = "-" // exch.CurrencyPairs.Pairs[assetType].Available = exch.CurrencyPairs.Pairs[assetType].Available.Add(symbolPair) // if !exch.CurrencyPairs.Pairs[assetType].Enabled.Contains(symbolPair, true) { // err = exch.CurrencyPairs.EnablePair(assetType, symbolPair) // if err != nil { // panic(err) // } // } // ws, err := exch.GetWebsocket() // if err != nil { // panic(err) // } // ws.SetVerbose(true) // if !ws.IsConnected() { // err = ws.Connect() // if err != nil { // panic(err) // } // } // err = exch.Websocket.FlushChannels() // if err != nil { // panic(err) // } // { // newTaskJob := cron.New(cron.WithSeconds()) // newTaskJob.AddFunc("@every 10s", func() { // logger.Debugf("IsEnabled:%+v\t\tInit:%+v\tConnected:%+v\tIsConnecting:%+v\tIsConnectionMonitorRunning:%+v\tIsDataMonitorRunning:%+v\tIsTrafficMonitorRunning:%+v", // ws.IsEnabled(), // ws.Init, // ws.IsConnected(), // ws.IsConnecting(), // ws.IsConnectionMonitorRunning(), // ws.IsDataMonitorRunning(), // ws.IsTrafficMonitorRunning(), // ) // // if !ws.IsInit() && !ws.IsConnected() { // // logger.Debugf("Enable 准备关闭 \tIsEnabled:%+v\t\tInit:%+v\tConnected:%+v\tIsConnecting:%+v\tIsConnectionMonitorRunning:%+v\tIsDataMonitorRunning:%+v\tIsTrafficMonitorRunning:%+v", // // ws.IsEnabled(), // // ws.Init, // // ws.IsConnected(), // // ws.IsConnecting(), // // ws.IsConnectionMonitorRunning(), // // ws.IsDataMonitorRunning(), // // ws.IsTrafficMonitorRunning(), // // ) // // err = ws.Disable() // // if err != nil { // // panic(err) // // } // // logger.Debugf("Enable 关闭完成 \tIsEnabled:%+v\t\tInit:%+v\tConnected:%+v\tIsConnecting:%+v\tIsConnectionMonitorRunning:%+v\tIsDataMonitorRunning:%+v\tIsTrafficMonitorRunning:%+v", // // ws.IsEnabled(), // // ws.Init, // // ws.IsConnected(), // // ws.IsConnecting(), // // ws.IsConnectionMonitorRunning(), // // ws.IsDataMonitorRunning(), // // ws.IsTrafficMonitorRunning(), // // ) // // err = ws.Enable() // // if err != nil { // // panic(err) // // } // // logger.Debugf("Enable 重新打开 \tIsEnabled:%+v\t\tInit:%+v\tConnected:%+v\tIsConnecting:%+v\tIsConnectionMonitorRunning:%+v\tIsDataMonitorRunning:%+v\tIsTrafficMonitorRunning:%+v", // // ws.IsEnabled(), // // ws.Init, // // ws.IsConnected(), // // ws.IsConnecting(), // // ws.IsConnectionMonitorRunning(), // // ws.IsDataMonitorRunning(), // // ws.IsTrafficMonitorRunning(), // // ) // // } // }) // newTaskJob.Start() // } // }() // go func() { // for { // select { // case data := <-exch.Websocket.ToRoutine: // switch d := data.(type) { // case *ticker.Price: // logger.Debugf("[%s]*ticker.Price\t%+v", d.Pair, d) // // case binance.MarkPriceStreamResponse: // // logger.Debugf("[%s]ticker.Price\t%+v", d.Symbol, d) // // default: // // logger.Errorf("%+v", d) // } // } // } // }() // interruptxx := signaler.WaitForInterrupt() // gctlog.Infof(gctlog.Global, "Captured %v, shutdown requested.\n", interruptxx) // return //------- 测试WebSocket Spot 结束 // ----- 获取手续费 // { // assetType := asset.Spot // spotFee, err := exch.GetSpotTradeFee(ctx, "BTCUSDT") // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, spotFee) // assetType = asset.USDTMarginedFutures // result, err := exch.GetContractTradeFee(ctx, assetType, "BTCUSDT") // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, result) // assetType = asset.CoinMarginedFutures // result, err = exch.GetContractTradeFee(ctx, assetType, "BTCUSD_PERP") // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, result) // } //------- 查询持仓模式 // { // assetType := asset.USDTMarginedFutures // result, err := exch.DualQuery(ctx, assetType) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, result) // assetType = asset.CoinMarginedFutures // result, err = exch.DualQuery(ctx, assetType) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, result) // } //------- 获取最新价格 // { // assetType := asset.Spot // symbolPair, _ := currency.NewPairFromStrings("BTC", "USDT") // symbolPair.Delimiter = "-" // spotPrice, err := exch.GetLatestSpotPrice(ctx, symbolPair) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, spotPrice) // assetType = asset.USDTMarginedFutures // symbolPair, _ = currency.NewPairFromStrings("BTC", "USDT") // symbolPair.Delimiter = "" // uFturePrice, err := exch.USymbolPriceTicker(ctx, symbolPair) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, uFturePrice) // assetType = asset.CoinMarginedFutures // symbolPair, _ = currency.NewPairFromStrings("BTCUSD", "PERP") // symbolPair.Delimiter = "_" // cFturePrice, err := exch.GetFuturesSymbolPriceTicker(ctx, symbolPair, "") // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, cFturePrice) // } //-------- GetExchangeInfo // { // // assetType := asset.Spot // // spotExchangeInfo, err := exch.GetExchangeInfo(ctx) // // if err != nil { // // panic(err) // // } // // fmt.Printf("%s:%+v\n", assetType, spotExchangeInfo) // // assetType := asset.USDTMarginedFutures // // uFtureExchangeInfo, err := exch.UExchangeInfo(ctx) // // if err != nil { // // panic(err) // // } // // fmt.Printf("%s:%+v\n", assetType, uFtureExchangeInfo) // assetType := asset.CoinMarginedFutures // cFtureExchangeInfo, err := exch.FuturesExchangeInfo(ctx) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, cFtureExchangeInfo) // } //-------- Account 账户信息 // { // // assetType := asset.Spot // // spot, err := exch.GetAccount(ctx) // // if err != nil { // // panic(err) // // } // // fmt.Printf("%s:%+v\n", assetType, spot) // // assetType := asset.USDTMarginedFutures // // uFture, err := exch.UAccountInformationV2(ctx) // // if err != nil { // // panic(err) // // } // // fmt.Printf("%s:%+v\n", assetType, uFture) // // assetType := asset.CoinMarginedFutures // // cFture, err := exch.GetFuturesAccountInfo(ctx) // // if err != nil { // // panic(err) // // } // // fmt.Printf("%s:%+v\n", assetType, cFture) // } //----------- ADLQuantile 持仓ADL队列估算 // { // assetType := asset.USDTMarginedFutures // symbolPair, _ := currency.NewPairFromStrings("SXP", "USDT") // symbolPair.Delimiter = "" // uFture, err := exch.UPositionsADLEstimate(ctx, symbolPair) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, uFture) // assetType = asset.CoinMarginedFutures // symbolPair, _ = currency.NewPairFromStrings("BTCUSD", "PERP") // symbolPair.Delimiter = "" // cFtureExchangeInfo, err := exch.FuturesPositionsADLEstimate(ctx, symbolPair) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, cFtureExchangeInfo) // } //----------- Income 获取账户损益资金流水 // { // // assetType := asset.USDTMarginedFutures // // symbolPair, _ := currency.NewPairFromStrings("SXP", "USDT") // // symbolPair.Delimiter = "" // // uFture, err := exch.UAccountIncomeHistory(ctx, symbolPair, "", 100, time.Time{}, time.Time{}) // // if err != nil { // // panic(err) // // } // // fmt.Printf("%s:%+v\n", assetType, uFture) // assetType := asset.CoinMarginedFutures // symbolPair, _ := currency.NewPairFromStrings("BTCUSD", "PERP") // symbolPair.Delimiter = "" // cFtureExchangeInfo, err := exch.FuturesIncomeHistory(ctx, symbolPair, "", time.Time{}, time.Time{}, 100) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, cFtureExchangeInfo) // } // ----------- 获取手续费 // { // assetType := asset.USDTMarginedFutures // symbolPair, _ := currency.NewPairFromStrings("SXP", "USDT") // symbolPair.Delimiter = "" // uFture, err := exch.GetContractTradeFee(ctx, assetType, symbolPair.String()) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, uFture) // assetType = asset.CoinMarginedFutures // symbolPair, _ = currency.NewPairFromStrings("BTCUSD", "PERP") // symbolPair.Delimiter = "_" // cFture, err := exch.GetContractTradeFee(ctx, assetType, symbolPair.String()) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, cFture) // } // return // //--------- GetPremiumIndex 最新标记价格和资金费率 // { // assetType := asset.USDTMarginedFutures // symbolPair, _ := currency.NewPairFromStrings("SXP", "USDT") // symbolPair.Delimiter = "" // uFture, err := exch.UGetMarkPrice(ctx, symbolPair) // if err != nil { // panic(err) // } // for _, v := range uFture { // fmt.Printf("%s:%+v\n", assetType, v) // } // assetType = asset.CoinMarginedFutures // symbolPair, _ = currency.NewPairFromStrings("BTCUSD", "PERP") // symbolPair.Delimiter = "_" // cFtureExchangeInfo, err := exch.GetIndexAndMarkPrice(ctx, symbolPair.String(), "") // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, cFtureExchangeInfo) // } // return //--------- GetFundingRate 查询资金费率历史 // { // assetType := asset.USDTMarginedFutures // symbolPair, _ := currency.NewPairFromStrings("SXP", "USDT") // symbolPair.Delimiter = "" // uFture, err := exch.UGetFundingHistory(ctx, symbolPair, 100, time.Time{}, time.Time{}) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, uFture) // assetType = asset.CoinMarginedFutures // symbolPair, _ = currency.NewPairFromStrings("BTCUSD", "PERP") // symbolPair.Delimiter = "_" // cFtureExchangeInfo, err := exch.FuturesGetFundingHistory(ctx, symbolPair, 100, time.Time{}, time.Time{}) // if err != nil { // panic(err) // } // fmt.Printf("%s:%+v\n", assetType, cFtureExchangeInfo) // } //---------- PositionRisk 用户持仓风险V2 // { // assetType := asset.USDTMarginedFutures // symbolPair, _ := currency.NewPairFromStrings("SXP", "USDT") // symbolPair.Delimiter = "" // uFture, err := exch.UPositionsInfoV2(ctx, symbolPair) // if err != nil { // panic(err) // } // for _, v := range uFture { // fmt.Printf("%s:%+v\n", assetType, v) // } // // assetType = asset.CoinMarginedFutures // // symbolPair, _ = currency.NewPairFromStrings("BTCUSD", "PERP") // // symbolPair.Delimiter = "_" // // cFtureExchangeInfo, err := exch.FuturesPositionsInfo(ctx, "", symbolPair.String()) // // if err != nil { // // panic(err) // // } // // fmt.Printf("%s:%+v\n", assetType, cFtureExchangeInfo) // } // return // // //------- 测试WebSocket USDTMarginedFutures 开始 // go func() { // assetType := asset.USDTMarginedFutures // exch.CurrencyPairs.Pairs[assetType] = &currency.PairStore{ // RequestFormat: &currency.PairFormat{ // Uppercase: true, // }, // ConfigFormat: &currency.PairFormat{ // Uppercase: true, // }, // } // if err = exch.CurrencyPairs.SetAssetEnabled(assetType, true); err != nil { // panic(err) // } // symbolPair, _ := currency.NewPairFromStrings("XRP", "USDT") // symbolPair.Delimiter = "" // exch.CurrencyPairs.Pairs[assetType].Available = exch.CurrencyPairs.Pairs[assetType].Available.Add(symbolPair) // if !exch.CurrencyPairs.Pairs[assetType].Enabled.Contains(symbolPair, true) { // err = exch.CurrencyPairs.EnablePair(assetType, symbolPair) // if err != nil { // panic(err) // } // } // ws := exch.UFuturesWebsocket // if ws.IsEnabled() { // err = ws.Connect() // if err != nil { // panic(err) // } // } // }() // go func() { // logName := fmt.Sprintf("access-%s.log", "web") // logErrName := fmt.Sprintf("access-%s.error.log", "web") // loggerInstance := logger.New() // loggerInstance.InfoFileName = logName // loggerInstance.ErrorFileName = logErrName // loggerInstance.LevelSeparate = true // loggerInstance.JSONFormat = false // loggerInstance.SetDivision(logger.DivisionTime) // loggerInstance.MaxSize = 10 // loggerInstance.InitLogger(false) // for { // select { // case data := <-exch.UFuturesWebsocket.ToRoutine: // switch d := data.(type) { // case *ticker.Price: // logger.Debugf("[%s]*ticker.Price\t%+v", d.Pair, d) // case ticker.Price: // logger.Debugf("[%s]ticker.Price\t%+v", d.Pair, d) // case binance.MarkPriceStreamResponse: // logger.Debugf("[%s]MarkPriceStreamResponse\t%+v", d.Symbol, d) // case error: // logger.Errorf("%+v\n", d) // default: // // logger.Errorf("%+v\n", d) // } // } // } // }() // interruptxx := signaler.WaitForInterrupt() // gctlog.Infof(gctlog.Global, "Captured %v, shutdown requested.\n", interruptxx) // return // //------- 测试WebSocket Future 结束 // if err != nil { // panic(err) // } // // } // return // FutureAccount 账户信息V2 (USER_DATA) // list, err := exch.GetContractAccount(asset.PerpetualContract) // if err != nil { // panic(err) // } else { // // for _, v := range list.Symbols { // // if v.ContractType == "PERPETUAL" { // fmt.Printf("%+v\n", list) // // } // // } // } // return // 测试用户强平单历史 (USER_DATA) // symbolFuturePair := currency.NewPair(currency.NewCode("XLM"), currency.NewCode("USDT")) // symbolFuturePair.Delimiter = "" // list, err := exch.ForceOrders("ETHUSDT", 0, 0, 0) // if err != nil { // panic(err) // } else { // for _, v := range list { // fmt.Printf("%+v\n", v) // } // } // return // 持仓ADL队列估算 // symbolPair := currency.NewPair(currency.NewCode("BTCUSD"), currency.NewCode("PERP")) // symbolPair.Delimiter = "_" // list, err := exch.GetContractADLQuantile(asset.PerpetualContract, symbolPair) // if err != nil { // panic(err) // } else { // fmt.Printf("%+v\n", list) // } // return // 调整逐仓保证金 // symbolFuturePair := currency.NewPair(currency.NewCode("ETH"), currency.NewCode("USDT")) // symbolFuturePair.Delimiter = "" // list, err := exch.PositionMargin(binance.PositionMarginRequest{ // Symbol: symbolFuturePair, // PositionSide: binance.PositionSideSHORT, // Type: binance.PositionMarginTypeSub, // Amount: 10, // }) // if err != nil { // panic(err) // } else { // fmt.Printf("%+v\n", list) // } // 逐仓保证金变动历史 (TRADE) // symbolFuturePair := currency.NewPair(currency.NewCode("ETH"), currency.NewCode("USDT")) // symbolFuturePair.Delimiter = "" // list, err := exch.PositionMarginHistory(binance.PositionMarginHistoryRequest{ // Symbol: symbolFuturePair, // // PositionSide: binance.PositionSideSHORT, // // Type: binance.PositionMarginTypeAdd, // // Amount: 10, // }) // if err != nil { // panic(err) // } else { // for _, v := range list { // fmt.Printf("%+v\n", v) // } // } // return // 获取资金费率表 // list, err := exch.GetFutureFundingRate(binance.FutureFundingRateRequest{ // Limit: 1, // }) // if err != nil { // panic(err) // } else { // for _, v := range list { // fmt.Printf("%+v\n", v) // } // } // return // 获取用户手续费率 // symbolFuturePair := currency.NewPair(currency.NewCode("DOTUSD"), currency.NewCode("PERP")) // symbolFuturePair.Delimiter = "_" // // symbolPair := currency.NewPair(currency.NewCode("DOTUSD"), currency.NewCode("PERP")) // // symbolPair.Delimiter = "-" // list, err := exch.MarginType(asset.PerpetualContract, symbolFuturePair, binance.MarginType_CROSSED) // if err != nil { // panic(err) // } else { // fmt.Printf("%+v\n", list) // } // return //获取交易规则和交易对 // list, err := exch.GetExchangeInfo(asset.PerpetualContract) // if err != nil { // panic(err) // } else { // for _, v := range list.Symbols { // fmt.Printf("%s %s \t%+v\t%s BaseAssetPrecision[%d]QuoteOrderQtyMarketAllowed[%d]PricePrecision:%d\n", v.BaseAsset, v.QuoteAsset, v.Symbol, v.ContractType, v.BaseAssetPrecision, v.QuotePrecision, v.PricePrecision) // fmt.Println(v.ContractSize) // } // } // return // 设置杠杆倍数 // symbolFuturePair := currency.NewPair(currency.NewCode("DOTUSD"), currency.NewCode("PERP")) // symbolFuturePair.Delimiter = "_" // futureLeverageResponse, err := exch.Leverage(asset.PerpetualContract, symbolFuturePair.String(), 10) // if err != nil { // panic(err) // } else { // fmt.Printf("v:%+v\n", futureLeverageResponse) // } // return // 查看持仓风险 // assetType := asset.PerpetualContract // symbol, _ := currency.NewPairFromStrings("DOTUSD", "PERP") // symbol.Delimiter = "_" // // symbol := currency.NewPair(currency.NewCode("SXP"), currency.NewCode("USDT")) // // symbol.Delimiter = "" // list, err := exch.PositionRisk(assetType, symbol.Base.String()) // if err != nil { // panic(err) // } else { // for _, v := range list { // fmt.Printf("v:%+v\n", v) // } // } // return // 下合约订单 // symbolFuturePair := currency.NewPair(currency.NewCode("ETH"), currency.NewCode("USDT")) // symbolFuturePair.Delimiter = "" // oresp, err := exch.NewOrderFuture(&binance.FutureNewOrderRequest{ // Symbol: symbolFuturePair.String(), // Side: order.Sell, // Type: binance.BinanceRequestParamsOrderLimit, // PositionSide: binance.PositionSideSHORT, // TimeInForce: binance.BinanceRequestParamsTimeGTC, // Quantity: 0.01, // Price: 1500.0, // }) // if err != nil { // panic(err) // } else { // fmt.Printf("oresp:%+v\n", oresp) // } // return // 查询合约订单 // symbolFuturePair := currency.NewPair(currency.NewCode("DOTUSD"), currency.NewCode("PERP")) // symbolFuturePair.Delimiter = "_" // assetType := asset.PerpetualContract // oresp, err := exch.QueryOrderContract(assetType, symbolFuturePair.String(), 620332404, "") // if err != nil { // panic(err) // } else { // fmt.Printf("oresp:%+v\n", oresp) // } // return // 查询打开的订单 // symbolPair := currency.NewPair(currency.NewCode("SXP"), currency.NewCode("USDT")) // symbolPair.Delimiter = "" // symbolPair := currency.NewPair(currency.NewCode("BTCUSD"), currency.NewCode("PERP")) // symbolPair.Delimiter = "_" // list, err := exch.OpenOrdersContract(asset.PerpetualContract, symbolPair.String()) // if err != nil { // panic(err) // } else { // for _, v := range list { // fmt.Printf("OpenOrdersFuture:%+v", v) // } // } // return // 取消合约订单 // symbolFuturePair := currency.NewPair(currency.NewCode("ETH"), currency.NewCode("USDT")) // symbolFuturePair.Delimiter = "" // oresp, err := exch.CancelExistingOrderFuture(symbolFuturePair.String(), 8389765490780171484, "") // if err != nil { // panic(err) // } else { // fmt.Printf("oresp:%+v\n", oresp) // } // return // 获取合约K线 // symbol, _ := currency.NewPairFromStrings("BTC", "USDT") // symbol.Delimiter = "" // startTime := time.Now().Add(-time.Minute * 20) // list, err := exch.GetHistoricCandlesFuture(symbol, binance.ContractTypePERPETUAL, startTime, time.Now(), kline.FiveMin) // if err != nil { // panic(err) // } else { // for _, v := range list.Candles { // fmt.Printf("%+v\n", v) // } // } // 万向划转 // tranid, err := exch.Transfer(binance.TransferType_MAIN_UMFUTURE, "USDT", 10) // if err != nil { // panic(err) // } else { // fmt.Printf("%+v\n", tranid) // } // 获取账户损益资金流水 // todayTimeStat := "2021-01-11 20:40:10" // loc, _ := time.LoadLocation("Local") //重要:获取时区 // timeStat, _ := time.ParseInLocation("2006-01-02 15:04:05", todayTimeStat, loc) // timeStatID := timeStat.UnixNano() / int64(time.Millisecond) // fmt.Println("") // 1610381770000 // 1610380800000 // list, err := exch.GetContractIncome(asset.PerpetualContract, binance.FutureIncomeRequest{}) // if err != nil { // panic(err) // } else { // for _, v := range list { // fmt.Printf("%+v\n", v) // } // } // return // 获取永续合约当前价格 // symbol, _ := currency.NewPairFromStrings("BTC", "USDT") // symbol.Delimiter = "" // startTime := time.Now().Add(-time.Minute * 20) // list, err := exch.GetHistoricCandlesFuture(symbol, asset.PERPETUAL, startTime, time.Now(), kline.FiveMin) // if err != nil { // panic(err) // } else { // for _, v := range list.Candles { // fmt.Printf("%+v\n", v) // } // } // return // 最新标记价格和资金费率 // assetType := asset.PerpetualContract // symbol, _ := currency.NewPairFromStrings("SXP", "USDT") // symbol.Delimiter = "" // // symbol := currency.NewPair(currency.NewCode("DOTUSD"), currency.NewCode("PERP")) // // symbol.Delimiter = "_" // list, err := exch.GetPremiumIndex(assetType, symbol) // if err != nil { // panic(err) // } else { // fmt.Printf("%+v\n", list) // } // return // 最新标记价格和资金费率 // symbol, _ := currency.NewPairFromStrings("BTC", "USDT") // symbol.Delimiter = "" // list, err := exch.GetFundingRate(asset.Future, binance.FundingRateRequest{ // Symbol: symbol, // Limit: 540, // }) // if err != nil { // panic(err) // } else { // for _, v := range list { // fmt.Printf("%+v\n", v) // } // } // return // } // return // //--------历史委托信息 // // req := huobi.ContractHisordersRequest{ // // Symbol: "BTC", // // TradeType: huobi.TradeType0, // // Type: huobi.ContractHisOrderType1, // // Status: huobi.ContractOrderStatus0, // // CreateDate: 90, // // } // // if res, err := huobiExch.GetContractHisorders(req); err != nil { // // panic(err) // // } else { // // fmt.Println("res", res) // // } // } gctscript.Setup() engine.PrintSettings(&engine.Bot.Settings) if err = engine.Bot.Start(); err != nil { gctlog.Errorf(gctlog.Global, "Unable to start bot engine. Error: %s\n", err) os.Exit(1) } interrupt := signaler.WaitForInterrupt() gctlog.Infof(gctlog.Global, "Captured %v, shutdown requested.\n", interrupt) engine.Bot.Stop() gctlog.Infoln(gctlog.Global, "Exiting.") } <file_sep>package holdings import ( "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) // Create makes a Holding struct to track total values of strategy holdings over the course of a backtesting run func Create(ev ClosePriceReader, funding funding.IPairReader) (Holding, error) { if ev == nil { return Holding{}, common.ErrNilEvent } if funding.QuoteInitialFunds().LessThan(decimal.Zero) { return Holding{}, ErrInitialFundsZero } return Holding{ Offset: ev.GetOffset(), Pair: ev.Pair(), Asset: ev.GetAssetType(), Exchange: ev.GetExchange(), Timestamp: ev.GetTime(), QuoteInitialFunds: funding.QuoteInitialFunds(), QuoteSize: funding.QuoteInitialFunds(), BaseInitialFunds: funding.BaseInitialFunds(), BaseSize: funding.BaseInitialFunds(), TotalInitialValue: funding.QuoteInitialFunds().Add(funding.BaseInitialFunds().Mul(ev.GetClosePrice())), }, nil } // Update calculates holding statistics for the events time func (h *Holding) Update(e fill.Event, f funding.IPairReader) { h.Timestamp = e.GetTime() h.Offset = e.GetOffset() h.update(e, f) } // UpdateValue calculates the holding's value for a data event's time and price func (h *Holding) UpdateValue(d common.DataEventHandler) { h.Timestamp = d.GetTime() latest := d.GetClosePrice() h.Offset = d.GetOffset() h.updateValue(latest) } // HasInvestments determines whether there are any holdings in the base funds func (h *Holding) HasInvestments() bool { return h.BaseSize.GreaterThan(decimal.Zero) } // HasFunds determines whether there are any holdings in the quote funds func (h *Holding) HasFunds() bool { return h.QuoteSize.GreaterThan(decimal.Zero) } func (h *Holding) update(e fill.Event, f funding.IPairReader) { direction := e.GetDirection() if o := e.GetOrder(); o != nil { amount := decimal.NewFromFloat(o.Amount) fee := decimal.NewFromFloat(o.Fee) price := decimal.NewFromFloat(o.Price) h.BaseSize = f.BaseAvailable() h.QuoteSize = f.QuoteAvailable() h.BaseValue = h.BaseSize.Mul(price) h.TotalFees = h.TotalFees.Add(fee) switch direction { case order.Buy: h.BoughtAmount = h.BoughtAmount.Add(amount) h.BoughtValue = h.BoughtAmount.Mul(price) case order.Sell: h.SoldAmount = h.SoldAmount.Add(amount) h.SoldValue = h.SoldAmount.Mul(price) case common.DoNothing, common.CouldNotSell, common.CouldNotBuy, common.MissingData, common.TransferredFunds, "": } } h.TotalValueLostToVolumeSizing = h.TotalValueLostToVolumeSizing.Add(e.GetClosePrice().Sub(e.GetVolumeAdjustedPrice()).Mul(e.GetAmount())) h.TotalValueLostToSlippage = h.TotalValueLostToSlippage.Add(e.GetVolumeAdjustedPrice().Sub(e.GetPurchasePrice()).Mul(e.GetAmount())) h.updateValue(e.GetClosePrice()) } func (h *Holding) updateValue(latestPrice decimal.Decimal) { origPosValue := h.BaseValue origBoughtValue := h.BoughtValue origSoldValue := h.SoldValue origTotalValue := h.TotalValue h.BaseValue = h.BaseSize.Mul(latestPrice) h.BoughtValue = h.BoughtAmount.Mul(latestPrice) h.SoldValue = h.SoldAmount.Mul(latestPrice) h.TotalValue = h.BaseValue.Add(h.QuoteSize) h.TotalValueDifference = h.TotalValue.Sub(origTotalValue) h.BoughtValueDifference = h.BoughtValue.Sub(origBoughtValue) h.PositionsValueDifference = h.BaseValue.Sub(origPosValue) h.SoldValueDifference = h.SoldValue.Sub(origSoldValue) if !origTotalValue.IsZero() { h.ChangeInTotalValuePercent = h.TotalValue.Sub(origTotalValue).Div(origTotalValue) } } <file_sep>package tests import ( "fmt" "io/ioutil" "os" "reflect" "testing" "github.com/idoall/gocryptotrader/database" "github.com/idoall/gocryptotrader/database/drivers" psqlConn "github.com/idoall/gocryptotrader/database/drivers/postgres" sqliteConn "github.com/idoall/gocryptotrader/database/drivers/sqlite3" ) var ( tempDir string postgresTestDatabase *database.Config ) func getConnectionDetails() *database.Config { _, exists := os.LookupEnv("TRAVIS") if exists { return &database.Config{ Enabled: true, Driver: "postgres", ConnectionDetails: drivers.ConnectionDetails{ Host: "localhost", Port: 5432, Username: "postgres", Password: "", Database: "gct_dev_ci", SSLMode: "", }, } } _, exists = os.LookupEnv("APPVEYOR") if exists { return &database.Config{ Enabled: true, Driver: "postgres", ConnectionDetails: drivers.ConnectionDetails{ Host: "localhost", Port: 5432, Username: "postgres", Password: "<PASSWORD>!", Database: "gct_dev_ci", SSLMode: "", }, } } return &database.Config{ Enabled: true, Driver: "postgres", ConnectionDetails: drivers.ConnectionDetails{ //Host: "", //Port: 5432, //Username: "", //Password: "", //Database: "", //SSLMode: "", }, } } func TestMain(m *testing.M) { var err error postgresTestDatabase = getConnectionDetails() tempDir, err = ioutil.TempDir("", "gct-temp") if err != nil { fmt.Printf("failed to create temp file: %v", err) os.Exit(1) } t := m.Run() err = os.RemoveAll(tempDir) if err != nil { fmt.Printf("Failed to remove temp db file: %v", err) } os.Exit(t) } func TestDatabaseConnect(t *testing.T) { testCases := []struct { name string config *database.Config closer func(t *testing.T, dbConn *database.Db) error output interface{} }{ { "SQLite", &database.Config{ Driver: database.DBSQLite3, ConnectionDetails: drivers.ConnectionDetails{Database: "./testdb.db"}, }, closeDatabase, nil, }, { "SQliteNoDatabase", &database.Config{ Driver: database.DBSQLite3, ConnectionDetails: drivers.ConnectionDetails{ Host: "localhost", }, }, nil, database.ErrNoDatabaseProvided, }, { name: "Postgres", config: postgresTestDatabase, output: nil, }, } for _, tests := range testCases { test := tests t.Run(test.name, func(t *testing.T) { if !checkValidConfig(t, &test.config.ConnectionDetails) { t.Skip("database not configured skipping test") } dbConn, err := connectToDatabase(t, test.config) if err != nil { switch v := test.output.(type) { case error: if v.Error() != err.Error() { t.Fatal(err) } return default: break } } if test.closer != nil { err = test.closer(t, dbConn) if err != nil { t.Log(err) } } }) } } func connectToDatabase(t *testing.T, conn *database.Config) (dbConn *database.Db, err error) { t.Helper() database.DB.Config = conn if conn.Driver == database.DBPostgreSQL { dbConn, err = psqlConn.Connect() if err != nil { return nil, err } } else if conn.Driver == database.DBSQLite3 || conn.Driver == database.DBSQLite { database.DB.DataPath = tempDir dbConn, err = sqliteConn.Connect() if err != nil { return nil, err } } database.DB.Connected = true return } func closeDatabase(t *testing.T, conn *database.Db) (err error) { t.Helper() if conn != nil { return conn.SQL.Close() } return nil } func checkValidConfig(t *testing.T, config *drivers.ConnectionDetails) bool { t.Helper() return !reflect.DeepEqual(drivers.ConnectionDetails{}, *config) } <file_sep>package lbank // GetKlines checks and returns a requested kline if it exists // func (l *Lbank) GetKlines(arg interface{}) ([]*kline.Kline, error) { // var klines []*kline.Kline // return klines, common.ErrFunctionNotSupported // } <file_sep>package common import ( "errors" "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/kline" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) const ( // DoNothing is an explicit signal for the backtester to not perform an action // based upon indicator results DoNothing order.Side = "DO NOTHING" // TransferredFunds is a status signal to do nothing TransferredFunds order.Side = "TRANSFERRED FUNDS" // CouldNotBuy is flagged when a BUY signal is raised in the strategy/signal phase, but the // portfolio manager or exchange cannot place an order CouldNotBuy order.Side = "COULD NOT BUY" // CouldNotSell is flagged when a SELL signal is raised in the strategy/signal phase, but the // portfolio manager or exchange cannot place an order CouldNotSell order.Side = "COULD NOT SELL" // MissingData is signalled during the strategy/signal phase when data has been identified as missing // No buy or sell events can occur MissingData order.Side = "MISSING DATA" // CandleStr is a config readable data type to tell the backtester to retrieve candle data CandleStr = "candle" // TradeStr is a config readable data type to tell the backtester to retrieve trade data TradeStr = "trade" ) // DataCandle is an int64 representation of a candle data type const ( DataCandle = iota DataTrade ) var ( // ErrNilArguments is a common error response to highlight that nils were passed in // when they should not have been ErrNilArguments = errors.New("received nil argument(s)") // ErrNilEvent is a common error for whenever a nil event occurs when it shouldn't have ErrNilEvent = errors.New("nil event received") // ErrInvalidDataType occurs when an invalid data type is defined in the config ErrInvalidDataType = errors.New("invalid datatype received") ) // EventHandler interface implements required GetTime() & Pair() return type EventHandler interface { GetOffset() int64 SetOffset(int64) IsEvent() bool GetTime() time.Time Pair() currency.Pair GetExchange() string GetInterval() kline.Interval GetAssetType() asset.Item GetReason() string AppendReason(string) } // DataEventHandler interface used for loading and interacting with Data type DataEventHandler interface { EventHandler GetClosePrice() decimal.Decimal GetHighPrice() decimal.Decimal GetLowPrice() decimal.Decimal GetOpenPrice() decimal.Decimal } // Directioner dictates the side of an order type Directioner interface { SetDirection(side order.Side) GetDirection() order.Side } // ASCIILogo is a sweet logo that is optionally printed to the command line window const ASCIILogo = ` @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ ,,,,,, @@@@@@@@,,,,, @@@@@@@@@,,,,,,,, @@@@@@@@,,,,,,, @@@@@@@,,,,,,, @@@@@@(,,,,,,,, ,,@@@@@@@,,,,,, ,,@@@@@@,,,,,,,,, #,,,,,,,,,,,,,,,,, ,,,,*@@@@@@,,,,,,,,,,,,,,,,,,,,,,,,,,%%%%%%% ,,,,,,,*@@@@@@,,,,,,,,,,,,,,%%%%%,,,,,,%%%%%%%% ,,,,,,,,*@@@@@@,,,,,,,,,,,%%%%%%%%%%%%%%%%%%#%% ,,,,,,*@@@@@@,,,,,,,,,%%%,,,,,%%%%%%%%,,,,, ,,,*@@@@@@,,,,,,%%, ,,,,,,,@*%%,@,,,,,, *@@@@@@,,,,,,,,, ,,,,@@@@@@,,,,,, @@@@@@,,,,,,,,, @@@@@@@,,,,,, @@@@@@@@,,,,,,, @@@@@@@,,,,,,, @@@@@@@@@,,,, @@@@@@@@@#,,,,,,, @@@@@@@@@@@@@@@@@@@@@@@ *,,,, @@@@@@@@@@@@@@@@ ______ ______ __ ______ __ / ____/___ / ____/______ ______ / /_____/_ __/________ _____/ /__ _____ / / __/ __ \/ / / ___/ / / / __ \/ __/ __ \/ / / ___/ __ / __ / _ \/ ___/ / /_/ / /_/ / /___/ / / /_/ / /_/ / /_/ /_/ / / / / / /_/ / /_/ / __/ / \____/\____/\____/_/ \__, / .___/\__/\____/_/ /_/ \__,_/\__,_/\___/_/ /___/ ____ __ __ __ / __ )____ ______/ /__/ /____ _____/ /____ _____ / __ / __ / ___/ //_/ __/ _ \/ ___/ __/ _ \/ ___/ / /_/ / /_/ / /__/ ,< / /_/ __(__ ) /_/ __/ / /_____/\__,_/\___/_/|_|\__/\___/____/\__/\___/_/ ` <file_sep>package orderbook import ( "sync" "time" "github.com/gofrs/uuid" "github.com/idoall/gocryptotrader/dispatch" "github.com/idoall/gocryptotrader/exchanges/alert" "github.com/idoall/gocryptotrader/log" ) // Depth defines a linked list of orderbook items type Depth struct { asks bids // unexported stack of nodes stack *stack alert.Notice mux *dispatch.Mux id uuid.UUID options m sync.Mutex } // NewDepth returns a new depth item func newDepth(id uuid.UUID) *Depth { return &Depth{ stack: newStack(), id: id, mux: service.Mux, } } // Publish alerts any subscribed routines using a dispatch mux func (d *Depth) Publish() { err := d.mux.Publish([]uuid.UUID{d.id}, d.Retrieve()) if err != nil { log.Errorf(log.ExchangeSys, "Cannot publish orderbook update to mux %v", err) } } // GetAskLength returns length of asks func (d *Depth) GetAskLength() int { d.m.Lock() defer d.m.Unlock() return d.asks.length } // GetBidLength returns length of bids func (d *Depth) GetBidLength() int { d.m.Lock() defer d.m.Unlock() return d.bids.length } // Retrieve returns the orderbook base a copy of the underlying linked list // spread func (d *Depth) Retrieve() *Base { d.m.Lock() defer d.m.Unlock() return &Base{ Bids: d.bids.retrieve(), Asks: d.asks.retrieve(), Exchange: d.exchange, Asset: d.asset, Pair: d.pair, LastUpdated: d.lastUpdated, LastUpdateID: d.lastUpdateID, PriceDuplication: d.priceDuplication, IsFundingRate: d.isFundingRate, VerifyOrderbook: d.VerifyOrderbook, } } // TotalBidAmounts returns the total amount of bids and the total orderbook // bids value func (d *Depth) TotalBidAmounts() (liquidity, value float64) { d.m.Lock() defer d.m.Unlock() return d.bids.amount() } // TotalAskAmounts returns the total amount of asks and the total orderbook // asks value func (d *Depth) TotalAskAmounts() (liquidity, value float64) { d.m.Lock() defer d.m.Unlock() return d.asks.amount() } // LoadSnapshot flushes the bids and asks with a snapshot func (d *Depth) LoadSnapshot(bids, asks []Item, lastUpdateID int64, lastUpdated time.Time, updateByREST bool) { d.m.Lock() d.lastUpdateID = lastUpdateID d.lastUpdated = lastUpdated d.restSnapshot = updateByREST d.bids.load(bids, d.stack) d.asks.load(asks, d.stack) d.Alert() d.m.Unlock() } // Flush flushes the bid and ask depths func (d *Depth) Flush() { d.m.Lock() d.lastUpdateID = 0 d.lastUpdated = time.Time{} d.bids.load(nil, d.stack) d.asks.load(nil, d.stack) d.Alert() d.m.Unlock() } // UpdateBidAskByPrice updates the bid and ask spread by supplied updates, this // will trim total length of depth level to a specified supplied number func (d *Depth) UpdateBidAskByPrice(bidUpdts, askUpdts Items, maxDepth int, lastUpdateID int64, lastUpdated time.Time) { if len(bidUpdts) == 0 && len(askUpdts) == 0 { return } d.m.Lock() d.lastUpdateID = lastUpdateID d.lastUpdated = lastUpdated tn := getNow() if len(bidUpdts) != 0 { d.bids.updateInsertByPrice(bidUpdts, d.stack, maxDepth, tn) } if len(askUpdts) != 0 { d.asks.updateInsertByPrice(askUpdts, d.stack, maxDepth, tn) } d.Alert() d.m.Unlock() } // UpdateBidAskByID amends details by ID func (d *Depth) UpdateBidAskByID(bidUpdts, askUpdts Items, lastUpdateID int64, lastUpdated time.Time) error { if len(bidUpdts) == 0 && len(askUpdts) == 0 { return nil } d.m.Lock() defer d.m.Unlock() if len(bidUpdts) != 0 { err := d.bids.updateByID(bidUpdts) if err != nil { return err } } if len(askUpdts) != 0 { err := d.asks.updateByID(askUpdts) if err != nil { return err } } d.lastUpdateID = lastUpdateID d.lastUpdated = lastUpdated d.Alert() return nil } // DeleteBidAskByID deletes a price level by ID func (d *Depth) DeleteBidAskByID(bidUpdts, askUpdts Items, bypassErr bool, lastUpdateID int64, lastUpdated time.Time) error { if len(bidUpdts) == 0 && len(askUpdts) == 0 { return nil } d.m.Lock() defer d.m.Unlock() if len(bidUpdts) != 0 { err := d.bids.deleteByID(bidUpdts, d.stack, bypassErr) if err != nil { return err } } if len(askUpdts) != 0 { err := d.asks.deleteByID(askUpdts, d.stack, bypassErr) if err != nil { return err } } d.lastUpdateID = lastUpdateID d.lastUpdated = lastUpdated d.Alert() return nil } // InsertBidAskByID inserts new updates func (d *Depth) InsertBidAskByID(bidUpdts, askUpdts Items, lastUpdateID int64, lastUpdated time.Time) error { if len(bidUpdts) == 0 && len(askUpdts) == 0 { return nil } d.m.Lock() defer d.m.Unlock() if len(bidUpdts) != 0 { err := d.bids.insertUpdates(bidUpdts, d.stack) if err != nil { return err } } if len(askUpdts) != 0 { err := d.asks.insertUpdates(askUpdts, d.stack) if err != nil { return err } } d.lastUpdateID = lastUpdateID d.lastUpdated = lastUpdated d.Alert() return nil } // UpdateInsertByID updates or inserts by ID at current price level. func (d *Depth) UpdateInsertByID(bidUpdts, askUpdts Items, lastUpdateID int64, lastUpdated time.Time) error { if len(bidUpdts) == 0 && len(askUpdts) == 0 { return nil } d.m.Lock() defer d.m.Unlock() if len(bidUpdts) != 0 { err := d.bids.updateInsertByID(bidUpdts, d.stack) if err != nil { return err } } if len(askUpdts) != 0 { err := d.asks.updateInsertByID(askUpdts, d.stack) if err != nil { return err } } d.Alert() d.lastUpdateID = lastUpdateID d.lastUpdated = lastUpdated return nil } // AssignOptions assigns the initial options for the depth instance func (d *Depth) AssignOptions(b *Base) { d.m.Lock() d.options = options{ exchange: b.Exchange, pair: b.Pair, asset: b.Asset, lastUpdated: b.LastUpdated, lastUpdateID: b.LastUpdateID, priceDuplication: b.PriceDuplication, isFundingRate: b.IsFundingRate, VerifyOrderbook: b.VerifyOrderbook, restSnapshot: b.RestSnapshot, idAligned: b.IDAlignment, } d.m.Unlock() } // GetName returns name of exchange func (d *Depth) GetName() string { d.m.Lock() defer d.m.Unlock() return d.exchange } // IsRestSnapshot returns if the depth item was updated via REST func (d *Depth) IsRestSnapshot() bool { d.m.Lock() defer d.m.Unlock() return d.restSnapshot } // LastUpdateID returns the last Update ID func (d *Depth) LastUpdateID() int64 { d.m.Lock() defer d.m.Unlock() return d.lastUpdateID } // IsFundingRate returns if the depth is a funding rate func (d *Depth) IsFundingRate() bool { d.m.Lock() defer d.m.Unlock() return d.isFundingRate } <file_sep>package portfolio import ( "errors" "testing" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/compliance" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/holdings" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/risk" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/size" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/eventtypes/kline" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" "github.com/idoall/gocryptotrader/backtester/eventtypes/signal" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) const testExchange = "binance" func TestReset(t *testing.T) { t.Parallel() p := Portfolio{ exchangeAssetPairSettings: make(map[string]map[asset.Item]map[currency.Pair]*Settings), } p.Reset() if p.exchangeAssetPairSettings != nil { t.Error("expected nil") } } func TestSetup(t *testing.T) { t.Parallel() _, err := Setup(nil, nil, decimal.NewFromInt(-1)) if !errors.Is(err, errSizeManagerUnset) { t.Errorf("received: %v, expected: %v", err, errSizeManagerUnset) } _, err = Setup(&size.Size{}, nil, decimal.NewFromInt(-1)) if !errors.Is(err, errNegativeRiskFreeRate) { t.Errorf("received: %v, expected: %v", err, errNegativeRiskFreeRate) } _, err = Setup(&size.Size{}, nil, decimal.NewFromInt(1)) if !errors.Is(err, errRiskManagerUnset) { t.Errorf("received: %v, expected: %v", err, errRiskManagerUnset) } var p *Portfolio p, err = Setup(&size.Size{}, &risk.Risk{}, decimal.NewFromInt(1)) if err != nil { t.Error(err) } if !p.riskFreeRate.Equal(decimal.NewFromInt(1)) { t.Error("expected 1") } } func TestSetupCurrencySettingsMap(t *testing.T) { t.Parallel() p := &Portfolio{} _, err := p.SetupCurrencySettingsMap(nil) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{}) if !errors.Is(err, errExchangeUnset) { t.Errorf("received: %v, expected: %v", err, errExchangeUnset) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi"}) if !errors.Is(err, errAssetUnset) { t.Errorf("received: %v, expected: %v", err, errAssetUnset) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi", Asset: asset.Spot}) if !errors.Is(err, errCurrencyPairUnset) { t.Errorf("received: %v, expected: %v", err, errCurrencyPairUnset) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi", Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } } func TestSetHoldings(t *testing.T) { t.Parallel() p := &Portfolio{} err := p.setHoldingsForOffset(&holdings.Holding{}, false) if !errors.Is(err, errHoldingsNoTimestamp) { t.Errorf("received: %v, expected: %v", err, errHoldingsNoTimestamp) } tt := time.Now() err = p.setHoldingsForOffset(&holdings.Holding{Timestamp: tt}, false) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } err = p.setHoldingsForOffset(&holdings.Holding{ Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, false) if err != nil { t.Error(err) } err = p.setHoldingsForOffset(&holdings.Holding{ Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, true) if err != nil { t.Error(err) } } func TestGetLatestHoldingsForAllCurrencies(t *testing.T) { t.Parallel() p := &Portfolio{} h := p.GetLatestHoldingsForAllCurrencies() if len(h) != 0 { t.Error("expected 0") } tt := time.Now() err := p.setHoldingsForOffset(&holdings.Holding{ Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, true) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } h = p.GetLatestHoldingsForAllCurrencies() if len(h) != 0 { t.Errorf("received %v, expected %v", len(h), 0) } err = p.setHoldingsForOffset(&holdings.Holding{ Offset: 1, Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, false) if err != nil { t.Error(err) } h = p.GetLatestHoldingsForAllCurrencies() if len(h) != 1 { t.Errorf("received %v, expected %v", len(h), 1) } err = p.setHoldingsForOffset(&holdings.Holding{ Offset: 1, Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, false) if !errors.Is(err, errHoldingsAlreadySet) { t.Errorf("received: %v, expected: %v", err, errHoldingsAlreadySet) } err = p.setHoldingsForOffset(&holdings.Holding{ Offset: 1, Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, true) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } h = p.GetLatestHoldingsForAllCurrencies() if len(h) != 1 { t.Errorf("received %v, expected %v", len(h), 1) } } func TestViewHoldingAtTimePeriod(t *testing.T) { t.Parallel() p := Portfolio{} tt := time.Now() s := &signal.Signal{ Base: event.Base{ Time: tt, Exchange: testExchange, AssetType: asset.Spot, CurrencyPair: currency.NewPair(currency.BTC, currency.USD), }, } _, err := p.ViewHoldingAtTimePeriod(s) if !errors.Is(err, errNoHoldings) { t.Errorf("received: %v, expected: %v", err, errNoHoldings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } err = p.setHoldingsForOffset(&holdings.Holding{ Offset: 1, Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, false) if err != nil { t.Error(err) } err = p.setHoldingsForOffset(&holdings.Holding{ Offset: 2, Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt.Add(time.Hour)}, false) if err != nil { t.Error(err) } var h *holdings.Holding h, err = p.ViewHoldingAtTimePeriod(s) if err != nil { t.Fatal(err) } if !h.Timestamp.Equal(tt) { t.Errorf("expected %v received %v", tt, h.Timestamp) } } func TestUpdate(t *testing.T) { t.Parallel() p := Portfolio{} err := p.UpdateHoldings(nil, nil) if !errors.Is(err, common.ErrNilEvent) { t.Errorf("received: %v, expected: %v", err, common.ErrNilEvent) } err = p.UpdateHoldings(&kline.Kline{}, nil) if !errors.Is(err, funding.ErrFundsNotFound) { t.Errorf("received '%v' expected '%v'", err, funding.ErrFundsNotFound) } b, err := funding.CreateItem(testExchange, asset.Spot, currency.BTC, decimal.NewFromInt(1), decimal.Zero) if err != nil { t.Fatal(err) } q, err := funding.CreateItem(testExchange, asset.Spot, currency.USDT, decimal.NewFromInt(100), decimal.Zero) if err != nil { t.Fatal(err) } pair, err := funding.CreatePair(b, q) if err != nil { t.Fatal(err) } err = p.UpdateHoldings(&kline.Kline{}, pair) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received '%v' expected '%v'", err, errNoPortfolioSettings) } tt := time.Now() err = p.setHoldingsForOffset(&holdings.Holding{ Offset: 1, Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: tt}, false) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } err = p.UpdateHoldings(&kline.Kline{ Base: event.Base{ Time: tt, Exchange: testExchange, CurrencyPair: currency.NewPair(currency.BTC, currency.USD), AssetType: asset.Spot, }, }, pair) if err != nil { t.Error(err) } } func TestGetFee(t *testing.T) { t.Parallel() p := Portfolio{} f := p.GetFee("", "", currency.Pair{}) if !f.IsZero() { t.Error("expected 0") } _, err := p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi", Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } p.SetFee("hi", asset.Spot, currency.NewPair(currency.BTC, currency.USD), decimal.NewFromInt(1337)) f = p.GetFee("hi", asset.Spot, currency.NewPair(currency.BTC, currency.USD)) if !f.Equal(decimal.NewFromInt(1337)) { t.Errorf("expected %v received %v", 1337, f) } } func TestGetComplianceManager(t *testing.T) { t.Parallel() p := Portfolio{} _, err := p.GetComplianceManager("", "", currency.Pair{}) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi", Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } var cm *compliance.Manager cm, err = p.GetComplianceManager("hi", asset.Spot, currency.NewPair(currency.BTC, currency.USD)) if err != nil { t.Error(err) } if cm == nil { t.Error("expected not nil") } } func TestAddComplianceSnapshot(t *testing.T) { t.Parallel() p := Portfolio{} err := p.addComplianceSnapshot(nil) if !errors.Is(err, common.ErrNilEvent) { t.Errorf("received: %v, expected: %v", err, common.ErrNilEvent) } err = p.addComplianceSnapshot(&fill.Fill{}) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi", Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } err = p.addComplianceSnapshot(&fill.Fill{ Base: event.Base{ Exchange: "hi", CurrencyPair: currency.NewPair(currency.BTC, currency.USD), AssetType: asset.Spot, }, Order: &gctorder.Detail{ Exchange: "hi", Pair: currency.NewPair(currency.BTC, currency.USD), AssetType: asset.Spot, }, }) if err != nil { t.Error(err) } } func TestOnFill(t *testing.T) { t.Parallel() p := Portfolio{} _, err := p.OnFill(nil, nil) if !errors.Is(err, common.ErrNilEvent) { t.Errorf("received: %v, expected: %v", err, common.ErrNilEvent) } f := &fill.Fill{ Base: event.Base{ Exchange: "hi", CurrencyPair: currency.NewPair(currency.BTC, currency.USD), AssetType: asset.Spot, }, Order: &gctorder.Detail{ Exchange: "hi", Pair: currency.NewPair(currency.BTC, currency.USD), AssetType: asset.Spot, }, } _, err = p.OnFill(f, nil) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi", Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } b, err := funding.CreateItem(testExchange, asset.Spot, currency.BTC, decimal.NewFromInt(1), decimal.Zero) if err != nil { t.Fatal(err) } q, err := funding.CreateItem(testExchange, asset.Spot, currency.USDT, decimal.NewFromInt(100), decimal.Zero) if err != nil { t.Fatal(err) } pair, err := funding.CreatePair(b, q) if err != nil { t.Fatal(err) } _, err = p.OnFill(f, pair) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } f.Direction = gctorder.Buy _, err = p.OnFill(f, pair) if err != nil { t.Error(err) } } func TestOnSignal(t *testing.T) { t.Parallel() p := Portfolio{} _, err := p.OnSignal(nil, nil, nil) if !errors.Is(err, common.ErrNilArguments) { t.Error(err) } s := &signal.Signal{} _, err = p.OnSignal(s, &exchange.Settings{}, nil) if !errors.Is(err, errSizeManagerUnset) { t.Errorf("received: %v, expected: %v", err, errSizeManagerUnset) } p.sizeManager = &size.Size{} _, err = p.OnSignal(s, &exchange.Settings{}, nil) if !errors.Is(err, errRiskManagerUnset) { t.Errorf("received: %v, expected: %v", err, errRiskManagerUnset) } p.riskManager = &risk.Risk{} _, err = p.OnSignal(s, &exchange.Settings{}, nil) if !errors.Is(err, funding.ErrFundsNotFound) { t.Errorf("received: %v, expected: %v", err, funding.ErrFundsNotFound) } b, err := funding.CreateItem(testExchange, asset.Spot, currency.BTC, decimal.NewFromInt(1337), decimal.Zero) if err != nil { t.Fatal(err) } q, err := funding.CreateItem(testExchange, asset.Spot, currency.USDT, decimal.NewFromInt(1337), decimal.Zero) if err != nil { t.Fatal(err) } pair, err := funding.CreatePair(b, q) if err != nil { t.Fatal(err) } _, err = p.OnSignal(s, &exchange.Settings{}, pair) if !errors.Is(err, errInvalidDirection) { t.Errorf("received: %v, expected: %v", err, errInvalidDirection) } s.Direction = gctorder.Buy _, err = p.OnSignal(s, &exchange.Settings{}, pair) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "hi", Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } s = &signal.Signal{ Base: event.Base{ Exchange: "hi", CurrencyPair: currency.NewPair(currency.BTC, currency.USD), AssetType: asset.Spot, }, Direction: gctorder.Buy, } var resp *order.Order resp, err = p.OnSignal(s, &exchange.Settings{}, pair) if err != nil { t.Fatal(err) } if resp.Reason == "" { t.Error("expected issue") } s.Direction = gctorder.Sell _, err = p.OnSignal(s, &exchange.Settings{}, pair) if err != nil { t.Error(err) } if resp.Reason == "" { t.Error("expected issue") } s.Direction = common.MissingData _, err = p.OnSignal(s, &exchange.Settings{}, pair) if err != nil { t.Error(err) } s.Direction = gctorder.Buy err = p.setHoldingsForOffset(&holdings.Holding{ Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD), Timestamp: time.Now(), QuoteSize: decimal.NewFromInt(1337)}, false) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } _, err = p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: testExchange, Asset: asset.Spot, Pair: currency.NewPair(currency.BTC, currency.USD)}) if err != nil { t.Error(err) } resp, err = p.OnSignal(s, &exchange.Settings{}, pair) if err != nil { t.Error(err) } if resp.Direction != common.CouldNotBuy { t.Errorf("expected common.CouldNotBuy, received %v", resp.Direction) } s.ClosePrice = decimal.NewFromInt(10) s.Direction = gctorder.Buy resp, err = p.OnSignal(s, &exchange.Settings{}, pair) if err != nil { t.Error(err) } if resp.Amount.IsZero() { t.Error("expected an amount to be sized") } } func TestGetLatestHoldings(t *testing.T) { t.Parallel() cs := Settings{} h := cs.GetLatestHoldings() if !h.Timestamp.IsZero() { t.Error("expected unset holdings") } tt := time.Now() cs.HoldingsSnapshots = append(cs.HoldingsSnapshots, holdings.Holding{Timestamp: tt}) h = cs.GetLatestHoldings() if !h.Timestamp.Equal(tt) { t.Errorf("expected %v, received %v", tt, h.Timestamp) } } func TestGetSnapshotAtTime(t *testing.T) { t.Parallel() p := Portfolio{} _, err := p.GetLatestOrderSnapshotForEvent(&kline.Kline{}) if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } cp := currency.NewPair(currency.XRP, currency.DOGE) s, err := p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "exch", Asset: asset.Spot, Pair: currency.NewPair(currency.XRP, currency.DOGE)}) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } tt := time.Now() err = s.ComplianceManager.AddSnapshot([]compliance.SnapshotOrder{ { Detail: &gctorder.Detail{ Exchange: "exch", AssetType: asset.Spot, Pair: cp, Amount: 1337, }, }, }, tt, 0, false) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } e := &kline.Kline{ Base: event.Base{ Exchange: "exch", Time: tt, Interval: gctkline.OneDay, CurrencyPair: cp, AssetType: asset.Spot, }, } ss, err := p.GetLatestOrderSnapshotForEvent(e) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } if len(ss.Orders) != 1 { t.Fatal("expected 1") } if ss.Orders[0].Amount != 1337 { t.Error("expected 1") } } func TestGetLatestSnapshot(t *testing.T) { t.Parallel() p := Portfolio{} _, err := p.GetLatestOrderSnapshots() if !errors.Is(err, errNoPortfolioSettings) { t.Errorf("received: %v, expected: %v", err, errNoPortfolioSettings) } cp := currency.NewPair(currency.XRP, currency.DOGE) s, err := p.SetupCurrencySettingsMap(&exchange.Settings{Exchange: "exch", Asset: asset.Spot, Pair: currency.NewPair(currency.XRP, currency.DOGE)}) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } tt := time.Now() err = s.ComplianceManager.AddSnapshot([]compliance.SnapshotOrder{ { Detail: &gctorder.Detail{ Exchange: "exch", AssetType: asset.Spot, Pair: cp, Amount: 1337, }, }, }, tt, 0, false) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } ss, err := p.GetLatestOrderSnapshots() if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } err = s.ComplianceManager.AddSnapshot([]compliance.SnapshotOrder{ ss[0].Orders[0], { Detail: &gctorder.Detail{ Exchange: "exch", AssetType: asset.Spot, Pair: cp, Amount: 1338, }, }, }, tt, 1, false) if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } ss, err = p.GetLatestOrderSnapshots() if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } if len(ss) != 1 { t.Fatal("expected 1") } if len(ss[0].Orders) != 2 { t.Error("expected 2") } } <file_sep>package orderbook import ( "sync" "time" "github.com/idoall/gocryptotrader/exchanges/alert" ) // Unsafe is an exported linked list reference to the current bid/ask heads and // a reference to the underlying depth mutex. This allows for the exposure of // the internal list to an external strategy or subsystem. The bid and ask // fields point to the actual head fields contained on both linked list structs, // so that this struct can be reusable and not needed to be called on each // inspection. type Unsafe struct { BidHead **Node AskHead **Node m *sync.Mutex // UpdatedViaREST defines if sync manager is updating this book via the REST // protocol then this book is not considered live and cannot be trusted. UpdatedViaREST *bool LastUpdated *time.Time *alert.Notice } // Lock locks down the underlying linked list which inhibits all pending updates // for strategy inspection. func (src *Unsafe) Lock() { src.m.Lock() } // Unlock unlocks the underlying linked list after inspection by a strategy to // resume normal operations func (src *Unsafe) Unlock() { src.m.Unlock() } // LockWith locks both books for the context of cross orderbook inspection. // WARNING: When inspecting diametrically opposed books a higher order mutex // MUST be used or a dead lock will occur. func (src *Unsafe) LockWith(dst sync.Locker) { src.m.Lock() dst.Lock() } // UnlockWith unlocks both books for the context of cross orderbook inspection func (src *Unsafe) UnlockWith(dst sync.Locker) { dst.Unlock() // Unlock in reverse order src.m.Unlock() } // GetUnsafe returns an unsafe orderbook with pointers to the linked list heads. func (d *Depth) GetUnsafe() Unsafe { return Unsafe{ BidHead: &d.bids.linkedList.head, AskHead: &d.asks.linkedList.head, m: &d.m, Notice: &d.Notice, UpdatedViaREST: &d.options.restSnapshot, LastUpdated: &d.options.lastUpdated, } } <file_sep>module github.com/idoall/gocryptotrader go 1.17 require ( github.com/d5/tengo/v2 v2.10.0 github.com/gofrs/uuid v4.2.0+incompatible github.com/google/go-querystring v1.1.0 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.2 github.com/kat-co/vala v0.0.0-20170210184112-42e1d8b61f12 github.com/lib/pq v1.10.4 github.com/mattn/go-sqlite3 v1.14.10 github.com/pkg/errors v0.9.1 github.com/pquerna/otp v1.3.0 github.com/shopspring/decimal v1.3.1 github.com/spf13/viper v1.10.1 github.com/thrasher-corp/gct-ta v0.0.0-20200623072738-f2b55b7f9f41 github.com/thrasher-corp/goose v2.7.0-rc4.0.20191002032028-0f2c2a27abdb+incompatible github.com/thrasher-corp/sqlboiler v1.0.1-0.20191001234224-71e17f37a85e github.com/urfave/cli/v2 v2.3.0 github.com/volatiletech/null v8.0.0+incompatible golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d golang.org/x/time v0.0.0-20191024005414-555d28b269f0 google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa google.golang.org/grpc v1.43.0 google.golang.org/protobuf v1.27.1 ) require ( github.com/golang/protobuf v1.5.2 github.com/toorop/go-pusher v0.0.0-20180521062818-4521e2eb39fb ) require ( github.com/BurntSushi/toml v0.3.1 // indirect github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect github.com/friendsofgo/errors v0.9.2 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/golang/glog v1.0.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/idoall/TokenExchangeCommon v0.0.0-20210826162402-3cd32beb497d // indirect github.com/idoall/logger v0.0.0-20200226150847-c2e7d71fdeb4 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kr/text v0.2.0 // indirect github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible // indirect github.com/lestrrat-go/strftime v1.0.1 // indirect github.com/magiconair/properties v1.8.5 // indirect github.com/mitchellh/mapstructure v1.4.3 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect github.com/pelletier/go-toml v1.9.4 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect github.com/russross/blackfriday/v2 v2.0.1 // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/spf13/afero v1.6.0 // indirect github.com/spf13/cast v1.4.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.2.0 // indirect github.com/volatiletech/inflect v0.0.1 // indirect github.com/volatiletech/sqlboiler v3.7.1+incompatible // indirect go.uber.org/atomic v1.5.0 // indirect go.uber.org/multierr v1.3.0 // indirect go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee // indirect go.uber.org/zap v1.14.0 // indirect golang.org/x/lint v0.0.0-20190930215403-16217165b5de // indirect golang.org/x/mod v0.3.0 // indirect golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.0.0-20210106214847-113979e3529a // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0 // indirect gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect gopkg.in/ini.v1 v1.66.2 // indirect gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect honnef.co/go/tools v0.0.1-2019.2.3 // indirect sigs.k8s.io/yaml v1.3.0 // indirect ) <file_sep>package backtest import ( "context" "errors" "fmt" "path/filepath" "runtime" "strings" "sync" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/config" "github.com/idoall/gocryptotrader/backtester/data" "github.com/idoall/gocryptotrader/backtester/data/kline" "github.com/idoall/gocryptotrader/backtester/data/kline/api" "github.com/idoall/gocryptotrader/backtester/data/kline/csv" "github.com/idoall/gocryptotrader/backtester/data/kline/database" "github.com/idoall/gocryptotrader/backtester/data/kline/live" "github.com/idoall/gocryptotrader/backtester/eventhandlers/eventholder" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange/slippage" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/compliance" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/holdings" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/risk" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/size" "github.com/idoall/gocryptotrader/backtester/eventhandlers/statistics" "github.com/idoall/gocryptotrader/backtester/eventhandlers/strategies" "github.com/idoall/gocryptotrader/backtester/eventhandlers/strategies/base" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" "github.com/idoall/gocryptotrader/backtester/eventtypes/signal" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/backtester/funding/trackingcurrencies" "github.com/idoall/gocryptotrader/backtester/report" gctcommon "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/convert" "github.com/idoall/gocryptotrader/currency" gctdatabase "github.com/idoall/gocryptotrader/database" "github.com/idoall/gocryptotrader/engine" gctexchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/log" "github.com/shopspring/decimal" ) // New returns a new BackTest instance func New() *BackTest { return &BackTest{ shutdown: make(chan struct{}), Datas: &data.HandlerPerCurrency{}, EventQueue: &eventholder.Holder{}, } } // Reset BackTest values to default func (bt *BackTest) Reset() { bt.EventQueue.Reset() bt.Datas.Reset() bt.Portfolio.Reset() bt.Statistic.Reset() bt.Exchange.Reset() bt.Funding.Reset() bt.exchangeManager = nil bt.orderManager = nil bt.databaseManager = nil } // NewFromConfig takes a strategy config and configures a backtester variable to run func NewFromConfig(cfg *config.Config, templatePath, output string) (*BackTest, error) { log.Infoln(log.BackTester, "loading config...") if cfg == nil { return nil, errNilConfig } var err error bt := New() bt.exchangeManager = engine.SetupExchangeManager() bt.orderManager, err = engine.SetupOrderManager(bt.exchangeManager, &engine.CommunicationManager{}, &sync.WaitGroup{}, false) if err != nil { return nil, err } err = bt.orderManager.Start() if err != nil { return nil, err } if cfg.DataSettings.DatabaseData != nil { bt.databaseManager, err = engine.SetupDatabaseConnectionManager(&cfg.DataSettings.DatabaseData.Config) if err != nil { return nil, err } } reports := &report.Data{ Config: cfg, TemplatePath: templatePath, OutputPath: output, } bt.Reports = reports buyRule := exchange.MinMax{ MinimumSize: cfg.PortfolioSettings.BuySide.MinimumSize, MaximumSize: cfg.PortfolioSettings.BuySide.MaximumSize, MaximumTotal: cfg.PortfolioSettings.BuySide.MaximumTotal, } sellRule := exchange.MinMax{ MinimumSize: cfg.PortfolioSettings.SellSide.MinimumSize, MaximumSize: cfg.PortfolioSettings.SellSide.MaximumSize, MaximumTotal: cfg.PortfolioSettings.SellSide.MaximumTotal, } sizeManager := &size.Size{ BuySide: buyRule, SellSide: sellRule, } funds := funding.SetupFundingManager( cfg.StrategySettings.UseExchangeLevelFunding, cfg.StrategySettings.DisableUSDTracking, ) if cfg.StrategySettings.UseExchangeLevelFunding { for i := range cfg.StrategySettings.ExchangeLevelFunding { var a asset.Item a, err = asset.New(cfg.StrategySettings.ExchangeLevelFunding[i].Asset) if err != nil { return nil, err } cq := currency.NewCode(cfg.StrategySettings.ExchangeLevelFunding[i].Currency) var item *funding.Item item, err = funding.CreateItem(cfg.StrategySettings.ExchangeLevelFunding[i].ExchangeName, a, cq, cfg.StrategySettings.ExchangeLevelFunding[i].InitialFunds, cfg.StrategySettings.ExchangeLevelFunding[i].TransferFee) if err != nil { return nil, err } err = funds.AddItem(item) if err != nil { return nil, err } } } var emm = make(map[string]gctexchange.IBotExchange) for i := range cfg.CurrencySettings { _, ok := emm[cfg.CurrencySettings[i].ExchangeName] if ok { continue } var exch gctexchange.IBotExchange exch, err = bt.exchangeManager.NewExchangeByName(cfg.CurrencySettings[i].ExchangeName) if err != nil { return nil, err } _, err = exch.GetDefaultConfig() if err != nil { return nil, err } exchBase := exch.GetBase() err = exch.UpdateTradablePairs(context.Background(), true) if err != nil { return nil, err } assets := exchBase.CurrencyPairs.GetAssetTypes(false) for i := range assets { exchBase.CurrencyPairs.Pairs[assets[i]].AssetEnabled = convert.BoolPtr(true) err = exch.SetPairs(exchBase.CurrencyPairs.Pairs[assets[i]].Available, assets[i], true) if err != nil { return nil, err } } bt.exchangeManager.Add(exch) emm[cfg.CurrencySettings[i].ExchangeName] = exch } portfolioRisk := &risk.Risk{ CurrencySettings: make(map[string]map[asset.Item]map[currency.Pair]*risk.CurrencySettings), } for i := range cfg.CurrencySettings { if portfolioRisk.CurrencySettings[cfg.CurrencySettings[i].ExchangeName] == nil { portfolioRisk.CurrencySettings[cfg.CurrencySettings[i].ExchangeName] = make(map[asset.Item]map[currency.Pair]*risk.CurrencySettings) } var a asset.Item a, err = asset.New(cfg.CurrencySettings[i].Asset) if err != nil { return nil, fmt.Errorf( "%w for %v %v %v. Err %v", errInvalidConfigAsset, cfg.CurrencySettings[i].ExchangeName, cfg.CurrencySettings[i].Asset, cfg.CurrencySettings[i].Base+cfg.CurrencySettings[i].Quote, err) } if portfolioRisk.CurrencySettings[cfg.CurrencySettings[i].ExchangeName][a] == nil { portfolioRisk.CurrencySettings[cfg.CurrencySettings[i].ExchangeName][a] = make(map[currency.Pair]*risk.CurrencySettings) } var curr currency.Pair var b, q currency.Code b = currency.NewCode(cfg.CurrencySettings[i].Base) q = currency.NewCode(cfg.CurrencySettings[i].Quote) curr = currency.NewPair(b, q) var exch gctexchange.IBotExchange exch, err = bt.exchangeManager.GetExchangeByName(cfg.CurrencySettings[i].ExchangeName) if err != nil { return nil, err } exchBase := exch.GetBase() var requestFormat currency.PairFormat requestFormat, err = exchBase.GetPairFormat(a, true) if err != nil { return nil, fmt.Errorf("could not format currency %v, %w", curr, err) } curr = curr.Format(requestFormat.Delimiter, requestFormat.Uppercase) err = exchBase.CurrencyPairs.EnablePair(a, curr) if err != nil && !errors.Is(err, currency.ErrPairAlreadyEnabled) { return nil, fmt.Errorf( "could not enable currency %v %v %v. Err %w", cfg.CurrencySettings[i].ExchangeName, cfg.CurrencySettings[i].Asset, cfg.CurrencySettings[i].Base+cfg.CurrencySettings[i].Quote, err) } portfolioRisk.CurrencySettings[cfg.CurrencySettings[i].ExchangeName][a][curr] = &risk.CurrencySettings{ MaximumOrdersWithLeverageRatio: cfg.CurrencySettings[i].Leverage.MaximumOrdersWithLeverageRatio, MaxLeverageRate: cfg.CurrencySettings[i].Leverage.MaximumLeverageRate, MaximumHoldingRatio: cfg.CurrencySettings[i].MaximumHoldingsRatio, } if cfg.CurrencySettings[i].MakerFee.GreaterThan(cfg.CurrencySettings[i].TakerFee) { log.Warnf(log.BackTester, "maker fee '%v' should not exceed taker fee '%v'. Please review config", cfg.CurrencySettings[i].MakerFee, cfg.CurrencySettings[i].TakerFee) } var baseItem, quoteItem *funding.Item if cfg.StrategySettings.UseExchangeLevelFunding { // add any remaining currency items that have no funding data in the strategy config baseItem, err = funding.CreateItem(cfg.CurrencySettings[i].ExchangeName, a, b, decimal.Zero, decimal.Zero) if err != nil { return nil, err } quoteItem, err = funding.CreateItem(cfg.CurrencySettings[i].ExchangeName, a, q, decimal.Zero, decimal.Zero) if err != nil { return nil, err } err = funds.AddItem(baseItem) if err != nil && !errors.Is(err, funding.ErrAlreadyExists) { return nil, err } err = funds.AddItem(quoteItem) if err != nil && !errors.Is(err, funding.ErrAlreadyExists) { return nil, err } } else { var bFunds, qFunds decimal.Decimal if cfg.CurrencySettings[i].InitialBaseFunds != nil { bFunds = *cfg.CurrencySettings[i].InitialBaseFunds } if cfg.CurrencySettings[i].InitialQuoteFunds != nil { qFunds = *cfg.CurrencySettings[i].InitialQuoteFunds } baseItem, err = funding.CreateItem( cfg.CurrencySettings[i].ExchangeName, a, curr.Base, bFunds, decimal.Zero) if err != nil { return nil, err } quoteItem, err = funding.CreateItem( cfg.CurrencySettings[i].ExchangeName, a, curr.Quote, qFunds, decimal.Zero) if err != nil { return nil, err } var pair *funding.Pair pair, err = funding.CreatePair(baseItem, quoteItem) if err != nil { return nil, err } err = funds.AddPair(pair) if err != nil { return nil, err } } } bt.Funding = funds var p *portfolio.Portfolio p, err = portfolio.Setup(sizeManager, portfolioRisk, cfg.StatisticSettings.RiskFreeRate) if err != nil { return nil, err } bt.Strategy, err = strategies.LoadStrategyByName(cfg.StrategySettings.Name, cfg.StrategySettings.SimultaneousSignalProcessing) if err != nil { return nil, err } bt.Strategy.SetDefaults() if cfg.StrategySettings.CustomSettings != nil { err = bt.Strategy.SetCustomSettings(cfg.StrategySettings.CustomSettings) if err != nil && !errors.Is(err, base.ErrCustomSettingsUnsupported) { return nil, err } } stats := &statistics.Statistic{ StrategyName: bt.Strategy.Name(), StrategyNickname: cfg.Nickname, StrategyDescription: bt.Strategy.Description(), StrategyGoal: cfg.Goal, ExchangeAssetPairStatistics: make(map[string]map[asset.Item]map[currency.Pair]*statistics.CurrencyPairStatistic), RiskFreeRate: cfg.StatisticSettings.RiskFreeRate, CandleInterval: gctkline.Interval(cfg.DataSettings.Interval), FundManager: bt.Funding, } bt.Statistic = stats reports.Statistics = stats if !cfg.StrategySettings.DisableUSDTracking { var trackingPairs []trackingcurrencies.TrackingPair for i := range cfg.CurrencySettings { trackingPairs = append(trackingPairs, trackingcurrencies.TrackingPair{ Exchange: cfg.CurrencySettings[i].ExchangeName, Asset: cfg.CurrencySettings[i].Asset, Base: cfg.CurrencySettings[i].Base, Quote: cfg.CurrencySettings[i].Quote, }) } trackingPairs, err = trackingcurrencies.CreateUSDTrackingPairs(trackingPairs, bt.exchangeManager) if err != nil { return nil, err } trackingPairCheck: for i := range trackingPairs { for j := range cfg.CurrencySettings { if cfg.CurrencySettings[j].ExchangeName == trackingPairs[i].Exchange && cfg.CurrencySettings[j].Asset == trackingPairs[i].Asset && cfg.CurrencySettings[j].Base == trackingPairs[i].Base && cfg.CurrencySettings[j].Quote == trackingPairs[i].Quote { continue trackingPairCheck } } cfg.CurrencySettings = append(cfg.CurrencySettings, config.CurrencySettings{ ExchangeName: trackingPairs[i].Exchange, Asset: trackingPairs[i].Asset, Base: trackingPairs[i].Base, Quote: trackingPairs[i].Quote, USDTrackingPair: true, }) } } e, err := bt.setupExchangeSettings(cfg) if err != nil { return nil, err } bt.Exchange = &e for i := range e.CurrencySettings { var lookup *portfolio.Settings lookup, err = p.SetupCurrencySettingsMap(&e.CurrencySettings[i]) if err != nil { return nil, err } lookup.Fee = e.CurrencySettings[i].TakerFee lookup.Leverage = e.CurrencySettings[i].Leverage lookup.BuySideSizing = e.CurrencySettings[i].BuySide lookup.SellSideSizing = e.CurrencySettings[i].SellSide lookup.ComplianceManager = compliance.Manager{ Snapshots: []compliance.Snapshot{}, } } bt.Portfolio = p cfg.PrintSetting() return bt, nil } func (bt *BackTest) setupExchangeSettings(cfg *config.Config) (exchange.Exchange, error) { log.Infoln(log.BackTester, "setting exchange settings...") resp := exchange.Exchange{} for i := range cfg.CurrencySettings { exch, pair, a, err := bt.loadExchangePairAssetBase( cfg.CurrencySettings[i].ExchangeName, cfg.CurrencySettings[i].Base, cfg.CurrencySettings[i].Quote, cfg.CurrencySettings[i].Asset) if err != nil { return resp, err } exchangeName := strings.ToLower(exch.GetName()) bt.Datas.Setup() klineData, err := bt.loadData(cfg, exch, pair, a, cfg.CurrencySettings[i].USDTrackingPair) if err != nil { return resp, err } err = bt.Funding.AddUSDTrackingData(klineData) if err != nil && !errors.Is(err, trackingcurrencies.ErrCurrencyDoesNotContainsUSD) && !errors.Is(err, funding.ErrUSDTrackingDisabled) { return resp, err } if !cfg.CurrencySettings[i].USDTrackingPair { bt.Datas.SetDataForCurrency(exchangeName, a, pair, klineData) var makerFee, takerFee decimal.Decimal if cfg.CurrencySettings[i].MakerFee.GreaterThan(decimal.Zero) { makerFee = cfg.CurrencySettings[i].MakerFee } if cfg.CurrencySettings[i].TakerFee.GreaterThan(decimal.Zero) { takerFee = cfg.CurrencySettings[i].TakerFee } if makerFee.IsZero() || takerFee.IsZero() { var apiMakerFee, apiTakerFee decimal.Decimal apiMakerFee, apiTakerFee = getFees(context.TODO(), exch, pair) if makerFee.IsZero() { makerFee = apiMakerFee } if takerFee.IsZero() { takerFee = apiTakerFee } } if cfg.CurrencySettings[i].MaximumSlippagePercent.LessThan(decimal.Zero) { log.Warnf(log.BackTester, "invalid maximum slippage percent '%v'. Slippage percent is defined as a number, eg '100.00', defaulting to '%v'", cfg.CurrencySettings[i].MaximumSlippagePercent, slippage.DefaultMaximumSlippagePercent) cfg.CurrencySettings[i].MaximumSlippagePercent = slippage.DefaultMaximumSlippagePercent } if cfg.CurrencySettings[i].MaximumSlippagePercent.IsZero() { cfg.CurrencySettings[i].MaximumSlippagePercent = slippage.DefaultMaximumSlippagePercent } if cfg.CurrencySettings[i].MinimumSlippagePercent.LessThan(decimal.Zero) { log.Warnf(log.BackTester, "invalid minimum slippage percent '%v'. Slippage percent is defined as a number, eg '80.00', defaulting to '%v'", cfg.CurrencySettings[i].MinimumSlippagePercent, slippage.DefaultMinimumSlippagePercent) cfg.CurrencySettings[i].MinimumSlippagePercent = slippage.DefaultMinimumSlippagePercent } if cfg.CurrencySettings[i].MinimumSlippagePercent.IsZero() { cfg.CurrencySettings[i].MinimumSlippagePercent = slippage.DefaultMinimumSlippagePercent } if cfg.CurrencySettings[i].MaximumSlippagePercent.LessThan(cfg.CurrencySettings[i].MinimumSlippagePercent) { cfg.CurrencySettings[i].MaximumSlippagePercent = slippage.DefaultMaximumSlippagePercent } realOrders := false if cfg.DataSettings.LiveData != nil { realOrders = cfg.DataSettings.LiveData.RealOrders } buyRule := exchange.MinMax{ MinimumSize: cfg.CurrencySettings[i].BuySide.MinimumSize, MaximumSize: cfg.CurrencySettings[i].BuySide.MaximumSize, MaximumTotal: cfg.CurrencySettings[i].BuySide.MaximumTotal, } sellRule := exchange.MinMax{ MinimumSize: cfg.CurrencySettings[i].SellSide.MinimumSize, MaximumSize: cfg.CurrencySettings[i].SellSide.MaximumSize, MaximumTotal: cfg.CurrencySettings[i].SellSide.MaximumTotal, } limits, err := exch.GetOrderExecutionLimits(a, pair) if err != nil && !errors.Is(err, gctorder.ErrExchangeLimitNotLoaded) { return resp, err } if limits != nil { if !cfg.CurrencySettings[i].CanUseExchangeLimits { log.Warnf(log.BackTester, "exchange %s order execution limits supported but disabled for %s %s, live results may differ", cfg.CurrencySettings[i].ExchangeName, pair, a) cfg.CurrencySettings[i].ShowExchangeOrderLimitWarning = true } } resp.CurrencySettings = append(resp.CurrencySettings, exchange.Settings{ Exchange: cfg.CurrencySettings[i].ExchangeName, MinimumSlippageRate: cfg.CurrencySettings[i].MinimumSlippagePercent, MaximumSlippageRate: cfg.CurrencySettings[i].MaximumSlippagePercent, Pair: pair, Asset: a, ExchangeFee: takerFee, MakerFee: takerFee, TakerFee: makerFee, UseRealOrders: realOrders, BuySide: buyRule, SellSide: sellRule, Leverage: exchange.Leverage{ CanUseLeverage: cfg.CurrencySettings[i].Leverage.CanUseLeverage, MaximumLeverageRate: cfg.CurrencySettings[i].Leverage.MaximumLeverageRate, MaximumOrdersWithLeverageRatio: cfg.CurrencySettings[i].Leverage.MaximumOrdersWithLeverageRatio, }, Limits: limits, SkipCandleVolumeFitting: cfg.CurrencySettings[i].SkipCandleVolumeFitting, CanUseExchangeLimits: cfg.CurrencySettings[i].CanUseExchangeLimits, }) } } return resp, nil } func (bt *BackTest) loadExchangePairAssetBase(exch, base, quote, ass string) (gctexchange.IBotExchange, currency.Pair, asset.Item, error) { e, err := bt.exchangeManager.GetExchangeByName(exch) if err != nil { return nil, currency.Pair{}, "", err } var cp, fPair currency.Pair cp, err = currency.NewPairFromStrings(base, quote) if err != nil { return nil, currency.Pair{}, "", err } var a asset.Item a, err = asset.New(ass) if err != nil { return nil, currency.Pair{}, "", err } exchangeBase := e.GetBase() if !exchangeBase.ValidateAPICredentials() { log.Warnf(log.BackTester, "no credentials set for %v, this is theoretical only", exchangeBase.Name) } fPair, err = exchangeBase.FormatExchangeCurrency(cp, a) if err != nil { return nil, currency.Pair{}, "", err } return e, fPair, a, nil } // getFees will return an exchange's fee rate from GCT's wrapper function func getFees(ctx context.Context, exch gctexchange.IBotExchange, fPair currency.Pair) (makerFee, takerFee decimal.Decimal) { fTakerFee, err := exch.GetFeeByType(ctx, &gctexchange.FeeBuilder{FeeType: gctexchange.OfflineTradeFee, Pair: fPair, IsMaker: false, PurchasePrice: 1, Amount: 1, }) if err != nil { log.Errorf(log.BackTester, "Could not retrieve taker fee for %v. %v", exch.GetName(), err) } fMakerFee, err := exch.GetFeeByType(ctx, &gctexchange.FeeBuilder{ FeeType: gctexchange.OfflineTradeFee, Pair: fPair, IsMaker: true, PurchasePrice: 1, Amount: 1, }) if err != nil { log.Errorf(log.BackTester, "Could not retrieve maker fee for %v. %v", exch.GetName(), err) } return decimal.NewFromFloat(fMakerFee), decimal.NewFromFloat(fTakerFee) } // loadData will create kline data from the sources defined in start config files. It can exist from databases, csv or API endpoints // it can also be generated from trade data which will be converted into kline data func (bt *BackTest) loadData(cfg *config.Config, exch gctexchange.IBotExchange, fPair currency.Pair, a asset.Item, isUSDTrackingPair bool) (*kline.DataFromKline, error) { if exch == nil { return nil, engine.ErrExchangeNotFound } b := exch.GetBase() if cfg.DataSettings.DatabaseData == nil && cfg.DataSettings.LiveData == nil && cfg.DataSettings.APIData == nil && cfg.DataSettings.CSVData == nil { return nil, errNoDataSource } if (cfg.DataSettings.APIData != nil && cfg.DataSettings.DatabaseData != nil) || (cfg.DataSettings.APIData != nil && cfg.DataSettings.LiveData != nil) || (cfg.DataSettings.APIData != nil && cfg.DataSettings.CSVData != nil) || (cfg.DataSettings.DatabaseData != nil && cfg.DataSettings.LiveData != nil) || (cfg.DataSettings.CSVData != nil && cfg.DataSettings.LiveData != nil) || (cfg.DataSettings.CSVData != nil && cfg.DataSettings.DatabaseData != nil) { return nil, errAmbiguousDataSource } dataType, err := common.DataTypeToInt(cfg.DataSettings.DataType) if err != nil { return nil, err } log.Infof(log.BackTester, "loading data for %v %v %v...\n", exch.GetName(), a, fPair) resp := &kline.DataFromKline{} switch { case cfg.DataSettings.CSVData != nil: if cfg.DataSettings.Interval <= 0 { return nil, errIntervalUnset } resp, err = csv.LoadData( dataType, cfg.DataSettings.CSVData.FullPath, strings.ToLower(exch.GetName()), cfg.DataSettings.Interval, fPair, a, isUSDTrackingPair) if err != nil { return nil, fmt.Errorf("%v. Please check your GoCryptoTrader configuration", err) } resp.Item.RemoveDuplicates() resp.Item.SortCandlesByTimestamp(false) resp.RangeHolder, err = gctkline.CalculateCandleDateRanges( resp.Item.Candles[0].Time, resp.Item.Candles[len(resp.Item.Candles)-1].Time.Add(cfg.DataSettings.Interval), gctkline.Interval(cfg.DataSettings.Interval), 0, ) if err != nil { return nil, err } resp.RangeHolder.SetHasDataFromCandles(resp.Item.Candles) summary := resp.RangeHolder.DataSummary(false) if len(summary) > 0 { log.Warnf(log.BackTester, "%v", summary) } case cfg.DataSettings.DatabaseData != nil: if cfg.DataSettings.DatabaseData.InclusiveEndDate { cfg.DataSettings.DatabaseData.EndDate = cfg.DataSettings.DatabaseData.EndDate.Add(cfg.DataSettings.Interval) } if cfg.DataSettings.DatabaseData.Path == "" { cfg.DataSettings.DatabaseData.Path = filepath.Join(gctcommon.GetDefaultDataDir(runtime.GOOS), "database") } gctdatabase.DB.DataPath = filepath.Join(cfg.DataSettings.DatabaseData.Path) err = gctdatabase.DB.SetConfig(&cfg.DataSettings.DatabaseData.Config) if err != nil { return nil, err } err = bt.databaseManager.Start(&sync.WaitGroup{}) if err != nil { return nil, err } defer func() { stopErr := bt.databaseManager.Stop() if stopErr != nil { log.Error(log.BackTester, stopErr) } }() resp, err = loadDatabaseData(cfg, exch.GetName(), fPair, a, dataType, isUSDTrackingPair) if err != nil { return nil, fmt.Errorf("unable to retrieve data from GoCryptoTrader database. Error: %v. Please ensure the database is setup correctly and has data before use", err) } resp.Item.RemoveDuplicates() resp.Item.SortCandlesByTimestamp(false) resp.RangeHolder, err = gctkline.CalculateCandleDateRanges( cfg.DataSettings.DatabaseData.StartDate, cfg.DataSettings.DatabaseData.EndDate, gctkline.Interval(cfg.DataSettings.Interval), 0, ) if err != nil { return nil, err } resp.RangeHolder.SetHasDataFromCandles(resp.Item.Candles) summary := resp.RangeHolder.DataSummary(false) if len(summary) > 0 { log.Warnf(log.BackTester, "%v", summary) } case cfg.DataSettings.APIData != nil: if cfg.DataSettings.APIData.InclusiveEndDate { cfg.DataSettings.APIData.EndDate = cfg.DataSettings.APIData.EndDate.Add(cfg.DataSettings.Interval) } resp, err = loadAPIData( cfg, exch, fPair, a, b.Features.Enabled.Kline.ResultLimit, dataType) if err != nil { return resp, err } case cfg.DataSettings.LiveData != nil: if isUSDTrackingPair { return nil, errLiveUSDTrackingNotSupported } if len(cfg.CurrencySettings) > 1 { return nil, errors.New("live data simulation only supports one currency") } err = loadLiveData(cfg, b) if err != nil { return nil, err } go bt.loadLiveDataLoop( resp, cfg, exch, fPair, a, dataType) return resp, nil } if resp == nil { return nil, fmt.Errorf("processing error, response returned nil") } err = b.ValidateKline(fPair, a, resp.Item.Interval) if err != nil { if dataType != common.DataTrade || !strings.EqualFold(err.Error(), "interval not supported") { return nil, err } } err = resp.Load() if err != nil { return nil, err } bt.Reports.AddKlineItem(&resp.Item) return resp, nil } func loadDatabaseData(cfg *config.Config, name string, fPair currency.Pair, a asset.Item, dataType int64, isUSDTrackingPair bool) (*kline.DataFromKline, error) { if cfg == nil || cfg.DataSettings.DatabaseData == nil { return nil, errors.New("nil config data received") } if cfg.DataSettings.Interval <= 0 { return nil, errIntervalUnset } return database.LoadData( cfg.DataSettings.DatabaseData.StartDate, cfg.DataSettings.DatabaseData.EndDate, cfg.DataSettings.Interval, strings.ToLower(name), dataType, fPair, a, isUSDTrackingPair) } func loadAPIData(cfg *config.Config, exch gctexchange.IBotExchange, fPair currency.Pair, a asset.Item, resultLimit uint32, dataType int64) (*kline.DataFromKline, error) { if cfg.DataSettings.Interval <= 0 { return nil, errIntervalUnset } dates, err := gctkline.CalculateCandleDateRanges( cfg.DataSettings.APIData.StartDate, cfg.DataSettings.APIData.EndDate, gctkline.Interval(cfg.DataSettings.Interval), resultLimit) if err != nil { return nil, err } candles, err := api.LoadData(context.TODO(), dataType, cfg.DataSettings.APIData.StartDate, cfg.DataSettings.APIData.EndDate, cfg.DataSettings.Interval, exch, fPair, a) if err != nil { return nil, fmt.Errorf("%v. Please check your GoCryptoTrader configuration", err) } dates.SetHasDataFromCandles(candles.Candles) summary := dates.DataSummary(false) if len(summary) > 0 { log.Warnf(log.BackTester, "%v", summary) } candles.FillMissingDataWithEmptyEntries(dates) candles.RemoveOutsideRange(cfg.DataSettings.APIData.StartDate, cfg.DataSettings.APIData.EndDate) return &kline.DataFromKline{ Item: *candles, RangeHolder: dates, }, nil } func loadLiveData(cfg *config.Config, base *gctexchange.Base) error { if cfg == nil || base == nil || cfg.DataSettings.LiveData == nil { return common.ErrNilArguments } if cfg.DataSettings.Interval <= 0 { return errIntervalUnset } if cfg.DataSettings.LiveData.APIKeyOverride != "" { base.API.Credentials.Key = cfg.DataSettings.LiveData.APIKeyOverride } if cfg.DataSettings.LiveData.APISecretOverride != "" { base.API.Credentials.Secret = cfg.DataSettings.LiveData.APISecretOverride } if cfg.DataSettings.LiveData.APIClientIDOverride != "" { base.API.Credentials.ClientID = cfg.DataSettings.LiveData.APIClientIDOverride } if cfg.DataSettings.LiveData.API2FAOverride != "" { base.API.Credentials.PEMKey = cfg.DataSettings.LiveData.API2FAOverride } if cfg.DataSettings.LiveData.APISubAccountOverride != "" { base.API.Credentials.Subaccount = cfg.DataSettings.LiveData.APISubAccountOverride } validated := base.ValidateAPICredentials() base.API.AuthenticatedSupport = validated if !validated && cfg.DataSettings.LiveData.RealOrders { log.Warn(log.BackTester, "invalid API credentials set, real orders set to false") cfg.DataSettings.LiveData.RealOrders = false } return nil } // Run will iterate over loaded data events // save them and then handle the event based on its type func (bt *BackTest) Run() error { log.Info(log.BackTester, "running backtester against pre-defined data") dataLoadingIssue: for ev := bt.EventQueue.NextEvent(); ; ev = bt.EventQueue.NextEvent() { if ev == nil { dataHandlerMap := bt.Datas.GetAllData() for exchangeName, exchangeMap := range dataHandlerMap { for assetItem, assetMap := range exchangeMap { var hasProcessedData bool for currencyPair, dataHandler := range assetMap { d := dataHandler.Next() if d == nil { if !bt.hasHandledEvent { log.Errorf(log.BackTester, "Unable to perform `Next` for %v %v %v", exchangeName, assetItem, currencyPair) } break dataLoadingIssue } if bt.Strategy.UsingSimultaneousProcessing() && hasProcessedData { continue } bt.EventQueue.AppendEvent(d) hasProcessedData = true } } } } if ev != nil { err := bt.handleEvent(ev) if err != nil { return err } } if !bt.hasHandledEvent { bt.hasHandledEvent = true } } return nil } // handleEvent is the main processor of data for the backtester // after data has been loaded and Run has appended a data event to the queue, // handle event will process events and add further events to the queue if they // are required func (bt *BackTest) handleEvent(ev common.EventHandler) error { funds, err := bt.Funding.GetFundingForEvent(ev) if err != nil { return err } switch eType := ev.(type) { case common.DataEventHandler: if bt.Strategy.UsingSimultaneousProcessing() { err = bt.processSimultaneousDataEvents() if err != nil { return err } bt.Funding.CreateSnapshot(ev.GetTime()) return nil } err = bt.processSingleDataEvent(eType, funds) if err != nil { return err } bt.Funding.CreateSnapshot(ev.GetTime()) return nil case signal.Event: bt.processSignalEvent(eType, funds) case order.Event: bt.processOrderEvent(eType, funds) case fill.Event: bt.processFillEvent(eType, funds) default: return fmt.Errorf("%w %v received, could not process", errUnhandledDatatype, ev) } return nil } func (bt *BackTest) processSingleDataEvent(ev common.DataEventHandler, funds funding.IPairReader) error { err := bt.updateStatsForDataEvent(ev, funds) if err != nil { return err } d := bt.Datas.GetDataForCurrency(ev.GetExchange(), ev.GetAssetType(), ev.Pair()) s, err := bt.Strategy.OnSignal(d, bt.Funding, bt.Portfolio) if err != nil { if errors.Is(err, base.ErrTooMuchBadData) { // too much bad data is a severe error and backtesting must cease return err } log.Error(log.BackTester, err) return nil } err = bt.Statistic.SetEventForOffset(s) if err != nil { log.Error(log.BackTester, err) } bt.EventQueue.AppendEvent(s) return nil } // processSimultaneousDataEvents determines what signal events are generated and appended // to the event queue based on whether it is running a multi-currency consideration strategy order not // // for multi-currency-consideration it will pass all currency datas to the strategy for it to determine what // currencies to act upon // // for non-multi-currency-consideration strategies, it will simply process every currency individually // against the strategy and generate signals func (bt *BackTest) processSimultaneousDataEvents() error { var dataEvents []data.Handler dataHandlerMap := bt.Datas.GetAllData() for _, exchangeMap := range dataHandlerMap { for _, assetMap := range exchangeMap { for _, dataHandler := range assetMap { latestData := dataHandler.Latest() funds, err := bt.Funding.GetFundingForEAP(latestData.GetExchange(), latestData.GetAssetType(), latestData.Pair()) if err != nil { return err } err = bt.updateStatsForDataEvent(latestData, funds) if err != nil && err == statistics.ErrAlreadyProcessed { continue } dataEvents = append(dataEvents, dataHandler) } } } signals, err := bt.Strategy.OnSimultaneousSignals(dataEvents, bt.Funding, bt.Portfolio) if err != nil { if errors.Is(err, base.ErrTooMuchBadData) { // too much bad data is a severe error and backtesting must cease return err } log.Error(log.BackTester, err) return nil } for i := range signals { err = bt.Statistic.SetEventForOffset(signals[i]) if err != nil { log.Error(log.BackTester, err) } bt.EventQueue.AppendEvent(signals[i]) } return nil } // updateStatsForDataEvent makes various systems aware of price movements from // data events func (bt *BackTest) updateStatsForDataEvent(ev common.DataEventHandler, funds funding.IPairReader) error { // update statistics with the latest price err := bt.Statistic.SetupEventForTime(ev) if err != nil { if err == statistics.ErrAlreadyProcessed { return err } log.Error(log.BackTester, err) } // update portfolio manager with the latest price err = bt.Portfolio.UpdateHoldings(ev, funds) if err != nil { log.Error(log.BackTester, err) } return nil } // processSignalEvent receives an event from the strategy for processing under the portfolio func (bt *BackTest) processSignalEvent(ev signal.Event, funds funding.IPairReserver) { cs, err := bt.Exchange.GetCurrencySettings(ev.GetExchange(), ev.GetAssetType(), ev.Pair()) if err != nil { log.Error(log.BackTester, err) return } var o *order.Order o, err = bt.Portfolio.OnSignal(ev, &cs, funds) if err != nil { log.Error(log.BackTester, err) return } err = bt.Statistic.SetEventForOffset(o) if err != nil { log.Error(log.BackTester, err) } bt.EventQueue.AppendEvent(o) } func (bt *BackTest) processOrderEvent(ev order.Event, funds funding.IPairReleaser) { d := bt.Datas.GetDataForCurrency(ev.GetExchange(), ev.GetAssetType(), ev.Pair()) f, err := bt.Exchange.ExecuteOrder(ev, d, bt.orderManager, funds) if err != nil { if f == nil { log.Errorf(log.BackTester, "fill event should always be returned, please fix, %v", err) return } log.Errorf(log.BackTester, "%v %v %v %v", f.GetExchange(), f.GetAssetType(), f.Pair(), err) } err = bt.Statistic.SetEventForOffset(f) if err != nil { log.Error(log.BackTester, err) } bt.EventQueue.AppendEvent(f) } func (bt *BackTest) processFillEvent(ev fill.Event, funds funding.IPairReader) { t, err := bt.Portfolio.OnFill(ev, funds) if err != nil { log.Error(log.BackTester, err) return } err = bt.Statistic.SetEventForOffset(t) if err != nil { log.Error(log.BackTester, err) } var holding *holdings.Holding holding, err = bt.Portfolio.ViewHoldingAtTimePeriod(ev) if err != nil { log.Error(log.BackTester, err) } err = bt.Statistic.AddHoldingsForTime(holding) if err != nil { log.Error(log.BackTester, err) } var cp *compliance.Manager cp, err = bt.Portfolio.GetComplianceManager(ev.GetExchange(), ev.GetAssetType(), ev.Pair()) if err != nil { log.Error(log.BackTester, err) } snap := cp.GetLatestSnapshot() err = bt.Statistic.AddComplianceSnapshotForTime(snap, ev) if err != nil { log.Error(log.BackTester, err) } } // RunLive is a proof of concept function that does not yet support multi currency usage // It runs by constantly checking for new live datas and running through the list of events // once new data is processed. It will run until application close event has been received func (bt *BackTest) RunLive() error { log.Info(log.BackTester, "running backtester against live data") timeoutTimer := time.NewTimer(time.Minute * 5) // a frequent timer so that when a new candle is released by an exchange // that it can be processed quickly processEventTicker := time.NewTicker(time.Second) doneARun := false for { select { case <-bt.shutdown: return nil case <-timeoutTimer.C: return errLiveDataTimeout case <-processEventTicker.C: for e := bt.EventQueue.NextEvent(); ; e = bt.EventQueue.NextEvent() { if e == nil { // as live only supports singular currency, just get the proper reference manually var d data.Handler dd := bt.Datas.GetAllData() for k1, v1 := range dd { for k2, v2 := range v1 { for k3 := range v2 { d = dd[k1][k2][k3] } } } de := d.Next() if de == nil { break } bt.EventQueue.AppendEvent(de) doneARun = true continue } err := bt.handleEvent(e) if err != nil { return err } } if doneARun { timeoutTimer = time.NewTimer(time.Minute * 5) } } } } // loadLiveDataLoop is an incomplete function to continuously retrieve exchange data on a loop // from live. Its purpose is to be able to perform strategy analysis against current data func (bt *BackTest) loadLiveDataLoop(resp *kline.DataFromKline, cfg *config.Config, exch gctexchange.IBotExchange, fPair currency.Pair, a asset.Item, dataType int64) { startDate := time.Now().Add(-cfg.DataSettings.Interval * 2) dates, err := gctkline.CalculateCandleDateRanges( startDate, startDate.AddDate(1, 0, 0), gctkline.Interval(cfg.DataSettings.Interval), 0) if err != nil { log.Errorf(log.BackTester, "%v. Please check your GoCryptoTrader configuration", err) return } candles, err := live.LoadData(context.TODO(), exch, dataType, cfg.DataSettings.Interval, fPair, a) if err != nil { log.Errorf(log.BackTester, "%v. Please check your GoCryptoTrader configuration", err) return } dates.SetHasDataFromCandles(candles.Candles) resp.RangeHolder = dates resp.Item = *candles loadNewDataTimer := time.NewTimer(time.Second * 5) for { select { case <-bt.shutdown: return case <-loadNewDataTimer.C: log.Infof(log.BackTester, "fetching data for %v %v %v %v", exch.GetName(), a, fPair, cfg.DataSettings.Interval) loadNewDataTimer.Reset(time.Second * 15) err = bt.loadLiveData(resp, cfg, exch, fPair, a, dataType) if err != nil { log.Error(log.BackTester, err) return } } } } func (bt *BackTest) loadLiveData(resp *kline.DataFromKline, cfg *config.Config, exch gctexchange.IBotExchange, fPair currency.Pair, a asset.Item, dataType int64) error { if resp == nil { return errNilData } if cfg == nil { return errNilConfig } if exch == nil { return errNilExchange } candles, err := live.LoadData(context.TODO(), exch, dataType, cfg.DataSettings.Interval, fPair, a) if err != nil { return err } if len(candles.Candles) == 0 { return nil } resp.AppendResults(candles) bt.Reports.UpdateItem(&resp.Item) log.Info(log.BackTester, "sleeping for 30 seconds before checking for new candle data") return nil } // Stop shuts down the live data loop func (bt *BackTest) Stop() { close(bt.shutdown) } <file_sep>package funding import ( "errors" "fmt" "sort" "strings" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/data/kline" "github.com/idoall/gocryptotrader/backtester/funding/trackingcurrencies" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) var ( // ErrFundsNotFound used when funds are requested but the funding is not found in the manager ErrFundsNotFound = errors.New("funding not found") // ErrAlreadyExists used when a matching item or pair is already in the funding manager ErrAlreadyExists = errors.New("funding already exists") // ErrUSDTrackingDisabled used when attempting to track USD values when disabled ErrUSDTrackingDisabled = errors.New("USD tracking disabled") errCannotAllocate = errors.New("cannot allocate funds") errZeroAmountReceived = errors.New("amount received less than or equal to zero") errNegativeAmountReceived = errors.New("received negative decimal") errNotEnoughFunds = errors.New("not enough funds") errCannotTransferToSameFunds = errors.New("cannot send funds to self") errTransferMustBeSameCurrency = errors.New("cannot transfer to different currency") errCannotMatchTrackingToItem = errors.New("cannot match tracking data to funding items") ) // SetupFundingManager creates the funding holder. It carries knowledge about levels of funding // across all execution handlers and enables fund transfers func SetupFundingManager(usingExchangeLevelFunding, disableUSDTracking bool) *FundManager { return &FundManager{ usingExchangeLevelFunding: usingExchangeLevelFunding, disableUSDTracking: disableUSDTracking, } } // CreateItem creates a new funding item func CreateItem(exch string, a asset.Item, ci currency.Code, initialFunds, transferFee decimal.Decimal) (*Item, error) { if initialFunds.IsNegative() { return nil, fmt.Errorf("%v %v %v %w initial funds: %v", exch, a, ci, errNegativeAmountReceived, initialFunds) } if transferFee.IsNegative() { return nil, fmt.Errorf("%v %v %v %w transfer fee: %v", exch, a, ci, errNegativeAmountReceived, transferFee) } return &Item{ exchange: exch, asset: a, currency: ci, initialFunds: initialFunds, available: initialFunds, transferFee: transferFee, snapshot: make(map[time.Time]ItemSnapshot), }, nil } // CreateSnapshot creates a Snapshot for an event's point in time // as funding.snapshots is a map, it allows for the last event // in the chronological list to establish the canon at X time func (f *FundManager) CreateSnapshot(t time.Time) { for i := range f.items { if f.items[i].snapshot == nil { f.items[i].snapshot = make(map[time.Time]ItemSnapshot) } iss := ItemSnapshot{ Available: f.items[i].available, Time: t, } if !f.disableUSDTracking { var usdClosePrice decimal.Decimal if f.items[i].usdTrackingCandles == nil { continue } usdCandles := f.items[i].usdTrackingCandles.GetStream() for j := range usdCandles { if usdCandles[j].GetTime().Equal(t) { usdClosePrice = usdCandles[j].GetClosePrice() break } } iss.USDClosePrice = usdClosePrice iss.USDValue = usdClosePrice.Mul(f.items[i].available) } f.items[i].snapshot[t] = iss } } // AddUSDTrackingData adds USD tracking data to a funding item // only in the event that it is not USD and there is data func (f *FundManager) AddUSDTrackingData(k *kline.DataFromKline) error { if f == nil || f.items == nil { return common.ErrNilArguments } if f.disableUSDTracking { return ErrUSDTrackingDisabled } baseSet := false quoteSet := false var basePairedWith currency.Code for i := range f.items { if baseSet && quoteSet { return nil } if strings.EqualFold(f.items[i].exchange, k.Item.Exchange) && f.items[i].asset == k.Item.Asset { if f.items[i].currency == k.Item.Pair.Base { if f.items[i].usdTrackingCandles == nil && trackingcurrencies.CurrencyIsUSDTracked(k.Item.Pair.Quote) { f.items[i].usdTrackingCandles = k if f.items[i].pairedWith != nil { basePairedWith = f.items[i].pairedWith.currency } } baseSet = true } if trackingcurrencies.CurrencyIsUSDTracked(f.items[i].currency) { if f.items[i].pairedWith != nil && f.items[i].currency != basePairedWith { continue } if f.items[i].usdTrackingCandles == nil { usdCandles := gctkline.Item{ Exchange: k.Item.Exchange, Pair: currency.Pair{Delimiter: k.Item.Pair.Delimiter, Base: f.items[i].currency, Quote: currency.USD}, Asset: k.Item.Asset, Interval: k.Item.Interval, Candles: make([]gctkline.Candle, len(k.Item.Candles)), } copy(usdCandles.Candles, k.Item.Candles) for j := range usdCandles.Candles { // usd stablecoins do not always match in value, // this is a simplified implementation that can allow // USD tracking for many different currencies across many exchanges // without retrieving n candle history and exchange rates usdCandles.Candles[j].Open = 1 usdCandles.Candles[j].High = 1 usdCandles.Candles[j].Low = 1 usdCandles.Candles[j].Close = 1 } cpy := *k cpy.Item = usdCandles if err := cpy.Load(); err != nil { return err } f.items[i].usdTrackingCandles = &cpy } quoteSet = true } } } if baseSet { return nil } return fmt.Errorf("%w %v %v %v", errCannotMatchTrackingToItem, k.Item.Exchange, k.Item.Asset, k.Item.Pair) } // CreatePair adds two funding items and associates them with one another // the association allows for the same currency to be used multiple times when // usingExchangeLevelFunding is false. eg BTC-USDT and LTC-USDT do not share the same // USDT level funding func CreatePair(base, quote *Item) (*Pair, error) { if base == nil { return nil, fmt.Errorf("base %w", common.ErrNilArguments) } if quote == nil { return nil, fmt.Errorf("quote %w", common.ErrNilArguments) } // copy to prevent the off chance of sending in the same base OR quote // to create a new pair with a new base OR quote bCopy := *base qCopy := *quote bCopy.pairedWith = &qCopy qCopy.pairedWith = &bCopy return &Pair{Base: &bCopy, Quote: &qCopy}, nil } // Reset clears all settings func (f *FundManager) Reset() { *f = FundManager{} } // USDTrackingDisabled clears all settings func (f *FundManager) USDTrackingDisabled() bool { return f.disableUSDTracking } // GenerateReport builds report data for result HTML report func (f *FundManager) GenerateReport() *Report { report := Report{ USDTotalsOverTime: make(map[time.Time]ItemSnapshot), UsingExchangeLevelFunding: f.usingExchangeLevelFunding, DisableUSDTracking: f.disableUSDTracking, } var items []ReportItem for i := range f.items { item := ReportItem{ Exchange: f.items[i].exchange, Asset: f.items[i].asset, Currency: f.items[i].currency, InitialFunds: f.items[i].initialFunds, TransferFee: f.items[i].transferFee, FinalFunds: f.items[i].available, } if !f.disableUSDTracking && f.items[i].usdTrackingCandles != nil { usdStream := f.items[i].usdTrackingCandles.GetStream() item.USDInitialFunds = f.items[i].initialFunds.Mul(usdStream[0].GetClosePrice()) item.USDFinalFunds = f.items[i].available.Mul(usdStream[len(usdStream)-1].GetClosePrice()) item.USDInitialCostForOne = usdStream[0].GetClosePrice() item.USDFinalCostForOne = usdStream[len(usdStream)-1].GetClosePrice() item.USDPairCandle = f.items[i].usdTrackingCandles } var pricingOverTime []ItemSnapshot for _, v := range f.items[i].snapshot { pricingOverTime = append(pricingOverTime, v) if !f.disableUSDTracking { usdTotalForPeriod := report.USDTotalsOverTime[v.Time] usdTotalForPeriod.Time = v.Time usdTotalForPeriod.USDValue = usdTotalForPeriod.USDValue.Add(v.USDValue) report.USDTotalsOverTime[v.Time] = usdTotalForPeriod } } sort.Slice(pricingOverTime, func(i, j int) bool { return pricingOverTime[i].Time.Before(pricingOverTime[j].Time) }) item.Snapshots = pricingOverTime if f.items[i].initialFunds.IsZero() { item.ShowInfinite = true } else { item.Difference = f.items[i].available.Sub(f.items[i].initialFunds).Div(f.items[i].initialFunds).Mul(decimal.NewFromInt(100)) } if f.items[i].pairedWith != nil { item.PairedWith = f.items[i].pairedWith.currency } items = append(items, item) } report.Items = items return &report } // Transfer allows transferring funds from one pretend exchange to another func (f *FundManager) Transfer(amount decimal.Decimal, sender, receiver *Item, inclusiveFee bool) error { if sender == nil || receiver == nil { return common.ErrNilArguments } if amount.LessThanOrEqual(decimal.Zero) { return errZeroAmountReceived } if inclusiveFee { if sender.available.LessThan(amount) { return fmt.Errorf("%w for %v", errNotEnoughFunds, sender.currency) } } else { if sender.available.LessThan(amount.Add(sender.transferFee)) { return fmt.Errorf("%w for %v", errNotEnoughFunds, sender.currency) } } if sender.currency != receiver.currency { return errTransferMustBeSameCurrency } if sender.currency == receiver.currency && sender.exchange == receiver.exchange && sender.asset == receiver.asset { return fmt.Errorf("%v %v %v %w", sender.exchange, sender.asset, sender.currency, errCannotTransferToSameFunds) } sendAmount := amount receiveAmount := amount if inclusiveFee { receiveAmount = amount.Sub(sender.transferFee) } else { sendAmount = amount.Add(sender.transferFee) } err := sender.Reserve(sendAmount) if err != nil { return err } receiver.IncreaseAvailable(receiveAmount) return sender.Release(sendAmount, decimal.Zero) } // AddItem appends a new funding item. Will reject if exists by exchange asset currency func (f *FundManager) AddItem(item *Item) error { if f.Exists(item) { return fmt.Errorf("cannot add item %v %v %v %w", item.exchange, item.asset, item.currency, ErrAlreadyExists) } f.items = append(f.items, item) return nil } // Exists verifies whether there is a funding item that exists // with the same exchange, asset and currency func (f *FundManager) Exists(item *Item) bool { for i := range f.items { if f.items[i].Equal(item) { return true } } return false } // AddPair adds a pair to the fund manager if it does not exist func (f *FundManager) AddPair(p *Pair) error { if f.Exists(p.Base) { return fmt.Errorf("%w %v", ErrAlreadyExists, p.Base) } if f.Exists(p.Quote) { return fmt.Errorf("%w %v", ErrAlreadyExists, p.Quote) } f.items = append(f.items, p.Base, p.Quote) return nil } // IsUsingExchangeLevelFunding returns if using usingExchangeLevelFunding func (f *FundManager) IsUsingExchangeLevelFunding() bool { return f.usingExchangeLevelFunding } // GetFundingForEvent This will construct a funding based on a backtesting event func (f *FundManager) GetFundingForEvent(ev common.EventHandler) (*Pair, error) { return f.GetFundingForEAP(ev.GetExchange(), ev.GetAssetType(), ev.Pair()) } // GetFundingForEAC This will construct a funding based on the exchange, asset, currency code func (f *FundManager) GetFundingForEAC(exch string, a asset.Item, c currency.Code) (*Item, error) { for i := range f.items { if f.items[i].BasicEqual(exch, a, c, currency.Code{}) { return f.items[i], nil } } return nil, ErrFundsNotFound } // GetFundingForEAP This will construct a funding based on the exchange, asset, currency pair func (f *FundManager) GetFundingForEAP(exch string, a asset.Item, p currency.Pair) (*Pair, error) { var resp Pair for i := range f.items { if f.items[i].BasicEqual(exch, a, p.Base, p.Quote) { resp.Base = f.items[i] continue } if f.items[i].BasicEqual(exch, a, p.Quote, p.Base) { resp.Quote = f.items[i] } } if resp.Base == nil { return nil, fmt.Errorf("base %w", ErrFundsNotFound) } if resp.Quote == nil { return nil, fmt.Errorf("quote %w", ErrFundsNotFound) } return &resp, nil } // BaseInitialFunds returns the initial funds // from the base in a currency pair func (p *Pair) BaseInitialFunds() decimal.Decimal { return p.Base.initialFunds } // QuoteInitialFunds returns the initial funds // from the quote in a currency pair func (p *Pair) QuoteInitialFunds() decimal.Decimal { return p.Quote.initialFunds } // BaseAvailable returns the available funds // from the base in a currency pair func (p *Pair) BaseAvailable() decimal.Decimal { return p.Base.available } // QuoteAvailable returns the available funds // from the quote in a currency pair func (p *Pair) QuoteAvailable() decimal.Decimal { return p.Quote.available } // Reserve allocates an amount of funds to be used at a later time // it prevents multiple events from claiming the same resource // changes which currency to affect based on the order side func (p *Pair) Reserve(amount decimal.Decimal, side order.Side) error { switch side { case order.Buy: return p.Quote.Reserve(amount) case order.Sell: return p.Base.Reserve(amount) default: return fmt.Errorf("%w for %v %v %v. Unknown side %v", errCannotAllocate, p.Base.exchange, p.Base.asset, p.Base.currency, side) } } // Release reduces the amount of funding reserved and adds any difference // back to the available amount // changes which currency to affect based on the order side func (p *Pair) Release(amount, diff decimal.Decimal, side order.Side) error { switch side { case order.Buy: return p.Quote.Release(amount, diff) case order.Sell: return p.Base.Release(amount, diff) default: return fmt.Errorf("%w for %v %v %v. Unknown side %v", errCannotAllocate, p.Base.exchange, p.Base.asset, p.Base.currency, side) } } // IncreaseAvailable adds funding to the available amount // changes which currency to affect based on the order side func (p *Pair) IncreaseAvailable(amount decimal.Decimal, side order.Side) { switch side { case order.Buy: p.Base.IncreaseAvailable(amount) case order.Sell: p.Quote.IncreaseAvailable(amount) } } // CanPlaceOrder does a > 0 check to see if there are any funds // to place an order with // changes which currency to affect based on the order side func (p *Pair) CanPlaceOrder(side order.Side) bool { switch side { case order.Buy: return p.Quote.CanPlaceOrder() case order.Sell: return p.Base.CanPlaceOrder() } return false } // Reserve allocates an amount of funds to be used at a later time // it prevents multiple events from claiming the same resource func (i *Item) Reserve(amount decimal.Decimal) error { if amount.LessThanOrEqual(decimal.Zero) { return errZeroAmountReceived } if amount.GreaterThan(i.available) { return fmt.Errorf("%w for %v %v %v. Requested %v Available: %v", errCannotAllocate, i.exchange, i.asset, i.currency, amount, i.available) } i.available = i.available.Sub(amount) i.reserved = i.reserved.Add(amount) return nil } // Release reduces the amount of funding reserved and adds any difference // back to the available amount func (i *Item) Release(amount, diff decimal.Decimal) error { if amount.LessThanOrEqual(decimal.Zero) { return errZeroAmountReceived } if diff.IsNegative() { return fmt.Errorf("%w diff", errNegativeAmountReceived) } if amount.GreaterThan(i.reserved) { return fmt.Errorf("%w for %v %v %v. Requested %v Reserved: %v", errCannotAllocate, i.exchange, i.asset, i.currency, amount, i.reserved) } i.reserved = i.reserved.Sub(amount) i.available = i.available.Add(diff) return nil } // IncreaseAvailable adds funding to the available amount func (i *Item) IncreaseAvailable(amount decimal.Decimal) { if amount.IsNegative() || amount.IsZero() { return } i.available = i.available.Add(amount) } // CanPlaceOrder checks if the item has any funds available func (i *Item) CanPlaceOrder() bool { return i.available.GreaterThan(decimal.Zero) } // Equal checks for equality via an Item to compare to func (i *Item) Equal(item *Item) bool { if i == nil && item == nil { return true } if item == nil || i == nil { return false } if i.currency == item.currency && i.asset == item.asset && i.exchange == item.exchange { if i.pairedWith == nil && item.pairedWith == nil { return true } if i.pairedWith == nil || item.pairedWith == nil { return false } if i.pairedWith.currency == item.pairedWith.currency && i.pairedWith.asset == item.pairedWith.asset && i.pairedWith.exchange == item.pairedWith.exchange { return true } } return false } // BasicEqual checks for equality via passed in values func (i *Item) BasicEqual(exch string, a asset.Item, currency, pairedCurrency currency.Code) bool { return i != nil && i.exchange == exch && i.asset == a && i.currency == currency && (i.pairedWith == nil || (i.pairedWith != nil && i.pairedWith.currency == pairedCurrency)) } // MatchesCurrency checks that an item's currency is equal func (i *Item) MatchesCurrency(c currency.Code) bool { return i != nil && i.currency == c } // MatchesItemCurrency checks that an item's currency is equal func (i *Item) MatchesItemCurrency(item *Item) bool { return i != nil && item != nil && i.currency == item.currency } // MatchesExchange checks that an item's exchange is equal func (i *Item) MatchesExchange(item *Item) bool { return i != nil && item != nil && i.exchange == item.exchange } <file_sep>package statistics import ( "fmt" "sort" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/common/convert" gctmath "github.com/idoall/gocryptotrader/common/math" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" "github.com/idoall/gocryptotrader/log" "github.com/shopspring/decimal" ) // CalculateFundingStatistics calculates funding statistics for total USD strategy results // along with individual funding item statistics func CalculateFundingStatistics(funds funding.IFundingManager, currStats map[string]map[asset.Item]map[currency.Pair]*CurrencyPairStatistic, riskFreeRate decimal.Decimal, interval gctkline.Interval) (*FundingStatistics, error) { if currStats == nil { return nil, common.ErrNilArguments } report := funds.GenerateReport() response := &FundingStatistics{ Report: report, } for i := range report.Items { exchangeAssetStats, ok := currStats[report.Items[i].Exchange][report.Items[i].Asset] if !ok { return nil, fmt.Errorf("%w for %v %v", errNoRelevantStatsFound, report.Items[i].Exchange, report.Items[i].Asset) } var relevantStats []relatedCurrencyPairStatistics for k, v := range exchangeAssetStats { if k.Base == report.Items[i].Currency { relevantStats = append(relevantStats, relatedCurrencyPairStatistics{isBaseCurrency: true, stat: v}) continue } if k.Quote == report.Items[i].Currency { relevantStats = append(relevantStats, relatedCurrencyPairStatistics{stat: v}) } } fundingStat, err := CalculateIndividualFundingStatistics(report.DisableUSDTracking, &report.Items[i], relevantStats) if err != nil { return nil, err } response.Items = append(response.Items, *fundingStat) } if report.DisableUSDTracking { return response, nil } usdStats := &TotalFundingStatistics{ HighestHoldingValue: ValueAtTime{}, LowestHoldingValue: ValueAtTime{}, RiskFreeRate: riskFreeRate, } for i := range response.Items { usdStats.TotalOrders += response.Items[i].TotalOrders usdStats.BuyOrders += response.Items[i].BuyOrders usdStats.SellOrders += response.Items[i].SellOrders } for k, v := range report.USDTotalsOverTime { if usdStats.HighestHoldingValue.Value.LessThan(v.USDValue) { usdStats.HighestHoldingValue.Time = k usdStats.HighestHoldingValue.Value = v.USDValue } if usdStats.LowestHoldingValue.Value.IsZero() { usdStats.LowestHoldingValue.Time = k usdStats.LowestHoldingValue.Value = v.USDValue } if usdStats.LowestHoldingValue.Value.GreaterThan(v.USDValue) && !usdStats.LowestHoldingValue.Value.IsZero() { usdStats.LowestHoldingValue.Time = k usdStats.LowestHoldingValue.Value = v.USDValue } usdStats.HoldingValues = append(usdStats.HoldingValues, ValueAtTime{Time: k, Value: v.USDValue}) } sort.Slice(usdStats.HoldingValues, func(i, j int) bool { return usdStats.HoldingValues[i].Time.Before(usdStats.HoldingValues[j].Time) }) if len(usdStats.HoldingValues) == 0 { return nil, fmt.Errorf("%w and holding values", errMissingSnapshots) } if !usdStats.HoldingValues[0].Value.IsZero() { usdStats.StrategyMovement = usdStats.HoldingValues[len(usdStats.HoldingValues)-1].Value.Sub( usdStats.HoldingValues[0].Value).Div( usdStats.HoldingValues[0].Value).Mul( decimal.NewFromInt(100)) } usdStats.InitialHoldingValue = usdStats.HoldingValues[0] usdStats.FinalHoldingValue = usdStats.HoldingValues[len(usdStats.HoldingValues)-1] usdStats.HoldingValueDifference = usdStats.FinalHoldingValue.Value.Sub(usdStats.InitialHoldingValue.Value).Div(usdStats.InitialHoldingValue.Value).Mul(decimal.NewFromInt(100)) riskFreeRatePerCandle := usdStats.RiskFreeRate.Div(decimal.NewFromFloat(interval.IntervalsPerYear())) returnsPerCandle := make([]decimal.Decimal, len(usdStats.HoldingValues)) benchmarkRates := make([]decimal.Decimal, len(usdStats.HoldingValues)) benchmarkMovement := usdStats.HoldingValues[0].Value benchmarkRates[0] = usdStats.HoldingValues[0].Value for j := range usdStats.HoldingValues { if j != 0 && !usdStats.HoldingValues[j-1].Value.IsZero() { benchmarkMovement = benchmarkMovement.Add(benchmarkMovement.Mul(riskFreeRatePerCandle)) benchmarkRates[j] = riskFreeRatePerCandle returnsPerCandle[j] = usdStats.HoldingValues[j].Value.Sub(usdStats.HoldingValues[j-1].Value).Div(usdStats.HoldingValues[j-1].Value) } } benchmarkRates = benchmarkRates[1:] returnsPerCandle = returnsPerCandle[1:] usdStats.BenchmarkMarketMovement = benchmarkMovement.Sub(usdStats.HoldingValues[0].Value).Div(usdStats.HoldingValues[0].Value).Mul(decimal.NewFromInt(100)) var err error usdStats.MaxDrawdown, err = CalculateBiggestValueAtTimeDrawdown(usdStats.HoldingValues, interval) if err != nil { return nil, err } sep := "USD Totals |\t" usdStats.ArithmeticRatios, usdStats.GeometricRatios, err = CalculateRatios(benchmarkRates, returnsPerCandle, riskFreeRatePerCandle, &usdStats.MaxDrawdown, sep) if err != nil { return nil, err } if !usdStats.HoldingValues[0].Value.IsZero() { cagr, err := gctmath.DecimalCompoundAnnualGrowthRate( usdStats.HoldingValues[0].Value, usdStats.HoldingValues[len(usdStats.HoldingValues)-1].Value, decimal.NewFromFloat(interval.IntervalsPerYear()), decimal.NewFromInt(int64(len(usdStats.HoldingValues))), ) if err != nil { return nil, err } if !cagr.IsZero() { usdStats.CompoundAnnualGrowthRate = cagr } } usdStats.DidStrategyMakeProfit = usdStats.HoldingValues[len(usdStats.HoldingValues)-1].Value.GreaterThan(usdStats.HoldingValues[0].Value) usdStats.DidStrategyBeatTheMarket = usdStats.StrategyMovement.GreaterThan(usdStats.BenchmarkMarketMovement) response.TotalUSDStatistics = usdStats return response, nil } // CalculateIndividualFundingStatistics calculates statistics for an individual report item func CalculateIndividualFundingStatistics(disableUSDTracking bool, reportItem *funding.ReportItem, relatedStats []relatedCurrencyPairStatistics) (*FundingItemStatistics, error) { if reportItem == nil { return nil, fmt.Errorf("%w - nil report item", common.ErrNilArguments) } item := &FundingItemStatistics{ ReportItem: reportItem, } if disableUSDTracking { return item, nil } closePrices := reportItem.Snapshots if len(closePrices) == 0 { return nil, errMissingSnapshots } item.StartingClosePrice = ValueAtTime{ Time: closePrices[0].Time, Value: closePrices[0].USDClosePrice, } item.EndingClosePrice = ValueAtTime{ Time: closePrices[len(closePrices)-1].Time, Value: closePrices[len(closePrices)-1].USDClosePrice, } for i := range closePrices { if closePrices[i].USDClosePrice.LessThan(item.LowestClosePrice.Value) || item.LowestClosePrice.Value.IsZero() { item.LowestClosePrice.Value = closePrices[i].USDClosePrice item.LowestClosePrice.Time = closePrices[i].Time } if closePrices[i].USDClosePrice.GreaterThan(item.HighestClosePrice.Value) || item.HighestClosePrice.Value.IsZero() { item.HighestClosePrice.Value = closePrices[i].USDClosePrice item.HighestClosePrice.Time = closePrices[i].Time } } for i := range relatedStats { if relatedStats[i].stat == nil { return nil, fmt.Errorf("%w related stats", common.ErrNilArguments) } if relatedStats[i].isBaseCurrency { item.BuyOrders += relatedStats[i].stat.BuyOrders item.SellOrders += relatedStats[i].stat.SellOrders } } item.TotalOrders = item.BuyOrders + item.SellOrders if !item.ReportItem.ShowInfinite { if item.ReportItem.Snapshots[0].USDValue.IsZero() { item.ReportItem.ShowInfinite = true } else { item.StrategyMovement = item.ReportItem.Snapshots[len(item.ReportItem.Snapshots)-1].USDValue.Sub( item.ReportItem.Snapshots[0].USDValue).Div( item.ReportItem.Snapshots[0].USDValue).Mul( decimal.NewFromInt(100)) } } if !item.ReportItem.Snapshots[0].USDClosePrice.IsZero() { item.MarketMovement = item.ReportItem.Snapshots[len(item.ReportItem.Snapshots)-1].USDClosePrice.Sub( item.ReportItem.Snapshots[0].USDClosePrice).Div( item.ReportItem.Snapshots[0].USDClosePrice).Mul( decimal.NewFromInt(100)) } item.DidStrategyBeatTheMarket = item.StrategyMovement.GreaterThan(item.MarketMovement) item.HighestCommittedFunds = ValueAtTime{} for j := range item.ReportItem.Snapshots { if item.ReportItem.Snapshots[j].USDValue.GreaterThan(item.HighestCommittedFunds.Value) { item.HighestCommittedFunds = ValueAtTime{ Time: item.ReportItem.Snapshots[j].Time, Value: item.ReportItem.Snapshots[j].USDValue, } } } if item.ReportItem.USDPairCandle == nil { return nil, fmt.Errorf("%w usd candles missing", errMissingSnapshots) } s := item.ReportItem.USDPairCandle.GetStream() if len(s) == 0 { return nil, fmt.Errorf("%w stream missing", errMissingSnapshots) } var err error item.MaxDrawdown, err = CalculateBiggestEventDrawdown(s) if err != nil { return nil, err } return item, nil } // PrintResults outputs all calculated funding statistics to the command line func (f *FundingStatistics) PrintResults(wasAnyDataMissing bool) error { if f.Report == nil { return fmt.Errorf("%w requires report to be generated", common.ErrNilArguments) } log.Info(log.BackTester, "------------------Funding------------------------------------") log.Info(log.BackTester, "------------------Funding Item Results-----------------------") for i := range f.Report.Items { sep := fmt.Sprintf("%v %v %v |\t", f.Report.Items[i].Exchange, f.Report.Items[i].Asset, f.Report.Items[i].Currency) if !f.Report.Items[i].PairedWith.IsEmpty() { log.Infof(log.BackTester, "%s Paired with: %v", sep, f.Report.Items[i].PairedWith) } log.Infof(log.BackTester, "%s Initial funds: %s", sep, convert.DecimalToHumanFriendlyString(f.Report.Items[i].InitialFunds, 8, ".", ",")) log.Infof(log.BackTester, "%s Final funds: %s", sep, convert.DecimalToHumanFriendlyString(f.Report.Items[i].FinalFunds, 8, ".", ",")) if !f.Report.DisableUSDTracking && f.Report.UsingExchangeLevelFunding { log.Infof(log.BackTester, "%s Initial funds in USD: $%s", sep, convert.DecimalToHumanFriendlyString(f.Report.Items[i].USDInitialFunds, 2, ".", ",")) log.Infof(log.BackTester, "%s Final funds in USD: $%s", sep, convert.DecimalToHumanFriendlyString(f.Report.Items[i].USDFinalFunds, 2, ".", ",")) } if f.Report.Items[i].ShowInfinite { log.Infof(log.BackTester, "%s Difference: ∞%%", sep) } else { log.Infof(log.BackTester, "%s Difference: %s%%", sep, convert.DecimalToHumanFriendlyString(f.Report.Items[i].Difference, 8, ".", ",")) } if f.Report.Items[i].TransferFee.GreaterThan(decimal.Zero) { log.Infof(log.BackTester, "%s Transfer fee: %s", sep, convert.DecimalToHumanFriendlyString(f.Report.Items[i].TransferFee, 8, ".", ",")) } log.Info(log.BackTester, "") } if f.Report.DisableUSDTracking { return nil } log.Info(log.BackTester, "------------------USD Tracking Totals------------------------") sep := "USD Tracking Total |\t" log.Infof(log.BackTester, "%s Initial value: $%s at %v", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.InitialHoldingValue.Value, 8, ".", ","), f.TotalUSDStatistics.InitialHoldingValue.Time) log.Infof(log.BackTester, "%s Final value: $%s at %v", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.FinalHoldingValue.Value, 8, ".", ","), f.TotalUSDStatistics.FinalHoldingValue.Time) log.Infof(log.BackTester, "%s Benchmark Market Movement: %s%%", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.BenchmarkMarketMovement, 8, ".", ",")) log.Infof(log.BackTester, "%s Strategy Movement: %s%%", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.StrategyMovement, 8, ".", ",")) log.Infof(log.BackTester, "%s Did strategy make a profit: %v", sep, f.TotalUSDStatistics.DidStrategyMakeProfit) log.Infof(log.BackTester, "%s Did strategy beat the benchmark: %v", sep, f.TotalUSDStatistics.DidStrategyBeatTheMarket) log.Infof(log.BackTester, "%s Buy Orders: %s", sep, convert.IntToHumanFriendlyString(f.TotalUSDStatistics.BuyOrders, ",")) log.Infof(log.BackTester, "%s Sell Orders: %s", sep, convert.IntToHumanFriendlyString(f.TotalUSDStatistics.SellOrders, ",")) log.Infof(log.BackTester, "%s Total Orders: %s", sep, convert.IntToHumanFriendlyString(f.TotalUSDStatistics.TotalOrders, ",")) log.Infof(log.BackTester, "%s Highest funds: $%s at %v", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.HighestHoldingValue.Value, 8, ".", ","), f.TotalUSDStatistics.HighestHoldingValue.Time) log.Infof(log.BackTester, "%s Lowest funds: $%s at %v", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.LowestHoldingValue.Value, 8, ".", ","), f.TotalUSDStatistics.LowestHoldingValue.Time) log.Info(log.BackTester, "------------------Ratios------------------------------------------------") log.Info(log.BackTester, "------------------Rates-------------------------------------------------") log.Infof(log.BackTester, "%s Risk free rate: %s%%", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.RiskFreeRate.Mul(decimal.NewFromInt(100)), 2, ".", ",")) log.Infof(log.BackTester, "%s Compound Annual Growth Rate: %v%%", sep, convert.DecimalToHumanFriendlyString(f.TotalUSDStatistics.CompoundAnnualGrowthRate, 8, ".", ",")) if f.TotalUSDStatistics.ArithmeticRatios == nil || f.TotalUSDStatistics.GeometricRatios == nil { return fmt.Errorf("%w missing ratio calculations", common.ErrNilArguments) } log.Info(log.BackTester, "------------------Arithmetic--------------------------------------------") if wasAnyDataMissing { log.Infoln(log.BackTester, "Missing data was detected during this backtesting run") log.Infoln(log.BackTester, "Ratio calculations will be skewed") } log.Infof(log.BackTester, "%s Sharpe ratio: %v", sep, f.TotalUSDStatistics.ArithmeticRatios.SharpeRatio.Round(4)) log.Infof(log.BackTester, "%s Sortino ratio: %v", sep, f.TotalUSDStatistics.ArithmeticRatios.SortinoRatio.Round(4)) log.Infof(log.BackTester, "%s Information ratio: %v", sep, f.TotalUSDStatistics.ArithmeticRatios.InformationRatio.Round(4)) log.Infof(log.BackTester, "%s Calmar ratio: %v", sep, f.TotalUSDStatistics.ArithmeticRatios.CalmarRatio.Round(4)) log.Info(log.BackTester, "------------------Geometric--------------------------------------------") if wasAnyDataMissing { log.Infoln(log.BackTester, "Missing data was detected during this backtesting run") log.Infoln(log.BackTester, "Ratio calculations will be skewed") } log.Infof(log.BackTester, "%s Sharpe ratio: %v", sep, f.TotalUSDStatistics.GeometricRatios.SharpeRatio.Round(4)) log.Infof(log.BackTester, "%s Sortino ratio: %v", sep, f.TotalUSDStatistics.GeometricRatios.SortinoRatio.Round(4)) log.Infof(log.BackTester, "%s Information ratio: %v", sep, f.TotalUSDStatistics.GeometricRatios.InformationRatio.Round(4)) log.Infof(log.BackTester, "%s Calmar ratio: %v\n\n", sep, f.TotalUSDStatistics.GeometricRatios.CalmarRatio.Round(4)) return nil } <file_sep>package portfolio import ( "errors" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/compliance" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/holdings" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/risk" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" "github.com/idoall/gocryptotrader/backtester/eventtypes/signal" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/shopspring/decimal" ) var ( errInvalidDirection = errors.New("invalid direction") errRiskManagerUnset = errors.New("risk manager unset") errSizeManagerUnset = errors.New("size manager unset") errAssetUnset = errors.New("asset unset") errCurrencyPairUnset = errors.New("currency pair unset") errExchangeUnset = errors.New("exchange unset") errNegativeRiskFreeRate = errors.New("received negative risk free rate") errNoPortfolioSettings = errors.New("no portfolio settings") errNoHoldings = errors.New("no holdings found") errHoldingsNoTimestamp = errors.New("holding with unset timestamp received") errHoldingsAlreadySet = errors.New("holding already set") ) // Portfolio stores all holdings and rules to assess orders, allowing the portfolio manager to // modify, accept or reject strategy signals type Portfolio struct { riskFreeRate decimal.Decimal sizeManager SizeHandler riskManager risk.Handler exchangeAssetPairSettings map[string]map[asset.Item]map[currency.Pair]*Settings } // Handler contains all functions expected to operate a portfolio manager type Handler interface { OnSignal(signal.Event, *exchange.Settings, funding.IPairReserver) (*order.Order, error) OnFill(fill.Event, funding.IPairReader) (*fill.Fill, error) GetLatestOrderSnapshotForEvent(common.EventHandler) (compliance.Snapshot, error) GetLatestOrderSnapshots() ([]compliance.Snapshot, error) ViewHoldingAtTimePeriod(common.EventHandler) (*holdings.Holding, error) setHoldingsForOffset(*holdings.Holding, bool) error UpdateHoldings(common.DataEventHandler, funding.IPairReader) error GetComplianceManager(string, asset.Item, currency.Pair) (*compliance.Manager, error) SetFee(string, asset.Item, currency.Pair, decimal.Decimal) GetFee(string, asset.Item, currency.Pair) decimal.Decimal Reset() } // SizeHandler is the interface to help size orders type SizeHandler interface { SizeOrder(order.Event, decimal.Decimal, *exchange.Settings) (*order.Order, error) } // Settings holds all important information for the portfolio manager // to assess purchasing decisions type Settings struct { Fee decimal.Decimal BuySideSizing exchange.MinMax SellSideSizing exchange.MinMax Leverage exchange.Leverage HoldingsSnapshots []holdings.Holding ComplianceManager compliance.Manager } <file_sep>package funding import ( "errors" "testing" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/data/kline" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) var ( elite = decimal.NewFromInt(1337) neg = decimal.NewFromInt(-1) one = decimal.NewFromInt(1) exch = "exch" a = asset.Spot base = currency.DOGE quote = currency.XRP pair = currency.NewPair(base, quote) ) func TestSetupFundingManager(t *testing.T) { t.Parallel() f := SetupFundingManager(true, false) if !f.usingExchangeLevelFunding { t.Errorf("expected '%v received '%v'", true, false) } if f.disableUSDTracking { t.Errorf("expected '%v received '%v'", false, true) } f = SetupFundingManager(false, true) if f.usingExchangeLevelFunding { t.Errorf("expected '%v received '%v'", false, true) } if !f.disableUSDTracking { t.Errorf("expected '%v received '%v'", true, false) } } func TestReset(t *testing.T) { t.Parallel() f := SetupFundingManager(true, false) baseItem, err := CreateItem(exch, a, base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddItem(baseItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } f.Reset() if f.usingExchangeLevelFunding { t.Errorf("expected '%v received '%v'", false, true) } if f.Exists(baseItem) { t.Errorf("expected '%v received '%v'", false, true) } } func TestIsUsingExchangeLevelFunding(t *testing.T) { t.Parallel() f := SetupFundingManager(true, false) if !f.IsUsingExchangeLevelFunding() { t.Errorf("expected '%v received '%v'", true, false) } } func TestTransfer(t *testing.T) { t.Parallel() f := FundManager{ usingExchangeLevelFunding: false, items: nil, } err := f.Transfer(decimal.Zero, nil, nil, false) if !errors.Is(err, common.ErrNilArguments) { t.Errorf("received '%v' expected '%v'", err, common.ErrNilArguments) } err = f.Transfer(decimal.Zero, &Item{}, nil, false) if !errors.Is(err, common.ErrNilArguments) { t.Errorf("received '%v' expected '%v'", err, common.ErrNilArguments) } err = f.Transfer(decimal.Zero, &Item{}, &Item{}, false) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = f.Transfer(elite, &Item{}, &Item{}, false) if !errors.Is(err, errNotEnoughFunds) { t.Errorf("received '%v' expected '%v'", err, errNotEnoughFunds) } item1 := &Item{exchange: "hello", asset: a, currency: base, available: elite} err = f.Transfer(elite, item1, item1, false) if !errors.Is(err, errCannotTransferToSameFunds) { t.Errorf("received '%v' expected '%v'", err, errCannotTransferToSameFunds) } item2 := &Item{exchange: "hello", asset: a, currency: quote} err = f.Transfer(elite, item1, item2, false) if !errors.Is(err, errTransferMustBeSameCurrency) { t.Errorf("received '%v' expected '%v'", err, errTransferMustBeSameCurrency) } item2.exchange = "moto" item2.currency = base err = f.Transfer(elite, item1, item2, false) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } if !item2.available.Equal(elite) { t.Errorf("received '%v' expected '%v'", item2.available, elite) } if !item1.available.Equal(decimal.Zero) { t.Errorf("received '%v' expected '%v'", item1.available, decimal.Zero) } item2.transferFee = one err = f.Transfer(elite, item2, item1, true) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } if !item1.available.Equal(elite.Sub(item2.transferFee)) { t.Errorf("received '%v' expected '%v'", item2.available, elite.Sub(item2.transferFee)) } } func TestAddItem(t *testing.T) { t.Parallel() f := FundManager{} err := f.AddItem(nil) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem, err := CreateItem(exch, a, base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddItem(baseItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddItem(baseItem) if !errors.Is(err, ErrAlreadyExists) { t.Errorf("received '%v' expected '%v'", err, ErrAlreadyExists) } } func TestExists(t *testing.T) { t.Parallel() f := FundManager{} exists := f.Exists(nil) if exists { t.Errorf("received '%v' expected '%v'", exists, false) } conflictingSingleItem, err := CreateItem(exch, a, base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddItem(conflictingSingleItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } exists = f.Exists(conflictingSingleItem) if !exists { t.Errorf("received '%v' expected '%v'", exists, true) } baseItem, err := CreateItem(exch, a, base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } p, err := CreatePair(baseItem, quoteItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddPair(p) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } pairItems, err := f.GetFundingForEAP(exch, a, pair) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } exists = f.Exists(pairItems.Base) if !exists { t.Errorf("received '%v' expected '%v'", exists, true) } exists = f.Exists(pairItems.Quote) if !exists { t.Errorf("received '%v' expected '%v'", exists, true) } funds, err := f.GetFundingForEAP(exch, a, pair) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } // demonstration that you don't need the original *Items // to check for existence, just matching fields baseCopy := *funds.Base quoteCopy := *funds.Quote quoteCopy.pairedWith = &baseCopy exists = f.Exists(&baseCopy) if !exists { t.Errorf("received '%v' expected '%v'", exists, true) } currFunds, err := f.GetFundingForEAC(exch, a, base) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } if currFunds.pairedWith != nil { t.Errorf("received '%v' expected '%v'", nil, currFunds.pairedWith) } } func TestAddPair(t *testing.T) { t.Parallel() f := FundManager{} baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } p, err := CreatePair(baseItem, quoteItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddPair(p) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } resp, err := f.GetFundingForEAP(exch, a, pair) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } if resp.Base.exchange != exch || resp.Base.asset != a || resp.Base.currency != pair.Base { t.Error("woah nelly") } if resp.Quote.exchange != exch || resp.Quote.asset != a || resp.Quote.currency != pair.Quote { t.Error("woah nelly") } if resp.Quote.pairedWith != resp.Base { t.Errorf("received '%v' expected '%v'", resp.Base, resp.Quote.pairedWith) } if resp.Base.pairedWith != resp.Quote { t.Errorf("received '%v' expected '%v'", resp.Quote, resp.Base.pairedWith) } if !resp.Base.initialFunds.Equal(decimal.Zero) { t.Errorf("received '%v' expected '%v'", resp.Base.initialFunds, decimal.Zero) } if !resp.Quote.initialFunds.Equal(elite) { t.Errorf("received '%v' expected '%v'", resp.Quote.initialFunds, elite) } p, err = CreatePair(baseItem, quoteItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddPair(p) if !errors.Is(err, ErrAlreadyExists) { t.Errorf("received '%v' expected '%v'", err, ErrAlreadyExists) } } // fakeEvent implements common.EventHandler without // caring about the response, or dealing with import cycles type fakeEvent struct{} func (f *fakeEvent) GetOffset() int64 { return 0 } func (f *fakeEvent) SetOffset(int64) {} func (f *fakeEvent) IsEvent() bool { return true } func (f *fakeEvent) GetTime() time.Time { return time.Now() } func (f *fakeEvent) Pair() currency.Pair { return pair } func (f *fakeEvent) GetExchange() string { return exch } func (f *fakeEvent) GetInterval() gctkline.Interval { return gctkline.OneMin } func (f *fakeEvent) GetAssetType() asset.Item { return asset.Spot } func (f *fakeEvent) GetReason() string { return "" } func (f *fakeEvent) AppendReason(string) {} func TestGetFundingForEvent(t *testing.T) { t.Parallel() e := &fakeEvent{} f := FundManager{} _, err := f.GetFundingForEvent(e) if !errors.Is(err, ErrFundsNotFound) { t.Errorf("received '%v' expected '%v'", err, ErrFundsNotFound) } baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } p, err := CreatePair(baseItem, quoteItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddPair(p) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } _, err = f.GetFundingForEvent(e) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } } func TestGetFundingForEAC(t *testing.T) { t.Parallel() f := FundManager{} _, err := f.GetFundingForEAC(exch, a, base) if !errors.Is(err, ErrFundsNotFound) { t.Errorf("received '%v' expected '%v'", err, ErrFundsNotFound) } baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddItem(baseItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } fundo, err := f.GetFundingForEAC(exch, a, base) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } if !baseItem.Equal(fundo) { t.Errorf("received '%v' expected '%v'", baseItem, fundo) } } func TestGetFundingForEAP(t *testing.T) { t.Parallel() f := FundManager{} _, err := f.GetFundingForEAP(exch, a, pair) if !errors.Is(err, ErrFundsNotFound) { t.Errorf("received '%v' expected '%v'", err, ErrFundsNotFound) } baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } p, err := CreatePair(baseItem, quoteItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddPair(p) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } _, err = f.GetFundingForEAP(exch, a, pair) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } _, err = CreatePair(baseItem, nil) if !errors.Is(err, common.ErrNilArguments) { t.Errorf("received '%v' expected '%v'", err, common.ErrNilArguments) } _, err = CreatePair(nil, quoteItem) if !errors.Is(err, common.ErrNilArguments) { t.Errorf("received '%v' expected '%v'", err, common.ErrNilArguments) } p, err = CreatePair(baseItem, quoteItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddPair(p) if !errors.Is(err, ErrAlreadyExists) { t.Errorf("received '%v' expected '%v'", err, ErrAlreadyExists) } } func TestBaseInitialFunds(t *testing.T) { t.Parallel() baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem.pairedWith = quoteItem quoteItem.pairedWith = baseItem pairItems := Pair{Base: baseItem, Quote: quoteItem} funds := pairItems.BaseInitialFunds() if !funds.IsZero() { t.Errorf("received '%v' expected '%v'", funds, baseItem.available) } } func TestQuoteInitialFunds(t *testing.T) { t.Parallel() baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem.pairedWith = quoteItem quoteItem.pairedWith = baseItem pairItems := Pair{Base: baseItem, Quote: quoteItem} funds := pairItems.QuoteInitialFunds() if !funds.Equal(elite) { t.Errorf("received '%v' expected '%v'", funds, elite) } } func TestBaseAvailable(t *testing.T) { t.Parallel() baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem.pairedWith = quoteItem quoteItem.pairedWith = baseItem pairItems := Pair{Base: baseItem, Quote: quoteItem} funds := pairItems.BaseAvailable() if !funds.IsZero() { t.Errorf("received '%v' expected '%v'", funds, baseItem.available) } } func TestQuoteAvailable(t *testing.T) { t.Parallel() baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem.pairedWith = quoteItem quoteItem.pairedWith = baseItem pairItems := Pair{Base: baseItem, Quote: quoteItem} funds := pairItems.QuoteAvailable() if !funds.Equal(elite) { t.Errorf("received '%v' expected '%v'", funds, elite) } } func TestReservePair(t *testing.T) { t.Parallel() baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem.pairedWith = quoteItem quoteItem.pairedWith = baseItem pairItems := Pair{Base: baseItem, Quote: quoteItem} err = pairItems.Reserve(decimal.Zero, gctorder.Buy) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = pairItems.Reserve(elite, gctorder.Buy) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = pairItems.Reserve(decimal.Zero, gctorder.Sell) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = pairItems.Reserve(elite, gctorder.Sell) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } err = pairItems.Reserve(elite, common.DoNothing) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } } func TestReleasePair(t *testing.T) { t.Parallel() baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem.pairedWith = quoteItem quoteItem.pairedWith = baseItem pairItems := Pair{Base: baseItem, Quote: quoteItem} err = pairItems.Reserve(decimal.Zero, gctorder.Buy) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = pairItems.Reserve(elite, gctorder.Buy) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = pairItems.Reserve(decimal.Zero, gctorder.Sell) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = pairItems.Reserve(elite, gctorder.Sell) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } err = pairItems.Release(decimal.Zero, decimal.Zero, gctorder.Buy) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = pairItems.Release(elite, decimal.Zero, gctorder.Buy) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = pairItems.Release(elite, decimal.Zero, gctorder.Buy) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } err = pairItems.Release(elite, decimal.Zero, common.DoNothing) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } err = pairItems.Release(elite, decimal.Zero, gctorder.Sell) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } err = pairItems.Release(decimal.Zero, decimal.Zero, gctorder.Sell) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } } func TestIncreaseAvailablePair(t *testing.T) { t.Parallel() baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } baseItem.pairedWith = quoteItem quoteItem.pairedWith = baseItem pairItems := Pair{Base: baseItem, Quote: quoteItem} pairItems.IncreaseAvailable(decimal.Zero, gctorder.Buy) if !pairItems.Quote.available.Equal(elite) { t.Errorf("received '%v' expected '%v'", elite, pairItems.Quote.available) } pairItems.IncreaseAvailable(decimal.Zero, gctorder.Sell) if !pairItems.Base.available.Equal(decimal.Zero) { t.Errorf("received '%v' expected '%v'", decimal.Zero, pairItems.Base.available) } pairItems.IncreaseAvailable(elite.Neg(), gctorder.Sell) if !pairItems.Quote.available.Equal(elite) { t.Errorf("received '%v' expected '%v'", elite, pairItems.Quote.available) } pairItems.IncreaseAvailable(elite, gctorder.Buy) if !pairItems.Base.available.Equal(elite) { t.Errorf("received '%v' expected '%v'", elite, pairItems.Base.available) } pairItems.IncreaseAvailable(elite, common.DoNothing) if !pairItems.Base.available.Equal(elite) { t.Errorf("received '%v' expected '%v'", elite, pairItems.Base.available) } } func TestCanPlaceOrderPair(t *testing.T) { t.Parallel() p := Pair{ Base: &Item{}, Quote: &Item{}, } if p.CanPlaceOrder(common.DoNothing) { t.Error("expected false") } if p.CanPlaceOrder(gctorder.Buy) { t.Error("expected false") } if p.CanPlaceOrder(gctorder.Sell) { t.Error("expected false") } p.Quote.available = decimal.NewFromInt(32) if !p.CanPlaceOrder(gctorder.Buy) { t.Error("expected true") } p.Base.available = decimal.NewFromInt(32) if !p.CanPlaceOrder(gctorder.Sell) { t.Error("expected true") } } func TestIncreaseAvailable(t *testing.T) { t.Parallel() i := Item{} i.IncreaseAvailable(elite) if !i.available.Equal(elite) { t.Errorf("expected %v", elite) } i.IncreaseAvailable(decimal.Zero) i.IncreaseAvailable(neg) if !i.available.Equal(elite) { t.Errorf("expected %v", elite) } } func TestRelease(t *testing.T) { t.Parallel() i := Item{} err := i.Release(decimal.Zero, decimal.Zero) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = i.Release(elite, decimal.Zero) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } i.reserved = elite err = i.Release(elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } i.reserved = elite err = i.Release(elite, one) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = i.Release(neg, decimal.Zero) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = i.Release(elite, neg) if !errors.Is(err, errNegativeAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errNegativeAmountReceived) } } func TestReserve(t *testing.T) { t.Parallel() i := Item{} err := i.Reserve(decimal.Zero) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } err = i.Reserve(elite) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } i.reserved = elite err = i.Reserve(elite) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } i.available = elite err = i.Reserve(elite) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = i.Reserve(elite) if !errors.Is(err, errCannotAllocate) { t.Errorf("received '%v' expected '%v'", err, errCannotAllocate) } err = i.Reserve(neg) if !errors.Is(err, errZeroAmountReceived) { t.Errorf("received '%v' expected '%v'", err, errZeroAmountReceived) } } func TestMatchesItemCurrency(t *testing.T) { t.Parallel() i := Item{} if i.MatchesItemCurrency(nil) { t.Errorf("received '%v' expected '%v'", true, false) } baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } if baseItem.MatchesItemCurrency(quoteItem) { t.Errorf("received '%v' expected '%v'", true, false) } if !baseItem.MatchesItemCurrency(baseItem) { t.Errorf("received '%v' expected '%v'", false, true) } } func TestMatchesExchange(t *testing.T) { t.Parallel() i := Item{} if i.MatchesExchange(nil) { t.Errorf("received '%v' expected '%v'", true, false) } baseItem, err := CreateItem(exch, a, pair.Base, decimal.Zero, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } if !baseItem.MatchesExchange(quoteItem) { t.Errorf("received '%v' expected '%v'", false, true) } if !baseItem.MatchesExchange(baseItem) { t.Errorf("received '%v' expected '%v'", false, true) } } func TestGenerateReport(t *testing.T) { t.Parallel() f := FundManager{} report := f.GenerateReport() if report == nil { t.Fatal("shouldn't be nil") } if len(report.Items) > 0 { t.Error("expected 0") } item := &Item{ exchange: exch, initialFunds: decimal.NewFromInt(100), available: decimal.NewFromInt(200), currency: currency.BTC, asset: a, } err := f.AddItem(item) if err != nil { t.Fatal(err) } report = f.GenerateReport() if len(report.Items) != 1 { t.Fatal("expected 1") } if report.Items[0].Exchange != item.exchange { t.Error("expected matching name") } f.usingExchangeLevelFunding = true err = f.AddItem(&Item{ exchange: exch, initialFunds: decimal.NewFromInt(100), available: decimal.NewFromInt(200), currency: currency.USD, asset: a, }) if err != nil { t.Fatal(err) } dfk := &kline.DataFromKline{ Item: gctkline.Item{ Exchange: exch, Pair: currency.NewPair(currency.BTC, currency.USD), Asset: a, Interval: gctkline.OneHour, Candles: []gctkline.Candle{ { Time: time.Now(), }, }, }, } err = dfk.Load() if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddUSDTrackingData(dfk) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } f.items[0].usdTrackingCandles = dfk f.CreateSnapshot(dfk.Item.Candles[0].Time) report = f.GenerateReport() if len(report.Items) != 2 { t.Fatal("expected 2") } if report.Items[0].Exchange != item.exchange { t.Error("expected matching name") } if !report.Items[1].FinalFunds.Equal(decimal.NewFromInt(200)) { t.Errorf("received %v expected %v", report.Items[1].FinalFunds, decimal.NewFromInt(200)) } } func TestMatchesCurrency(t *testing.T) { t.Parallel() i := Item{ currency: currency.BTC, } if i.MatchesCurrency(currency.USDT) { t.Error("expected false") } if !i.MatchesCurrency(currency.BTC) { t.Error("expected true") } if i.MatchesCurrency(currency.Code{}) { t.Error("expected false") } if i.MatchesCurrency(currency.NewCode("")) { t.Error("expected false") } } func TestCreateSnapshot(t *testing.T) { f := FundManager{} f.CreateSnapshot(time.Time{}) f.items = append(f.items, &Item{ exchange: "", asset: "", currency: currency.Code{}, initialFunds: decimal.Decimal{}, available: decimal.Decimal{}, reserved: decimal.Decimal{}, transferFee: decimal.Decimal{}, pairedWith: nil, usdTrackingCandles: nil, snapshot: nil, }) f.CreateSnapshot(time.Time{}) dfk := &kline.DataFromKline{ Item: gctkline.Item{ Candles: []gctkline.Candle{ { Time: time.Now(), }, }, }, } if err := dfk.Load(); err != nil { t.Error(err) } f.items = append(f.items, &Item{ exchange: "test", asset: asset.Spot, currency: currency.BTC, initialFunds: decimal.NewFromInt(1337), available: decimal.NewFromInt(1337), reserved: decimal.NewFromInt(1337), transferFee: decimal.NewFromInt(1337), usdTrackingCandles: dfk, }) f.CreateSnapshot(dfk.Item.Candles[0].Time) } func TestAddUSDTrackingData(t *testing.T) { f := FundManager{} err := f.AddUSDTrackingData(nil) if !errors.Is(err, common.ErrNilArguments) { t.Errorf("received '%v' expected '%v'", err, common.ErrNilArguments) } err = f.AddUSDTrackingData(&kline.DataFromKline{}) if !errors.Is(err, common.ErrNilArguments) { t.Errorf("received '%v' expected '%v'", err, common.ErrNilArguments) } dfk := &kline.DataFromKline{ Item: gctkline.Item{ Candles: []gctkline.Candle{ { Time: time.Now(), }, }, }, } err = dfk.Load() if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } quoteItem, err := CreateItem(exch, a, pair.Quote, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddItem(quoteItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } f.disableUSDTracking = true err = f.AddUSDTrackingData(dfk) if !errors.Is(err, ErrUSDTrackingDisabled) { t.Errorf("received '%v' expected '%v'", err, ErrUSDTrackingDisabled) } f.disableUSDTracking = false err = f.AddUSDTrackingData(dfk) if !errors.Is(err, errCannotMatchTrackingToItem) { t.Errorf("received '%v' expected '%v'", err, errCannotMatchTrackingToItem) } dfk = &kline.DataFromKline{ Item: gctkline.Item{ Exchange: exch, Pair: currency.NewPair(pair.Quote, currency.USD), Asset: a, Interval: gctkline.OneHour, Candles: []gctkline.Candle{ { Time: time.Now(), }, }, }, } err = dfk.Load() if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddUSDTrackingData(dfk) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } usdtItem, err := CreateItem(exch, a, currency.USDT, elite, decimal.Zero) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddItem(usdtItem) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } err = f.AddUSDTrackingData(dfk) if !errors.Is(err, nil) { t.Errorf("received '%v' expected '%v'", err, nil) } } func TestUSDTrackingDisabled(t *testing.T) { f := FundManager{} if f.USDTrackingDisabled() { t.Error("received true, expected false") } f.disableUSDTracking = true if !f.USDTrackingDisabled() { t.Error("received false, expected true") } } <file_sep>package ntpclient import ( "encoding/binary" "net" "time" "github.com/idoall/gocryptotrader/log" ) type ntppacket struct { Settings uint8 // leap yr indicator, ver number, and mode Stratum uint8 // stratum of local clock Poll int8 // poll exponent Precision int8 // precision exponent RootDelay uint32 // root delay RootDispersion uint32 // root dispersion ReferenceID uint32 // reference id RefTimeSec uint32 // reference timestamp sec RefTimeFrac uint32 // reference timestamp fractional OrigTimeSec uint32 // origin time secs OrigTimeFrac uint32 // origin time fractional RxTimeSec uint32 // receive time secs RxTimeFrac uint32 // receive time frac TxTimeSec uint32 // transmit time secs TxTimeFrac uint32 // transmit time frac } // NTPClient create's a new NTPClient and returns local based on ntp servers provided timestamp // if no server can be reached will return local time in UTC() func NTPClient(pool []string) time.Time { for i := range pool { con, err := net.DialTimeout("udp", pool[i], 5*time.Second) if err != nil { log.Warnf(log.TimeMgr, "Unable to connect to hosts %v attempting next", pool[i]) continue } if err := con.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { log.Warnf(log.TimeMgr, "Unable to SetDeadline. Error: %s\n", err) con.Close() continue } req := &ntppacket{Settings: 0x1B} if err := binary.Write(con, binary.BigEndian, req); err != nil { con.Close() continue } rsp := &ntppacket{} if err := binary.Read(con, binary.BigEndian, rsp); err != nil { con.Close() continue } secs := float64(rsp.TxTimeSec) - 2208988800 nanos := (int64(rsp.TxTimeFrac) * 1e9) >> 32 con.Close() return time.Unix(int64(secs), nanos) } log.Warnln(log.TimeMgr, "No valid NTP servers found, using current system time") return time.Now().UTC() } <file_sep>package statistics import ( "testing" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/compliance" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/holdings" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/backtester/eventtypes/kline" "github.com/idoall/gocryptotrader/backtester/eventtypes/signal" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) func TestCalculateResults(t *testing.T) { t.Parallel() cs := CurrencyPairStatistic{} tt1 := time.Now() tt2 := time.Now().Add(gctkline.OneDay.Duration()) exch := testExchange a := asset.Spot p := currency.NewPair(currency.BTC, currency.USDT) even := event.Base{ Exchange: exch, Time: tt1, Interval: gctkline.OneDay, CurrencyPair: p, AssetType: a, } ev := EventStore{ Holdings: holdings.Holding{ ChangeInTotalValuePercent: decimal.NewFromFloat(0.1333), Timestamp: tt1, QuoteInitialFunds: decimal.NewFromInt(1337), }, Transactions: compliance.Snapshot{ Orders: []compliance.SnapshotOrder{ { ClosePrice: decimal.NewFromInt(1338), VolumeAdjustedPrice: decimal.NewFromInt(1338), SlippageRate: decimal.NewFromInt(1338), CostBasis: decimal.NewFromInt(1338), Detail: &order.Detail{Side: order.Buy}, }, { ClosePrice: decimal.NewFromInt(1337), VolumeAdjustedPrice: decimal.NewFromInt(1337), SlippageRate: decimal.NewFromInt(1337), CostBasis: decimal.NewFromInt(1337), Detail: &order.Detail{Side: order.Sell}, }, }, }, DataEvent: &kline.Kline{ Base: even, Open: decimal.NewFromInt(2000), Close: decimal.NewFromInt(2000), Low: decimal.NewFromInt(2000), High: decimal.NewFromInt(2000), Volume: decimal.NewFromInt(2000), }, SignalEvent: &signal.Signal{ Base: even, ClosePrice: decimal.NewFromInt(2000), }, } even2 := even even2.Time = tt2 ev2 := EventStore{ Holdings: holdings.Holding{ ChangeInTotalValuePercent: decimal.NewFromFloat(0.1337), Timestamp: tt2, QuoteInitialFunds: decimal.NewFromInt(1337), }, Transactions: compliance.Snapshot{ Orders: []compliance.SnapshotOrder{ { ClosePrice: decimal.NewFromInt(1338), VolumeAdjustedPrice: decimal.NewFromInt(1338), SlippageRate: decimal.NewFromInt(1338), CostBasis: decimal.NewFromInt(1338), Detail: &order.Detail{Side: order.Buy}, }, { ClosePrice: decimal.NewFromInt(1337), VolumeAdjustedPrice: decimal.NewFromInt(1337), SlippageRate: decimal.NewFromInt(1337), CostBasis: decimal.NewFromInt(1337), Detail: &order.Detail{Side: order.Sell}, }, }, }, DataEvent: &kline.Kline{ Base: even2, Open: decimal.NewFromInt(1337), Close: decimal.NewFromInt(1337), Low: decimal.NewFromInt(1337), High: decimal.NewFromInt(1337), Volume: decimal.NewFromInt(1337), }, SignalEvent: &signal.Signal{ Base: even2, ClosePrice: decimal.NewFromInt(1337), Direction: common.MissingData, }, } cs.Events = append(cs.Events, ev, ev2) err := cs.CalculateResults(decimal.NewFromFloat(0.03)) if err != nil { t.Error(err) } if !cs.MarketMovement.Equal(decimal.NewFromFloat(-33.15)) { t.Error("expected -33.15") } ev3 := ev2 ev3.DataEvent = &kline.Kline{ Base: even2, Open: decimal.NewFromInt(1339), Close: decimal.NewFromInt(1339), Low: decimal.NewFromInt(1339), High: decimal.NewFromInt(1339), Volume: decimal.NewFromInt(1339), } cs.Events = append(cs.Events, ev, ev3) cs.Events[0].DataEvent = &kline.Kline{ Base: even2, Open: decimal.Zero, Close: decimal.Zero, Low: decimal.Zero, High: decimal.Zero, Volume: decimal.Zero, } err = cs.CalculateResults(decimal.NewFromFloat(0.03)) if err != nil { t.Error(err) } cs.Events[1].DataEvent = &kline.Kline{ Base: even2, Open: decimal.Zero, Close: decimal.Zero, Low: decimal.Zero, High: decimal.Zero, Volume: decimal.Zero, } err = cs.CalculateResults(decimal.NewFromFloat(0.03)) if err != nil { t.Error(err) } } func TestPrintResults(t *testing.T) { cs := CurrencyPairStatistic{} tt1 := time.Now() tt2 := time.Now().Add(gctkline.OneDay.Duration()) exch := testExchange a := asset.Spot p := currency.NewPair(currency.BTC, currency.USDT) even := event.Base{ Exchange: exch, Time: tt1, Interval: gctkline.OneDay, CurrencyPair: p, AssetType: a, } ev := EventStore{ Holdings: holdings.Holding{ ChangeInTotalValuePercent: decimal.NewFromFloat(0.1333), Timestamp: tt1, QuoteInitialFunds: decimal.NewFromInt(1337), }, Transactions: compliance.Snapshot{ Orders: []compliance.SnapshotOrder{ { ClosePrice: decimal.NewFromInt(1338), VolumeAdjustedPrice: decimal.NewFromInt(1338), SlippageRate: decimal.NewFromInt(1338), CostBasis: decimal.NewFromInt(1338), Detail: &order.Detail{Side: order.Buy}, }, { ClosePrice: decimal.NewFromInt(1337), VolumeAdjustedPrice: decimal.NewFromInt(1337), SlippageRate: decimal.NewFromInt(1337), CostBasis: decimal.NewFromInt(1337), Detail: &order.Detail{Side: order.Sell}, }, }, }, DataEvent: &kline.Kline{ Base: even, Open: decimal.NewFromInt(2000), Close: decimal.NewFromInt(2000), Low: decimal.NewFromInt(2000), High: decimal.NewFromInt(2000), Volume: decimal.NewFromInt(2000), }, SignalEvent: &signal.Signal{ Base: even, ClosePrice: decimal.NewFromInt(2000), }, } even2 := even even2.Time = tt2 ev2 := EventStore{ Holdings: holdings.Holding{ ChangeInTotalValuePercent: decimal.NewFromFloat(0.1337), Timestamp: tt2, QuoteInitialFunds: decimal.NewFromInt(1337), }, Transactions: compliance.Snapshot{ Orders: []compliance.SnapshotOrder{ { ClosePrice: decimal.NewFromInt(1338), VolumeAdjustedPrice: decimal.NewFromInt(1338), SlippageRate: decimal.NewFromInt(1338), CostBasis: decimal.NewFromInt(1338), Detail: &order.Detail{Side: order.Buy}, }, { ClosePrice: decimal.NewFromInt(1337), VolumeAdjustedPrice: decimal.NewFromInt(1337), SlippageRate: decimal.NewFromInt(1337), CostBasis: decimal.NewFromInt(1337), Detail: &order.Detail{Side: order.Sell}, }, }, }, DataEvent: &kline.Kline{ Base: even2, Open: decimal.NewFromInt(1337), Close: decimal.NewFromInt(1337), Low: decimal.NewFromInt(1337), High: decimal.NewFromInt(1337), Volume: decimal.NewFromInt(1337), }, SignalEvent: &signal.Signal{ Base: even2, ClosePrice: decimal.NewFromInt(1337), }, } cs.Events = append(cs.Events, ev, ev2) cs.PrintResults(exch, a, p, true) } func TestCalculateHighestCommittedFunds(t *testing.T) { t.Parallel() c := CurrencyPairStatistic{} c.calculateHighestCommittedFunds() if !c.HighestCommittedFunds.Time.IsZero() { t.Error("expected no time with not committed funds") } tt1 := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) tt2 := time.Date(2021, 2, 1, 0, 0, 0, 0, time.UTC) tt3 := time.Date(2021, 3, 1, 0, 0, 0, 0, time.UTC) c.Events = append(c.Events, EventStore{DataEvent: &kline.Kline{Close: decimal.NewFromInt(1337)}, Holdings: holdings.Holding{Timestamp: tt1, BaseSize: decimal.NewFromInt(10)}}, EventStore{DataEvent: &kline.Kline{Close: decimal.NewFromInt(1338)}, Holdings: holdings.Holding{Timestamp: tt2, BaseSize: decimal.NewFromInt(1337)}}, EventStore{DataEvent: &kline.Kline{Close: decimal.NewFromInt(1339)}, Holdings: holdings.Holding{Timestamp: tt3, BaseSize: decimal.NewFromInt(11)}}, ) c.calculateHighestCommittedFunds() if c.HighestCommittedFunds.Time != tt2 { t.Errorf("expected %v, received %v", tt2, c.HighestCommittedFunds.Time) } } <file_sep>package currency import "testing" func TestGetTranslation(t *testing.T) { currencyPair := NewPair(BTC, USD) expected := XBT actual := GetTranslation(currencyPair.Base) if expected != actual { t.Error("GetTranslation: translation result was different to expected result") } currencyPair.Base = NEO actual = GetTranslation(currencyPair.Base) if actual != currencyPair.Base { t.Error("GetTranslation: no error on non translatable currency") } expected = BTC currencyPair.Base = XBT actual = GetTranslation(currencyPair.Base) if expected != actual { t.Error("GetTranslation: translation result was different to expected result") } } <file_sep>package portfolio import ( "errors" "fmt" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/compliance" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/holdings" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/risk" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" "github.com/idoall/gocryptotrader/backtester/eventtypes/signal" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/log" "github.com/shopspring/decimal" ) // Setup creates a portfolio manager instance and sets private fields func Setup(sh SizeHandler, r risk.Handler, riskFreeRate decimal.Decimal) (*Portfolio, error) { if sh == nil { return nil, errSizeManagerUnset } if riskFreeRate.IsNegative() { return nil, errNegativeRiskFreeRate } if r == nil { return nil, errRiskManagerUnset } p := &Portfolio{} p.sizeManager = sh p.riskManager = r p.riskFreeRate = riskFreeRate return p, nil } // Reset returns the portfolio manager to its default state func (p *Portfolio) Reset() { p.exchangeAssetPairSettings = nil } // GetLatestOrderSnapshotForEvent gets orders related to the event func (p *Portfolio) GetLatestOrderSnapshotForEvent(e common.EventHandler) (compliance.Snapshot, error) { eapSettings, ok := p.exchangeAssetPairSettings[e.GetExchange()][e.GetAssetType()][e.Pair()] if !ok { return compliance.Snapshot{}, fmt.Errorf("%w for %v %v %v", errNoPortfolioSettings, e.GetExchange(), e.GetAssetType(), e.Pair()) } return eapSettings.ComplianceManager.GetLatestSnapshot(), nil } // GetLatestOrderSnapshots returns the latest snapshots from all stored pair data func (p *Portfolio) GetLatestOrderSnapshots() ([]compliance.Snapshot, error) { var resp []compliance.Snapshot for _, exchangeMap := range p.exchangeAssetPairSettings { for _, assetMap := range exchangeMap { for _, pairMap := range assetMap { resp = append(resp, pairMap.ComplianceManager.GetLatestSnapshot()) } } } if len(resp) == 0 { return nil, errNoPortfolioSettings } return resp, nil } // OnSignal receives the event from the strategy on whether it has signalled to buy, do nothing or sell // on buy/sell, the portfolio manager will size the order and assess the risk of the order // if successful, it will pass on an order.Order to be used by the exchange event handler to place an order based on // the portfolio manager's recommendations func (p *Portfolio) OnSignal(ev signal.Event, cs *exchange.Settings, funds funding.IPairReserver) (*order.Order, error) { if ev == nil || cs == nil { return nil, common.ErrNilArguments } if p.sizeManager == nil { return nil, errSizeManagerUnset } if p.riskManager == nil { return nil, errRiskManagerUnset } if funds == nil { return nil, funding.ErrFundsNotFound } o := &order.Order{ Base: event.Base{ Offset: ev.GetOffset(), Exchange: ev.GetExchange(), Time: ev.GetTime(), CurrencyPair: ev.Pair(), AssetType: ev.GetAssetType(), Interval: ev.GetInterval(), Reason: ev.GetReason(), }, Direction: ev.GetDirection(), } if ev.GetDirection() == "" { return o, errInvalidDirection } lookup := p.exchangeAssetPairSettings[ev.GetExchange()][ev.GetAssetType()][ev.Pair()] if lookup == nil { return nil, fmt.Errorf("%w for %v %v %v", errNoPortfolioSettings, ev.GetExchange(), ev.GetAssetType(), ev.Pair()) } if ev.GetDirection() == common.DoNothing || ev.GetDirection() == common.MissingData || ev.GetDirection() == common.TransferredFunds || ev.GetDirection() == "" { return o, nil } if !funds.CanPlaceOrder(ev.GetDirection()) { if ev.GetDirection() == gctorder.Sell { o.AppendReason("no holdings to sell") o.SetDirection(common.CouldNotSell) } else if ev.GetDirection() == gctorder.Buy { o.AppendReason("not enough funds to buy") o.SetDirection(common.CouldNotBuy) } ev.SetDirection(o.Direction) return o, nil } o.Price = ev.GetPrice() o.OrderType = gctorder.Market o.BuyLimit = ev.GetBuyLimit() o.SellLimit = ev.GetSellLimit() var sizingFunds decimal.Decimal if ev.GetDirection() == gctorder.Sell { sizingFunds = funds.BaseAvailable() } else { sizingFunds = funds.QuoteAvailable() } sizedOrder := p.sizeOrder(ev, cs, o, sizingFunds, funds) return p.evaluateOrder(ev, o, sizedOrder) } func (p *Portfolio) evaluateOrder(d common.Directioner, originalOrderSignal, sizedOrder *order.Order) (*order.Order, error) { var evaluatedOrder *order.Order cm, err := p.GetComplianceManager(originalOrderSignal.GetExchange(), originalOrderSignal.GetAssetType(), originalOrderSignal.Pair()) if err != nil { return nil, err } evaluatedOrder, err = p.riskManager.EvaluateOrder(sizedOrder, p.GetLatestHoldingsForAllCurrencies(), cm.GetLatestSnapshot()) if err != nil { originalOrderSignal.AppendReason(err.Error()) switch d.GetDirection() { case gctorder.Buy: originalOrderSignal.Direction = common.CouldNotBuy case gctorder.Sell: originalOrderSignal.Direction = common.CouldNotSell case common.CouldNotBuy, common.CouldNotSell: default: originalOrderSignal.Direction = common.DoNothing } d.SetDirection(originalOrderSignal.Direction) return originalOrderSignal, nil } return evaluatedOrder, nil } func (p *Portfolio) sizeOrder(d common.Directioner, cs *exchange.Settings, originalOrderSignal *order.Order, sizingFunds decimal.Decimal, funds funding.IPairReserver) *order.Order { sizedOrder, err := p.sizeManager.SizeOrder(originalOrderSignal, sizingFunds, cs) if err != nil { originalOrderSignal.AppendReason(err.Error()) switch originalOrderSignal.Direction { case gctorder.Buy: originalOrderSignal.Direction = common.CouldNotBuy case gctorder.Sell: originalOrderSignal.Direction = common.CouldNotSell default: originalOrderSignal.Direction = common.DoNothing } d.SetDirection(originalOrderSignal.Direction) return originalOrderSignal } if sizedOrder.Amount.IsZero() { switch originalOrderSignal.Direction { case gctorder.Buy: originalOrderSignal.Direction = common.CouldNotBuy case gctorder.Sell: originalOrderSignal.Direction = common.CouldNotSell default: originalOrderSignal.Direction = common.DoNothing } d.SetDirection(originalOrderSignal.Direction) originalOrderSignal.AppendReason("sized order to 0") } if d.GetDirection() == gctorder.Sell { err = funds.Reserve(sizedOrder.Amount, gctorder.Sell) sizedOrder.AllocatedFunds = sizedOrder.Amount } else { err = funds.Reserve(sizedOrder.Amount.Mul(sizedOrder.Price), gctorder.Buy) sizedOrder.AllocatedFunds = sizedOrder.Amount.Mul(sizedOrder.Price) } if err != nil { sizedOrder.Direction = common.DoNothing sizedOrder.AppendReason(err.Error()) } return sizedOrder } // OnFill processes the event after an order has been placed by the exchange. Its purpose is to track holdings for future portfolio decisions. func (p *Portfolio) OnFill(ev fill.Event, funding funding.IPairReader) (*fill.Fill, error) { if ev == nil { return nil, common.ErrNilEvent } lookup := p.exchangeAssetPairSettings[ev.GetExchange()][ev.GetAssetType()][ev.Pair()] if lookup == nil { return nil, fmt.Errorf("%w for %v %v %v", errNoPortfolioSettings, ev.GetExchange(), ev.GetAssetType(), ev.Pair()) } var err error // Get the holding from the previous iteration, create it if it doesn't yet have a timestamp h := lookup.GetHoldingsForTime(ev.GetTime().Add(-ev.GetInterval().Duration())) if !h.Timestamp.IsZero() { h.Update(ev, funding) } else { h = lookup.GetLatestHoldings() if h.Timestamp.IsZero() { h, err = holdings.Create(ev, funding) if err != nil { return nil, err } } else { h.Update(ev, funding) } } err = p.setHoldingsForOffset(&h, true) if errors.Is(err, errNoHoldings) { err = p.setHoldingsForOffset(&h, false) } if err != nil { log.Error(log.BackTester, err) } err = p.addComplianceSnapshot(ev) if err != nil { log.Error(log.BackTester, err) } direction := ev.GetDirection() if direction == common.DoNothing || direction == common.CouldNotBuy || direction == common.CouldNotSell || direction == common.MissingData || direction == "" { fe, ok := ev.(*fill.Fill) if !ok { return nil, fmt.Errorf("%w expected fill event", common.ErrInvalidDataType) } fe.ExchangeFee = decimal.Zero return fe, nil } fe, ok := ev.(*fill.Fill) if !ok { return nil, fmt.Errorf("%w expected fill event", common.ErrInvalidDataType) } return fe, nil } // addComplianceSnapshot gets the previous snapshot of compliance events, updates with the latest fillevent // then saves the snapshot to the c func (p *Portfolio) addComplianceSnapshot(fillEvent fill.Event) error { if fillEvent == nil { return common.ErrNilEvent } complianceManager, err := p.GetComplianceManager(fillEvent.GetExchange(), fillEvent.GetAssetType(), fillEvent.Pair()) if err != nil { return err } prevSnap := complianceManager.GetLatestSnapshot() if fo := fillEvent.GetOrder(); fo != nil { price := decimal.NewFromFloat(fo.Price) amount := decimal.NewFromFloat(fo.Amount) fee := decimal.NewFromFloat(fo.Fee) snapOrder := compliance.SnapshotOrder{ ClosePrice: fillEvent.GetClosePrice(), VolumeAdjustedPrice: fillEvent.GetVolumeAdjustedPrice(), SlippageRate: fillEvent.GetSlippageRate(), Detail: fo, CostBasis: price.Mul(amount).Add(fee), } prevSnap.Orders = append(prevSnap.Orders, snapOrder) } return complianceManager.AddSnapshot(prevSnap.Orders, fillEvent.GetTime(), fillEvent.GetOffset(), false) } // GetComplianceManager returns the order snapshots for a given exchange, asset, pair func (p *Portfolio) GetComplianceManager(exchangeName string, a asset.Item, cp currency.Pair) (*compliance.Manager, error) { lookup := p.exchangeAssetPairSettings[exchangeName][a][cp] if lookup == nil { return nil, fmt.Errorf("%w for %v %v %v could not retrieve compliance manager", errNoPortfolioSettings, exchangeName, a, cp) } return &lookup.ComplianceManager, nil } // SetFee sets the fee rate func (p *Portfolio) SetFee(exch string, a asset.Item, cp currency.Pair, fee decimal.Decimal) { lookup := p.exchangeAssetPairSettings[exch][a][cp] lookup.Fee = fee } // GetFee can panic for bad requests, but why are you getting things that don't exist? func (p *Portfolio) GetFee(exchangeName string, a asset.Item, cp currency.Pair) decimal.Decimal { if p.exchangeAssetPairSettings == nil { return decimal.Zero } lookup := p.exchangeAssetPairSettings[exchangeName][a][cp] if lookup == nil { return decimal.Zero } return lookup.Fee } // UpdateHoldings updates the portfolio holdings for the data event func (p *Portfolio) UpdateHoldings(ev common.DataEventHandler, funds funding.IPairReader) error { if ev == nil { return common.ErrNilEvent } if funds == nil { return funding.ErrFundsNotFound } lookup, ok := p.exchangeAssetPairSettings[ev.GetExchange()][ev.GetAssetType()][ev.Pair()] if !ok { return fmt.Errorf("%w for %v %v %v", errNoPortfolioSettings, ev.GetExchange(), ev.GetAssetType(), ev.Pair()) } h := lookup.GetLatestHoldings() if h.Timestamp.IsZero() { var err error h, err = holdings.Create(ev, funds) if err != nil { return err } } h.UpdateValue(ev) err := p.setHoldingsForOffset(&h, true) if errors.Is(err, errNoHoldings) { err = p.setHoldingsForOffset(&h, false) } return err } // GetLatestHoldingsForAllCurrencies will return the current holdings for all loaded currencies // this is useful to assess the position of your entire portfolio in order to help with risk decisions func (p *Portfolio) GetLatestHoldingsForAllCurrencies() []holdings.Holding { var resp []holdings.Holding for _, x := range p.exchangeAssetPairSettings { for _, y := range x { for _, z := range y { holds := z.GetLatestHoldings() if !holds.Timestamp.IsZero() { resp = append(resp, holds) } } } } return resp } func (p *Portfolio) setHoldingsForOffset(h *holdings.Holding, overwriteExisting bool) error { if h.Timestamp.IsZero() { return errHoldingsNoTimestamp } lookup, ok := p.exchangeAssetPairSettings[h.Exchange][h.Asset][h.Pair] if !ok { return fmt.Errorf("%w for %v %v %v", errNoPortfolioSettings, h.Exchange, h.Asset, h.Pair) } if overwriteExisting && len(lookup.HoldingsSnapshots) == 0 { return errNoHoldings } for i := len(lookup.HoldingsSnapshots) - 1; i >= 0; i-- { if lookup.HoldingsSnapshots[i].Offset == h.Offset { if overwriteExisting { lookup.HoldingsSnapshots[i] = *h return nil } return errHoldingsAlreadySet } } if overwriteExisting { return fmt.Errorf("%w at %v", errNoHoldings, h.Timestamp) } lookup.HoldingsSnapshots = append(lookup.HoldingsSnapshots, *h) return nil } // ViewHoldingAtTimePeriod retrieves a snapshot of holdings at a specific time period, // returning empty when not found func (p *Portfolio) ViewHoldingAtTimePeriod(ev common.EventHandler) (*holdings.Holding, error) { exchangeAssetPairSettings := p.exchangeAssetPairSettings[ev.GetExchange()][ev.GetAssetType()][ev.Pair()] if exchangeAssetPairSettings == nil { return nil, fmt.Errorf("%w for %v %v %v", errNoHoldings, ev.GetExchange(), ev.GetAssetType(), ev.Pair()) } for i := len(exchangeAssetPairSettings.HoldingsSnapshots) - 1; i >= 0; i-- { if ev.GetTime().Equal(exchangeAssetPairSettings.HoldingsSnapshots[i].Timestamp) { return &exchangeAssetPairSettings.HoldingsSnapshots[i], nil } } return nil, fmt.Errorf("%w for %v %v %v at %v", errNoHoldings, ev.GetExchange(), ev.GetAssetType(), ev.Pair(), ev.GetTime()) } // SetupCurrencySettingsMap ensures a map is created and no panics happen func (p *Portfolio) SetupCurrencySettingsMap(settings *exchange.Settings) (*Settings, error) { if settings == nil { return nil, errNoPortfolioSettings } if settings.Exchange == "" { return nil, errExchangeUnset } if settings.Asset == "" { return nil, errAssetUnset } if settings.Pair.IsEmpty() { return nil, errCurrencyPairUnset } if p.exchangeAssetPairSettings == nil { p.exchangeAssetPairSettings = make(map[string]map[asset.Item]map[currency.Pair]*Settings) } if p.exchangeAssetPairSettings[settings.Exchange] == nil { p.exchangeAssetPairSettings[settings.Exchange] = make(map[asset.Item]map[currency.Pair]*Settings) } if p.exchangeAssetPairSettings[settings.Exchange][settings.Asset] == nil { p.exchangeAssetPairSettings[settings.Exchange][settings.Asset] = make(map[currency.Pair]*Settings) } if _, ok := p.exchangeAssetPairSettings[settings.Exchange][settings.Asset][settings.Pair]; !ok { p.exchangeAssetPairSettings[settings.Exchange][settings.Asset][settings.Pair] = &Settings{} } return p.exchangeAssetPairSettings[settings.Exchange][settings.Asset][settings.Pair], nil } // GetLatestHoldings returns the latest holdings after being sorted by time func (e *Settings) GetLatestHoldings() holdings.Holding { if len(e.HoldingsSnapshots) == 0 { return holdings.Holding{} } return e.HoldingsSnapshots[len(e.HoldingsSnapshots)-1] } // GetHoldingsForTime returns the holdings for a time period, or an empty holding if not found func (e *Settings) GetHoldingsForTime(t time.Time) holdings.Holding { if e.HoldingsSnapshots == nil { // no holdings yet return holdings.Holding{} } for i := len(e.HoldingsSnapshots) - 1; i >= 0; i-- { if e.HoldingsSnapshots[i].Timestamp.Equal(t) { return e.HoldingsSnapshots[i] } } return holdings.Holding{} } <file_sep>package ftx import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "math" "net/http" "net/url" "strconv" "strings" "time" "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/crypto" "github.com/idoall/gocryptotrader/currency" exchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/exchanges/request" ) // FTX is the overarching type across this package type FTX struct { exchange.Base } const ( ftxAPIURL = "https://ftx.com/api" // Public endpoints getMarkets = "/markets" getMarket = "/markets/" getOrderbook = "/markets/%s/orderbook?depth=%s" getTrades = "/markets/%s/trades" getHistoricalData = "/markets/%s/candles" getFutures = "/futures" getFuture = "/futures/" getFutureStats = "/futures/%s/stats" getFundingRates = "/funding_rates" getIndexWeights = "/indexes/%s/weights" getAllWalletBalances = "/wallet/all_balances" getIndexCandles = "/indexes/%s/candles" // Authenticated endpoints getAccountInfo = "/account" getPositions = "/positions" setLeverage = "/account/leverage" getCoins = "/wallet/coins" getBalances = "/wallet/balances" getDepositAddress = "/wallet/deposit_address/" getDepositHistory = "/wallet/deposits" getWithdrawalHistory = "/wallet/withdrawals" withdrawRequest = "/wallet/withdrawals" getOpenOrders = "/orders" getOrderHistory = "/orders/history" getOpenTriggerOrders = "/conditional_orders" getTriggerOrderTriggers = "/conditional_orders/%s/triggers" getTriggerOrderHistory = "/conditional_orders/history" placeOrder = "/orders" placeTriggerOrder = "/conditional_orders" modifyOrder = "/orders/%s/modify" modifyOrderByClientID = "/orders/by_client_id/%s/modify" modifyTriggerOrder = "/conditional_orders/%s/modify" getOrderStatus = "/orders/" getOrderStatusByClientID = "/orders/by_client_id/" deleteOrder = "/orders/" deleteOrderByClientID = "/orders/by_client_id/" cancelTriggerOrder = "/conditional_orders/" getFills = "/fills" getFundingPayments = "/funding_payments" getLeveragedTokens = "/lt/tokens" getTokenInfo = "/lt/" getLTBalances = "/lt/balances" getLTCreations = "/lt/creations" requestLTCreation = "/lt/%s/create" getLTRedemptions = "/lt/redemptions" requestLTRedemption = "/lt/%s/redeem" getListQuotes = "/options/requests" getMyQuotesRequests = "/options/my_requests" createQuoteRequest = "/options/requests" deleteQuote = "/options/requests/" endpointQuote = "/options/requests/%s/quotes" getMyQuotes = "/options/my_quotes" deleteMyQuote = "/options/quotes/" acceptQuote = "/options/quotes/%s/accept" getOptionsInfo = "/options/account_info" getOptionsPositions = "/options/positions" getPublicOptionsTrades = "/options/trades" getOptionsFills = "/options/fills" requestOTCQuote = "/otc/quotes" getOTCQuoteStatus = "/otc/quotes/" acceptOTCQuote = "/otc/quotes/%s/accept" subaccounts = "/subaccounts" subaccountsUpdateName = "/subaccounts/update_name" subaccountsBalance = "/subaccounts/%s/balances" subaccountsTransfer = "/subaccounts/transfer" // Margin Endpoints marginBorrowRates = "/spot_margin/borrow_rates" marginLendingRates = "/spot_margin/lending_rates" marginLendingHistory = "/spot_margin/history" dailyBorrowedAmounts = "/spot_margin/borrow_summary" marginMarketInfo = "/spot_margin/market_info?market=%s" marginBorrowHistory = "/spot_margin/borrow_history" marginLendHistory = "/spot_margin/lending_history" marginLendingOffers = "/spot_margin/offers" marginLendingInfo = "/spot_margin/lending_info" submitLendingOrder = "/spot_margin/offers" // Staking endpoints stakes = "/staking/stakes" unstakeRequests = "/staking/unstake_requests" stakeBalances = "/staking/balances" stakingRewards = "/staking/staking_rewards" serumStakes = "/srm_stakes/stakes" // Other Consts trailingStopOrderType = "trailingStop" takeProfitOrderType = "takeProfit" closedStatus = "closed" spotString = "spot" futuresString = "future" ratePeriod = time.Second rateLimit = 30 ) var ( errInvalidOrderID = errors.New("invalid order ID") errStartTimeCannotBeAfterEndTime = errors.New("start timestamp cannot be after end timestamp") errSubaccountNameMustBeSpecified = errors.New("a subaccount name must be specified") errSubaccountUpdateNameInvalid = errors.New("invalid subaccount old/new name") errCoinMustBeSpecified = errors.New("a coin must be specified") errSubaccountTransferSizeGreaterThanZero = errors.New("transfer size must be greater than 0") errSubaccountTransferSourceDestinationMustNotBeEqual = errors.New("subaccount transfer source and destination must not be the same value") errUnrecognisedOrderStatus = errors.New("unrecognised order status received") errInvalidOrderAmounts = errors.New("filled amount should not exceed order amount") validResolutionData = []int64{15, 60, 300, 900, 3600, 14400, 86400} ) // GetHistoricalIndex gets historical index data func (f *FTX) GetHistoricalIndex(ctx context.Context, indexName string, resolution int64, startTime, endTime time.Time) ([]OHLCVData, error) { params := url.Values{} if indexName == "" { return nil, errors.New("indexName is a mandatory field") } params.Set("index_name", indexName) err := checkResolution(resolution) if err != nil { return nil, err } params.Set("resolution", strconv.FormatInt(resolution, 10)) if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } resp := struct { Data []OHLCVData `json:"result"` }{} endpoint := common.EncodeURLValues(fmt.Sprintf(getIndexCandles, indexName), params) return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, endpoint, &resp) } func checkResolution(res int64) error { for x := range validResolutionData { if validResolutionData[x] == res { return nil } } return errors.New("resolution data is a mandatory field and the data provided is invalid") } // GetMarkets gets market data func (f *FTX) GetMarkets(ctx context.Context) ([]MarketData, error) { resp := struct { Data []MarketData `json:"result"` }{} return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, getMarkets, &resp) } // GetMarket gets market data for a provided asset type func (f *FTX) GetMarket(ctx context.Context, marketName string) (MarketData, error) { resp := struct { Data MarketData `json:"result"` }{} return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, getMarket+marketName, &resp) } // GetOrderbook gets orderbook for a given market with a given depth (default depth 20) func (f *FTX) GetOrderbook(ctx context.Context, marketName string, depth int64) (OrderbookData, error) { result := struct { Data TempOBData `json:"result"` }{} strDepth := "20" // If we send a zero value we get zero asks from the // endpoint if depth != 0 { strDepth = strconv.FormatInt(depth, 10) } var resp OrderbookData err := f.SendHTTPRequest(ctx, exchange.RestSpot, fmt.Sprintf(getOrderbook, marketName, strDepth), &result) if err != nil { return resp, err } resp.MarketName = marketName for x := range result.Data.Asks { resp.Asks = append(resp.Asks, OData{ Price: result.Data.Asks[x][0], Size: result.Data.Asks[x][1], }) } for y := range result.Data.Bids { resp.Bids = append(resp.Bids, OData{ Price: result.Data.Bids[y][0], Size: result.Data.Bids[y][1], }) } return resp, nil } // GetTrades gets trades based on the conditions specified func (f *FTX) GetTrades(ctx context.Context, marketName string, startTime, endTime, limit int64) ([]TradeData, error) { if marketName == "" { return nil, errors.New("a market pair must be specified") } params := url.Values{} if limit != 0 { params.Set("limit", strconv.FormatInt(limit, 10)) } if startTime > 0 && endTime > 0 { if startTime >= (endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime, 10)) params.Set("end_time", strconv.FormatInt(endTime, 10)) } resp := struct { Data []TradeData `json:"result"` }{} endpoint := common.EncodeURLValues(fmt.Sprintf(getTrades, marketName), params) return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, endpoint, &resp) } // GetHistoricalData gets historical OHLCV data for a given market pair func (f *FTX) GetHistoricalData(ctx context.Context, marketName string, timeInterval, limit int64, startTime, endTime time.Time) ([]OHLCVData, error) { if marketName == "" { return nil, errors.New("a market pair must be specified") } err := checkResolution(timeInterval) if err != nil { return nil, err } params := url.Values{} params.Set("resolution", strconv.FormatInt(timeInterval, 10)) if limit != 0 { params.Set("limit", strconv.FormatInt(limit, 10)) } if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } resp := struct { Data []OHLCVData `json:"result"` }{} endpoint := common.EncodeURLValues(fmt.Sprintf(getHistoricalData, marketName), params) return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, endpoint, &resp) } // GetFutures gets data on futures func (f *FTX) GetFutures(ctx context.Context) ([]FuturesData, error) { resp := struct { Data []FuturesData `json:"result"` }{} return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, getFutures, &resp) } // GetFuture gets data on a given future func (f *FTX) GetFuture(ctx context.Context, futureName string) (FuturesData, error) { resp := struct { Data FuturesData `json:"result"` }{} return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, getFuture+futureName, &resp) } // GetFutureStats gets data on a given future's stats func (f *FTX) GetFutureStats(ctx context.Context, futureName string) (FutureStatsData, error) { resp := struct { Data FutureStatsData `json:"result"` }{} return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, fmt.Sprintf(getFutureStats, futureName), &resp) } // GetFundingRates gets data on funding rates func (f *FTX) GetFundingRates(ctx context.Context, startTime, endTime time.Time, future string) ([]FundingRatesData, error) { resp := struct { Data []FundingRatesData `json:"result"` }{} params := url.Values{} if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return resp.Data, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } if future != "" { params.Set("future", future) } endpoint := common.EncodeURLValues(getFundingRates, params) return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, endpoint, &resp) } // GetIndexWeights gets index weights func (f *FTX) GetIndexWeights(ctx context.Context, index string) (IndexWeights, error) { var resp IndexWeights return resp, f.SendHTTPRequest(ctx, exchange.RestSpot, fmt.Sprintf(getIndexWeights, index), &resp) } // SendHTTPRequest sends an unauthenticated HTTP request func (f *FTX) SendHTTPRequest(ctx context.Context, ep exchange.URL, path string, result interface{}) error { endpoint, err := f.API.Endpoints.GetURL(ep) if err != nil { return err } item := &request.Item{ Method: http.MethodGet, Path: endpoint + path, Result: result, Verbose: f.Verbose, HTTPDebugging: f.HTTPDebugging, HTTPRecording: f.HTTPRecording, } return f.SendPayload(ctx, request.Unset, func() (*request.Item, error) { return item, nil }) } // GetMarginBorrowRates gets borrowing rates for margin trading func (f *FTX) GetMarginBorrowRates(ctx context.Context) ([]MarginFundingData, error) { r := struct { Data []MarginFundingData `json:"result"` }{} return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginBorrowRates, nil, &r) } // GetMarginLendingRates gets lending rates for margin trading func (f *FTX) GetMarginLendingRates(ctx context.Context) ([]MarginFundingData, error) { r := struct { Data []MarginFundingData `json:"result"` }{} return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginLendingRates, nil, &r) } // MarginDailyBorrowedAmounts gets daily borrowed amounts for margin func (f *FTX) MarginDailyBorrowedAmounts(ctx context.Context) ([]MarginDailyBorrowStats, error) { r := struct { Data []MarginDailyBorrowStats `json:"result"` }{} return r.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, dailyBorrowedAmounts, &r) } // GetMarginMarketInfo gets margin market data func (f *FTX) GetMarginMarketInfo(ctx context.Context, market string) ([]MarginMarketInfo, error) { r := struct { Data []MarginMarketInfo `json:"result"` }{} return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, fmt.Sprintf(marginMarketInfo, market), nil, &r) } // GetMarginBorrowHistory gets the margin borrow history data func (f *FTX) GetMarginBorrowHistory(ctx context.Context, startTime, endTime time.Time) ([]MarginTransactionHistoryData, error) { r := struct { Data []MarginTransactionHistoryData `json:"result"` }{} params := url.Values{} if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } endpoint := common.EncodeURLValues(marginBorrowHistory, params) return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &r) } // GetMarginMarketLendingHistory gets the markets margin lending rate history func (f *FTX) GetMarginMarketLendingHistory(ctx context.Context, coin currency.Code, startTime, endTime time.Time) ([]MarginTransactionHistoryData, error) { r := struct { Data []MarginTransactionHistoryData `json:"result"` }{} params := url.Values{} if !coin.IsEmpty() { params.Set("coin", coin.Upper().String()) } if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } endpoint := common.EncodeURLValues(marginLendingHistory, params) return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, params, &r) } // GetMarginLendingHistory gets margin lending history func (f *FTX) GetMarginLendingHistory(ctx context.Context, coin currency.Code, startTime, endTime time.Time) ([]MarginTransactionHistoryData, error) { r := struct { Data []MarginTransactionHistoryData `json:"result"` }{} params := url.Values{} if !coin.IsEmpty() { params.Set("coin", coin.Upper().String()) } if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } endpoint := common.EncodeURLValues(marginLendHistory, params) return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginLendHistory, endpoint, &r) } // GetMarginLendingOffers gets margin lending offers func (f *FTX) GetMarginLendingOffers(ctx context.Context) ([]LendingOffersData, error) { r := struct { Data []LendingOffersData `json:"result"` }{} return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginLendingOffers, nil, &r) } // GetLendingInfo gets margin lending info func (f *FTX) GetLendingInfo(ctx context.Context) ([]LendingInfoData, error) { r := struct { Data []LendingInfoData `json:"result"` }{} return r.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, marginLendingInfo, nil, &r) } // SubmitLendingOffer submits an offer for margin lending func (f *FTX) SubmitLendingOffer(ctx context.Context, coin currency.Code, size, rate float64) error { resp := struct { Result string `json:"result"` Success bool `json:"success"` }{} req := make(map[string]interface{}) req["coin"] = coin.Upper().String() req["size"] = size req["rate"] = rate if err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, marginLendingOffers, req, &resp); err != nil { return err } if !resp.Success { return errors.New(resp.Result) } return nil } // GetAccountInfo gets account info func (f *FTX) GetAccountInfo(ctx context.Context) (AccountInfoData, error) { resp := struct { Data AccountInfoData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getAccountInfo, nil, &resp) } // GetPositions gets the users positions func (f *FTX) GetPositions(ctx context.Context) ([]PositionData, error) { resp := struct { Data []PositionData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getPositions, nil, &resp) } // ChangeAccountLeverage changes default leverage used by account func (f *FTX) ChangeAccountLeverage(ctx context.Context, leverage float64) error { req := make(map[string]interface{}) req["leverage"] = leverage return f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, setLeverage, req, nil) } // GetCoins gets coins' data in the account wallet func (f *FTX) GetCoins(ctx context.Context) ([]WalletCoinsData, error) { resp := struct { Data []WalletCoinsData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getCoins, nil, &resp) } // GetBalances gets balances of the account func (f *FTX) GetBalances(ctx context.Context) ([]WalletBalance, error) { resp := struct { Data []WalletBalance `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getBalances, nil, &resp) } // GetAllWalletBalances gets all wallets' balances func (f *FTX) GetAllWalletBalances(ctx context.Context) (AllWalletBalances, error) { resp := struct { Data AllWalletBalances `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getAllWalletBalances, nil, &resp) } // FetchDepositAddress gets deposit address for a given coin func (f *FTX) FetchDepositAddress(ctx context.Context, coin currency.Code, chain string) (*DepositData, error) { resp := struct { Data DepositData `json:"result"` }{} vals := url.Values{} if chain != "" { vals.Set("method", strings.ToLower(chain)) } path := common.EncodeURLValues(getDepositAddress+coin.Upper().String(), vals) return &resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, path, nil, &resp) } // FetchDepositHistory gets deposit history func (f *FTX) FetchDepositHistory(ctx context.Context) ([]DepositItem, error) { resp := struct { Data []DepositItem `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getDepositHistory, nil, &resp) } // FetchWithdrawalHistory gets withdrawal history func (f *FTX) FetchWithdrawalHistory(ctx context.Context) ([]WithdrawItem, error) { resp := struct { Data []WithdrawItem `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getWithdrawalHistory, nil, &resp) } // Withdraw sends a withdrawal request func (f *FTX) Withdraw(ctx context.Context, coin currency.Code, address, tag, password, chain, code string, size float64) (*WithdrawItem, error) { if coin.IsEmpty() || address == "" || size == 0 { return nil, errors.New("coin, address and size must be specified") } req := make(map[string]interface{}) req["coin"] = coin.Upper().String() req["size"] = size req["address"] = address if code != "" { req["code"] = code } if tag != "" { req["tag"] = tag } if password != "" { req["password"] = <PASSWORD> } if chain != "" { req["method"] = chain } resp := struct { Data WithdrawItem `json:"result"` }{} return &resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, withdrawRequest, req, &resp) } // GetOpenOrders gets open orders func (f *FTX) GetOpenOrders(ctx context.Context, marketName string) ([]OrderData, error) { params := url.Values{} if marketName != "" { params.Set("market", marketName) } resp := struct { Data []OrderData `json:"result"` }{} endpoint := common.EncodeURLValues(getOpenOrders, params) return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &resp) } // FetchOrderHistory gets order history func (f *FTX) FetchOrderHistory(ctx context.Context, marketName string, startTime, endTime time.Time, limit string) ([]OrderData, error) { resp := struct { Data []OrderData `json:"result"` }{} params := url.Values{} if marketName != "" { params.Set("market", marketName) } if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return resp.Data, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } if limit != "" { params.Set("limit", limit) } endpoint := common.EncodeURLValues(getOrderHistory, params) return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &resp) } // GetOpenTriggerOrders gets trigger orders that are currently open func (f *FTX) GetOpenTriggerOrders(ctx context.Context, marketName, orderType string) ([]TriggerOrderData, error) { params := url.Values{} if marketName != "" { params.Set("market", marketName) } if orderType != "" { params.Set("type", orderType) } resp := struct { Data []TriggerOrderData `json:"result"` }{} endpoint := common.EncodeURLValues(getOpenTriggerOrders, params) return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &resp) } // GetTriggerOrderTriggers gets trigger orders that are currently open func (f *FTX) GetTriggerOrderTriggers(ctx context.Context, orderID string) ([]TriggerData, error) { resp := struct { Data []TriggerData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, fmt.Sprintf(getTriggerOrderTriggers, orderID), nil, &resp) } // GetTriggerOrderHistory gets trigger orders that are currently open func (f *FTX) GetTriggerOrderHistory(ctx context.Context, marketName string, startTime, endTime time.Time, side, orderType, limit string) ([]TriggerOrderData, error) { params := url.Values{} if marketName != "" { params.Set("market", marketName) } if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } if side != "" { params.Set("side", side) } if orderType != "" { params.Set("type", orderType) } if limit != "" { params.Set("limit", limit) } resp := struct { Data []TriggerOrderData `json:"result"` }{} endpoint := common.EncodeURLValues(getTriggerOrderHistory, params) return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &resp) } // Order places an order func (f *FTX) Order( ctx context.Context, marketName, side, orderType string, reduceOnly, ioc, postOnly bool, clientID string, price, size float64, ) (OrderData, error) { req := make(map[string]interface{}) req["market"] = marketName req["side"] = side req["price"] = price req["type"] = orderType req["size"] = size if reduceOnly { req["reduceOnly"] = reduceOnly } if ioc { req["ioc"] = ioc } if postOnly { req["postOnly"] = postOnly } if clientID != "" { req["clientId"] = clientID } resp := struct { Data OrderData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, placeOrder, req, &resp) } // TriggerOrder places an order func (f *FTX) TriggerOrder(ctx context.Context, marketName, side, orderType, reduceOnly, retryUntilFilled string, size, triggerPrice, orderPrice, trailValue float64) (TriggerOrderData, error) { req := make(map[string]interface{}) req["market"] = marketName req["side"] = side req["type"] = orderType req["size"] = size if reduceOnly != "" { req["reduceOnly"] = reduceOnly } if retryUntilFilled != "" { req["retryUntilFilled"] = retryUntilFilled } if orderType == order.Stop.Lower() || orderType == "" { req["triggerPrice"] = triggerPrice req["orderPrice"] = orderPrice } if orderType == trailingStopOrderType { req["trailValue"] = trailValue } if orderType == takeProfitOrderType { req["triggerPrice"] = triggerPrice req["orderPrice"] = orderPrice } resp := struct { Data TriggerOrderData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, placeTriggerOrder, req, &resp) } // ModifyPlacedOrder modifies a placed order func (f *FTX) ModifyPlacedOrder(ctx context.Context, orderID, clientID string, price, size float64) (OrderData, error) { req := make(map[string]interface{}) req["price"] = price req["size"] = size if clientID != "" { req["clientID"] = clientID } resp := struct { Data OrderData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(modifyOrder, orderID), req, &resp) } // ModifyOrderByClientID modifies a placed order via clientOrderID func (f *FTX) ModifyOrderByClientID(ctx context.Context, clientOrderID, clientID string, price, size float64) (OrderData, error) { req := make(map[string]interface{}) req["price"] = price req["size"] = size if clientID != "" { req["clientID"] = clientID } resp := struct { Data OrderData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(modifyOrderByClientID, clientOrderID), req, &resp) } // ModifyTriggerOrder modifies an existing trigger order // Choices for ordertype include stop, trailingStop, takeProfit func (f *FTX) ModifyTriggerOrder(ctx context.Context, orderID, orderType string, size, triggerPrice, orderPrice, trailValue float64) (TriggerOrderData, error) { req := make(map[string]interface{}) req["size"] = size if orderType == order.Stop.Lower() || orderType == "" { req["triggerPrice"] = triggerPrice req["orderPrice"] = orderPrice } if orderType == trailingStopOrderType { req["trailValue"] = trailValue } if orderType == takeProfitOrderType { req["triggerPrice"] = triggerPrice req["orderPrice"] = orderPrice } resp := struct { Data TriggerOrderData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(modifyTriggerOrder, orderID), req, &resp) } // GetOrderStatus gets the order status of a given orderID func (f *FTX) GetOrderStatus(ctx context.Context, orderID string) (OrderData, error) { resp := struct { Data OrderData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getOrderStatus+orderID, nil, &resp) } // GetOrderStatusByClientID gets the order status of a given clientOrderID func (f *FTX) GetOrderStatusByClientID(ctx context.Context, clientOrderID string) (OrderData, error) { resp := struct { Data OrderData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getOrderStatusByClientID+clientOrderID, nil, &resp) } func (f *FTX) deleteOrderByPath(ctx context.Context, path string) (string, error) { resp := struct { Result string `json:"result"` Success bool `json:"success"` Error string `json:"error"` }{} err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete, path, nil, &resp) // If there is an error reported, but the resp struct reports one of a very few // specific error causes, we still consider this a successful cancellation. if err != nil && !resp.Success && (resp.Error == "Order already closed" || resp.Error == "Order already queued for cancellation") { return resp.Error, nil } return resp.Result, err } // DeleteOrder deletes an order func (f *FTX) DeleteOrder(ctx context.Context, orderID string) (string, error) { if orderID == "" { return "", errInvalidOrderID } return f.deleteOrderByPath(ctx, deleteOrder+orderID) } // DeleteOrderByClientID deletes an order func (f *FTX) DeleteOrderByClientID(ctx context.Context, clientID string) (string, error) { if clientID == "" { return "", errInvalidOrderID } return f.deleteOrderByPath(ctx, deleteOrderByClientID+clientID) } // DeleteTriggerOrder deletes an order func (f *FTX) DeleteTriggerOrder(ctx context.Context, orderID string) (string, error) { if orderID == "" { return "", errInvalidOrderID } return f.deleteOrderByPath(ctx, cancelTriggerOrder+orderID) } // GetFills gets fills' data func (f *FTX) GetFills(ctx context.Context, market, limit string, startTime, endTime time.Time) ([]FillsData, error) { resp := struct { Data []FillsData `json:"result"` }{} params := url.Values{} if market != "" { params.Set("market", market) } if limit != "" { params.Set("limit", limit) } if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return resp.Data, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } endpoint := common.EncodeURLValues(getFills, params) return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &resp) } // GetFundingPayments gets funding payments func (f *FTX) GetFundingPayments(ctx context.Context, startTime, endTime time.Time, future string) ([]FundingPaymentsData, error) { resp := struct { Data []FundingPaymentsData `json:"result"` }{} params := url.Values{} if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return resp.Data, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } if future != "" { params.Set("future", future) } endpoint := common.EncodeURLValues(getFundingPayments, params) return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, endpoint, nil, &resp) } // ListLeveragedTokens lists leveraged tokens func (f *FTX) ListLeveragedTokens(ctx context.Context) ([]LeveragedTokensData, error) { resp := struct { Data []LeveragedTokensData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getLeveragedTokens, nil, &resp) } // GetTokenInfo gets token info func (f *FTX) GetTokenInfo(ctx context.Context, tokenName string) ([]LeveragedTokensData, error) { resp := struct { Data []LeveragedTokensData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getTokenInfo+tokenName, nil, &resp) } // ListLTBalances gets leveraged tokens' balances func (f *FTX) ListLTBalances(ctx context.Context) ([]LTBalanceData, error) { resp := struct { Data []LTBalanceData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getLTBalances, nil, &resp) } // ListLTCreations lists the leveraged tokens' creation requests func (f *FTX) ListLTCreations(ctx context.Context) ([]LTCreationData, error) { resp := struct { Data []LTCreationData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getLTCreations, nil, &resp) } // RequestLTCreation sends a request to create a leveraged token func (f *FTX) RequestLTCreation(ctx context.Context, tokenName string, size float64) (RequestTokenCreationData, error) { req := make(map[string]interface{}) req["size"] = size resp := struct { Data RequestTokenCreationData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(requestLTCreation, tokenName), req, &resp) } // ListLTRedemptions lists the leveraged tokens' redemption requests func (f *FTX) ListLTRedemptions(ctx context.Context) ([]LTRedemptionData, error) { resp := struct { Data []LTRedemptionData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getLTRedemptions, nil, &resp) } // RequestLTRedemption sends a request to redeem a leveraged token func (f *FTX) RequestLTRedemption(ctx context.Context, tokenName string, size float64) (LTRedemptionRequestData, error) { req := make(map[string]interface{}) req["size"] = size resp := struct { Data LTRedemptionRequestData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(requestLTRedemption, tokenName), req, &resp) } // GetQuoteRequests gets a list of quote requests func (f *FTX) GetQuoteRequests(ctx context.Context) ([]QuoteRequestData, error) { resp := struct { Data []QuoteRequestData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getListQuotes, nil, &resp) } // GetYourQuoteRequests gets a list of your quote requests func (f *FTX) GetYourQuoteRequests(ctx context.Context) ([]PersonalQuotesData, error) { resp := struct { Data []PersonalQuotesData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getMyQuotesRequests, nil, &resp) } // CreateQuoteRequest sends a request to create a quote func (f *FTX) CreateQuoteRequest(ctx context.Context, underlying currency.Code, optionType, side string, expiry int64, requestExpiry string, strike, size, limitPrice, counterPartyID float64, hideLimitPrice bool) (CreateQuoteRequestData, error) { req := make(map[string]interface{}) req["underlying"] = underlying.Upper().String() req["type"] = optionType req["side"] = side req["strike"] = strike req["expiry"] = expiry req["size"] = size if limitPrice != 0 { req["limitPrice"] = limitPrice } if requestExpiry != "" { req["requestExpiry"] = requestExpiry } if counterPartyID != 0 { req["counterpartyId"] = counterPartyID } req["hideLimitPrice"] = hideLimitPrice resp := struct { Data CreateQuoteRequestData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, createQuoteRequest, req, &resp) } // DeleteQuote sends request to cancel a quote func (f *FTX) DeleteQuote(ctx context.Context, requestID string) (CancelQuoteRequestData, error) { resp := struct { Data CancelQuoteRequestData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete, deleteQuote+requestID, nil, &resp) } // GetQuotesForYourQuote gets a list of quotes for your quote func (f *FTX) GetQuotesForYourQuote(ctx context.Context, requestID string) (QuoteForQuoteData, error) { var resp QuoteForQuoteData return resp, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, fmt.Sprintf(endpointQuote, requestID), nil, &resp) } // MakeQuote makes a quote for a quote func (f *FTX) MakeQuote(ctx context.Context, requestID, price string) ([]QuoteForQuoteData, error) { params := url.Values{} params.Set("price", price) resp := struct { Data []QuoteForQuoteData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(endpointQuote, requestID), nil, &resp) } // MyQuotes gets a list of my quotes for quotes func (f *FTX) MyQuotes(ctx context.Context) ([]QuoteForQuoteData, error) { resp := struct { Data []QuoteForQuoteData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getMyQuotes, nil, &resp) } // DeleteMyQuote deletes my quote for quotes func (f *FTX) DeleteMyQuote(ctx context.Context, quoteID string) ([]QuoteForQuoteData, error) { resp := struct { Data []QuoteForQuoteData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete, deleteMyQuote+quoteID, nil, &resp) } // AcceptQuote accepts the quote for quote func (f *FTX) AcceptQuote(ctx context.Context, quoteID string) ([]QuoteForQuoteData, error) { resp := struct { Data []QuoteForQuoteData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(acceptQuote, quoteID), nil, &resp) } // GetAccountOptionsInfo gets account's options' info func (f *FTX) GetAccountOptionsInfo(ctx context.Context) (AccountOptionsInfoData, error) { resp := struct { Data AccountOptionsInfoData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getOptionsInfo, nil, &resp) } // GetOptionsPositions gets options' positions func (f *FTX) GetOptionsPositions(ctx context.Context) ([]OptionsPositionsData, error) { resp := struct { Data []OptionsPositionsData `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getOptionsPositions, nil, &resp) } // GetPublicOptionsTrades gets options' trades from public func (f *FTX) GetPublicOptionsTrades(ctx context.Context, startTime, endTime time.Time, limit string) ([]OptionsTradesData, error) { params := url.Values{} if !startTime.IsZero() && !endTime.IsZero() { if startTime.After(endTime) { return nil, errStartTimeCannotBeAfterEndTime } params.Set("start_time", strconv.FormatInt(startTime.Unix(), 10)) params.Set("end_time", strconv.FormatInt(endTime.Unix(), 10)) } if limit != "" { params.Set("limit", limit) } resp := struct { Data []OptionsTradesData `json:"result"` }{} endpoint := common.EncodeURLValues(getPublicOptionsTrades, params) return resp.Data, f.SendHTTPRequest(ctx, exchange.RestSpot, endpoint, &resp) } // GetOptionsFills gets fills data for options func (f *FTX) GetOptionsFills(ctx context.Context, startTime, endTime time.Time, limit string) ([]OptionFillsData, error) { resp := struct { Data []OptionFillsData `json:"result"` }{} req := make(map[string]interface{}) if !startTime.IsZero() && !endTime.IsZero() { req["start_time"] = strconv.FormatInt(startTime.Unix(), 10) req["end_time"] = strconv.FormatInt(endTime.Unix(), 10) if startTime.After(endTime) { return resp.Data, errStartTimeCannotBeAfterEndTime } } if limit != "" { req["limit"] = limit } return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getOptionsFills, req, &resp) } // GetStakes returns a list of staked assets func (f *FTX) GetStakes(ctx context.Context) ([]Stake, error) { resp := struct { Data []Stake `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, stakes, nil, &resp) } // GetUnstakeRequests returns a collection of unstake requests func (f *FTX) GetUnstakeRequests(ctx context.Context) ([]UnstakeRequest, error) { resp := struct { Data []UnstakeRequest `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, unstakeRequests, nil, &resp) } // GetStakeBalances returns a collection of staked coin balances func (f *FTX) GetStakeBalances(ctx context.Context) ([]StakeBalance, error) { resp := struct { Data []StakeBalance `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, stakeBalances, nil, &resp) } // UnstakeRequest unstakes an existing staked coin func (f *FTX) UnstakeRequest(ctx context.Context, coin currency.Code, size float64) (*UnstakeRequest, error) { resp := struct { Data UnstakeRequest `json:"result"` }{} req := make(map[string]interface{}) req["coin"] = coin.Upper().String() req["size"] = strconv.FormatFloat(size, 'f', -1, 64) return &resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, unstakeRequests, req, &resp) } // CancelUnstakeRequest cancels a pending unstake request func (f *FTX) CancelUnstakeRequest(ctx context.Context, requestID int64) (bool, error) { resp := struct { Result string }{} path := unstakeRequests + "/" + strconv.FormatInt(requestID, 10) if err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete, path, nil, &resp); err != nil { return false, err } if resp.Result != "Cancelled" { return false, errors.New("failed to cancel unstake request") } return true, nil } // GetStakingRewards returns a collection of staking rewards func (f *FTX) GetStakingRewards(ctx context.Context) ([]StakeReward, error) { resp := struct { Data []StakeReward `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, stakingRewards, nil, &resp) } // StakeRequest submits a stake request based on the specified currency and size func (f *FTX) StakeRequest(ctx context.Context, coin currency.Code, size float64) (*Stake, error) { resp := struct { Data Stake `json:"result"` }{} req := make(map[string]interface{}) req["coin"] = coin.Upper().String() req["size"] = strconv.FormatFloat(size, 'f', -1, 64) return &resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, serumStakes, req, &resp) } // SendAuthHTTPRequest sends an authenticated request func (f *FTX) SendAuthHTTPRequest(ctx context.Context, ep exchange.URL, method, path string, data, result interface{}) error { if !f.AllowAuthenticatedRequest() { return fmt.Errorf("%s %w", f.Name, exchange.ErrAuthenticatedRequestWithoutCredentialsSet) } endpoint, err := f.API.Endpoints.GetURL(ep) if err != nil { return err } newRequest := func() (*request.Item, error) { ts := strconv.FormatInt(time.Now().UnixMilli(), 10) var body io.Reader var hmac, payload []byte sigPayload := ts + method + "/api" + path if data != nil { payload, err = json.Marshal(data) if err != nil { return nil, err } body = bytes.NewBuffer(payload) sigPayload += string(payload) } hmac, err = crypto.GetHMAC(crypto.HashSHA256, []byte(sigPayload), []byte(f.API.Credentials.Secret)) if err != nil { return nil, err } headers := make(map[string]string) headers["FTX-KEY"] = f.API.Credentials.Key headers["FTX-SIGN"] = crypto.HexEncodeToString(hmac) headers["FTX-TS"] = ts if f.API.Credentials.Subaccount != "" { headers["FTX-SUBACCOUNT"] = url.QueryEscape(f.API.Credentials.Subaccount) } headers["Content-Type"] = "application/json" return &request.Item{ Method: method, Path: endpoint + path, Headers: headers, Body: body, Result: result, AuthRequest: true, Verbose: f.Verbose, HTTPDebugging: f.HTTPDebugging, HTTPRecording: f.HTTPRecording, }, nil } return f.SendPayload(ctx, request.Unset, newRequest) } // GetFee returns an estimate of fee based on type of transaction func (f *FTX) GetFee(ctx context.Context, feeBuilder *exchange.FeeBuilder) (float64, error) { var fee float64 if !f.GetAuthenticatedAPISupport(exchange.RestAuthentication) { feeBuilder.FeeType = exchange.OfflineTradeFee } switch feeBuilder.FeeType { case exchange.OfflineTradeFee: fee = getOfflineTradeFee(feeBuilder) default: feeData, err := f.GetAccountInfo(ctx) if err != nil { return 0, err } switch feeBuilder.IsMaker { case true: fee = feeData.MakerFee * feeBuilder.Amount * feeBuilder.PurchasePrice case false: fee = feeData.TakerFee * feeBuilder.Amount * feeBuilder.PurchasePrice } if fee < 0 { fee = 0 } } return fee, nil } // getOfflineTradeFee calculates the worst case-scenario trading fee func getOfflineTradeFee(feeBuilder *exchange.FeeBuilder) float64 { if feeBuilder.IsMaker { return 0.0002 * feeBuilder.PurchasePrice * feeBuilder.Amount } return 0.0007 * feeBuilder.PurchasePrice * feeBuilder.Amount } func (f *FTX) compatibleOrderVars(ctx context.Context, orderSide, orderStatus, orderType string, amount, filledAmount, avgFillPrice float64) (OrderVars, error) { if filledAmount > amount { return OrderVars{}, fmt.Errorf("%w, amount: %f filled: %f", errInvalidOrderAmounts, amount, filledAmount) } var resp OrderVars switch orderSide { case order.Buy.Lower(): resp.Side = order.Buy case order.Sell.Lower(): resp.Side = order.Sell } switch orderStatus { case strings.ToLower(order.New.String()): resp.Status = order.New case strings.ToLower(order.Open.String()): resp.Status = order.Open case closedStatus: switch { case filledAmount <= 0: // Order is closed with a filled amount of 0, which means it's // cancelled. resp.Status = order.Cancelled case math.Abs(filledAmount-amount) > 1e-6: // Order is closed with filledAmount above 0, but not equal to the // full amount, which means it's partially executed and then // cancelled. resp.Status = order.PartiallyCancelled default: // Order is closed and filledAmount == amount, which means it's // fully executed. resp.Status = order.Filled } default: return resp, fmt.Errorf("%w %s", errUnrecognisedOrderStatus, orderStatus) } var feeBuilder exchange.FeeBuilder feeBuilder.PurchasePrice = avgFillPrice feeBuilder.Amount = amount resp.OrderType = order.Market if strings.EqualFold(orderType, order.Limit.String()) { resp.OrderType = order.Limit feeBuilder.IsMaker = true } fee, err := f.GetFee(ctx, &feeBuilder) if err != nil { return resp, err } resp.Fee = fee return resp, nil } // RequestForQuotes requests for otc quotes func (f *FTX) RequestForQuotes(ctx context.Context, base, quote currency.Code, amount float64) (RequestQuoteData, error) { resp := struct { Data RequestQuoteData `json:"result"` }{} req := make(map[string]interface{}) req["fromCoin"] = base.Upper().String() req["toCoin"] = quote.Upper().String() req["size"] = amount return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, requestOTCQuote, req, &resp) } // GetOTCQuoteStatus gets quote status of a quote func (f *FTX) GetOTCQuoteStatus(ctx context.Context, marketName, quoteID string) (*QuoteStatusData, error) { resp := struct { Data QuoteStatusData `json:"result"` }{} params := url.Values{} params.Set("market", marketName) return &resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, getOTCQuoteStatus+quoteID, params, &resp) } // AcceptOTCQuote requests for otc quotes func (f *FTX) AcceptOTCQuote(ctx context.Context, quoteID string) error { return f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, fmt.Sprintf(acceptOTCQuote, quoteID), nil, nil) } // GetSubaccounts returns the users subaccounts func (f *FTX) GetSubaccounts(ctx context.Context) ([]Subaccount, error) { resp := struct { Data []Subaccount `json:"result"` }{} return resp.Data, f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, subaccounts, nil, &resp) } // CreateSubaccount creates a new subaccount func (f *FTX) CreateSubaccount(ctx context.Context, name string) (*Subaccount, error) { if name == "" { return nil, errSubaccountNameMustBeSpecified } d := make(map[string]string) d["nickname"] = name resp := struct { Data Subaccount `json:"result"` }{} if err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, subaccounts, d, &resp); err != nil { return nil, err } return &resp.Data, nil } // UpdateSubaccountName updates an existing subaccount name func (f *FTX) UpdateSubaccountName(ctx context.Context, oldName, newName string) (*Subaccount, error) { if oldName == "" || newName == "" || oldName == newName { return nil, errSubaccountUpdateNameInvalid } d := make(map[string]string) d["nickname"] = oldName d["newNickname"] = newName resp := struct { Data Subaccount `json:"result"` }{} if err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, subaccountsUpdateName, d, &resp); err != nil { return nil, err } return &resp.Data, nil } // DeleteSubaccount deletes the specified subaccount name func (f *FTX) DeleteSubaccount(ctx context.Context, name string) error { if name == "" { return errSubaccountNameMustBeSpecified } d := make(map[string]string) d["nickname"] = name resp := struct { Data Subaccount `json:"result"` }{} return f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete, subaccounts, d, &resp) } // SubaccountBalances returns the user's subaccount balances func (f *FTX) SubaccountBalances(ctx context.Context, name string) ([]SubaccountBalance, error) { if name == "" { return nil, errSubaccountNameMustBeSpecified } resp := struct { Data []SubaccountBalance `json:"result"` }{} if err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, fmt.Sprintf(subaccountsBalance, name), nil, &resp); err != nil { return nil, err } return resp.Data, nil } // SubaccountTransfer transfers a desired coin to the specified subaccount func (f *FTX) SubaccountTransfer(ctx context.Context, coin currency.Code, source, destination string, size float64) (*SubaccountTransferStatus, error) { if coin.IsEmpty() { return nil, errCoinMustBeSpecified } if size <= 0 { return nil, errSubaccountTransferSizeGreaterThanZero } if source == destination { return nil, errSubaccountTransferSourceDestinationMustNotBeEqual } d := make(map[string]interface{}) d["coin"] = coin.Upper().String() d["size"] = size if source == "" { source = "main" } d["source"] = source if destination == "" { destination = "main" } d["destination"] = destination resp := struct { Data SubaccountTransferStatus `json:"result"` }{} if err := f.SendAuthHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, subaccountsTransfer, d, &resp); err != nil { return nil, err } return &resp.Data, nil } // FetchExchangeLimits fetches spot order execution limits func (f *FTX) FetchExchangeLimits(ctx context.Context) ([]order.MinMaxLevel, error) { data, err := f.GetMarkets(ctx) if err != nil { return nil, err } var limits []order.MinMaxLevel for x := range data { if !data[x].Enabled { continue } var cp currency.Pair var a asset.Item switch data[x].MarketType { case "future": a = asset.Futures cp, err = currency.NewPairFromString(data[x].Name) if err != nil { return nil, err } case "spot": a = asset.Spot cp, err = currency.NewPairFromStrings(data[x].BaseCurrency, data[x].QuoteCurrency) if err != nil { return nil, err } default: return nil, fmt.Errorf("unhandled data type %s, cannot process exchange limit", data[x].MarketType) } limits = append(limits, order.MinMaxLevel{ Pair: cp, Asset: a, StepPrice: data[x].PriceIncrement, StepAmount: data[x].SizeIncrement, MinAmount: data[x].MinProvideSize, }) } return limits, nil } <file_sep>package event import ( "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/kline" ) // GetOffset returns the offset func (b *Base) GetOffset() int64 { return b.Offset } // SetOffset sets the offset func (b *Base) SetOffset(o int64) { b.Offset = o } // IsEvent returns whether the event is an event func (b *Base) IsEvent() bool { return true } // GetTime returns the time func (b *Base) GetTime() time.Time { return b.Time } // Pair returns the currency pair func (b *Base) Pair() currency.Pair { return b.CurrencyPair } // GetExchange returns the exchange func (b *Base) GetExchange() string { return b.Exchange } // GetAssetType returns the asset type func (b *Base) GetAssetType() asset.Item { return b.AssetType } // GetInterval returns the interval func (b *Base) GetInterval() kline.Interval { return b.Interval } // AppendReason adds reasoning for a decision being made func (b *Base) AppendReason(y string) { if b.Reason == "" { b.Reason = y } else { b.Reason = y + ". " + b.Reason } } // GetReason returns the why func (b *Base) GetReason() string { return b.Reason } <file_sep>package btcmarkets import ( "encoding/json" "errors" "fmt" "net/http" "strconv" "time" "github.com/gorilla/websocket" "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/crypto" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/exchanges/orderbook" "github.com/idoall/gocryptotrader/exchanges/stream" "github.com/idoall/gocryptotrader/exchanges/stream/buffer" "github.com/idoall/gocryptotrader/exchanges/ticker" "github.com/idoall/gocryptotrader/exchanges/trade" "github.com/idoall/gocryptotrader/log" ) const ( btcMarketsWSURL = "wss://socket.btcmarkets.net/v2" ) // WsConnect connects to a websocket feed func (b *BTCMarkets) WsConnect() error { if !b.Websocket.IsEnabled() || !b.IsEnabled() { return errors.New(stream.WebsocketNotEnabled) } var dialer websocket.Dialer err := b.Websocket.Conn.Dial(&dialer, http.Header{}) if err != nil { return err } if b.Verbose { log.Debugf(log.ExchangeSys, "%s Connected to Websocket.\n", b.Name) } b.Websocket.Wg.Add(1) go b.wsReadData() return nil } // wsReadData receives and passes on websocket messages for processing func (b *BTCMarkets) wsReadData() { defer b.Websocket.Wg.Done() for { resp := b.Websocket.Conn.ReadMessage() if resp.Raw == nil { return } err := b.wsHandleData(resp.Raw) if err != nil { b.Websocket.DataHandler <- err } } } func (b *BTCMarkets) wsHandleData(respRaw []byte) error { var wsResponse WsMessageType err := json.Unmarshal(respRaw, &wsResponse) if err != nil { return err } switch wsResponse.MessageType { case heartbeat: if b.Verbose { log.Debugf(log.ExchangeSys, "%v - Websocket heartbeat received %s", b.Name, respRaw) } case wsOB: var ob WsOrderbook err := json.Unmarshal(respRaw, &ob) if err != nil { return err } p, err := currency.NewPairFromString(ob.Currency) if err != nil { return err } var bids, asks orderbook.Items for x := range ob.Bids { var price, amount float64 price, err = strconv.ParseFloat(ob.Bids[x][0].(string), 64) if err != nil { return err } amount, err = strconv.ParseFloat(ob.Bids[x][1].(string), 64) if err != nil { return err } bids = append(bids, orderbook.Item{ Amount: amount, Price: price, OrderCount: int64(ob.Bids[x][2].(float64)), }) } for x := range ob.Asks { var price, amount float64 price, err = strconv.ParseFloat(ob.Asks[x][0].(string), 64) if err != nil { return err } amount, err = strconv.ParseFloat(ob.Asks[x][1].(string), 64) if err != nil { return err } asks = append(asks, orderbook.Item{ Amount: amount, Price: price, OrderCount: int64(ob.Asks[x][2].(float64)), }) } if ob.Snapshot { bids.SortBids() // Alignment completely out, sort is needed. err = b.Websocket.Orderbook.LoadSnapshot(&orderbook.Base{ Pair: p, Bids: bids, Asks: asks, LastUpdated: ob.Timestamp, Asset: asset.Spot, Exchange: b.Name, VerifyOrderbook: b.CanVerifyOrderbook, }) } else { err = b.Websocket.Orderbook.Update(&buffer.Update{ UpdateTime: ob.Timestamp, Asset: asset.Spot, Bids: bids, Asks: asks, Pair: p, }) } if err != nil { return err } case tradeEndPoint: if !b.IsSaveTradeDataEnabled() { return nil } var t WsTrade err := json.Unmarshal(respRaw, &t) if err != nil { return err } p, err := currency.NewPairFromString(t.Currency) if err != nil { return err } side := order.Buy if t.Side == "Ask" { side = order.Sell } return trade.AddTradesToBuffer(b.Name, trade.Data{ Timestamp: t.Timestamp, CurrencyPair: p, AssetType: asset.Spot, Exchange: b.Name, Price: t.Price, Amount: t.Volume, Side: side, TID: strconv.FormatInt(t.TradeID, 10), }) case tick: var tick WsTick err := json.Unmarshal(respRaw, &tick) if err != nil { return err } p, err := currency.NewPairFromString(tick.Currency) if err != nil { return err } b.Websocket.DataHandler <- &ticker.Price{ ExchangeName: b.Name, Volume: tick.Volume, High: tick.High24, Low: tick.Low24h, Bid: tick.Bid, Ask: tick.Ask, Last: tick.Last, LastUpdated: tick.Timestamp, AssetType: asset.Spot, Pair: p, } case fundChange: var transferData WsFundTransfer err := json.Unmarshal(respRaw, &transferData) if err != nil { return err } b.Websocket.DataHandler <- transferData case orderChange: var orderData WsOrderChange err := json.Unmarshal(respRaw, &orderData) if err != nil { return err } originalAmount := orderData.OpenVolume var price float64 var trades []order.TradeHistory var orderID = strconv.FormatInt(orderData.OrderID, 10) for x := range orderData.Trades { var isMaker bool if orderData.Trades[x].LiquidityType == "Maker" { isMaker = true } trades = append(trades, order.TradeHistory{ Price: orderData.Trades[x].Price, Amount: orderData.Trades[x].Volume, Fee: orderData.Trades[x].Fee, Exchange: b.Name, TID: strconv.FormatInt(orderData.Trades[x].TradeID, 10), IsMaker: isMaker, }) price = orderData.Trades[x].Price originalAmount += orderData.Trades[x].Volume } oType, err := order.StringToOrderType(orderData.OrderType) if err != nil { b.Websocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: orderID, Err: err, } } oSide, err := order.StringToOrderSide(orderData.Side) if err != nil { b.Websocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: orderID, Err: err, } } oStatus, err := order.StringToOrderStatus(orderData.Status) if err != nil { b.Websocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: orderID, Err: err, } } p, err := currency.NewPairFromString(orderData.MarketID) if err != nil { b.Websocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: orderID, Err: err, } } b.Websocket.DataHandler <- &order.Detail{ Price: price, Amount: originalAmount, RemainingAmount: orderData.OpenVolume, Exchange: b.Name, ID: orderID, ClientID: b.API.Credentials.ClientID, Type: oType, Side: oSide, Status: oStatus, AssetType: asset.Spot, Date: orderData.Timestamp, Trades: trades, Pair: p, } case "error": var wsErr WsError err := json.Unmarshal(respRaw, &wsErr) if err != nil { return err } return fmt.Errorf("%v websocket error. Code: %v Message: %v", b.Name, wsErr.Code, wsErr.Message) default: b.Websocket.DataHandler <- stream.UnhandledMessageWarning{Message: b.Name + stream.UnhandledMessage + string(respRaw)} return nil } return nil } func (b *BTCMarkets) generateDefaultSubscriptions() ([]stream.ChannelSubscription, error) { var channels = []string{wsOB, tick, tradeEndPoint} enabledCurrencies, err := b.GetEnabledPairs(asset.Spot) if err != nil { return nil, err } var subscriptions []stream.ChannelSubscription for i := range channels { for j := range enabledCurrencies { subscriptions = append(subscriptions, stream.ChannelSubscription{ Channel: channels[i], Currency: enabledCurrencies[j], Asset: asset.Spot, }) } } var authChannels = []string{fundChange, heartbeat, orderChange} if b.Websocket.CanUseAuthenticatedEndpoints() { for i := range authChannels { subscriptions = append(subscriptions, stream.ChannelSubscription{ Channel: authChannels[i], }) } } return subscriptions, nil } // Subscribe sends a websocket message to receive data from the channel func (b *BTCMarkets) Subscribe(channelsToSubscribe []stream.ChannelSubscription) error { var authChannels = []string{fundChange, heartbeat, orderChange} var payload WsSubscribe payload.MessageType = subscribe for i := range channelsToSubscribe { payload.Channels = append(payload.Channels, channelsToSubscribe[i].Channel) if channelsToSubscribe[i].Currency.String() != "" { if !common.StringDataCompare(payload.MarketIDs, channelsToSubscribe[i].Currency.String()) { payload.MarketIDs = append(payload.MarketIDs, channelsToSubscribe[i].Currency.String()) } } } for i := range authChannels { if !common.StringDataCompare(payload.Channels, authChannels[i]) { continue } signTime := strconv.FormatInt(time.Now().UnixMilli(), 10) strToSign := "/users/self/subscribe" + "\n" + signTime tempSign, err := crypto.GetHMAC(crypto.HashSHA512, []byte(strToSign), []byte(b.API.Credentials.Secret)) if err != nil { return err } sign := crypto.Base64Encode(tempSign) payload.Key = b.API.Credentials.Key payload.Signature = sign payload.Timestamp = signTime break } err := b.Websocket.Conn.SendJSONMessage(payload) if err != nil { return err } b.Websocket.AddSuccessfulSubscriptions(channelsToSubscribe...) return nil } <file_sep>package binance import ( "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/order" ) const ( // perpetualApiURL = "https://dapi.binance.com" // futureApiURL = "https://fapi.binance.com" // binanceAPIVersion = "1" // binanceAPIVersion2 = "2" // binanceAPIVersion3 = "3" // binanceSpotRESTBasePath = "api" // binanceSAPIRESTBasePath = "sapi" // binanceFutureRESTBasePath = "fapi" // binancePerpetualRESTBasePath = "dapi" // 用户万向划转 defaultTransfer = "/sapi/v1/asset/transfer" // 手续费 spotTradeFee = "/sapi/v1/asset/tradeFee" ufuturesTradeFree = "/fapi/v1/commissionRate" cfuturesTradeFree = "/dapi/v1/commissionRate" spotPingServer = "/api/v3/ping" ufuturesPingServer = "/fapi/v1/ping" cfuturesPingServer = "/dapi/v1/ping" // 查询/查询持仓模式(USER_DATA) ufuturesDualQuery = "/fapi/v1/positionSide/dual" cfuturesDualQuery = "/dapi/v1/positionSide/dual" // 更改持仓模式(USER_DATA) // ufuturesDualUpdate = "/fapi/v1/positionSide/dual" // cfuturesDualUpdate = "/dapi/v1/positionSide/dual" // // PERPETUAL // binanceContractExchangeInfo = "exchangeInfo" // // 账户信息V2 (USER_DATA) // binanceContractAccount = "account" // // 持仓ADL队列估算 (USER_DATA) // binanceContractAdlQuantile = "adlQuantile" // // 获取账户损益资金流水(USER_DATA) // binanceContractIncome = "income" // // 调整开仓杠杆 // binanceLeverage = "leverage" // // 查看当前全部挂单 // binanceContractOpenOrders = "openOrders" // //下单 (TRADE) // binanceContractNewOrder = "order" // // 撤销订单 (TRADE) // binanceCancelOrder = "order" // // 用户强平单历史 (USER_DATA) // binanceContractForceOrder = "forceOrders" // //查询订单 (TRADE) // binanceContractQueryOrder = "order" // // binanceContractFundingRate 查询资金费率历史 // binanceContractFundingRate = "fundingRate" // // binanceContractPreminuIndex 最新标记价格和资金费率 // binanceContractPreminuIndex = "premiumIndex" // // 用户持仓风险 // binancePositionRisk = "positionRisk" // // 变换逐全仓模式 (USER_DATA) // binanceMarginType = "marginType" // // 调整逐仓保证金 (TRADE) // binancePositionMargin = "positionMargin" // // 逐仓保证金变动历史 (TRADE) // binancePositionMarginHistory = "positionMargin/history" // // 更改持仓模式(TRADE) // // binanceDual = "positionSide/dual" // // K线数据 // binanceKlines = "klines" // // 最新价格 // binancePrice = "price" // // 现货手续费 // binanceSpotTradeFee = "tradeFee" // // 合约余额查询 // biananceContractbalance = "balance" // // 合约手续费查询 // biananceContractTradeFee = "commissionRate" // // PerpetualExchangeInfo = "/dapi/v1/exchangeInfo" // // futureExchangeInfo = "/fapi/v1/exchangeInfo" // binancePerpetualCandleStick = "/dapi/v1/klines" // binancePerpetualContractCandleStick = "/dapi/v1/continuousKlines" // binanceFutureCandleStick = "/fapi/v1/continuousKlines" // // 交易手续费率查询 // // binanceSpotTradeFee = "/wapi/v3/tradeFee.html" // binanceFutureTradeFee = "/fapi/v1/commissionRate" // userAccountFutureStream = "/fapi/v1/listenKey" // userAccountPerpStream = "/dapi/v1/listenKey" ) // 合约余额 type ContractBalanceResponse struct { AccountAlias string `json:"accountAlias"` //账户唯一识别码 Asset string `json:"asset"` // 资产 Balance float64 `json:"balance,string"` // 总余额 CrossWalletBalance float64 `json:"crossWalletBalance,string"` // 全仓余额 CrossUnPnl float64 `json:"crossUnPnl,string"` // 全仓持仓未实现盈亏 AvailableBalance float64 `json:"availableBalance,string"` // 下单可用余额 // MaxWithdrawAmount float64 `json:"maxWithdrawAmount,string"` // 最大可转出余额 WithdrawAvailable float64 `json:"withdrawAvailable,string"` // 可转出余额 MarginAvailable bool `json:"marginAvailable"` // 是否可用作联合保证金 UpdateTime int64 `json:"updateTime"` } type SpotTradeFeeResponse struct { Symbol string `json:"symbol"` // 交易对 MakerCommission float64 `json:"makerCommission,string"` TakerCommission float64 `json:"takerCommission,string"` } type ContractTradeFeeResponse struct { Symbol string `json:"symbol"` // 交易对 MakerCommission float64 `json:"makerCommissionRate,string"` TakerCommission float64 `json:"takerCommissionRate,string"` } // Submit contains all properties of an order that may be required // for an order to be created on an exchange // Each exchange has their own requirements, so not all fields // are required to be populated type SpotSubmit struct { AssetType asset.Item Symbol currency.Pair Side order.Side Type order.Type TimeInForce RequestParamsTimeForceType QuoteOrderQty float64 Quantity float64 Price float64 NewClientOrderId string StopPrice float64 IcebergQty float64 } // AccountInfoFuture U本位合约 账户信息V2 ( type AccountInfoFuture struct { FeeTier int `json:"feeTier"` // 手续费等级 CanTrade bool `json:"canTrade"` // 是否可以交易 CanDeposit bool `json:"canDeposit"` // 是否可以入金 CanWithdraw bool `json:"canWithdraw"` // 是否可以出金 UpdateTime int64 `json:"updateTime"` // 现货指数价格 TotalInitialMargin float64 `json:"totalInitialMargin,string"` // 但前所需起始保证金总额(存在逐仓请忽略), 仅计算usdt资产 TotalMaintMargin float64 `json:"totalMaintMargin,string"` // 维持保证金总额, 仅计算usdt资产 TotalWalletBalance float64 `json:"totalWalletBalance,string"` // 账户总余额, 仅计算usdt资产 TotalUnrealizedProfit float64 `json:"totalUnrealizedProfit,string"` // 持仓未实现盈亏总额, 仅计算usdt资产 TotalMarginBalance float64 `json:"totalMarginBalance,string"` // 保证金总余额, 仅计算usdt资产 TotalPositionInitialMargin float64 `json:"totalPositionInitialMargin,string"` // 持仓所需起始保证金(基于最新标记价格), 仅计算usdt资产 TotalOpenOrderInitialMargin float64 `json:"totalOpenOrderInitialMargin,string"` // 当前挂单所需起始保证金(基于最新标记价格), 仅计算usdt资产 TotalCrossWalletBalance float64 `json:"totalCrossWalletBalance,string"` // 全仓账户余额, 仅计算usdt资产 AvailableBalance float64 `json:"availableBalance,string"` // 可用余额, 仅计算usdt资产 MaxWithdrawAmount float64 `json:"maxWithdrawAmount,string"` // 最大可转出余额, 仅计算usdt资产 Assets []struct { Asset string `json:"asset"` //资产 WalletBalance float64 `json:"walletBalance,string"` //余额 UnrealizedProfit float64 `json:"unrealizedProfit,string"` // 未实现盈亏 MarginBalance float64 `json:"marginBalance,string"` // 保证金余额 MaintMargin float64 `json:"maintMargin,string"` // 维持保证金 InitialMargin float64 `json:"initialMargin,string"` // 当前所需起始保证金 PositionInitialMargin float64 `json:"positionInitialMargin,string"` // 持仓所需起始保证金(基于最新标记价格) PpenOrderInitialMargin float64 `json:"openOrderInitialMargin,string"` // 当前挂单所需起始保证金(基于最新标记价格) CrossWalletBalance float64 `json:"crossWalletBalance,string"` //全仓账户余额 CrossUnPnl float64 `json:"crossUnPnl,string"` // 全仓持仓未实现盈亏 AvailableBalance float64 `json:"availableBalance,string"` // 可用余额 MaxWithdrawAmount float64 `json:"maxWithdrawAmount,string"` // 最大可转出余额 } `json:"assets"` Positions []struct { Symbol string `json:"symbol"` // 交易对 InitialMargin float64 `json:"initialMargin,string"` // 当前所需起始保证金(基于最新标记价格) MaintMargin float64 `json:"maintMargin,string"` //维持保证金 UnrealizedProfit float64 `json:"unrealizedProfit,string"` // 持仓未实现盈亏 PositionInitialMargin float64 `json:"positionInitialMargin,string"` // 持仓所需起始保证金(基于最新标记价格) OpenOrderInitialMargin float64 `json:"openOrderInitialMargin,string"` // 当前挂单所需起始保证金(基于最新标记价格) Leverage float64 `json:"leverage,string"` // 杠杆倍率 Isolated bool `json:"isolated"` // 是否是逐仓模式 EntryPrice float64 `json:"entryPrice,string"` // 持仓成本价 MaxNotional float64 `json:"maxNotional,string"` // 当前杠杆下用户可用的最大名义价值 PositionSide PositionSide `json:"positionSide"` // 持仓方向 PositionAmt float64 `json:"positionAmt,string"` // 仓位 } `json:"positions"` // 头寸,将返回所有市场symbol } // MarkPriceStream holds the ticker stream data type MarkPriceStream struct { EventType string `json:"e"` // 事件类型 EventTime int64 `json:"E"` // 事件时间 Symbol string `json:"s"` // 交易对 MarkPrice float64 `json:"p,string"` // 标记价格 IndexPrice float64 `json:"i,string"` // 现货指数价格 EstimatedSettlePrice float64 `json:"P,string"` // 预估结算价,仅在结算前最后一小时有参考价值 LastFundingRate float64 `json:"r,string"` // 资金费率 NextFundingTime int64 `json:"T"` // 下次资金时间 } // AccountUpdateStream holds the ticker stream data type AccountUpdateStream struct { EventType string `json:"e"` // 事件类型 EventTime int64 `json:"E"` // 事件时间 TimeStamp int64 `json:"T"` // 撮合时间 AccountUpdateEvent struct { EventCause string `json:"m"` // 事件推出原因 Balance []struct { Asset string `json:"a"` // 资产名称 WalletBalance float64 `json:"wb,string"` // 钱包余额 RealyBalance float64 `json:"cw,string"` // 除去逐仓仓位保证金的钱包余额 } `json:"B"` // 余额信息 Position []struct { Symbol string `json:"s"` // 交易对 PositionAmt float64 `json:"pa,string"` // 仓位 EntryPrice float64 `json:"ep,string"` // 入仓价格 RealizedProfitAndLoss float64 `json:"cr,string"` // (费前)累计实现损益 UnRealizedProfit float64 `json:"up,string"` // 持仓未实现盈亏 MarginType string `json:"mt"` // 保证金模式 IsolatedMargin float64 `json:"iw,string"` // 若为逐仓,仓位保证金 PositionSide string `json:"ps"` // 若为逐仓,仓位保证金 } `json:"P"` // 持仓信息 } `json:"a"` // 账户更新事件 } type AccountUpdateEventBalance struct { Asset string `json:"a"` // 资产名称 WalletBalance float64 `json:"wb,string"` // 钱包余额 RealyBalance float64 `json:"cw,string"` // 除去逐仓仓位保证金的钱包余额 } type AccountUpdateEventPosition struct { Symbol currency.Pair `json:"s"` // 交易对 PositionAmt float64 `json:"pa,string"` // 仓位 EntryPrice float64 `json:"ep,string"` // 入仓价格 RealizedProfitAndLoss float64 `json:"cr,string"` // (费前)累计实现损益 UnRealizedProfit float64 `json:"up,string"` // 持仓未实现盈亏 MarginType MarginType `json:"mt"` // 保证金模式 IsolatedMargin float64 `json:"iw,string"` // 若为逐仓,仓位保证金 PositionSide PositionSide `json:"ps"` // 若为逐仓,仓位保证金 } type AccountUpdateStreamResponse struct { EventType string `json:"e"` // 事件类型 EventTime time.Time `json:"E"` // 事件时间 TimeStamp time.Time `json:"T"` // 撮合时间 AssetType asset.Item Exchange string AccountUpdateEvent struct { EventCause string // 事件推出原因 Balance []AccountUpdateEventBalance // 余额信息 Position []AccountUpdateEventPosition // 持仓信息 } // 账户更新事件 } type MarkPriceStreamResponse struct { AssetType asset.Item Exchange string EventType string // 事件类型 EventTime time.Time // 事件时间 Symbol currency.Pair // 交易对 MarkPrice float64 // 标记价格 IndexPrice float64 // 现货指数价格 EstimatedSettlePrice float64 // 预估结算价,仅在结算前最后一小时有参考价值 LastFundingRate float64 // 资金费率 NextFundingTime time.Time // 下次资金时间 } // AdlQuantileResponse 持仓ADL队列估算 (USER_DATA) type AdlQuantileResponse struct { Symbol string `json:"symbol"` AdlQuantile struct { LONG float64 `json:"LONG"` SHORT float64 `json:"SHORT"` HEDGE float64 `json:"HEDGE"` BOTH float64 `json:"BOTH"` } `json:"adlQuantile"` } // PositionMarginHistoryResponse 逐仓保证金变动历史 (TRADE) type PositionMarginHistoryResponse struct { Amount float64 `json:"amount"` // 保证金资金 Symbol string `json:"symbol"` Asset string `json:"asset"` // 持仓方向 Type PositionMarginType `json:"type"` Time time.Time `json:"time"` PositionSide PositionSide `json:"positionSide"` // 持仓方向 } // PositionMarginHistoryRequest 逐仓保证金变动历史 (TRADE) type PositionMarginHistoryRequest struct { Symbol currency.Pair `json:"symbol"` Type int `json:"type"` StartTime int64 `json:"startTime"` EndTime int64 `json:"endTime"` Limit int64 `json:"limit"` } // PositionMarginRequest 调整逐仓保证金 type PositionMarginRequest struct { Symbol currency.Pair `json:"symbol"` PositionSide PositionSide `json:"positionSide"` // 持仓方向 Amount float64 `json:"amount"` // 保证金资金 Type PositionMarginType `json:"type"` } // PositionMarginType 调整逐仓保证金-调整方向 type PositionMarginType int const ( // PositionMarginTypeAdd 增加逐仓保证金 PositionMarginTypeAdd = PositionMarginType(1) // PositionMarginTypeSub 减少逐仓保证金 PositionMarginTypeSub = PositionMarginType(2) ) // CommissionRateResponse 交易手续费率 type CommissionRateResponse struct { Symbol string Maker float64 Taker float64 } // PositionRiskResponse 用户持仓风险 type PositionRiskResponse struct { EntryPrice float64 `json:"entryPrice,string"` //开仓均价 MarginType MarginType `json:"marginType"` //逐仓模式或全仓模式 IsAutoAddMargin bool `json:"isAutoAddMargin, string"` IsolatedMargin float64 `json:"isolatedMargin, string"` // 逐仓保证金 Leverage int64 `json:"leverage, string"` // 当前杠杆倍数 LiquidationPrice float64 `json:"liquidationPrice, string"` // 参考强平价格 MarkPrice float64 `json:"markPrice, string"` // 当前标记价格 MaxNotionalValue float64 `json:"maxNotionalValue, string"` // 当前杠杆倍数允许的名义价值上限 PositionAmt float64 `json:"positionAmt, string"` // 头寸数量,符号代表多空方向, 正数为多,负数为空 Symbol string `json:"symbol"` // 交易对 UnRealizedProfit float64 `json:"unRealizedProfit, string"` // 持仓未实现盈亏 PositionSide PositionSide `json:"positionSide"` // 持仓方向 } // MarginType 保证金模式 type MarginType string const ( // MarginType_ISOLATED 逐仓 MarginType_ISOLATED = MarginType("ISOLATED") // MarginType_CROSSED 全仓 MarginType_CROSSED = MarginType("CROSSED") ) type FundingRateRequest struct { Symbol currency.Pair `json:"symbol"` //交易对 StartTime int64 `json:"startTime"` EndTime int64 `json:"endTime"` Limit int64 `json:"limit"` } type FundingRateResponeItem struct { Symbol string `json:"symbol"` FundingRate float64 `json:"fundingRate"` FundingTime time.Time `json:"fundingTime"` } type IncomeResponse struct { Symbol string `json:"symbol"` //交易对 Income float64 `json:"income, string"` //资金流数量,正数代表流入,负数代表流出 IncomeType IncomeType `json:"incomeType"` // 收益类型 Asset string `json:"asset"` Info string `json:"info,string"` Time time.Time `json:"time"` TranId int64 `json:"tranId,string"` TradeId int64 `json:"tradeId"` } type IncomeRequest struct { Symbol string `json:"symbol"` //交易对 IncomeType IncomeType `json:"incomeType"` // 收益类型 StartTime int64 `json:"startTime"` EndTime int64 `json:"endTime"` Limit int64 `json:"limit"` } // WorkingType 条件价格触发类型 (workingType) type WorkingType string const ( WorkingType_MARK_PRICE = WorkingType("MARK_PRICE") WorkingType_CONTRACT_PRICE = WorkingType("CONTRACT_PRICE") ) // IncomeType收益类型 type IncomeType string const ( IncomeType_TRANSFER = IncomeType("TRANSFER") IncomeType_WELCOME_BONUS = IncomeType("WELCOME_BONUS") IncomeType_REALIZED_PNL = IncomeType("REALIZED_PNL") IncomeType_FUNDING_FEE = IncomeType("FUNDING_FEE") IncomeType_COMMISSION = IncomeType("COMMISSION") IncomeType_INSURANCE_CLEAR = IncomeType("INSURANCE_CLEAR") IncomeType_ALL = IncomeType("") ) // TransferType 用户万向划转 类型 type TransferType string const ( //MAIN_C2C 现货钱包转向C2C钱包 TransferType_MAIN_C2C = TransferType("MAIN_C2C") //MAIN_UMFUTURE 现货钱包转向U本位合约钱包 TransferType_MAIN_UMFUTURE = TransferType("MAIN_UMFUTURE") //MAIN_CMFUTURE 现货钱包转向币本位合约钱包 TransferType_MAIN_CMFUTURE = TransferType("MAIN_CMFUTURE") //MAIN_MARGIN 现货钱包转向杠杆全仓钱包 TransferType_MAIN_MARGIN = TransferType("MAIN_MARGIN") //MAIN_MINING 现货钱包转向矿池钱包 TransferType_MAIN_MINING = TransferType("MAIN_MINING") //C2C_MAIN C2C钱包转向现货钱包 TransferType_C2C_MAIN = TransferType("C2C_MAIN") //C2C_UMFUTURE C2C钱包转向U本位合约钱包 TransferType_C2C_UMFUTURE = TransferType("C2C_UMFUTURE") //C2C_MINING C2C钱包转向矿池钱包 TransferType_C2C_MINING = TransferType("C2C_MINING") //UMFUTURE_MAIN U本位合约钱包转向现货钱包 TransferType_UMFUTURE_MAIN = TransferType("UMFUTURE_MAIN") //UMFUTURE_C2C U本位合约钱包转向C2C钱包 TransferType_UMFUTURE_C2C = TransferType("UMFUTURE_C2C") //UMFUTURE_MARGIN U本位合约钱包转向杠杆全仓钱包 TransferType_UMFUTURE_MARGIN = TransferType("UMFUTURE_MARGIN") //CMFUTURE_MAIN 币本位合约钱包转向现货钱包 TransferType_CMFUTURE_MAIN = TransferType("CMFUTURE_MAIN") //MARGIN_MAIN 杠杆全仓钱包转向现货钱包 TransferType_MARGIN_MAIN = TransferType("MARGIN_MAIN") //MARGIN_UMFUTURE 杠杆全仓钱包转向U本位合约钱包 TransferType_MARGIN_UMFUTURE = TransferType("MARGIN_UMFUTURE") //MINING_MAIN 矿池钱包转向现货钱包 TransferType_MINING_MAIN = TransferType("MINING_MAIN") //TransferType_MINING_UMFUTURE MINING_UMFUTURE 矿池钱包转向U本位合约钱包 TransferType_MINING_UMFUTURE = TransferType("MINING_UMFUTURE") // TransferType_MINING_C2CMINING_C2C 矿池钱包转向C2C钱包 TransferType_MINING_C2C = TransferType("MINING_C2C") ) type FutureLeverageResponse struct { Leverage int `json:"leverage,string"` // 平均成交价 MaxNotionalValue int64 `json:"maxNotionalValue, string"` // 用户自定义的订单号 Symbol string `json:"symbol"` //成交金额 } // FutureQueryOrderData holds query order data type FutureQueryOrderData struct { AvgPrice float64 `json:"avgPrice,string"` // 平均成交价 ClientOrderID string `json:"clientOrderId"` // 用户自定义的订单号 CumBase float64 `json:"cumBase,string"` //成交额(标的数量) CumQuote float64 `json:"cumQuote,string"` //成交金额 ExecutedQty float64 `json:"executedQty,string"` //成交量 OrderID int64 `json:"orderId"` OrigQty float64 `json:"origQty,string"` // 原始委托数量 OrigType string `json:"origType"` Price float64 `json:"price,string"` ReduceOnly bool `json:"reduceOnly"` // 是否仅减仓 Side order.Side `json:"side"` PositionSide PositionSide `json:"positionSide"` // 持仓方向 Status order.Status `json:"status"` StopPrice float64 `json:"stopPrice,string"` // 触发价,对`TRAILING_STOP_MARKET`无效 ClosePosition bool `json:"closePosition"` // 是否条件全平仓 Symbol string `json:"symbol"` Time time.Time `json:"time"` // 订单时间 TimeInForce RequestParamsTimeForceType `json:"timeInForce"` // 有效方法 Type string `json:"type"` //订单类型 ActivatePrice float64 `json:"activatePrice,string"` // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 PriceRate float64 `json:"priceRate,string"` // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 UpdateTime time.Time `json:"updateTime"` WorkingType WorkingType `json:"workingType"` // 条件价格触发类型 PriceProtect bool `json:"priceProtect"` // 是否开启条件单触发保护 } // PositionSide 持仓方向 type PositionSide string const ( // PositionSideBOTH 单一持仓方向 PositionSideBOTH = PositionSide("BOTH") // PositionSideLONG 多头(双向持仓下) PositionSideLONG = PositionSide("LONG") // PositionSideSHORT 空头(双向持仓下) PositionSideSHORT = PositionSide("SHORT") ) // ContractType 合约类型 type ContractType string const ( // ContractTypePERPETUAL 永续合约 ContractTypePERPETUAL = ContractType("PERPETUAL") // ContractTypeCURRENT_MONTH 当月交割合约 ContractTypeCURRENT_MONTH = ContractType("CURRENT_MONTH") // PositionSideSHORT 次月交割合约 ContractTypeNEXT_MONTH = ContractType("NEXT_MONTH") ) // NewOrderContractRequest request type type NewOrderContractRequest struct { // Symbol (currency pair to trade) Symbol string // Side Buy or Sell Side order.Side // 持仓方向,单向持仓模式下非必填,默认且仅可填BOTH;在双向持仓模式下必填,且仅可选择 LONG 或 SHORT PositionSide PositionSide // Type 订单类型 LIMIT, MARKET, STOP, TAKE_PROFIT, STOP_MARKET, TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET Type RequestParamsOrderType // true, false; 非双开模式下默认false;双开模式下不接受此参数; 使用closePosition不支持此参数。 ReduceOnly string // 下单数量,使用closePosition不支持此参数 Quantity float64 //委托价格 Price float64 //用户自定义的订单号,不可以重复出现在挂单中。如空缺系统会自动赋值。必须满足正则规则 ^[a-zA-Z0-9-_]{1,36}$ NewClientOrderID string StopPrice float64 // Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. // true, false;触发后全部平仓,仅支持STOP_MARKET和TAKE_PROFIT_MARKET;不与quantity合用;自带只平仓效果,不与reduceOnly 合用 ClosePosition float64 // 追踪止损激活价格,仅TRAILING_STOP_MARKET 需要此参数, 默认为下单当前市场价格(支持不同workingType) ActivationPrice float64 // 追踪止损回调比例,可取值范围[0.1, 5],其中 1代表1% ,仅TRAILING_STOP_MARKET 需要此参数 CallbackRate float64 // TimeInForce specifies how long the order remains in effect. // Examples are (Good Till Cancel (GTC), Immediate or Cancel (IOC) and Fill Or Kill (FOK)) TimeInForce RequestParamsTimeForceType // 触发类型: MARK_PRICE(标记价格), CONTRACT_PRICE(合约最新价). 默认 CONTRACT_PRICE WorkingType string // 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 STOP, STOP_MARKET, TAKE_PROFIT, TAKE_PROFIT_MARKET 需要此参数 priceProtect string NewOrderRespType string } // NewOrderContractResponse is the return structured response from the exchange type NewOrderContractResponse struct { Symbol string `json:"symbol"` //交易对 OrderID int64 `json:"orderId"` ClientOrderID string `json:"clientOrderId"` AvgPrice float64 `json:"avgPrice, string"` //平均成交价 Price float64 `json:"price,string"` //委托价格 OrigQty float64 `json:"origQty,string"` //原始委托数量 CumQty float64 `json:"cumQty,string"` CumQuote float64 `json:"cumQuote,string"` //成交金额 // The cumulative amount of the quote that has been spent (with a BUY order) or received (with a SELL order). ExecutedQty float64 `json:"executedQty,string"` //成交量 Status order.Status `json:"status"` //订单状态 TimeInForce RequestParamsTimeForceType `json:"timeInForce"` //有效方法 Type order.Type `json:"type"` //订单类型 Side order.Side `json:"side"` //买卖方向 PositionSide string `json:"positionSide"` //持仓方向 StopPrice string `json:"stopPrice"` //触发价,对`TRAILING_STOP_MARKET`无效 ClosePosition bool `json:"closePosition"` //是否条件全平仓 OrigType string `json:"origType"` //触发前订单类型 ActivatePrice string `json:"activatePrice"` //跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 PriceRate string `json:"priceRate"` //跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 UpdateTime time.Time `json:"updateTime"` // 更新时间 WorkingType WorkingType `json:"workingType"` // 条件价格触发类型 PriceProtect bool `json:"priceProtect"` // 是否开启条件单触发保护 } // KlinesContractRequestParams represents Klines request data. type KlinesContractRequestParams struct { Pair string // Required field; example LTCBTC, BTCUSDT contractType ContractType Interval string // Time interval period Limit int // Default 500; max 500. StartTime int64 EndTime int64 } // PreminuIndexResponse represents Klines request data. type PreminuIndexResponse struct { Symbol string `json:"symbol"` // Required field; example LTCBTC, BTCUSDT MarkPrice float64 `json:"markPrice"` // 标记价格 IndexPrice float64 `json:"indexPrice"` // 指数价格 LastFundingRate float64 `json:"lastFundingRate"` // 最近更新的资金费率 NextFundingTime time.Time `json:"nextFundingTime"` // 下次资金费时间 InterestRate float64 `json:"interestRate"` // 标的资产基础利率 Time time.Time `json:"time"` // 更新时间 } // AccountSnapshotRequest 查询每日资产快照 (USER_DATA) type AccountSnapshotRequest struct { Type asset.Item `json:"type"` Price float64 `json:"price"` Limit int64 `json:"limit"` StartTime int64 `json:"startTime"` EndTime int64 `json:"endTime"` } // AccountSnapshotResponse 查询每日资产快照 (USER_DATA) - 返回信息 type AccountSnapshotResponse struct { TotalAssetOfBtc float64 `json:"totalAssetOfBtc"` Asset asset.Item `json:"asset"` Symbol string `json:"symbol"` Free float64 `json:"free"` Locked float64 `json:"locked"` UpdateTime time.Time `json:"updateTime"` } <file_sep>package order import ( "errors" "fmt" "sync" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/shopspring/decimal" ) var ( // ErrExchangeLimitNotLoaded defines if an exchange does not have minmax // values ErrExchangeLimitNotLoaded = errors.New("exchange limits not loaded") // ErrPriceBelowMin is when the price is lower than the minimum price // limit accepted by the exchange ErrPriceBelowMin = errors.New("price below minimum limit") // ErrPriceExceedsMax is when the price is higher than the maximum price // limit accepted by the exchange ErrPriceExceedsMax = errors.New("price exceeds maximum limit") // ErrPriceExceedsStep is when the price is not divisible by its step ErrPriceExceedsStep = errors.New("price exceeds step limit") // ErrAmountBelowMin is when the amount is lower than the minimum amount // limit accepted by the exchange ErrAmountBelowMin = errors.New("amount below minimum limit") // ErrAmountExceedsMax is when the amount is higher than the maximum amount // limit accepted by the exchange ErrAmountExceedsMax = errors.New("amount exceeds maximum limit") // ErrAmountExceedsStep is when the amount is not divisible by its step ErrAmountExceedsStep = errors.New("amount exceeds step limit") // ErrNotionalValue is when the notional value does not exceed currency pair // requirements ErrNotionalValue = errors.New("total notional value is under minimum limit") // ErrMarketAmountBelowMin is when the amount is lower than the minimum // amount limit accepted by the exchange for a market order ErrMarketAmountBelowMin = errors.New("market order amount below minimum limit") // ErrMarketAmountExceedsMax is when the amount is higher than the maximum // amount limit accepted by the exchange for a market order ErrMarketAmountExceedsMax = errors.New("market order amount exceeds maximum limit") // ErrMarketAmountExceedsStep is when the amount is not divisible by its // step for a market order ErrMarketAmountExceedsStep = errors.New("market order amount exceeds step limit") errCannotValidateAsset = errors.New("cannot check limit, asset not loaded") errCannotValidateBaseCurrency = errors.New("cannot check limit, base currency not loaded") errCannotValidateQuoteCurrency = errors.New("cannot check limit, quote currency not loaded") errExchangeLimitAsset = errors.New("exchange limits not found for asset") errExchangeLimitBase = errors.New("exchange limits not found for base currency") errExchangeLimitQuote = errors.New("exchange limits not found for quote currency") errCannotLoadLimit = errors.New("cannot load limit, levels not supplied") errInvalidPriceLevels = errors.New("invalid price levels, cannot load limits") errInvalidAmountLevels = errors.New("invalid amount levels, cannot load limits") ) // ExecutionLimits defines minimum and maximum values in relation to // order size, order pricing, total notional values, total maximum orders etc // for execution on an exchange. type ExecutionLimits struct { m map[asset.Item]map[*currency.Item]map[*currency.Item]*Limits mtx sync.RWMutex } // MinMaxLevel defines the minimum and maximum parameters for a currency pair // for outbound exchange execution type MinMaxLevel struct { Pair currency.Pair Asset asset.Item MinPrice float64 MaxPrice float64 StepPrice float64 MultiplierUp float64 MultiplierDown float64 MultiplierDecimal float64 AveragePriceMinutes int64 MinAmount float64 MaxAmount float64 StepAmount float64 MinNotional float64 MaxIcebergParts int64 MarketMinQty float64 MarketMaxQty float64 MarketStepSize float64 MaxTotalOrders int64 MaxAlgoOrders int64 } // LoadLimits loads all limits levels into memory func (e *ExecutionLimits) LoadLimits(levels []MinMaxLevel) error { if len(levels) == 0 { return errCannotLoadLimit } e.mtx.Lock() defer e.mtx.Unlock() if e.m == nil { e.m = make(map[asset.Item]map[*currency.Item]map[*currency.Item]*Limits) } for x := range levels { if !levels[x].Asset.IsValid() { return fmt.Errorf("cannot load levels for '%s': %w", levels[x].Asset, asset.ErrNotSupported) } m1, ok := e.m[levels[x].Asset] if !ok { m1 = make(map[*currency.Item]map[*currency.Item]*Limits) e.m[levels[x].Asset] = m1 } m2, ok := m1[levels[x].Pair.Base.Item] if !ok { m2 = make(map[*currency.Item]*Limits) m1[levels[x].Pair.Base.Item] = m2 } limit, ok := m2[levels[x].Pair.Quote.Item] if !ok { limit = new(Limits) m2[levels[x].Pair.Quote.Item] = limit } if levels[x].MinPrice > 0 && levels[x].MaxPrice > 0 && levels[x].MinPrice > levels[x].MaxPrice { return fmt.Errorf("%w for %s %s supplied min: %f max: %f", errInvalidPriceLevels, levels[x].Asset, levels[x].Pair, levels[x].MinPrice, levels[x].MaxPrice) } if levels[x].MinAmount > 0 && levels[x].MaxAmount > 0 && levels[x].MinAmount > levels[x].MaxAmount { return fmt.Errorf("%w for %s %s supplied min: %f max: %f", errInvalidAmountLevels, levels[x].Asset, levels[x].Pair, levels[x].MinAmount, levels[x].MaxAmount) } limit.m.Lock() limit.minPrice = levels[x].MinPrice limit.maxPrice = levels[x].MaxPrice limit.stepIncrementSizePrice = levels[x].StepPrice limit.minAmount = levels[x].MinAmount limit.maxAmount = levels[x].MaxAmount limit.stepIncrementSizeAmount = levels[x].StepAmount limit.minNotional = levels[x].MinNotional limit.multiplierUp = levels[x].MultiplierUp limit.multiplierDown = levels[x].MultiplierDown limit.averagePriceMinutes = levels[x].AveragePriceMinutes limit.maxIcebergParts = levels[x].MaxIcebergParts limit.marketMinQty = levels[x].MarketMinQty limit.marketMaxQty = levels[x].MarketMaxQty limit.marketStepIncrementSize = levels[x].MarketStepSize limit.maxTotalOrders = levels[x].MaxTotalOrders limit.maxAlgoOrders = levels[x].MaxAlgoOrders limit.m.Unlock() } return nil } // GetOrderExecutionLimits returns the exchange limit parameters for a currency func (e *ExecutionLimits) GetOrderExecutionLimits(a asset.Item, cp currency.Pair) (*Limits, error) { e.mtx.RLock() defer e.mtx.RUnlock() if e.m == nil { return nil, ErrExchangeLimitNotLoaded } m1, ok := e.m[a] if !ok { return nil, errExchangeLimitAsset } m2, ok := m1[cp.Base.Item] if !ok { return nil, errExchangeLimitBase } limit, ok := m2[cp.Quote.Item] if !ok { return nil, errExchangeLimitQuote } return limit, nil } // CheckOrderExecutionLimits checks to see if the price and amount conforms with // exchange level order execution limits func (e *ExecutionLimits) CheckOrderExecutionLimits(a asset.Item, cp currency.Pair, price, amount float64, orderType Type) error { e.mtx.RLock() defer e.mtx.RUnlock() if e.m == nil { // No exchange limits loaded so we can nil this return nil } m1, ok := e.m[a] if !ok { return errCannotValidateAsset } m2, ok := m1[cp.Base.Item] if !ok { return errCannotValidateBaseCurrency } limit, ok := m2[cp.Quote.Item] if !ok { return errCannotValidateQuoteCurrency } err := limit.Conforms(price, amount, orderType) if err != nil { return fmt.Errorf("%w for %s %s", err, a, cp) } return nil } // Limits defines total limit values for an associated currency to be checked // before execution on an exchange type Limits struct { minPrice float64 maxPrice float64 stepIncrementSizePrice float64 minAmount float64 maxAmount float64 stepIncrementSizeAmount float64 minNotional float64 multiplierUp float64 multiplierDown float64 averagePriceMinutes int64 maxIcebergParts int64 marketMinQty float64 marketMaxQty float64 marketStepIncrementSize float64 maxTotalOrders int64 maxAlgoOrders int64 m sync.RWMutex } // Conforms checks outbound parameters func (l *Limits) Conforms(price, amount float64, orderType Type) error { if l == nil { // For when we return a nil pointer we can assume there's nothing to // check return nil } l.m.RLock() defer l.m.RUnlock() if l.minAmount != 0 && amount < l.minAmount { return fmt.Errorf("%w min: %.8f supplied %.8f", ErrAmountBelowMin, l.minAmount, amount) } if l.maxAmount != 0 && amount > l.maxAmount { return fmt.Errorf("%w min: %.8f supplied %.8f", ErrAmountExceedsMax, l.maxAmount, amount) } if l.stepIncrementSizeAmount != 0 { dAmount := decimal.NewFromFloat(amount) dMinAmount := decimal.NewFromFloat(l.minAmount) dStep := decimal.NewFromFloat(l.stepIncrementSizeAmount) if !dAmount.Sub(dMinAmount).Mod(dStep).IsZero() { return fmt.Errorf("%w stepSize: %.8f supplied %.8f", ErrAmountExceedsStep, l.stepIncrementSizeAmount, amount) } } // Multiplier checking not done due to the fact we need coherence with the // last average price (TODO) // l.multiplierUp will be used to determine how far our price can go up // l.multiplierDown will be used to determine how far our price can go down // l.averagePriceMinutes will be used to determine mean over this period // Max iceberg parts checking not done as we do not have that // functionality yet (TODO) // l.maxIcebergParts // How many components in an iceberg order // Max total orders not done due to order manager limitations (TODO) // l.maxTotalOrders // Max algo orders not done due to order manager limitations (TODO) // l.maxAlgoOrders // If order type is Market we do not need to do price checks if orderType != Market { if l.minPrice != 0 && price < l.minPrice { return fmt.Errorf("%w min: %.8f supplied %.8f", ErrPriceBelowMin, l.minPrice, price) } if l.maxPrice != 0 && price > l.maxPrice { return fmt.Errorf("%w max: %.8f supplied %.8f", ErrPriceExceedsMax, l.maxPrice, price) } if l.minNotional != 0 && (amount*price) < l.minNotional { return fmt.Errorf("%w minimum notional: %.8f value of order %.8f", ErrNotionalValue, l.minNotional, amount*price) } if l.stepIncrementSizePrice != 0 { dPrice := decimal.NewFromFloat(price) dMinPrice := decimal.NewFromFloat(l.minPrice) dStep := decimal.NewFromFloat(l.stepIncrementSizePrice) if !dPrice.Sub(dMinPrice).Mod(dStep).IsZero() { return fmt.Errorf("%w stepSize: %.8f supplied %.8f", ErrPriceExceedsStep, l.stepIncrementSizePrice, price) } } return nil } if l.marketMinQty != 0 && l.minAmount < l.marketMinQty && amount < l.marketMinQty { return fmt.Errorf("%w min: %.8f supplied %.8f", ErrMarketAmountBelowMin, l.marketMinQty, amount) } if l.marketMaxQty != 0 && l.maxAmount > l.marketMaxQty && amount > l.marketMaxQty { return fmt.Errorf("%w max: %.8f supplied %.8f", ErrMarketAmountExceedsMax, l.marketMaxQty, amount) } if l.marketStepIncrementSize != 0 && l.stepIncrementSizeAmount != l.marketStepIncrementSize { dAmount := decimal.NewFromFloat(amount) dMinMAmount := decimal.NewFromFloat(l.marketMinQty) dStep := decimal.NewFromFloat(l.marketStepIncrementSize) if !dAmount.Sub(dMinMAmount).Mod(dStep).IsZero() { return fmt.Errorf("%w stepSize: %.8f supplied %.8f", ErrMarketAmountExceedsStep, l.marketStepIncrementSize, amount) } } return nil } // ConformToDecimalAmount (POC) conforms amount to its amount interval func (l *Limits) ConformToDecimalAmount(amount decimal.Decimal) decimal.Decimal { if l == nil { return amount } l.m.Lock() defer l.m.Unlock() dStep := decimal.NewFromFloat(l.stepIncrementSizeAmount) if dStep.IsZero() || amount.Equal(dStep) { return amount } if amount.LessThan(dStep) { return decimal.Zero } mod := amount.Mod(dStep) // subtract modulus to get the floor return amount.Sub(mod) } // ConformToAmount (POC) conforms amount to its amount interval func (l *Limits) ConformToAmount(amount float64) float64 { if l == nil { // For when we return a nil pointer we can assume there's nothing to // check return amount } l.m.Lock() defer l.m.Unlock() if l.stepIncrementSizeAmount == 0 || amount == l.stepIncrementSizeAmount { return amount } if amount < l.stepIncrementSizeAmount { return 0 } // Convert floats to decimal types dAmount := decimal.NewFromFloat(amount) dStep := decimal.NewFromFloat(l.stepIncrementSizeAmount) // derive modulus mod := dAmount.Mod(dStep) // subtract modulus to get the floor rVal := dAmount.Sub(mod) fVal, _ := rVal.Float64() return fVal } <file_sep>package asset import ( "testing" "github.com/idoall/gocryptotrader/common" ) func TestString(t *testing.T) { a := Spot if a.String() != "spot" { t.Fatal("TestString returned an unexpected result") } } func TestToStringArray(t *testing.T) { a := Items{Spot, Futures} result := a.Strings() for x := range a { if !common.StringDataCompare(result, a[x].String()) { t.Fatal("TestToStringArray returned an unexpected result") } } } func TestContains(t *testing.T) { a := Items{Spot, Futures} if a.Contains("meow") { t.Fatal("TestContains returned an unexpected result") } if !a.Contains(Spot) { t.Fatal("TestContains returned an unexpected result") } if a.Contains(Binary) { t.Fatal("TestContains returned an unexpected result") } // Every asset should be created and matched with func New so this should // not be matched against list if a.Contains("SpOt") { t.Error("TestContains returned an unexpected result") } } func TestJoinToString(t *testing.T) { a := Items{Spot, Futures} if a.JoinToString(",") != "spot,futures" { t.Fatal("TestJoinToString returned an unexpected result") } } func TestIsValid(t *testing.T) { if Item("rawr").IsValid() { t.Fatal("TestIsValid returned an unexpected result") } if !Spot.IsValid() { t.Fatal("TestIsValid returned an unexpected result") } } func TestNew(t *testing.T) { if _, err := New("Spota"); err == nil { t.Fatal("TestNew returned an unexpected result") } a, err := New("SpOt") if err != nil { t.Fatal("TestNew returned an unexpected result", err) } if a != Spot { t.Fatal("TestNew returned an unexpected result") } } func TestSupported(t *testing.T) { s := Supported() if len(supported) != len(s) { t.Fatal("TestSupported mismatched lengths") } for i := 0; i < len(supported); i++ { if s[i] != supported[i] { t.Fatal("TestSupported returned an unexpected result") } } } <file_sep>package dispatch import ( "errors" "fmt" "sync" "sync/atomic" "time" "github.com/gofrs/uuid" "github.com/idoall/gocryptotrader/log" ) // ErrNotRunning defines an error when the dispatcher is not running var ErrNotRunning = errors.New("dispatcher not running") // Name is an exported subsystem name const Name = "dispatch" func init() { dispatcher = &Dispatcher{ routes: make(map[uuid.UUID][]chan interface{}), outbound: sync.Pool{ New: func() interface{} { // Create unbuffered channel for data pass return make(chan interface{}) }, }, } } // Start starts the dispatch system by spawning workers and allocating memory func Start(workers, jobsLimit int) error { if dispatcher == nil { return errors.New(errNotInitialised) } mtx.Lock() defer mtx.Unlock() return dispatcher.start(workers, jobsLimit) } // Stop attempts to stop the dispatch service, this will close all pipe channels // flush job list and drop all workers func Stop() error { if dispatcher == nil { return errors.New(errNotInitialised) } log.Debugln(log.DispatchMgr, "Dispatch manager shutting down...") mtx.Lock() defer mtx.Unlock() return dispatcher.stop() } // IsRunning checks to see if the dispatch service is running func IsRunning() bool { if dispatcher == nil { return false } return dispatcher.isRunning() } // DropWorker drops a worker routine func DropWorker() error { if dispatcher == nil { return errors.New(errNotInitialised) } dispatcher.dropWorker() return nil } // SpawnWorker starts a new worker routine func SpawnWorker() error { if dispatcher == nil { return errors.New(errNotInitialised) } return dispatcher.spawnWorker() } // start compares atomic running value, sets defaults, overides with // configuration, then spawns workers func (d *Dispatcher) start(workers, channelCapacity int) error { if atomic.LoadUint32(&d.running) == 1 { return errors.New("dispatcher already running") } if workers < 1 { log.Warn(log.DispatchMgr, "Dispatcher: workers cannot be zero, using default values") workers = DefaultMaxWorkers } if channelCapacity < 1 { log.Warn(log.DispatchMgr, "Dispatcher: jobs limit cannot be zero, using default values") channelCapacity = DefaultJobsLimit } d.jobs = make(chan *job, channelCapacity) d.maxWorkers = int32(workers) d.shutdown = make(chan *sync.WaitGroup) if atomic.LoadInt32(&d.count) != 0 { return errors.New("dispatcher leaked workers found") } for i := int32(0); i < d.maxWorkers; i++ { err := d.spawnWorker() if err != nil { return err } } atomic.SwapUint32(&d.running, 1) return nil } // stop stops the service and shuts down all worker routines func (d *Dispatcher) stop() error { if !atomic.CompareAndSwapUint32(&d.running, 1, 0) { return ErrNotRunning } close(d.shutdown) ch := make(chan struct{}) timer := time.NewTimer(1 * time.Second) defer func() { if !timer.Stop() { select { case <-timer.C: default: } } }() go func(ch chan struct{}) { d.wg.Wait(); ch <- struct{}{} }(ch) select { case <-ch: // close all routes for key := range d.routes { for i := range d.routes[key] { close(d.routes[key][i]) } d.routes[key] = nil } for len(d.jobs) != 0 { // drain jobs channel for old data <-d.jobs } log.Debugln(log.DispatchMgr, "Dispatch manager shutdown.") return nil case <-timer.C: return errors.New(errShutdownRoutines) } } // isRunning returns if the dispatch system is running func (d *Dispatcher) isRunning() bool { if d == nil { return false } return atomic.LoadUint32(&d.running) == 1 } // dropWorker deallocates a worker routine func (d *Dispatcher) dropWorker() { wg := sync.WaitGroup{} wg.Add(1) d.shutdown <- &wg wg.Wait() } // spawnWorker allocates a new worker for job processing func (d *Dispatcher) spawnWorker() error { if atomic.LoadInt32(&d.count) >= d.maxWorkers { return errors.New("dispatcher cannot spawn more workers; ceiling reached") } var spawnWg sync.WaitGroup spawnWg.Add(1) go d.relayer(&spawnWg) spawnWg.Wait() return nil } // relayer routine relays communications across the defined routes func (d *Dispatcher) relayer(i *sync.WaitGroup) { atomic.AddInt32(&d.count, 1) d.wg.Add(1) timeout := time.NewTimer(0) i.Done() for { select { case j := <-d.jobs: d.rMtx.RLock() if _, ok := d.routes[j.ID]; !ok { d.rMtx.RUnlock() continue } // Channel handshake timeout feature if a channel is blocked for any // period of time due to an issue with the receiving routine. // This will wait on channel then fall over to the next route when // the timer actuates and continue over the route list. Have to // iterate across full length of routes so every routine can get // their new info, cannot be buffered as we dont want to have an old // orderbook etc contained in a buffered channel when a routine // actually is ready for a receive. // TODO: Need to consider optimal timer length for i := range d.routes[j.ID] { if !timeout.Stop() { // Stop timer before reset // Drain channel if timer has already actuated select { case <-timeout.C: default: } } timeout.Reset(DefaultHandshakeTimeout) select { case d.routes[j.ID][i] <- j.Data: case <-timeout.C: } } d.rMtx.RUnlock() case v := <-d.shutdown: if !timeout.Stop() { select { case <-timeout.C: default: } } atomic.AddInt32(&d.count, -1) if v != nil { v.Done() } d.wg.Done() return } } } // publish relays data to the subscribed subsystems func (d *Dispatcher) publish(id uuid.UUID, data interface{}) error { if data == nil { return errors.New("dispatcher data cannot be nil") } if id == (uuid.UUID{}) { return errors.New("dispatcher uuid not set") } if atomic.LoadUint32(&d.running) == 0 { return nil } // Create a new job to publish newJob := &job{ Data: data, ID: id, } // Push job on stack here select { case d.jobs <- newJob: default: return fmt.Errorf("dispatcher jobs at limit [%d] current worker count [%d]. Spawn more workers via --dispatchworkers=x"+ ", or increase the jobs limit via --dispatchjobslimit=x", len(d.jobs), atomic.LoadInt32(&d.count)) } return nil } // Subscribe subscribes a system and returns a communication chan, this does not // ensure initial push. If your routine is out of sync with heartbeat and the // system does not get a change, its up to you to in turn get initial state. func (d *Dispatcher) subscribe(id uuid.UUID) (chan interface{}, error) { if atomic.LoadUint32(&d.running) == 0 { return nil, errors.New(errNotInitialised) } // Read lock to read route list d.rMtx.RLock() _, ok := d.routes[id] d.rMtx.RUnlock() if !ok { return nil, errors.New("dispatcher uuid not found in route list") } // Get an unused channel from the channel pool unusedChan, ok := d.outbound.Get().(chan interface{}) if !ok { return nil, errors.New("unable to type assert unusedChan") } // Lock for writing to the route list d.rMtx.Lock() d.routes[id] = append(d.routes[id], unusedChan) d.rMtx.Unlock() return unusedChan, nil } // Unsubscribe unsubs a routine from the dispatcher func (d *Dispatcher) unsubscribe(id uuid.UUID, usedChan chan interface{}) error { if atomic.LoadUint32(&d.running) == 0 { // reference will already be released in the stop function return nil } // Read lock to read route list d.rMtx.RLock() _, ok := d.routes[id] d.rMtx.RUnlock() if !ok { return errors.New("dispatcher uuid does not reference any channels") } // Lock for write to delete references d.rMtx.Lock() for i := range d.routes[id] { if d.routes[id][i] != usedChan { continue } // Delete individual reference d.routes[id][i] = d.routes[id][len(d.routes[id])-1] d.routes[id][len(d.routes[id])-1] = nil d.routes[id] = d.routes[id][:len(d.routes[id])-1] d.rMtx.Unlock() // Drain and put the used chan back in pool; only if it is not closed. select { case _, ok := <-usedChan: if !ok { return nil } default: } d.outbound.Put(usedChan) return nil } d.rMtx.Unlock() return errors.New("dispatcher channel not found in uuid reference slice") } // GetNewID returns a new ID func (d *Dispatcher) getNewID() (uuid.UUID, error) { // Generate new uuid newID, err := uuid.NewV4() if err != nil { return uuid.UUID{}, err } // Check to see if it already exists d.rMtx.RLock() if _, ok := d.routes[newID]; ok { d.rMtx.RUnlock() return newID, errors.New("dispatcher collision detected, uuid already exists") } d.rMtx.RUnlock() // Write the key into system d.rMtx.Lock() d.routes[newID] = nil d.rMtx.Unlock() return newID, nil } <file_sep>package event import ( "strings" "testing" "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" ) func TestEvent_AppendWhy(t *testing.T) { t.Parallel() e := &Base{} e.AppendReason("test") y := e.GetReason() if !strings.Contains(y, "test") { t.Error("expected test") } } func TestEvent_GetAssetType(t *testing.T) { t.Parallel() e := &Base{ AssetType: asset.Spot, } if y := e.GetAssetType(); y != asset.Spot { t.Error("expected spot") } } func TestEvent_GetExchange(t *testing.T) { t.Parallel() e := &Base{ Exchange: "test", } if y := e.GetExchange(); y != "test" { t.Error("expected test") } } func TestEvent_GetInterval(t *testing.T) { t.Parallel() e := &Base{ Interval: gctkline.OneMin, } if y := e.GetInterval(); y != gctkline.OneMin { t.Error("expected one minute") } } func TestEvent_GetTime(t *testing.T) { t.Parallel() tt := time.Now() e := &Base{ Time: tt, } y := e.GetTime() if !y.Equal(tt) { t.Errorf("expected %v", tt) } } func TestEvent_IsEvent(t *testing.T) { t.Parallel() e := &Base{} y := e.IsEvent() if !y { t.Error("it is an event") } } func TestEvent_Pair(t *testing.T) { t.Parallel() e := &Base{ CurrencyPair: currency.NewPair(currency.BTC, currency.USDT), } y := e.Pair() if y.IsEmpty() { t.Error("expected currency") } } <file_sep>package exchange import ( "context" "fmt" "github.com/gofrs/uuid" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/data" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange/slippage" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/engine" "github.com/idoall/gocryptotrader/exchanges/asset" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/exchanges/orderbook" "github.com/shopspring/decimal" ) // Reset returns the exchange to initial settings func (e *Exchange) Reset() { *e = Exchange{} } // ExecuteOrder assesses the portfolio manager's order event and if it passes validation // will send an order to the exchange/fake order manager to be stored and raise a fill event func (e *Exchange) ExecuteOrder(o order.Event, data data.Handler, orderManager *engine.OrderManager, funds funding.IPairReleaser) (*fill.Fill, error) { f := &fill.Fill{ Base: event.Base{ Offset: o.GetOffset(), Exchange: o.GetExchange(), Time: o.GetTime(), CurrencyPair: o.Pair(), AssetType: o.GetAssetType(), Interval: o.GetInterval(), Reason: o.GetReason(), }, Direction: o.GetDirection(), Amount: o.GetAmount(), ClosePrice: data.Latest().GetClosePrice(), } eventFunds := o.GetAllocatedFunds() cs, err := e.GetCurrencySettings(o.GetExchange(), o.GetAssetType(), o.Pair()) if err != nil { return f, err } f.ExchangeFee = cs.ExchangeFee // defaulting to just using taker fee right now without orderbook f.Direction = o.GetDirection() if o.GetDirection() != gctorder.Buy && o.GetDirection() != gctorder.Sell { return f, nil } highStr := data.StreamHigh() high := highStr[len(highStr)-1] lowStr := data.StreamLow() low := lowStr[len(lowStr)-1] volStr := data.StreamVol() volume := volStr[len(volStr)-1] var adjustedPrice, amount decimal.Decimal if cs.UseRealOrders { // get current orderbook var ob *orderbook.Base ob, err = orderbook.Get(f.Exchange, f.CurrencyPair, f.AssetType) if err != nil { return f, err } // calculate an estimated slippage rate adjustedPrice, amount = slippage.CalculateSlippageByOrderbook(ob, o.GetDirection(), eventFunds, f.ExchangeFee) f.Slippage = adjustedPrice.Sub(f.ClosePrice).Div(f.ClosePrice).Mul(decimal.NewFromInt(100)) } else { adjustedPrice, amount, err = e.sizeOfflineOrder(high, low, volume, &cs, f) if err != nil { switch f.GetDirection() { case gctorder.Buy: f.SetDirection(common.CouldNotBuy) case gctorder.Sell: f.SetDirection(common.CouldNotSell) default: f.SetDirection(common.DoNothing) } f.AppendReason(err.Error()) return f, err } } portfolioLimitedAmount := reduceAmountToFitPortfolioLimit(adjustedPrice, amount, eventFunds, f.GetDirection()) if !portfolioLimitedAmount.Equal(amount) { f.AppendReason(fmt.Sprintf("Order size shrunk from %v to %v to remain within portfolio limits", amount, portfolioLimitedAmount)) } limitReducedAmount := portfolioLimitedAmount if cs.CanUseExchangeLimits { // Conforms the amount to the exchange order defined step amount // reducing it when needed limitReducedAmount = cs.Limits.ConformToDecimalAmount(portfolioLimitedAmount) if !limitReducedAmount.Equal(portfolioLimitedAmount) { f.AppendReason(fmt.Sprintf("Order size shrunk from %v to %v to remain within exchange step amount limits", portfolioLimitedAmount, limitReducedAmount)) } } err = verifyOrderWithinLimits(f, limitReducedAmount, &cs) if err != nil { return f, err } f.ExchangeFee = calculateExchangeFee(adjustedPrice, limitReducedAmount, cs.ExchangeFee) orderID, err := e.placeOrder(context.TODO(), adjustedPrice, limitReducedAmount, cs.UseRealOrders, cs.CanUseExchangeLimits, f, orderManager) if err != nil { fundErr := funds.Release(eventFunds, eventFunds, f.GetDirection()) if fundErr != nil { f.AppendReason(fundErr.Error()) } if f.GetDirection() == gctorder.Buy { f.SetDirection(common.CouldNotBuy) } else if f.GetDirection() == gctorder.Sell { f.SetDirection(common.CouldNotSell) } return f, err } switch f.GetDirection() { case gctorder.Buy: err = funds.Release(eventFunds, eventFunds.Sub(limitReducedAmount.Mul(adjustedPrice)), f.GetDirection()) if err != nil { return f, err } funds.IncreaseAvailable(limitReducedAmount, f.GetDirection()) case gctorder.Sell: err = funds.Release(eventFunds, eventFunds.Sub(limitReducedAmount), f.GetDirection()) if err != nil { return f, err } funds.IncreaseAvailable(limitReducedAmount.Mul(adjustedPrice), f.GetDirection()) } ords := orderManager.GetOrdersSnapshot("") for i := range ords { if ords[i].ID != orderID { continue } ords[i].Date = o.GetTime() ords[i].LastUpdated = o.GetTime() ords[i].CloseTime = o.GetTime() f.Order = &ords[i] f.PurchasePrice = decimal.NewFromFloat(ords[i].Price) f.Total = f.PurchasePrice.Mul(limitReducedAmount).Add(f.ExchangeFee) } if f.Order == nil { return nil, fmt.Errorf("placed order %v not found in order manager", orderID) } return f, nil } // verifyOrderWithinLimits conforms the amount to fall into the minimum size and maximum size limit after reduced func verifyOrderWithinLimits(f *fill.Fill, limitReducedAmount decimal.Decimal, cs *Settings) error { if f == nil { return common.ErrNilEvent } if cs == nil { return errNilCurrencySettings } isBeyondLimit := false var minMax MinMax var direction gctorder.Side switch f.GetDirection() { case gctorder.Buy: minMax = cs.BuySide direction = common.CouldNotBuy case gctorder.Sell: minMax = cs.SellSide direction = common.CouldNotSell default: direction = f.GetDirection() f.SetDirection(common.DoNothing) return fmt.Errorf("%w: %v", errInvalidDirection, direction) } var minOrMax, belowExceed string var size decimal.Decimal if limitReducedAmount.LessThan(minMax.MinimumSize) && minMax.MinimumSize.GreaterThan(decimal.Zero) { isBeyondLimit = true belowExceed = "below" minOrMax = "minimum" size = minMax.MinimumSize } if limitReducedAmount.GreaterThan(minMax.MaximumSize) && minMax.MaximumSize.GreaterThan(decimal.Zero) { isBeyondLimit = true belowExceed = "exceeded" minOrMax = "maximum" size = minMax.MaximumSize } if isBeyondLimit { f.SetDirection(direction) e := fmt.Sprintf("Order size %v %s %s size %v", limitReducedAmount, belowExceed, minOrMax, size) f.AppendReason(e) return fmt.Errorf("%w %v", errExceededPortfolioLimit, e) } return nil } func reduceAmountToFitPortfolioLimit(adjustedPrice, amount, sizedPortfolioTotal decimal.Decimal, side gctorder.Side) decimal.Decimal { switch side { case gctorder.Buy: if adjustedPrice.Mul(amount).GreaterThan(sizedPortfolioTotal) { // adjusted amounts exceeds portfolio manager's allowed funds // the amount has to be reduced to equal the sizedPortfolioTotal amount = sizedPortfolioTotal.Div(adjustedPrice) } case gctorder.Sell: if amount.GreaterThan(sizedPortfolioTotal) { amount = sizedPortfolioTotal } } return amount } func (e *Exchange) placeOrder(ctx context.Context, price, amount decimal.Decimal, useRealOrders, useExchangeLimits bool, f *fill.Fill, orderManager *engine.OrderManager) (string, error) { if f == nil { return "", common.ErrNilEvent } u, err := uuid.NewV4() if err != nil { return "", err } var orderID string p, _ := price.Float64() a, _ := amount.Float64() fee, _ := f.ExchangeFee.Float64() o := &gctorder.Submit{ Price: p, Amount: a, Fee: fee, Exchange: f.Exchange, ID: u.String(), Side: f.Direction, AssetType: f.AssetType, Date: f.GetTime(), LastUpdated: f.GetTime(), Pair: f.Pair(), Type: gctorder.Market, } if useRealOrders { resp, err := orderManager.Submit(ctx, o) if resp != nil { orderID = resp.OrderID } if err != nil { return orderID, err } } else { rate, _ := f.Amount.Float64() submitResponse := gctorder.SubmitResponse{ IsOrderPlaced: true, OrderID: u.String(), Rate: rate, Fee: fee, Cost: p, FullyMatched: true, } resp, err := orderManager.SubmitFakeOrder(o, submitResponse, useExchangeLimits) if resp != nil { orderID = resp.OrderID } if err != nil { return orderID, err } } return orderID, nil } func (e *Exchange) sizeOfflineOrder(high, low, volume decimal.Decimal, cs *Settings, f *fill.Fill) (adjustedPrice, adjustedAmount decimal.Decimal, err error) { if cs == nil || f == nil { return decimal.Zero, decimal.Zero, common.ErrNilArguments } // provide history and estimate volatility slippageRate := slippage.EstimateSlippagePercentage(cs.MinimumSlippageRate, cs.MaximumSlippageRate) if cs.SkipCandleVolumeFitting { f.VolumeAdjustedPrice = f.ClosePrice adjustedAmount = f.Amount } else { f.VolumeAdjustedPrice, adjustedAmount = ensureOrderFitsWithinHLV(f.ClosePrice, f.Amount, high, low, volume) if !adjustedAmount.Equal(f.Amount) { f.AppendReason(fmt.Sprintf("Order size shrunk from %v to %v to fit candle", f.Amount, adjustedAmount)) } } if adjustedAmount.LessThanOrEqual(decimal.Zero) && f.Amount.GreaterThan(decimal.Zero) { return decimal.Zero, decimal.Zero, fmt.Errorf("amount set to 0, %w", errDataMayBeIncorrect) } adjustedPrice = applySlippageToPrice(f.GetDirection(), f.GetVolumeAdjustedPrice(), slippageRate) f.Slippage = slippageRate.Mul(decimal.NewFromInt(100)).Sub(decimal.NewFromInt(100)) f.ExchangeFee = calculateExchangeFee(adjustedPrice, adjustedAmount, cs.TakerFee) return adjustedPrice, adjustedAmount, nil } func applySlippageToPrice(direction gctorder.Side, price, slippageRate decimal.Decimal) decimal.Decimal { adjustedPrice := price if direction == gctorder.Buy { adjustedPrice = price.Add(price.Mul(decimal.NewFromInt(1).Sub(slippageRate))) } else if direction == gctorder.Sell { adjustedPrice = price.Mul(slippageRate) } return adjustedPrice } // SetExchangeAssetCurrencySettings sets the settings for an exchange, asset, currency func (e *Exchange) SetExchangeAssetCurrencySettings(exch string, a asset.Item, cp currency.Pair, c *Settings) { if c.Exchange == "" || c.Asset == "" || c.Pair.IsEmpty() { return } for i := range e.CurrencySettings { if e.CurrencySettings[i].Pair == cp && e.CurrencySettings[i].Asset == a && exch == e.CurrencySettings[i].Exchange { e.CurrencySettings[i] = *c return } } e.CurrencySettings = append(e.CurrencySettings, *c) } // GetCurrencySettings returns the settings for an exchange, asset currency func (e *Exchange) GetCurrencySettings(exch string, a asset.Item, cp currency.Pair) (Settings, error) { for i := range e.CurrencySettings { if e.CurrencySettings[i].Pair.Equal(cp) { if e.CurrencySettings[i].Asset == a { if exch == e.CurrencySettings[i].Exchange { return e.CurrencySettings[i], nil } } } } return Settings{}, fmt.Errorf("no currency settings found for %v %v %v", exch, a, cp) } func ensureOrderFitsWithinHLV(slippagePrice, amount, high, low, volume decimal.Decimal) (adjustedPrice, adjustedAmount decimal.Decimal) { adjustedPrice = slippagePrice if adjustedPrice.LessThan(low) { adjustedPrice = low } if adjustedPrice.GreaterThan(high) { adjustedPrice = high } if volume.LessThanOrEqual(decimal.Zero) { return adjustedPrice, adjustedAmount } currentVolume := amount.Mul(adjustedPrice) if currentVolume.GreaterThan(volume) { // reduce the volume to not exceed the total volume of the candle // it is slightly less than the total to still allow for the illusion // that open high low close values are valid with the remaining volume // this is very opinionated currentVolume = volume.Mul(decimal.NewFromFloat(0.99999999)) } // extract the amount from the adjusted volume adjustedAmount = currentVolume.Div(adjustedPrice) return adjustedPrice, adjustedAmount } func calculateExchangeFee(price, amount, fee decimal.Decimal) decimal.Decimal { return fee.Mul(price).Mul(amount) } <file_sep>package common import "fmt" // DataTypeToInt converts the config string value into an int func DataTypeToInt(dataType string) (int64, error) { switch dataType { case CandleStr: return DataCandle, nil case TradeStr: return DataTrade, nil default: return 0, fmt.Errorf("unrecognised dataType '%v'", dataType) } } <file_sep>package funding import ( "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/data/kline" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) // FundManager is the benevolent holder of all funding levels across all // currencies used in the backtester type FundManager struct { usingExchangeLevelFunding bool disableUSDTracking bool items []*Item } // IFundingManager limits funding usage for portfolio event handling type IFundingManager interface { Reset() IsUsingExchangeLevelFunding() bool GetFundingForEAC(string, asset.Item, currency.Code) (*Item, error) GetFundingForEvent(common.EventHandler) (*Pair, error) GetFundingForEAP(string, asset.Item, currency.Pair) (*Pair, error) Transfer(decimal.Decimal, *Item, *Item, bool) error GenerateReport() *Report AddUSDTrackingData(*kline.DataFromKline) error CreateSnapshot(time.Time) USDTrackingDisabled() bool } // IFundTransferer allows for funding amounts to be transferred // implementation can be swapped for live transferring type IFundTransferer interface { IsUsingExchangeLevelFunding() bool Transfer(decimal.Decimal, *Item, *Item, bool) error GetFundingForEAC(string, asset.Item, currency.Code) (*Item, error) GetFundingForEvent(common.EventHandler) (*Pair, error) GetFundingForEAP(string, asset.Item, currency.Pair) (*Pair, error) } // IPairReader is used to limit pair funding functions // to readonly type IPairReader interface { BaseInitialFunds() decimal.Decimal QuoteInitialFunds() decimal.Decimal BaseAvailable() decimal.Decimal QuoteAvailable() decimal.Decimal } // IPairReserver limits funding usage for portfolio event handling type IPairReserver interface { IPairReader CanPlaceOrder(order.Side) bool Reserve(decimal.Decimal, order.Side) error } // IPairReleaser limits funding usage for exchange event handling type IPairReleaser interface { IncreaseAvailable(decimal.Decimal, order.Side) Release(decimal.Decimal, decimal.Decimal, order.Side) error } // Item holds funding data per currency item type Item struct { exchange string asset asset.Item currency currency.Code initialFunds decimal.Decimal available decimal.Decimal reserved decimal.Decimal transferFee decimal.Decimal pairedWith *Item usdTrackingCandles *kline.DataFromKline snapshot map[time.Time]ItemSnapshot } // Pair holds two currencies that are associated with each other type Pair struct { Base *Item Quote *Item } // Report holds all funding data for result reporting type Report struct { DisableUSDTracking bool UsingExchangeLevelFunding bool Items []ReportItem USDTotalsOverTime map[time.Time]ItemSnapshot } // ReportItem holds reporting fields type ReportItem struct { Exchange string Asset asset.Item Currency currency.Code TransferFee decimal.Decimal InitialFunds decimal.Decimal FinalFunds decimal.Decimal USDInitialFunds decimal.Decimal USDInitialCostForOne decimal.Decimal USDFinalFunds decimal.Decimal USDFinalCostForOne decimal.Decimal Snapshots []ItemSnapshot USDPairCandle *kline.DataFromKline Difference decimal.Decimal ShowInfinite bool PairedWith currency.Code } // ItemSnapshot holds USD values to allow for tracking // across backtesting results type ItemSnapshot struct { Time time.Time Available decimal.Decimal USDClosePrice decimal.Decimal USDValue decimal.Decimal } <file_sep>package alert import ( "sync" "sync/atomic" ) // Notice defines fields required to alert sub-systems of a change of state so a // routine can re-check in memory data type Notice struct { // Channel to wait for an alert on. forAlert chan struct{} // Lets the updater functions know if there are any routines waiting for an // alert. sema uint32 // After closing the forAlert channel this will notify when all the routines // that have waited, have completed their checks. wg sync.WaitGroup // Segregated lock only for waiting routines, so as this does not interfere // with the main calling lock, this acts as a rolling gate. m sync.Mutex } // Alert establishes a state change on the required struct. func (n *Notice) Alert() { // CompareAndSwap is used to swap from 1 -> 2 so we don't keep actuating // the opposing compare and swap in method wait. This function can return // freely when an alert operation is in process. if !atomic.CompareAndSwapUint32(&n.sema, 1, 2) { // Return if no waiting routines or currently alerting. return } go n.actuate() } // Actuate lock in a different routine, as alerting is a second order priority // compared to updating and releasing calling routine. func (n *Notice) actuate() { n.m.Lock() // Closing; alerts many waiting routines. close(n.forAlert) // Wait for waiting routines to receive alert and return. n.wg.Wait() atomic.SwapUint32(&n.sema, 0) // Swap back to neutral state. n.m.Unlock() } // Wait pauses calling routine until change of state has been established via // notice method Alert. Kick allows for cancellation of waiting or when the // caller has been shut down, if this is not needed it can be set to nil. This // returns a channel so strategies can cleanly wait on a select statement case. func (n *Notice) Wait(kick <-chan struct{}) <-chan bool { reply := make(chan bool) n.m.Lock() n.wg.Add(1) if atomic.CompareAndSwapUint32(&n.sema, 0, 1) { n.forAlert = make(chan struct{}) } go n.hold(reply, kick) n.m.Unlock() return reply } // hold waits on either channel in the event that the routine has // finished/cancelled or an alert from an update has occurred. func (n *Notice) hold(ch chan<- bool, kick <-chan struct{}) { select { // In a select statement, if by chance there is no receiver or its late, // we can still close and return, limiting dead-lock potential. case <-n.forAlert: // Main waiting channel from alert select { case ch <- false: default: } case <-kick: // This can be nil. select { case ch <- true: default: } } n.wg.Done() close(ch) } <file_sep>package orderbook import ( "errors" "reflect" "testing" "time" "github.com/gofrs/uuid" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" ) var id, _ = uuid.NewV4() func TestGetLength(t *testing.T) { d := newDepth(id) if d.GetAskLength() != 0 { t.Errorf("expected len %v, but received %v", 0, d.GetAskLength()) } d.asks.load([]Item{{Price: 1337}}, d.stack) if d.GetAskLength() != 1 { t.Errorf("expected len %v, but received %v", 1, d.GetAskLength()) } d = newDepth(id) if d.GetBidLength() != 0 { t.Errorf("expected len %v, but received %v", 0, d.GetBidLength()) } d.bids.load([]Item{{Price: 1337}}, d.stack) if d.GetBidLength() != 1 { t.Errorf("expected len %v, but received %v", 1, d.GetBidLength()) } } func TestRetrieve(t *testing.T) { d := newDepth(id) d.asks.load([]Item{{Price: 1337}}, d.stack) d.bids.load([]Item{{Price: 1337}}, d.stack) d.options = options{ exchange: "THE BIG ONE!!!!!!", pair: currency.NewPair(currency.THETA, currency.USD), asset: "Silly asset", lastUpdated: time.Now(), lastUpdateID: 007, priceDuplication: true, isFundingRate: true, VerifyOrderbook: true, restSnapshot: true, idAligned: true, } // If we add anymore options to the options struct later this will complain // generally want to return a full carbon copy mirrored := reflect.Indirect(reflect.ValueOf(d.options)) for n := 0; n < mirrored.NumField(); n++ { structVal := mirrored.Field(n) if structVal.IsZero() { t.Fatalf("struct value options not set for field %v", mirrored.Type().Field(n).Name) } } theBigD := d.Retrieve() if len(theBigD.Asks) != 1 { t.Errorf("expected len %v, but received %v", 1, len(theBigD.Bids)) } if len(theBigD.Bids) != 1 { t.Errorf("expected len %v, but received %v", 1, len(theBigD.Bids)) } } func TestTotalAmounts(t *testing.T) { d := newDepth(id) liquidity, value := d.TotalBidAmounts() if liquidity != 0 || value != 0 { t.Fatalf("liquidity expected %f received %f value expected %f received %f", 0., liquidity, 0., value) } liquidity, value = d.TotalAskAmounts() if liquidity != 0 || value != 0 { t.Fatalf("liquidity expected %f received %f value expected %f received %f", 0., liquidity, 0., value) } d.asks.load([]Item{{Price: 1337, Amount: 1}}, d.stack) d.bids.load([]Item{{Price: 1337, Amount: 10}}, d.stack) liquidity, value = d.TotalBidAmounts() if liquidity != 10 || value != 13370 { t.Fatalf("liquidity expected %f received %f value expected %f received %f", 10., liquidity, 13370., value) } liquidity, value = d.TotalAskAmounts() if liquidity != 1 || value != 1337 { t.Fatalf("liquidity expected %f received %f value expected %f received %f", 1., liquidity, 1337., value) } } func TestLoadSnapshot(t *testing.T) { d := newDepth(id) d.LoadSnapshot(Items{{Price: 1337, Amount: 1}}, Items{{Price: 1337, Amount: 10}}, 0, time.Time{}, false) if d.Retrieve().Asks[0].Price != 1337 || d.Retrieve().Bids[0].Price != 1337 { t.Fatal("not set") } } func TestFlush(t *testing.T) { d := newDepth(id) d.LoadSnapshot(Items{{Price: 1337, Amount: 1}}, Items{{Price: 1337, Amount: 10}}, 0, time.Time{}, false) d.Flush() if len(d.Retrieve().Asks) != 0 || len(d.Retrieve().Bids) != 0 { t.Fatal("not flushed") } d.LoadSnapshot(Items{{Price: 1337, Amount: 1}}, Items{{Price: 1337, Amount: 10}}, 0, time.Time{}, false) d.Flush() if len(d.Retrieve().Asks) != 0 || len(d.Retrieve().Bids) != 0 { t.Fatal("not flushed") } } func TestUpdateBidAskByPrice(t *testing.T) { d := newDepth(id) d.LoadSnapshot(Items{{Price: 1337, Amount: 1, ID: 1}}, Items{{Price: 1337, Amount: 10, ID: 2}}, 0, time.Time{}, false) d.UpdateBidAskByPrice(Items{{Price: 1337, Amount: 2, ID: 1}}, Items{{Price: 1337, Amount: 2, ID: 2}}, 0, 0, time.Time{}) if d.Retrieve().Asks[0].Amount != 2 || d.Retrieve().Bids[0].Amount != 2 { t.Fatal("orderbook amounts not updated correctly") } d.UpdateBidAskByPrice(Items{{Price: 1337, Amount: 0, ID: 1}}, Items{{Price: 1337, Amount: 0, ID: 2}}, 0, 0, time.Time{}) if d.GetAskLength() != 0 || d.GetBidLength() != 0 { t.Fatal("orderbook amounts not updated correctly") } } func TestDeleteBidAskByID(t *testing.T) { d := newDepth(id) d.LoadSnapshot(Items{{Price: 1337, Amount: 1, ID: 1}}, Items{{Price: 1337, Amount: 10, ID: 2}}, 0, time.Time{}, false) err := d.DeleteBidAskByID(Items{{Price: 1337, Amount: 2, ID: 1}}, Items{{Price: 1337, Amount: 2, ID: 2}}, false, 0, time.Time{}) if err != nil { t.Fatal(err) } if len(d.Retrieve().Asks) != 0 || len(d.Retrieve().Bids) != 0 { t.Fatal("items not deleted") } err = d.DeleteBidAskByID(Items{{Price: 1337, Amount: 2, ID: 1}}, nil, false, 0, time.Time{}) if !errors.Is(err, errIDCannotBeMatched) { t.Fatalf("error expected %v received %v", errIDCannotBeMatched, err) } err = d.DeleteBidAskByID(nil, Items{{Price: 1337, Amount: 2, ID: 2}}, false, 0, time.Time{}) if !errors.Is(err, errIDCannotBeMatched) { t.Fatalf("error expected %v received %v", errIDCannotBeMatched, err) } err = d.DeleteBidAskByID(nil, Items{{Price: 1337, Amount: 2, ID: 2}}, true, 0, time.Time{}) if !errors.Is(err, nil) { t.Fatalf("error expected %v received %v", nil, err) } } func TestUpdateBidAskByID(t *testing.T) { d := newDepth(id) d.LoadSnapshot(Items{{Price: 1337, Amount: 1, ID: 1}}, Items{{Price: 1337, Amount: 10, ID: 2}}, 0, time.Time{}, false) err := d.UpdateBidAskByID(Items{{Price: 1337, Amount: 2, ID: 1}}, Items{{Price: 1337, Amount: 2, ID: 2}}, 0, time.Time{}) if err != nil { t.Fatal(err) } if d.Retrieve().Asks[0].Amount != 2 || d.Retrieve().Bids[0].Amount != 2 { t.Fatal("orderbook amounts not updated correctly") } // random unmatching IDs err = d.UpdateBidAskByID(Items{{Price: 1337, Amount: 2, ID: 666}}, nil, 0, time.Time{}) if !errors.Is(err, errIDCannotBeMatched) { t.Fatalf("error expected %v received %v", errIDCannotBeMatched, err) } err = d.UpdateBidAskByID(nil, Items{{Price: 1337, Amount: 2, ID: 69}}, 0, time.Time{}) if !errors.Is(err, errIDCannotBeMatched) { t.Fatalf("error expected %v received %v", errIDCannotBeMatched, err) } } func TestInsertBidAskByID(t *testing.T) { d := newDepth(id) d.LoadSnapshot(Items{{Price: 1337, Amount: 1, ID: 1}}, Items{{Price: 1337, Amount: 10, ID: 2}}, 0, time.Time{}, false) err := d.InsertBidAskByID(Items{{Price: 1338, Amount: 2, ID: 3}}, Items{{Price: 1336, Amount: 2, ID: 4}}, 0, time.Time{}) if err != nil { t.Fatal(err) } if len(d.Retrieve().Asks) != 2 || len(d.Retrieve().Bids) != 2 { t.Fatal("items not added correctly") } } func TestUpdateInsertByID(t *testing.T) { d := newDepth(id) d.LoadSnapshot(Items{{Price: 1337, Amount: 1, ID: 1}}, Items{{Price: 1337, Amount: 10, ID: 2}}, 0, time.Time{}, false) err := d.UpdateInsertByID(Items{{Price: 1338, Amount: 0, ID: 3}}, Items{{Price: 1336, Amount: 2, ID: 4}}, 0, time.Time{}) if !errors.Is(err, errAmountCannotBeLessOrEqualToZero) { t.Fatalf("expected: %v but received: %v", errAmountCannotBeLessOrEqualToZero, err) } err = d.UpdateInsertByID(Items{{Price: 1338, Amount: 2, ID: 3}}, Items{{Price: 1336, Amount: 0, ID: 4}}, 0, time.Time{}) if !errors.Is(err, errAmountCannotBeLessOrEqualToZero) { t.Fatalf("expected: %v but received: %v", errAmountCannotBeLessOrEqualToZero, err) } err = d.UpdateInsertByID(Items{{Price: 1338, Amount: 2, ID: 3}}, Items{{Price: 1336, Amount: 2, ID: 4}}, 0, time.Time{}) if err != nil { t.Fatal(err) } if len(d.Retrieve().Asks) != 2 || len(d.Retrieve().Bids) != 2 { t.Fatal("items not added correctly") } } func TestAssignOptions(t *testing.T) { d := Depth{} cp := currency.NewPair(currency.LINK, currency.BTC) tn := time.Now() d.AssignOptions(&Base{ Exchange: "test", Pair: cp, Asset: asset.Spot, LastUpdated: tn, LastUpdateID: 1337, PriceDuplication: true, IsFundingRate: true, VerifyOrderbook: true, RestSnapshot: true, IDAlignment: true, }) if d.exchange != "test" || d.pair != cp || d.asset != asset.Spot || d.lastUpdated != tn || d.lastUpdateID != 1337 || !d.priceDuplication || !d.isFundingRate || !d.VerifyOrderbook || !d.restSnapshot || !d.idAligned { t.Fatal("failed to set correctly") } } func TestGetName(t *testing.T) { d := Depth{} d.exchange = "test" if d.GetName() != "test" { t.Fatal("failed to get correct value") } } func TestIsRestSnapshot(t *testing.T) { d := Depth{} d.restSnapshot = true if !d.IsRestSnapshot() { t.Fatal("failed to set correctly") } } func TestLastUpdateID(t *testing.T) { d := Depth{} d.lastUpdateID = 1337 if d.LastUpdateID() != 1337 { t.Fatal("failed to get correct value") } } func TestIsFundingRate(t *testing.T) { d := Depth{} d.isFundingRate = true if !d.IsFundingRate() { t.Fatal("failed to get correct value") } } func TestPublish(t *testing.T) { d := Depth{} d.Publish() } <file_sep>package main import ( "flag" "fmt" "os" "path/filepath" "github.com/idoall/gocryptotrader/backtester/backtest" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/config" "github.com/idoall/gocryptotrader/log" "github.com/idoall/gocryptotrader/signaler" ) func main() { var configPath, templatePath, reportOutput string var printLogo, generateReport, darkReport bool wd, err := os.Getwd() if err != nil { fmt.Printf("Could not get working directory. Error: %v.\n", err) os.Exit(1) } flag.StringVar( &configPath, "configpath", filepath.Join( wd, "config", "examples", "dca-api-candles.strat"), "the config containing strategy params") flag.StringVar( &templatePath, "templatepath", filepath.Join( wd, "report", "tpl.gohtml"), "the report template to use") flag.BoolVar( &generateReport, "generatereport", true, "whether to generate the report file") flag.StringVar( &reportOutput, "outputpath", filepath.Join( wd, "results"), "the path where to output results") flag.BoolVar( &printLogo, "printlogo", true, "print out the logo to the command line, projected profits likely won't be affected if disabled") flag.BoolVar( &darkReport, "darkreport", false, "sets the output report to use a dark theme by default") flag.Parse() var bt *backtest.BackTest var cfg *config.Config log.GlobalLogConfig = log.GenDefaultSettings() err = log.SetupGlobalLogger() if err != nil { fmt.Printf("Could not setup global logger. Error: %v.\n", err) os.Exit(1) } cfg, err = config.ReadConfigFromFile(configPath) if err != nil { fmt.Printf("Could not read config. Error: %v.\n", err) os.Exit(1) } if printLogo { fmt.Print(common.ASCIILogo) } err = cfg.Validate() if err != nil { fmt.Printf("Could not read config. Error: %v.\n", err) os.Exit(1) } bt, err = backtest.NewFromConfig(cfg, templatePath, reportOutput) if err != nil { fmt.Printf("Could not setup backtester from config. Error: %v.\n", err) os.Exit(1) } if cfg.DataSettings.LiveData != nil { go func() { err = bt.RunLive() if err != nil { fmt.Printf("Could not complete live run. Error: %v.\n", err) os.Exit(-1) } }() interrupt := signaler.WaitForInterrupt() log.Infof(log.Global, "Captured %v, shutdown requested.\n", interrupt) bt.Stop() } else { err = bt.Run() if err != nil { fmt.Printf("Could not complete run. Error: %v.\n", err) os.Exit(1) } } err = bt.Statistic.CalculateAllResults() if err != nil { log.Error(log.BackTester, err) os.Exit(1) } if generateReport { bt.Reports.UseDarkMode(darkReport) err = bt.Reports.GenerateReport() if err != nil { log.Error(log.BackTester, err) } } } <file_sep>package gateio import "github.com/idoall/gocryptotrader/currency" const ( gateioFeeList = "/private/feelist" ) // SpotMarketInfoResponse holds the market info data type SpotMarketInfoResponse struct { Result string `json:"result"` Pairs []SpotMarketInfoPairsResponse `json:"pairs"` } // SpotMarketInfoPairsResponse 交易市场的参数信息-交易对 type SpotMarketInfoPairsResponse struct { Symbol currency.Pair // DecimalPlaces 价格精度 DecimalPlaces float64 // DecimalPlaces 价格精度 AmountDecimalPlaces float64 // MinAmount 最小下单量 MinAmount float64 // MinAmountA 最小下单量 MinAmountA float64 // MinAmountB 最小下单量 MinAmountB float64 // Fee 交易费 Fee float64 // TradeDisabled 是否禁止交易 TradeDisabled bool // BuyDisabled 是否禁止买 BuyDisabled bool // BuyDisabled 是否禁止卖 SellDisabled bool } <file_sep>package currency import ( "encoding/json" "strings" ) // String returns a currency pair string func (p Pair) String() string { return p.Base.String() + p.Delimiter + p.Quote.String() } // Lower converts the pair object to lowercase func (p Pair) Lower() Pair { return Pair{ Delimiter: p.Delimiter, Base: p.Base.Lower(), Quote: p.Quote.Lower(), } } // Upper converts the pair object to uppercase func (p Pair) Upper() Pair { return Pair{ Delimiter: p.Delimiter, Base: p.Base.Upper(), Quote: p.Quote.Upper(), } } // UnmarshalJSON comforms type to the umarshaler interface func (p *Pair) UnmarshalJSON(d []byte) error { var pair string err := json.Unmarshal(d, &pair) if err != nil { return err } newPair, err := NewPairFromString(pair) if err != nil { return err } p.Base = newPair.Base p.Quote = newPair.Quote p.Delimiter = newPair.Delimiter return nil } // MarshalJSON conforms type to the marshaler interface func (p Pair) MarshalJSON() ([]byte, error) { return json.Marshal(p.String()) } // Format changes the currency based on user preferences overriding the default // String() display func (p Pair) Format(delimiter string, uppercase bool) Pair { newP := Pair{Base: p.Base, Quote: p.Quote, Delimiter: delimiter} if uppercase { return newP.Upper() } return newP.Lower() } // Equal compares two currency pairs and returns whether or not they are equal func (p Pair) Equal(cPair Pair) bool { return strings.EqualFold(p.Base.String(), cPair.Base.String()) && strings.EqualFold(p.Quote.String(), cPair.Quote.String()) } // EqualIncludeReciprocal compares two currency pairs and returns whether or not // they are the same including reciprocal currencies. func (p Pair) EqualIncludeReciprocal(cPair Pair) bool { if (p.Base.Item == cPair.Base.Item && p.Quote.Item == cPair.Quote.Item) || (p.Base.Item == cPair.Quote.Item && p.Quote.Item == cPair.Base.Item) { return true } return false } // IsCryptoPair checks to see if the pair is a crypto pair e.g. BTCLTC func (p Pair) IsCryptoPair() bool { return storage.IsCryptocurrency(p.Base) && storage.IsCryptocurrency(p.Quote) } // IsCryptoFiatPair checks to see if the pair is a crypto fiat pair e.g. BTCUSD func (p Pair) IsCryptoFiatPair() bool { return (storage.IsCryptocurrency(p.Base) && storage.IsFiatCurrency(p.Quote)) || (storage.IsFiatCurrency(p.Base) && storage.IsCryptocurrency(p.Quote)) } // IsFiatPair checks to see if the pair is a fiat pair e.g. EURUSD func (p Pair) IsFiatPair() bool { return storage.IsFiatCurrency(p.Base) && storage.IsFiatCurrency(p.Quote) } // IsInvalid checks invalid pair if base and quote are the same func (p Pair) IsInvalid() bool { return p.Base.Item == p.Quote.Item } // Swap turns the currency pair into its reciprocal func (p Pair) Swap() Pair { return Pair{Base: p.Quote, Quote: p.Base} } // IsEmpty returns whether or not the pair is empty or is missing a currency // code func (p Pair) IsEmpty() bool { return p.Base.IsEmpty() && p.Quote.IsEmpty() } // ContainsCurrency checks to see if a pair contains a specific currency func (p Pair) ContainsCurrency(c Code) bool { return p.Base.Item == c.Item || p.Quote.Item == c.Item } <file_sep>package order import ( "errors" "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" ) // var error definitions var ( ErrSubmissionIsNil = errors.New("order submission is nil") ErrCancelOrderIsNil = errors.New("cancel order is nil") ErrGetOrdersRequestIsNil = errors.New("get order request is nil") ErrModifyOrderIsNil = errors.New("modify order request is nil") ErrPairIsEmpty = errors.New("order pair is empty") ErrAssetNotSet = errors.New("order asset type is not set") ErrSideIsInvalid = errors.New("order side is invalid") ErrTypeIsInvalid = errors.New("order type is invalid") ErrAmountIsInvalid = errors.New("order amount is equal or less than zero") ErrPriceMustBeSetIfLimitOrder = errors.New("order price must be set if limit order type is desired") ErrOrderIDNotSet = errors.New("order id or client order id is not set") ) // Submit contains all properties of an order that may be required // for an order to be created on an exchange // Each exchange has their own requirements, so not all fields // are required to be populated type Submit struct { ImmediateOrCancel bool HiddenOrder bool FillOrKill bool PostOnly bool ReduceOnly bool Leverage float64 QuoteOrderQty float64 // 币安需要,市价单时使用成交额 PositionSide string // 币安合约使用, 持仓方向,单向持仓模式下非必填,默认且仅可填BOTH;在双向持仓模式下必填,且仅可选择 LONG 或 SHORT Price float64 Amount float64 StopPrice float64 LimitPriceUpper float64 LimitPriceLower float64 TriggerPrice float64 TargetAmount float64 ExecutedAmount float64 RemainingAmount float64 Fee float64 Exchange string InternalOrderID string ID string AccountID string ClientID string ClientOrderID string WalletAddress string Offset string Type Type Side Side Status Status AssetType asset.Item Date time.Time LastUpdated time.Time Pair currency.Pair Trades []TradeHistory } // SubmitResponse is what is returned after submitting an order to an exchange type SubmitResponse struct { IsOrderPlaced bool FullyMatched bool OrderID string Rate float64 Fee float64 Cost float64 Trades []TradeHistory } // Modify contains all properties of an order // that may be updated after it has been created // Each exchange has their own requirements, so not all fields // are required to be populated type Modify struct { ImmediateOrCancel bool HiddenOrder bool FillOrKill bool PostOnly bool Leverage float64 Price float64 Amount float64 LimitPriceUpper float64 LimitPriceLower float64 TriggerPrice float64 TargetAmount float64 ExecutedAmount float64 RemainingAmount float64 Fee float64 Exchange string InternalOrderID string ID string ClientOrderID string AccountID string ClientID string WalletAddress string Type Type Side Side Status Status AssetType asset.Item Date time.Time LastUpdated time.Time Pair currency.Pair Trades []TradeHistory } // ModifyResponse is an order modifying return type type ModifyResponse struct { OrderID string } // Detail contains all properties of an order // Each exchange has their own requirements, so not all fields // are required to be populated type Detail struct { ImmediateOrCancel bool HiddenOrder bool FillOrKill bool PostOnly bool Leverage float64 Price float64 Amount float64 LimitPriceUpper float64 LimitPriceLower float64 TriggerPrice float64 AverageExecutedPrice float64 TargetAmount float64 ExecutedAmount float64 RemainingAmount float64 Cost float64 CostAsset currency.Code Fee float64 FeeAsset currency.Code Exchange string InternalOrderID string ID string ClientOrderID string AccountID string ClientID string WalletAddress string Type Type Side Side Status Status AssetType asset.Item Date time.Time CloseTime time.Time LastUpdated time.Time Pair currency.Pair Trades []TradeHistory StopPrice float64 TimeInForce string } // Filter contains all properties an order can be filtered for // empty strings indicate to ignore the property otherwise all need to match type Filter struct { Exchange string InternalOrderID string ID string ClientOrderID string AccountID string ClientID string WalletAddress string Type Type Side Side Status Status AssetType asset.Item Pair currency.Pair } // Cancel contains all properties that may be required // to cancel an order on an exchange // Each exchange has their own requirements, so not all fields // are required to be populated type Cancel struct { Price float64 Amount float64 Exchange string ID string ClientOrderID string AccountID string ClientID string WalletAddress string Type Type Side Side Status Status AssetType asset.Item Date time.Time Pair currency.Pair Symbol string Trades []TradeHistory } // CancelAllResponse returns the status from attempting to // cancel all orders on an exchange type CancelAllResponse struct { Status map[string]string Count int64 } // CancelBatchResponse returns the status of orders // that have been requested for cancellation type CancelBatchResponse struct { Status map[string]string } // TradeHistory holds exchange history data type TradeHistory struct { Price float64 Amount float64 Fee float64 Exchange string TID string Description string Type Type Side Side Timestamp time.Time IsMaker bool FeeAsset string Total float64 } // GetOrdersRequest used for GetOrderHistory and GetOpenOrders wrapper functions type GetOrdersRequest struct { Type Type Side Side StartTime time.Time EndTime time.Time OrderID string // Currencies Empty array = all currencies. Some endpoints only support // singular currency enquiries Pairs currency.Pairs AssetType asset.Item } // Status defines order status types type Status string // All order status types const ( AnyStatus Status = "ANY" New Status = "NEW" Active Status = "ACTIVE" PartiallyCancelled Status = "PARTIALLY_CANCELLED" PartiallyFilled Status = "PARTIALLY_FILLED" Filled Status = "FILLED" Cancelled Status = "CANCELLED" PendingCancel Status = "PENDING_CANCEL" InsufficientBalance Status = "INSUFFICIENT_BALANCE" MarketUnavailable Status = "MARKET_UNAVAILABLE" Rejected Status = "REJECTED" Expired Status = "EXPIRED" Hidden Status = "HIDDEN" UnknownStatus Status = "UNKNOWN" Open Status = "OPEN" AutoDeleverage Status = "ADL" Closed Status = "CLOSED" Pending Status = "PENDING" ) // Type enforces a standard for order types across the code base type Type string // Defined package order types const ( AnyType Type = "ANY" Limit Type = "LIMIT" Market Type = "MARKET" PostOnly Type = "POST_ONLY" ImmediateOrCancel Type = "IMMEDIATE_OR_CANCEL" Stop Type = "STOP" StopLimit Type = "STOP LIMIT" StopLossLimit Type = "STOP_LOSS_LIMIT" StopMarket Type = "STOP MARKET" TakeProfit Type = "TAKE PROFIT" TakeProfitLimit Type = "TAKE_PROFIT_LIMIT" TakeProfitMarket Type = "TAKE PROFIT MARKET" TrailingStop Type = "TRAILING_STOP" FillOrKill Type = "FOK" IOS Type = "IOS" UnknownType Type = "UNKNOWN" Liquidation Type = "LIQUIDATION" Trigger Type = "TRIGGER" ) // Side enforces a standard for order sides across the code base type Side string // Order side types const ( AnySide Side = "ANY" Buy Side = "BUY" Sell Side = "SELL" Bid Side = "BID" Ask Side = "ASK" UnknownSide Side = "UNKNOWN" ) // ByPrice used for sorting orders by price type ByPrice []Detail // ByOrderType used for sorting orders by order type type ByOrderType []Detail // ByCurrency used for sorting orders by order currency type ByCurrency []Detail // ByDate used for sorting orders by order date type ByDate []Detail // ByOrderSide used for sorting orders by order side (buy sell) type ByOrderSide []Detail // ClassificationError returned when an order status // side or type cannot be recognised type ClassificationError struct { Exchange string OrderID string Err error } <file_sep>package currency import ( "encoding/json" "errors" "fmt" "strings" "unicode" ) func (r Role) String() string { switch r { case Unset: return UnsetRoleString case Fiat: return FiatCurrencyString case Cryptocurrency: return CryptocurrencyString case Token: return TokenString case Contract: return ContractString default: return "UNKNOWN" } } // MarshalJSON conforms Role to the marshaller interface func (r Role) MarshalJSON() ([]byte, error) { return json.Marshal(r.String()) } // UnmarshalJSON conforms Role to the unmarshaller interface func (r *Role) UnmarshalJSON(d []byte) error { var incoming string err := json.Unmarshal(d, &incoming) if err != nil { return err } switch incoming { case UnsetRoleString: *r = Unset case FiatCurrencyString: *r = Fiat case CryptocurrencyString: *r = Cryptocurrency case TokenString: *r = Token case ContractString: *r = Contract default: return fmt.Errorf("unmarshal error role type %s unsupported for currency", incoming) } return nil } // HasData returns true if the type contains data func (b *BaseCodes) HasData() bool { b.mtx.Lock() defer b.mtx.Unlock() return len(b.Items) != 0 } // GetFullCurrencyData returns a type that is read to dump to file func (b *BaseCodes) GetFullCurrencyData() (File, error) { var file File for i := range b.Items { switch b.Items[i].Role { case Unset: file.UnsetCurrency = append(file.UnsetCurrency, *b.Items[i]) case Fiat: file.FiatCurrency = append(file.FiatCurrency, *b.Items[i]) case Cryptocurrency: file.Cryptocurrency = append(file.Cryptocurrency, *b.Items[i]) case Token: file.Token = append(file.Token, *b.Items[i]) case Contract: file.Contracts = append(file.Contracts, *b.Items[i]) default: return file, errors.New("role undefined") } } file.LastMainUpdate = b.LastMainUpdate.Unix() return file, nil } // GetCurrencies gets the full currency list from the base code type available // from the currency system func (b *BaseCodes) GetCurrencies() Currencies { var currencies Currencies b.mtx.Lock() for i := range b.Items { currencies = append(currencies, Code{ Item: b.Items[i], }) } b.mtx.Unlock() return currencies } // UpdateCurrency updates or registers a currency/contract func (b *BaseCodes) UpdateCurrency(fullName, symbol, blockchain string, id int, r Role) error { if r == Unset { return fmt.Errorf("role cannot be unset in update currency for %s", symbol) } b.mtx.Lock() defer b.mtx.Unlock() for i := range b.Items { if b.Items[i].Symbol != symbol { continue } if b.Items[i].Role == Unset { b.Items[i].FullName = fullName b.Items[i].Role = r b.Items[i].AssocChain = blockchain b.Items[i].ID = id return nil } if b.Items[i].Role != r { // Captures same name currencies and duplicates to different roles break } b.Items[i].FullName = fullName b.Items[i].AssocChain = blockchain b.Items[i].ID = id return nil } b.Items = append(b.Items, &Item{ Symbol: symbol, FullName: fullName, Role: r, AssocChain: blockchain, ID: id, }) return nil } // Register registers a currency from a string and returns a currency code func (b *BaseCodes) Register(c string) Code { var format bool if c != "" { format = unicode.IsUpper(rune(c[0])) } // Force upper string storage and matching c = strings.ToUpper(c) b.mtx.Lock() defer b.mtx.Unlock() for i := range b.Items { if b.Items[i].Symbol == c { return Code{ Item: b.Items[i], UpperCase: format, } } } newItem := &Item{Symbol: c} b.Items = append(b.Items, newItem) return Code{ Item: newItem, UpperCase: format, } } // RegisterFiat registers a fiat currency from a string and returns a currency // code func (b *BaseCodes) RegisterFiat(c string) Code { c = strings.ToUpper(c) b.mtx.Lock() defer b.mtx.Unlock() for i := range b.Items { if b.Items[i].Symbol == c { if b.Items[i].Role == Unset { b.Items[i].Role = Fiat } if b.Items[i].Role != Fiat { continue } return Code{Item: b.Items[i], UpperCase: true} } } item := &Item{Symbol: c, Role: Fiat} b.Items = append(b.Items, item) return Code{Item: item, UpperCase: true} } // LoadItem sets item data func (b *BaseCodes) LoadItem(item *Item) error { b.mtx.Lock() defer b.mtx.Unlock() for i := range b.Items { if b.Items[i].Symbol != item.Symbol || (b.Items[i].Role != Unset && item.Role != Unset && b.Items[i].Role != item.Role) { continue } b.Items[i].AssocChain = item.AssocChain b.Items[i].ID = item.ID b.Items[i].Role = item.Role b.Items[i].FullName = item.FullName return nil } b.Items = append(b.Items, item) return nil } // NewCode returns a new currency registered code func NewCode(c string) Code { return storage.ValidateCode(c) } // String conforms to the stringer interface func (i *Item) String() string { return i.FullName } // String converts the code to string func (c Code) String() string { if c.Item == nil { return "" } if c.UpperCase { return strings.ToUpper(c.Item.Symbol) } return strings.ToLower(c.Item.Symbol) } // Lower converts the code to lowercase formatting func (c Code) Lower() Code { c.UpperCase = false return c } // Upper converts the code to uppercase formatting func (c Code) Upper() Code { c.UpperCase = true return c } // UnmarshalJSON comforms type to the umarshaler interface func (c *Code) UnmarshalJSON(d []byte) error { var newcode string err := json.Unmarshal(d, &newcode) if err != nil { return err } *c = NewCode(newcode) return nil } // MarshalJSON conforms type to the marshaler interface func (c Code) MarshalJSON() ([]byte, error) { if c.Item == nil { return json.Marshal("") } return json.Marshal(c.String()) } // IsEmpty returns true if the code is empty func (c Code) IsEmpty() bool { if c.Item == nil { return true } return c.Item.Symbol == "" } // Match returns if the code supplied is the same as the corresponding code func (c Code) Match(check Code) bool { return c.Item == check.Item } // IsDefaultFiatCurrency checks if the currency passed in matches the default // fiat currency func (c Code) IsDefaultFiatCurrency() bool { return storage.IsDefaultCurrency(c) } // IsDefaultCryptocurrency checks if the currency passed in matches the default // cryptocurrency func (c Code) IsDefaultCryptocurrency() bool { return storage.IsDefaultCryptocurrency(c) } // IsFiatCurrency checks if the currency passed is an enabled fiat currency func (c Code) IsFiatCurrency() bool { return storage.IsFiatCurrency(c) } // IsCryptocurrency checks if the currency passed is an enabled CRYPTO currency. func (c Code) IsCryptocurrency() bool { return storage.IsCryptocurrency(c) } <file_sep>package size import ( "fmt" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) // SizeOrder is responsible for ensuring that the order size is within config limits func (s *Size) SizeOrder(o order.Event, amountAvailable decimal.Decimal, cs *exchange.Settings) (*order.Order, error) { if o == nil || cs == nil { return nil, common.ErrNilArguments } if amountAvailable.LessThanOrEqual(decimal.Zero) { return nil, errNoFunds } retOrder, ok := o.(*order.Order) if !ok { return nil, fmt.Errorf("%w expected order event", common.ErrInvalidDataType) } var amount decimal.Decimal var err error switch retOrder.GetDirection() { case gctorder.Buy: // check size against currency specific settings amount, err = s.calculateBuySize(retOrder.Price, amountAvailable, cs.ExchangeFee, o.GetBuyLimit(), cs.BuySide) if err != nil { return nil, err } // check size against portfolio specific settings var portfolioSize decimal.Decimal portfolioSize, err = s.calculateBuySize(retOrder.Price, amountAvailable, cs.ExchangeFee, o.GetBuyLimit(), s.BuySide) if err != nil { return nil, err } // global settings overrule individual currency settings if amount.GreaterThan(portfolioSize) { amount = portfolioSize } case gctorder.Sell: // check size against currency specific settings amount, err = s.calculateSellSize(retOrder.Price, amountAvailable, cs.ExchangeFee, o.GetSellLimit(), cs.SellSide) if err != nil { return nil, err } // check size against portfolio specific settings portfolioSize, err := s.calculateSellSize(retOrder.Price, amountAvailable, cs.ExchangeFee, o.GetSellLimit(), s.SellSide) if err != nil { return nil, err } // global settings overrule individual currency settings if amount.GreaterThan(portfolioSize) { amount = portfolioSize } } amount = amount.Round(8) if amount.LessThanOrEqual(decimal.Zero) { return retOrder, fmt.Errorf("%w at %v for %v %v %v", errCannotAllocate, o.GetTime(), o.GetExchange(), o.GetAssetType(), o.Pair()) } retOrder.SetAmount(amount) return retOrder, nil } // calculateBuySize respects config rules and calculates the amount of money // that is allowed to be spent/sold for an event. // As fee calculation occurs during the actual ordering process // this can only attempt to factor the potential fee to remain under the max rules func (s *Size) calculateBuySize(price, availableFunds, feeRate, buyLimit decimal.Decimal, minMaxSettings exchange.MinMax) (decimal.Decimal, error) { if availableFunds.LessThanOrEqual(decimal.Zero) { return decimal.Zero, errNoFunds } if price.IsZero() { return decimal.Zero, nil } amount := availableFunds.Mul(decimal.NewFromInt(1).Sub(feeRate)).Div(price) if !buyLimit.IsZero() && buyLimit.GreaterThanOrEqual(minMaxSettings.MinimumSize) && (buyLimit.LessThanOrEqual(minMaxSettings.MaximumSize) || minMaxSettings.MaximumSize.IsZero()) && buyLimit.LessThanOrEqual(amount) { amount = buyLimit } if minMaxSettings.MaximumSize.GreaterThan(decimal.Zero) && amount.GreaterThan(minMaxSettings.MaximumSize) { amount = minMaxSettings.MaximumSize.Mul(decimal.NewFromInt(1).Sub(feeRate)) } if minMaxSettings.MaximumTotal.GreaterThan(decimal.Zero) && amount.Add(feeRate).Mul(price).GreaterThan(minMaxSettings.MaximumTotal) { amount = minMaxSettings.MaximumTotal.Mul(decimal.NewFromInt(1).Sub(feeRate)).Div(price) } if amount.LessThan(minMaxSettings.MinimumSize) && minMaxSettings.MinimumSize.GreaterThan(decimal.Zero) { return decimal.Zero, fmt.Errorf("%w. Sized: '%v' Minimum: '%v'", errLessThanMinimum, amount, minMaxSettings.MinimumSize) } return amount, nil } // calculateSellSize respects config rules and calculates the amount of money // that is allowed to be spent/sold for an event. // baseAmount is the base currency quantity that the portfolio currently has that can be sold // eg BTC-USD baseAmount will be BTC to be sold // As fee calculation occurs during the actual ordering process // this can only attempt to factor the potential fee to remain under the max rules func (s *Size) calculateSellSize(price, baseAmount, feeRate, sellLimit decimal.Decimal, minMaxSettings exchange.MinMax) (decimal.Decimal, error) { if baseAmount.LessThanOrEqual(decimal.Zero) { return decimal.Zero, errNoFunds } if price.IsZero() { return decimal.Zero, nil } oneMFeeRate := decimal.NewFromInt(1).Sub(feeRate) amount := baseAmount.Mul(oneMFeeRate) if !sellLimit.IsZero() && sellLimit.GreaterThanOrEqual(minMaxSettings.MinimumSize) && (sellLimit.LessThanOrEqual(minMaxSettings.MaximumSize) || minMaxSettings.MaximumSize.IsZero()) && sellLimit.LessThanOrEqual(amount) { amount = sellLimit } if minMaxSettings.MaximumSize.GreaterThan(decimal.Zero) && amount.GreaterThan(minMaxSettings.MaximumSize) { amount = minMaxSettings.MaximumSize.Mul(oneMFeeRate) } if minMaxSettings.MaximumTotal.GreaterThan(decimal.Zero) && amount.Mul(price).GreaterThan(minMaxSettings.MaximumTotal) { amount = minMaxSettings.MaximumTotal.Mul(oneMFeeRate).Div(price) } if amount.LessThan(minMaxSettings.MinimumSize) && minMaxSettings.MinimumSize.GreaterThan(decimal.Zero) { return decimal.Zero, fmt.Errorf("%w. Sized: '%v' Minimum: '%v'", errLessThanMinimum, amount, minMaxSettings.MinimumSize) } return amount, nil } <file_sep>package engine import ( "errors" "sync" "github.com/idoall/gocryptotrader/config" ) // websocketRoutineManager is used to process websocket updates from a unified location type websocketRoutineManager struct { started int32 verbose bool exchangeManager iExchangeManager orderManager iOrderManager syncer iCurrencyPairSyncer currencyConfig *config.CurrencyConfig shutdown chan struct{} wg sync.WaitGroup } var ( errNilOrderManager = errors.New("nil order manager received") errNilCurrencyPairSyncer = errors.New("nil currency pair syncer received") errNilCurrencyConfig = errors.New("nil currency config received") errNilCurrencyPairFormat = errors.New("nil currency pair format received") ) <file_sep>package common import ( "fmt" "testing" ) func TestDataTypeConversion(t *testing.T) { for _, ti := range []struct { title string dataType string want int64 expectErr bool }{ { title: "Candle data type", dataType: CandleStr, want: DataCandle, }, { title: "Trade data type", dataType: TradeStr, want: DataTrade, }, { title: "Unknown data type", dataType: "unknown", want: 0, expectErr: true, }, } { t.Run(ti.title, func(t *testing.T) { got, err := DataTypeToInt(ti.dataType) if ti.expectErr { if err == nil { t.Error("expected error") } } else { if err != nil || got != ti.want { t.Error(fmt.Errorf("%s: expected %d, got %d, err: %v", ti.dataType, ti.want, got, err)) } } }) } } <file_sep>package binance import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "strconv" "strings" "time" "github.com/gorilla/websocket" "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/currency" exchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/order" "github.com/idoall/gocryptotrader/exchanges/request" "github.com/idoall/gocryptotrader/exchanges/stream" "github.com/idoall/gocryptotrader/exchanges/ticker" "github.com/idoall/gocryptotrader/exchanges/trade" "github.com/idoall/gocryptotrader/log" ) const ( uFuturesbinanceDefaultWebsocketURL = "wss://fstream.binance.com/stream" uFuturesbinanceDefaultWebsocketURLListenKey = "wss://fstream.binance.com/ws" uFuturespingDelay = time.Minute * 9 ) var uFutureslistenKey string var ( // uFuturesmaxWSUpdateBuffer defines max websocket updates to apply when an // orderbook is initially fetched uFuturesmaxWSUpdateBuffer = 150 // uFuturesmaxWSOrderbookJobs defines max websocket orderbook jobs in queue to fetch // an orderbook snapshot via REST uFuturesmaxWSOrderbookJobs = 2000 // uFuturesmaxWSOrderbookWorkers defines a max amount of workers allowed to execute // jobs from the job channel uFuturesmaxWSOrderbookWorkers = 10 ) // UFuturesWsConnect initiates a websocket connection func (b *Binance) UFuturesWsConnect() error { if !b.UFuturesWebsocket.IsEnabled() || !b.IsEnabled() { return errors.New(stream.WebsocketNotEnabled) } var dialer websocket.Dialer dialer.HandshakeTimeout = b.Config.HTTPTimeout dialer.Proxy = http.ProxyFromEnvironment var err error if b.UFuturesWebsocket.CanUseAuthenticatedEndpoints() { listenKey, err = b.UFutureGetWsAuthStreamKey(context.TODO()) if err != nil { b.UFuturesWebsocket.SetCanUseAuthenticatedEndpoints(false) log.Errorf(log.ExchangeSys, "%v unable to connect to authenticated Websocket. Error: %s", b.Name, err) } else { // cleans on failed connection // clean := strings.Split(b.UFuturesWebsocket.GetWebsocketURL(), "?streams=") authPayload := uFuturesbinanceDefaultWebsocketURLListenKey + "/" + uFutureslistenKey err = b.UFuturesWebsocket.SetWebsocketURL(authPayload, false, false) if err != nil { return err } } } err = b.UFuturesWebsocket.Conn.Dial(&dialer, http.Header{}) if err != nil { return fmt.Errorf("%v - Unable to connect to Websocket. Error: %s", b.Name, err) } if b.UFuturesWebsocket.CanUseAuthenticatedEndpoints() { go b.UFuturesKeepAuthKeyAlive() } b.UFuturesWebsocket.Conn.SetupPingHandler(stream.PingHandler{ UseGorillaHandler: true, MessageType: websocket.PongMessage, Delay: pingDelay, }) b.UFuturesWebsocket.Wg.Add(1) go b.uFutureswsReadData() // b.uFuturessetupOrderbookManager() return nil } // func (b *Binance) uFuturessetupOrderbookManager() { // if b.obm == nil { // b.obm = &orderbookManager{ // state: make(map[currency.Code]map[currency.Code]map[asset.Item]*update), // jobs: make(chan job, maxWSOrderbookJobs), // } // } else { // // Change state on reconnect for initial sync. // for _, m1 := range b.obm.state { // for _, m2 := range m1 { // for _, update := range m2 { // update.initialSync = true // update.needsFetchingBook = true // update.lastUpdateID = 0 // } // } // } // } // for i := 0; i < maxWSOrderbookWorkers; i++ { // // 10 workers for synchronising book // b.UFuturesSynchroniseWebsocketOrderbook() // } // } // UFuturesKeepAuthKeyAlive will continuously send messages to // keep the WS auth key active func (b *Binance) UFuturesKeepAuthKeyAlive() { b.UFuturesWebsocket.Wg.Add(1) defer b.UFuturesWebsocket.Wg.Done() ticks := time.NewTicker(time.Minute * 30) for { select { case <-b.UFuturesWebsocket.ShutdownC: ticks.Stop() return case <-ticks.C: err := b.UFutureMaintainWsAuthStreamKey(context.TODO()) if err != nil { b.UFuturesWebsocket.DataHandler <- err log.Warnf(log.ExchangeSys, b.Name+" - Unable to renew auth websocket token, may experience shutdown") } } } } // UFutureMaintainWsAuthStreamKey will keep the key alive func (b *Binance) UFutureMaintainWsAuthStreamKey(ctx context.Context) error { endpointPath, err := b.API.Endpoints.GetURL(exchange.RestUSDTMargined) if err != nil { return err } if listenKey == "" { listenKey, err = b.UFutureGetWsAuthStreamKey(ctx) return err } path := endpointPath + "/fapi/v1/listenKey" params := url.Values{} params.Set("listenKey", listenKey) path = common.EncodeURLValues(path, params) headers := make(map[string]string) headers["X-MBX-APIKEY"] = b.API.Credentials.Key item := &request.Item{ Method: http.MethodPut, Path: path, Headers: headers, AuthRequest: true, Verbose: b.Verbose, HTTPDebugging: b.HTTPDebugging, HTTPRecording: b.HTTPRecording, } return b.SendPayload(ctx, request.Unset, func() (*request.Item, error) { return item, nil }) } // UFutureGetWsAuthStreamKey will retrieve a key to use for authorised WS streaming func (b *Binance) UFutureGetWsAuthStreamKey(ctx context.Context) (string, error) { endpointPath, err := b.API.Endpoints.GetURL(exchange.RestUSDTMargined) if err != nil { return "", err } var resp UserAccountStream headers := make(map[string]string) headers["X-MBX-APIKEY"] = b.API.Credentials.Key item := &request.Item{ Method: http.MethodPost, Path: endpointPath + "/fapi/v1/listenKey", Headers: headers, Result: &resp, AuthRequest: true, Verbose: b.Verbose, HTTPDebugging: b.HTTPDebugging, HTTPRecording: b.HTTPRecording, } err = b.SendPayload(ctx, request.Unset, func() (*request.Item, error) { return item, nil }) if err != nil { return "", err } return resp.ListenKey, nil } // uFutureswsReadData receives and passes on websocket messages for processing func (b *Binance) uFutureswsReadData() { defer b.UFuturesWebsocket.Wg.Done() for { resp := b.UFuturesWebsocket.Conn.ReadMessage() if resp.Raw == nil { return } err := b.uFutureswsHandleData(resp.Raw) if err != nil { b.UFuturesWebsocket.DataHandler <- err } } } func (b *Binance) uFutureswsHandleData(respRaw []byte) error { var multiStreamData map[string]interface{} err := json.Unmarshal(respRaw, &multiStreamData) if err != nil { return err } if r, ok := multiStreamData["result"]; ok { if r == nil { return nil } } if method, ok := multiStreamData["method"].(string); ok { // TODO handle subscription handling if strings.EqualFold(method, "subscribe") { return nil } if strings.EqualFold(method, "unsubscribe") { return nil } } if e, ok := multiStreamData["e"].(string); ok { pairs, err := b.GetEnabledPairs(asset.USDTMarginedFutures) if err != nil { return err } format, err := b.GetPairFormat(asset.USDTMarginedFutures, true) if err != nil { return err } switch e { case "markPriceUpdate": var _stream MarkPriceStream err := json.Unmarshal(respRaw, &_stream) if err != nil { return fmt.Errorf("%v - Could not convert to a MarkPriceStream structure %s", b.Name, err) } pair, err := currency.NewPairFromFormattedPairs(_stream.Symbol, pairs, format) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- MarkPriceStreamResponse{ Symbol: pair, EventType: _stream.EventType, EventTime: time.Unix(0, _stream.EventTime*int64(time.Millisecond)), MarkPrice: _stream.MarkPrice, IndexPrice: _stream.IndexPrice, EstimatedSettlePrice: _stream.EstimatedSettlePrice, LastFundingRate: _stream.LastFundingRate, NextFundingTime: time.Unix(0, _stream.NextFundingTime*int64(time.Millisecond)), AssetType: asset.USDTMarginedFutures, Exchange: b.Name, } return nil case "24hrTicker": var t TickerStream err := json.Unmarshal(respRaw, &t) if err != nil { return fmt.Errorf("%v - Could not convert to a TickerStream structure %s", b.Name, err.Error()) } pair, err := currency.NewPairFromFormattedPairs(t.Symbol, pairs, format) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- ticker.Price{ ExchangeName: b.Name, Open: t.OpenPrice, Close: t.ClosePrice, Volume: t.TotalTradedVolume, QuoteVolume: t.TotalTradedQuoteVolume, High: t.HighPrice, Low: t.LowPrice, Bid: t.BestBidPrice, Ask: t.BestAskPrice, Last: t.LastPrice, LastUpdated: t.EventTime, AssetType: asset.USDTMarginedFutures, Pair: pair, } return nil case "kline": var kline UFutureKlineStream err := json.Unmarshal(respRaw, &kline) if err != nil { return fmt.Errorf("%v - Could not convert to a KlineStream structure %s", b.Name, err) } pair, err := currency.NewPairFromFormattedPairs(kline.Symbol, pairs, format) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- stream.KlineData{ Timestamp: time.UnixMilli(kline.EventTime), Pair: pair, AssetType: asset.USDTMarginedFutures, Exchange: b.Name, StartTime: time.UnixMilli(kline.Kline.StartTime), CloseTime: time.UnixMilli(kline.Kline.CloseTime), Interval: kline.Kline.Interval, OpenPrice: kline.Kline.OpenPrice, ClosePrice: kline.Kline.ClosePrice, HighPrice: kline.Kline.HighPrice, LowPrice: kline.Kline.LowPrice, Volume: kline.Kline.Volume, } return nil } } if newdata, ok := multiStreamData["data"].(map[string]interface{}); ok { if e, ok := newdata["e"].(string); ok { switch e { case "outboundAccountInfo": var data wsAccountInfo err := json.Unmarshal(respRaw, &data) if err != nil { return fmt.Errorf("%v - Could not convert to outboundAccountInfo structure %s", b.Name, err) } b.UFuturesWebsocket.DataHandler <- data return nil case "outboundAccountPosition": var data wsAccountPosition err := json.Unmarshal(respRaw, &data) if err != nil { return fmt.Errorf("%v - Could not convert to outboundAccountPosition structure %s", b.Name, err) } b.UFuturesWebsocket.DataHandler <- data return nil case "balanceUpdate": var data wsBalanceUpdate err := json.Unmarshal(respRaw, &data) if err != nil { return fmt.Errorf("%v - Could not convert to balanceUpdate structure %s", b.Name, err) } b.UFuturesWebsocket.DataHandler <- data return nil case "executionReport": var data wsOrderUpdate err := json.Unmarshal(respRaw, &data) if err != nil { return fmt.Errorf("%v - Could not convert to executionReport structure %s", b.Name, err) } averagePrice := 0.0 if data.Data.CumulativeFilledQuantity != 0 { averagePrice = data.Data.CumulativeQuoteTransactedQuantity / data.Data.CumulativeFilledQuantity } remainingAmount := data.Data.Quantity - data.Data.CumulativeFilledQuantity pair, assetType, err := b.GetRequestFormattedPairAndAssetType(data.Data.Symbol) if err != nil { return err } var feeAsset currency.Code if data.Data.CommissionAsset != "" { feeAsset = currency.NewCode(data.Data.CommissionAsset) } orderID := strconv.FormatInt(data.Data.OrderID, 10) orderStatus, err := stringToOrderStatus(data.Data.OrderStatus) if err != nil { b.UFuturesWebsocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: orderID, Err: err, } } clientOrderID := data.Data.ClientOrderID if orderStatus == order.Cancelled { clientOrderID = data.Data.CancelledClientOrderID } orderType, err := order.StringToOrderType(data.Data.OrderType) if err != nil { b.UFuturesWebsocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: orderID, Err: err, } } orderSide, err := order.StringToOrderSide(data.Data.Side) if err != nil { b.UFuturesWebsocket.DataHandler <- order.ClassificationError{ Exchange: b.Name, OrderID: orderID, Err: err, } } b.UFuturesWebsocket.DataHandler <- &order.Detail{ Price: data.Data.Price, Amount: data.Data.Quantity, AverageExecutedPrice: averagePrice, ExecutedAmount: data.Data.CumulativeFilledQuantity, RemainingAmount: remainingAmount, Cost: data.Data.CumulativeQuoteTransactedQuantity, CostAsset: pair.Quote, Fee: data.Data.Commission, FeeAsset: feeAsset, Exchange: b.Name, ID: orderID, ClientOrderID: clientOrderID, Type: orderType, Side: orderSide, Status: orderStatus, AssetType: assetType, Date: data.Data.OrderCreationTime, LastUpdated: data.Data.TransactionTime, Pair: pair, } return nil case "listStatus": var data wsListStatus err := json.Unmarshal(respRaw, &data) if err != nil { return fmt.Errorf("%v - Could not convert to listStatus structure %s", b.Name, err) } b.UFuturesWebsocket.DataHandler <- data return nil } } } if wsStream, ok := multiStreamData["stream"].(string); ok { streamType := strings.Split(wsStream, "@") if len(streamType) > 1 { if data, ok := multiStreamData["data"]; ok { rawData, err := json.Marshal(data) if err != nil { return err } pairs, err := b.GetEnabledPairs(asset.USDTMarginedFutures) if err != nil { return err } format, err := b.GetPairFormat(asset.USDTMarginedFutures, true) if err != nil { return err } switch streamType[1] { case "trade": saveTradeData := b.IsSaveTradeDataEnabled() if !saveTradeData && !b.IsTradeFeedEnabled() { return nil } var t TradeStream err := json.Unmarshal(rawData, &t) if err != nil { return fmt.Errorf("%v - Could not unmarshal trade data: %s", b.Name, err) } price, err := strconv.ParseFloat(t.Price, 64) if err != nil { return fmt.Errorf("%v - price conversion error: %s", b.Name, err) } amount, err := strconv.ParseFloat(t.Quantity, 64) if err != nil { return fmt.Errorf("%v - amount conversion error: %s", b.Name, err) } pair, err := currency.NewPairFromFormattedPairs(t.Symbol, pairs, format) if err != nil { return err } return b.UFuturesWebsocket.Trade.Update(saveTradeData, trade.Data{ CurrencyPair: pair, Timestamp: t.TimeStamp, Price: price, Amount: amount, Exchange: b.Name, AssetType: asset.Spot, TID: strconv.FormatInt(t.TradeID, 10), }) case "markPrice": var _stream MarkPriceStream err := json.Unmarshal(rawData, &_stream) if err != nil { return fmt.Errorf("%v - Could not convert to a MarkPriceStream structure %s", b.Name, err) } pair, assetType, err := b.GetRequestFormattedPairAndAssetType(_stream.Symbol) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- MarkPriceStreamResponse{ Symbol: pair, EventType: _stream.EventType, EventTime: time.Unix(0, _stream.EventTime*int64(time.Millisecond)), MarkPrice: _stream.MarkPrice, IndexPrice: _stream.IndexPrice, EstimatedSettlePrice: _stream.EstimatedSettlePrice, LastFundingRate: _stream.LastFundingRate, NextFundingTime: time.Unix(0, _stream.NextFundingTime*int64(time.Millisecond)), AssetType: assetType, Exchange: b.Name, } return nil case "ticker": var t TickerStream err := json.Unmarshal(rawData, &t) if err != nil { return fmt.Errorf("%v - Could not convert to a TickerStream structure %s", b.Name, err.Error()) } pair, err := currency.NewPairFromFormattedPairs(t.Symbol, pairs, format) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- &ticker.Price{ ExchangeName: b.Name, Open: t.OpenPrice, Close: t.ClosePrice, Volume: t.TotalTradedVolume, QuoteVolume: t.TotalTradedQuoteVolume, High: t.HighPrice, Low: t.LowPrice, Bid: t.BestBidPrice, Ask: t.BestAskPrice, Last: t.LastPrice, LastUpdated: t.EventTime, AssetType: asset.Spot, Pair: pair, } return nil case "kline_1m", "kline_3m", "kline_5m", "kline_15m", "kline_30m", "kline_1h", "kline_2h", "kline_4h", "kline_6h", "kline_8h", "kline_12h", "kline_1d", "kline_3d", "kline_1w", "kline_1M": var kline KlineStream err := json.Unmarshal(rawData, &kline) if err != nil { return fmt.Errorf("%v - Could not convert to a KlineStream structure %s", b.Name, err) } pair, err := currency.NewPairFromFormattedPairs(kline.Symbol, pairs, format) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- stream.KlineData{ Timestamp: kline.EventTime, Pair: pair, AssetType: asset.Spot, Exchange: b.Name, StartTime: kline.Kline.StartTime, CloseTime: kline.Kline.CloseTime, Interval: kline.Kline.Interval, OpenPrice: kline.Kline.OpenPrice, ClosePrice: kline.Kline.ClosePrice, HighPrice: kline.Kline.HighPrice, LowPrice: kline.Kline.LowPrice, Volume: kline.Kline.Volume, } return nil case "depth": var depth WebsocketDepthStream err := json.Unmarshal(rawData, &depth) if err != nil { return fmt.Errorf("%v - Could not convert to depthStream structure %s", b.Name, err) } init, err := b.UpdateLocalBuffer(&depth) if err != nil { if init { return nil } return fmt.Errorf("%v - UpdateLocalCache error: %s", b.Name, err) } return nil case "24hrTicker": var t TickerStream err := json.Unmarshal(respRaw, &t) if err != nil { return fmt.Errorf("%v - Could not convert to a TickerStream structure %s", b.Name, err.Error()) } pair, err := currency.NewPairFromFormattedPairs(t.Symbol, pairs, format) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- ticker.Price{ ExchangeName: b.Name, Open: t.OpenPrice, Close: t.ClosePrice, Volume: t.TotalTradedVolume, QuoteVolume: t.TotalTradedQuoteVolume, High: t.HighPrice, Low: t.LowPrice, Bid: t.BestBidPrice, Ask: t.BestAskPrice, Last: t.LastPrice, LastUpdated: t.EventTime, AssetType: asset.USDTMarginedFutures, Pair: pair, } return nil case "markPriceUpdate": var _stream MarkPriceStream err := json.Unmarshal(respRaw, &_stream) if err != nil { return fmt.Errorf("%v - Could not convert to a MarkPriceStream structure %s", b.Name, err) } pair, err := currency.NewPairFromFormattedPairs(_stream.Symbol, pairs, format) if err != nil { return err } b.UFuturesWebsocket.DataHandler <- MarkPriceStreamResponse{ Symbol: pair, EventType: _stream.EventType, EventTime: time.Unix(0, _stream.EventTime*int64(time.Millisecond)), MarkPrice: _stream.MarkPrice, IndexPrice: _stream.IndexPrice, EstimatedSettlePrice: _stream.EstimatedSettlePrice, LastFundingRate: _stream.LastFundingRate, NextFundingTime: time.Unix(0, _stream.NextFundingTime*int64(time.Millisecond)), AssetType: asset.USDTMarginedFutures, Exchange: b.Name, } return nil default: b.UFuturesWebsocket.DataHandler <- stream.UnhandledMessageWarning{ Message: b.Name + stream.UnhandledMessage + string(respRaw), } } } } } return fmt.Errorf("unhandled stream data %s", string(respRaw)) } // UFuturesGenerateSubscriptions generates the default subscription set func (b *Binance) UFuturesGenerateSubscriptions() ([]stream.ChannelSubscription, error) { var channels = []string{"@markPrice", "@kline_1m", "@forceOrder", "@ticker"} var subscriptions []stream.ChannelSubscription // assets := b.GetAssetTypes() assetType := asset.USDTMarginedFutures // for x := range assets { pairs, err := b.GetEnabledPairs(assetType) if err != nil { return nil, err } for y := range pairs { for z := range channels { lp := pairs[y].Lower() lp.Delimiter = "" subscriptions = append(subscriptions, stream.ChannelSubscription{ Channel: lp.String() + channels[z], Currency: pairs[y], Asset: assetType, }) } } // } return subscriptions, nil } // UFuturesSubscribe subscribes to a set of channels func (b *Binance) UFuturesSubscribe(channelsToSubscribe []stream.ChannelSubscription) error { payload := WsPayload{ Method: "SUBSCRIBE", } for i := range channelsToSubscribe { payload.Params = append(payload.Params, channelsToSubscribe[i].Channel) if i%50 == 0 && i != 0 { err := b.UFuturesWebsocket.Conn.SendJSONMessage(payload) if err != nil { return err } payload.Params = []string{} } } if len(payload.Params) > 0 { err := b.UFuturesWebsocket.Conn.SendJSONMessage(payload) if err != nil { return err } } b.UFuturesWebsocket.AddSuccessfulSubscriptions(channelsToSubscribe...) return nil } // UFuturesUnsubscribe unsubscribes from a set of channels func (b *Binance) UFuturesUnsubscribe(channelsToUnsubscribe []stream.ChannelSubscription) error { payload := WsPayload{ Method: "UNSUBSCRIBE", } for i := range channelsToUnsubscribe { payload.Params = append(payload.Params, channelsToUnsubscribe[i].Channel) if i%50 == 0 && i != 0 { err := b.UFuturesWebsocket.Conn.SendJSONMessage(payload) if err != nil { return err } payload.Params = []string{} } } if len(payload.Params) > 0 { err := b.UFuturesWebsocket.Conn.SendJSONMessage(payload) if err != nil { return err } } b.UFuturesWebsocket.RemoveSuccessfulUnsubscriptions(channelsToUnsubscribe...) return nil } // UFuturesSynchroniseWebsocketOrderbook synchronises full orderbook for currency pair // asset func (b *Binance) UFuturesSynchroniseWebsocketOrderbook() { b.UFuturesWebsocket.Wg.Add(1) go func() { defer b.UFuturesWebsocket.Wg.Done() for { select { case <-b.UFuturesWebsocket.ShutdownC: for { select { case <-b.obm.jobs: default: return } } case j := <-b.obm.jobs: err := b.processJob(j.Pair) if err != nil { log.Errorf(log.WebsocketMgr, "%s processing websocket orderbook error %v", b.Name, err) } } } }() } <file_sep>package account import ( "sync" "github.com/gofrs/uuid" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/dispatch" "github.com/idoall/gocryptotrader/exchanges/asset" ) // Vars for the ticker package var ( service *Service ) // Service holds ticker information for each individual exchange type Service struct { accounts map[string]*Account mux *dispatch.Mux sync.Mutex } // Account holds a stream ID and a pointer to the exchange holdings type Account struct { h *Holdings ID uuid.UUID } // Holdings is a generic type to hold each exchange's holdings for all enabled // currencies type Holdings struct { Exchange string Accounts []SubAccount } // SubAccount defines a singular account type with asocciated currency balances type SubAccount struct { ID string AssetType asset.Item Currencies []Balance } // Balance is a sub type to store currency name and individual totals type Balance struct { CurrencyName currency.Code TotalValue float64 Hold float64 } // Change defines incoming balance change on currency holdings type Change struct { Exchange string Currency currency.Code Asset asset.Item Amount float64 Account string } <file_sep>package kline import ( "testing" "github.com/shopspring/decimal" ) func TestClose(t *testing.T) { t.Parallel() k := Kline{ Close: decimal.NewFromInt(1337), } if !k.GetClosePrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestHigh(t *testing.T) { t.Parallel() k := Kline{ High: decimal.NewFromInt(1337), } if !k.GetHighPrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestLow(t *testing.T) { t.Parallel() k := Kline{ Low: decimal.NewFromInt(1337), } if !k.GetLowPrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } func TestOpen(t *testing.T) { t.Parallel() k := Kline{ Open: decimal.NewFromInt(1337), } if !k.GetOpenPrice().Equal(decimal.NewFromInt(1337)) { t.Error("expected decimal.NewFromInt(1337)") } } <file_sep>package gateio // GetMarketInfo returns information about all trading pairs, including // transaction fee, minimum order quantity, price accuracy and so on // func (g *Gateio) GetSpotMarketInfo(ctx context.Context) (SpotMarketInfoResponse, error) { // type response struct { // Result string `json:"result"` // Pairs []interface{} `json:"pairs"` // } // urlPath := fmt.Sprintf("/%s/%s", // gateioAPIVersion, // gateioMarketInfo) // resp := struct { // Data [][]string `json:"data"` // Result string `json:"result"` // }{} // var res response // var result SpotMarketInfoResponse // if err := g.SendHTTPRequest(ctx, exchange.RestSpotSupplementary, urlPath, &resp); err != nil { // return result, err // } // assetType := asset.Spot // format, err := g.GetPairFormat(assetType, true) // if err != nil { // return result, err // } // pairs, err := g.GetEnabledPairs(assetType) // if err != nil { // return result, err // } // result.Result = res.Result // for _, v := range res.Pairs { // item := v.(map[string]interface{}) // for itemk, itemv := range item { // pairv := itemv.(map[string]interface{}) // item := SpotMarketInfoPairsResponse{} // item.Symbol, err = currency.NewPairFromFormattedPairs(itemk, pairs, format) // if err != nil { // return result, err // } // item.DecimalPlaces = pairv["decimal_places"].(float64) // item.AmountDecimalPlaces = pairv["amount_decimal_places"].(float64) // item.MinAmount = pairv["min_amount"].(float64) // item.MinAmountA = pairv["min_amount_a"].(float64) // item.MinAmountB = pairv["min_amount_b"].(float64) // item.Fee = pairv["fee"].(float64) // if trade_disabled := pairv["trade_disabled"].(float64); trade_disabled == 1.0 { // item.TradeDisabled = true // } // if buy_disabled := pairv["buy_disabled"].(float64); buy_disabled == 1.0 { // item.BuyDisabled = true // } // if sell_disabled := pairv["sell_disabled"].(float64); sell_disabled == 1.0 { // item.SellDisabled = true // } // result.Pairs = append(result.Pairs, item) // } // } // return result, nil // } <file_sep>package config import ( "encoding/json" "errors" "fmt" "io/ioutil" "strings" "github.com/idoall/gocryptotrader/backtester/eventhandlers/strategies" "github.com/idoall/gocryptotrader/backtester/eventhandlers/strategies/base" gctcommon "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/file" "github.com/idoall/gocryptotrader/log" "github.com/shopspring/decimal" ) // ReadConfigFromFile will take a config from a path func ReadConfigFromFile(path string) (*Config, error) { if !file.Exists(path) { return nil, errors.New("file not found") } fileData, err := ioutil.ReadFile(path) if err != nil { return nil, err } return LoadConfig(fileData) } // LoadConfig unmarshalls byte data into a config struct func LoadConfig(data []byte) (resp *Config, err error) { err = json.Unmarshal(data, &resp) return resp, err } // PrintSetting prints relevant settings to the console for easy reading func (c *Config) PrintSetting() { log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------Backtester Settings------------------------") log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------Strategy Settings--------------------------") log.Info(log.BackTester, "-------------------------------------------------------------") log.Infof(log.BackTester, "Strategy: %s", c.StrategySettings.Name) if len(c.StrategySettings.CustomSettings) > 0 { log.Info(log.BackTester, "Custom strategy variables:") for k, v := range c.StrategySettings.CustomSettings { log.Infof(log.BackTester, "%s: %v", k, v) } } else { log.Info(log.BackTester, "Custom strategy variables: unset") } log.Infof(log.BackTester, "Simultaneous Signal Processing: %v", c.StrategySettings.SimultaneousSignalProcessing) log.Infof(log.BackTester, "Use Exchange Level Funding: %v", c.StrategySettings.UseExchangeLevelFunding) log.Infof(log.BackTester, "USD value tracking: %v", !c.StrategySettings.DisableUSDTracking) if c.StrategySettings.UseExchangeLevelFunding && c.StrategySettings.SimultaneousSignalProcessing { log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------Funding Settings---------------------------") for i := range c.StrategySettings.ExchangeLevelFunding { log.Infof(log.BackTester, "Initial funds for %v %v %v: %v", c.StrategySettings.ExchangeLevelFunding[i].ExchangeName, c.StrategySettings.ExchangeLevelFunding[i].Asset, c.StrategySettings.ExchangeLevelFunding[i].Currency, c.StrategySettings.ExchangeLevelFunding[i].InitialFunds.Round(8)) } } for i := range c.CurrencySettings { log.Info(log.BackTester, "-------------------------------------------------------------") currStr := fmt.Sprintf("------------------%v %v-%v Currency Settings---------------------------------------------------------", c.CurrencySettings[i].Asset, c.CurrencySettings[i].Base, c.CurrencySettings[i].Quote) log.Infof(log.BackTester, currStr[:61]) log.Info(log.BackTester, "-------------------------------------------------------------") log.Infof(log.BackTester, "Exchange: %v", c.CurrencySettings[i].ExchangeName) if !c.StrategySettings.UseExchangeLevelFunding { if c.CurrencySettings[i].InitialBaseFunds != nil { log.Infof(log.BackTester, "Initial base funds: %v %v", c.CurrencySettings[i].InitialBaseFunds.Round(8), c.CurrencySettings[i].Base) } if c.CurrencySettings[i].InitialQuoteFunds != nil { log.Infof(log.BackTester, "Initial quote funds: %v %v", c.CurrencySettings[i].InitialQuoteFunds.Round(8), c.CurrencySettings[i].Quote) } } log.Infof(log.BackTester, "Maker fee: %v", c.CurrencySettings[i].TakerFee.Round(8)) log.Infof(log.BackTester, "Taker fee: %v", c.CurrencySettings[i].MakerFee.Round(8)) log.Infof(log.BackTester, "Minimum slippage percent %v", c.CurrencySettings[i].MinimumSlippagePercent.Round(8)) log.Infof(log.BackTester, "Maximum slippage percent: %v", c.CurrencySettings[i].MaximumSlippagePercent.Round(8)) log.Infof(log.BackTester, "Buy rules: %+v", c.CurrencySettings[i].BuySide) log.Infof(log.BackTester, "Sell rules: %+v", c.CurrencySettings[i].SellSide) log.Infof(log.BackTester, "Leverage rules: %+v", c.CurrencySettings[i].Leverage) log.Infof(log.BackTester, "Can use exchange defined order execution limits: %+v", c.CurrencySettings[i].CanUseExchangeLimits) } log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------Portfolio Settings-------------------------") log.Info(log.BackTester, "-------------------------------------------------------------") log.Infof(log.BackTester, "Buy rules: %+v", c.PortfolioSettings.BuySide) log.Infof(log.BackTester, "Sell rules: %+v", c.PortfolioSettings.SellSide) log.Infof(log.BackTester, "Leverage rules: %+v", c.PortfolioSettings.Leverage) if c.DataSettings.LiveData != nil { log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------Live Settings------------------------------") log.Info(log.BackTester, "-------------------------------------------------------------") log.Infof(log.BackTester, "Data type: %v", c.DataSettings.DataType) log.Infof(log.BackTester, "Interval: %v", c.DataSettings.Interval) log.Infof(log.BackTester, "REAL ORDERS: %v", c.DataSettings.LiveData.RealOrders) log.Infof(log.BackTester, "Overriding GCT API settings: %v", c.DataSettings.LiveData.APIClientIDOverride != "") } if c.DataSettings.APIData != nil { log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------API Settings-------------------------------") log.Info(log.BackTester, "-------------------------------------------------------------") log.Infof(log.BackTester, "Data type: %v", c.DataSettings.DataType) log.Infof(log.BackTester, "Interval: %v", c.DataSettings.Interval) log.Infof(log.BackTester, "Start date: %v", c.DataSettings.APIData.StartDate.Format(gctcommon.SimpleTimeFormat)) log.Infof(log.BackTester, "End date: %v", c.DataSettings.APIData.EndDate.Format(gctcommon.SimpleTimeFormat)) } if c.DataSettings.CSVData != nil { log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------CSV Settings-------------------------------") log.Info(log.BackTester, "-------------------------------------------------------------") log.Infof(log.BackTester, "Data type: %v", c.DataSettings.DataType) log.Infof(log.BackTester, "Interval: %v", c.DataSettings.Interval) log.Infof(log.BackTester, "CSV file: %v", c.DataSettings.CSVData.FullPath) } if c.DataSettings.DatabaseData != nil { log.Info(log.BackTester, "-------------------------------------------------------------") log.Info(log.BackTester, "------------------Database Settings--------------------------") log.Info(log.BackTester, "-------------------------------------------------------------") log.Infof(log.BackTester, "Data type: %v", c.DataSettings.DataType) log.Infof(log.BackTester, "Interval: %v", c.DataSettings.Interval) log.Infof(log.BackTester, "Start date: %v", c.DataSettings.DatabaseData.StartDate.Format(gctcommon.SimpleTimeFormat)) log.Infof(log.BackTester, "End date: %v", c.DataSettings.DatabaseData.EndDate.Format(gctcommon.SimpleTimeFormat)) } log.Info(log.BackTester, "-------------------------------------------------------------\n\n") } // Validate checks all config settings func (c *Config) Validate() error { err := c.validateDate() if err != nil { return err } err = c.validateStrategySettings() if err != nil { return err } err = c.validateCurrencySettings() if err != nil { return err } return c.validateMinMaxes() } // validate ensures no one sets bad config values on purpose func (m *MinMax) validate() error { if m.MaximumSize.IsNegative() { return fmt.Errorf("invalid maximum size %w", errSizeLessThanZero) } if m.MinimumSize.IsNegative() { return fmt.Errorf("invalid minimum size %w", errSizeLessThanZero) } if m.MaximumTotal.IsNegative() { return fmt.Errorf("invalid maximum total set to %w", errSizeLessThanZero) } if m.MaximumSize.LessThan(m.MinimumSize) && !m.MinimumSize.IsZero() && !m.MaximumSize.IsZero() { return fmt.Errorf("%w maximum size %v vs minimum size %v", errMaxSizeMinSizeMismatch, m.MaximumSize, m.MinimumSize) } if m.MaximumSize.Equal(m.MinimumSize) && !m.MinimumSize.IsZero() && !m.MaximumSize.IsZero() { return fmt.Errorf("%w %v", errMinMaxEqual, m.MinimumSize) } return nil } func (c *Config) validateMinMaxes() (err error) { for i := range c.CurrencySettings { err = c.CurrencySettings[i].BuySide.validate() if err != nil { return err } err = c.CurrencySettings[i].SellSide.validate() if err != nil { return err } } err = c.PortfolioSettings.BuySide.validate() if err != nil { return err } err = c.PortfolioSettings.SellSide.validate() if err != nil { return err } return nil } func (c *Config) validateStrategySettings() error { if c.StrategySettings.UseExchangeLevelFunding && !c.StrategySettings.SimultaneousSignalProcessing { return errSimultaneousProcessingRequired } if len(c.StrategySettings.ExchangeLevelFunding) > 0 && !c.StrategySettings.UseExchangeLevelFunding { return errExchangeLevelFundingRequired } if c.StrategySettings.UseExchangeLevelFunding && len(c.StrategySettings.ExchangeLevelFunding) == 0 { return errExchangeLevelFundingDataRequired } if c.StrategySettings.UseExchangeLevelFunding { for i := range c.StrategySettings.ExchangeLevelFunding { if c.StrategySettings.ExchangeLevelFunding[i].InitialFunds.IsNegative() { return fmt.Errorf("%w for %v %v %v", errBadInitialFunds, c.StrategySettings.ExchangeLevelFunding[i].ExchangeName, c.StrategySettings.ExchangeLevelFunding[i].Asset, c.StrategySettings.ExchangeLevelFunding[i].Currency, ) } } } strats := strategies.GetStrategies() for i := range strats { if strings.EqualFold(strats[i].Name(), c.StrategySettings.Name) { return nil } } return fmt.Errorf("strategty %v %w", c.StrategySettings.Name, base.ErrStrategyNotFound) } // validateDate checks whether someone has set a date poorly in their config func (c *Config) validateDate() error { if c.DataSettings.DatabaseData != nil { if c.DataSettings.DatabaseData.StartDate.IsZero() || c.DataSettings.DatabaseData.EndDate.IsZero() { return errStartEndUnset } if c.DataSettings.DatabaseData.StartDate.After(c.DataSettings.DatabaseData.EndDate) || c.DataSettings.DatabaseData.StartDate.Equal(c.DataSettings.DatabaseData.EndDate) { return errBadDate } } if c.DataSettings.APIData != nil { if c.DataSettings.APIData.StartDate.IsZero() || c.DataSettings.APIData.EndDate.IsZero() { return errStartEndUnset } if c.DataSettings.APIData.StartDate.After(c.DataSettings.APIData.EndDate) || c.DataSettings.APIData.StartDate.Equal(c.DataSettings.APIData.EndDate) { return errBadDate } } return nil } // validateCurrencySettings checks whether someone has set invalid currency setting data in their config func (c *Config) validateCurrencySettings() error { if len(c.CurrencySettings) == 0 { return errNoCurrencySettings } for i := range c.CurrencySettings { if c.CurrencySettings[i].InitialLegacyFunds > 0 { // temporarily migrate legacy start config value log.Warn(log.BackTester, "config field 'initial-funds' no longer supported, please use 'initial-quote-funds'") log.Warnf(log.BackTester, "temporarily setting 'initial-quote-funds' to 'initial-funds' value of %v", c.CurrencySettings[i].InitialLegacyFunds) iqf := decimal.NewFromFloat(c.CurrencySettings[i].InitialLegacyFunds) c.CurrencySettings[i].InitialQuoteFunds = &iqf } if c.StrategySettings.UseExchangeLevelFunding { if c.CurrencySettings[i].InitialQuoteFunds != nil && c.CurrencySettings[i].InitialQuoteFunds.GreaterThan(decimal.Zero) { return fmt.Errorf("non-nil quote %w", errBadInitialFunds) } if c.CurrencySettings[i].InitialBaseFunds != nil && c.CurrencySettings[i].InitialBaseFunds.GreaterThan(decimal.Zero) { return fmt.Errorf("non-nil base %w", errBadInitialFunds) } } else { if c.CurrencySettings[i].InitialQuoteFunds == nil && c.CurrencySettings[i].InitialBaseFunds == nil { return fmt.Errorf("nil base and quote %w", errBadInitialFunds) } if c.CurrencySettings[i].InitialQuoteFunds != nil && c.CurrencySettings[i].InitialBaseFunds != nil && c.CurrencySettings[i].InitialBaseFunds.IsZero() && c.CurrencySettings[i].InitialQuoteFunds.IsZero() { return fmt.Errorf("base or quote funds set to zero %w", errBadInitialFunds) } if c.CurrencySettings[i].InitialQuoteFunds == nil { c.CurrencySettings[i].InitialQuoteFunds = &decimal.Zero } if c.CurrencySettings[i].InitialBaseFunds == nil { c.CurrencySettings[i].InitialBaseFunds = &decimal.Zero } } if c.CurrencySettings[i].Base == "" { return errUnsetCurrency } if c.CurrencySettings[i].Asset == "" { return errUnsetAsset } if c.CurrencySettings[i].ExchangeName == "" { return errUnsetExchange } if c.CurrencySettings[i].MinimumSlippagePercent.LessThan(decimal.Zero) || c.CurrencySettings[i].MaximumSlippagePercent.LessThan(decimal.Zero) || c.CurrencySettings[i].MinimumSlippagePercent.GreaterThan(c.CurrencySettings[i].MaximumSlippagePercent) { return errBadSlippageRates } c.CurrencySettings[i].ExchangeName = strings.ToLower(c.CurrencySettings[i].ExchangeName) } return nil } <file_sep>package exchange import ( "context" "errors" "strings" "testing" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/data/kline" "github.com/idoall/gocryptotrader/backtester/eventtypes/event" "github.com/idoall/gocryptotrader/backtester/eventtypes/fill" "github.com/idoall/gocryptotrader/backtester/eventtypes/order" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/engine" exchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" gctorder "github.com/idoall/gocryptotrader/exchanges/order" "github.com/shopspring/decimal" ) const testExchange = "binance" type fakeFund struct{} func (f *fakeFund) IncreaseAvailable(decimal.Decimal, gctorder.Side) {} func (f *fakeFund) Release(decimal.Decimal, decimal.Decimal, gctorder.Side) error { return nil } func TestReset(t *testing.T) { t.Parallel() e := Exchange{ CurrencySettings: []Settings{}, } e.Reset() if e.CurrencySettings != nil { t.Error("expected nil") } } func TestSetCurrency(t *testing.T) { t.Parallel() e := Exchange{} e.SetExchangeAssetCurrencySettings("", "", currency.Pair{}, &Settings{}) if len(e.CurrencySettings) != 0 { t.Error("expected 0") } cs := &Settings{ Exchange: testExchange, UseRealOrders: true, Pair: currency.NewPair(currency.BTC, currency.USDT), Asset: asset.Spot, ExchangeFee: decimal.Zero, MakerFee: decimal.Zero, TakerFee: decimal.Zero, BuySide: MinMax{}, SellSide: MinMax{}, Leverage: Leverage{}, MinimumSlippageRate: decimal.Zero, MaximumSlippageRate: decimal.Zero, } e.SetExchangeAssetCurrencySettings(testExchange, asset.Spot, currency.NewPair(currency.BTC, currency.USDT), cs) result, err := e.GetCurrencySettings(testExchange, asset.Spot, currency.NewPair(currency.BTC, currency.USDT)) if err != nil { t.Error(err) } if !result.UseRealOrders { t.Error("expected true") } e.SetExchangeAssetCurrencySettings(testExchange, asset.Spot, currency.NewPair(currency.BTC, currency.USDT), cs) if len(e.CurrencySettings) != 1 { t.Error("expected 1") } } func TestEnsureOrderFitsWithinHLV(t *testing.T) { t.Parallel() adjustedPrice, adjustedAmount := ensureOrderFitsWithinHLV(decimal.NewFromInt(123), decimal.NewFromInt(1), decimal.NewFromInt(100), decimal.NewFromInt(99), decimal.NewFromInt(100)) if !adjustedAmount.Equal(decimal.NewFromInt(1)) { t.Error("expected 1") } if !adjustedPrice.Equal(decimal.NewFromInt(100)) { t.Error("expected 100") } adjustedPrice, adjustedAmount = ensureOrderFitsWithinHLV(decimal.NewFromInt(123), decimal.NewFromInt(1), decimal.NewFromInt(100), decimal.NewFromInt(99), decimal.NewFromInt(80)) if !adjustedAmount.Equal(decimal.NewFromFloat(0.799999992)) { t.Errorf("received: %v, expected: %v", adjustedAmount, decimal.NewFromFloat(0.799999992)) } if !adjustedPrice.Equal(decimal.NewFromInt(100)) { t.Error("expected 100") } } func TestCalculateExchangeFee(t *testing.T) { t.Parallel() fee := calculateExchangeFee(decimal.NewFromInt(1), decimal.NewFromInt(1), decimal.NewFromFloat(0.1)) if !fee.Equal(decimal.NewFromFloat(0.1)) { t.Error("expected 0.1") } fee = calculateExchangeFee(decimal.NewFromInt(2), decimal.NewFromFloat(1), decimal.NewFromFloat(0.005)) if !fee.Equal(decimal.NewFromFloat(0.01)) { t.Error("expected 0.01") } } func TestSizeOrder(t *testing.T) { t.Parallel() e := Exchange{} _, _, err := e.sizeOfflineOrder(decimal.Zero, decimal.Zero, decimal.Zero, nil, nil) if !errors.Is(err, common.ErrNilArguments) { t.Error(err) } cs := &Settings{} f := &fill.Fill{ ClosePrice: decimal.NewFromInt(1337), Amount: decimal.NewFromInt(1), } _, _, err = e.sizeOfflineOrder(decimal.Zero, decimal.Zero, decimal.Zero, cs, f) if !errors.Is(err, errDataMayBeIncorrect) { t.Errorf("received: %v, expected: %v", err, errDataMayBeIncorrect) } var p, a decimal.Decimal p, a, err = e.sizeOfflineOrder(decimal.NewFromInt(10), decimal.NewFromInt(2), decimal.NewFromInt(10), cs, f) if err != nil { t.Error(err) } if !p.Equal(decimal.NewFromInt(10)) { t.Error("expected 10") } if !a.Equal(decimal.NewFromInt(1)) { t.Error("expected 1") } } func TestPlaceOrder(t *testing.T) { t.Parallel() bot := &engine.Engine{} var err error em := engine.SetupExchangeManager() exch, err := em.NewExchangeByName(testExchange) if err != nil { t.Fatal(err) } exch.SetDefaults() cfg, err := exch.GetDefaultConfig() if err != nil { t.Fatal(err) } err = exch.Setup(cfg) if err != nil { t.Fatal(err) } em.Add(exch) bot.ExchangeManager = em bot.OrderManager, err = engine.SetupOrderManager(em, &engine.CommunicationManager{}, &bot.ServicesWG, false) if err != nil { t.Error(err) } err = bot.OrderManager.Start() if err != nil { t.Error(err) } e := Exchange{} _, err = e.placeOrder(context.Background(), decimal.NewFromInt(1), decimal.NewFromInt(1), false, true, nil, nil) if !errors.Is(err, common.ErrNilEvent) { t.Errorf("received: %v, expected: %v", err, common.ErrNilEvent) } f := &fill.Fill{} _, err = e.placeOrder(context.Background(), decimal.NewFromInt(1), decimal.NewFromInt(1), false, true, f, bot.OrderManager) if err != nil && err.Error() != "order exchange name must be specified" { t.Error(err) } f.Exchange = testExchange _, err = e.placeOrder(context.Background(), decimal.NewFromInt(1), decimal.NewFromInt(1), false, true, f, bot.OrderManager) if !errors.Is(err, gctorder.ErrPairIsEmpty) { t.Errorf("received: %v, expected: %v", err, gctorder.ErrPairIsEmpty) } f.CurrencyPair = currency.NewPair(currency.BTC, currency.USDT) f.AssetType = asset.Spot f.Direction = gctorder.Buy _, err = e.placeOrder(context.Background(), decimal.NewFromInt(1), decimal.NewFromInt(1), false, true, f, bot.OrderManager) if err != nil { t.Error(err) } _, err = e.placeOrder(context.Background(), decimal.NewFromInt(1), decimal.NewFromInt(1), true, true, f, bot.OrderManager) if err != nil && !strings.Contains(err.Error(), "unset/default API keys") { t.Error(err) } } func TestExecuteOrder(t *testing.T) { t.Parallel() bot := &engine.Engine{} var err error em := engine.SetupExchangeManager() exch, err := em.NewExchangeByName(testExchange) if err != nil { t.Fatal(err) } exch.SetDefaults() cfg, err := exch.GetDefaultConfig() if err != nil { t.Fatal(err) } err = exch.Setup(cfg) if err != nil { t.Fatal(err) } em.Add(exch) bot.ExchangeManager = em bot.OrderManager, err = engine.SetupOrderManager(em, &engine.CommunicationManager{}, &bot.ServicesWG, false) if err != nil { t.Error(err) } err = bot.OrderManager.Start() if err != nil { t.Error(err) } p := currency.NewPair(currency.BTC, currency.USDT) a := asset.Spot _, err = exch.FetchOrderbook(context.Background(), p, a) if err != nil { t.Fatal(err) } cs := Settings{ Exchange: testExchange, UseRealOrders: false, Pair: p, Asset: a, ExchangeFee: decimal.NewFromFloat(0.01), MakerFee: decimal.NewFromFloat(0.01), TakerFee: decimal.NewFromFloat(0.01), BuySide: MinMax{}, SellSide: MinMax{}, Leverage: Leverage{}, MinimumSlippageRate: decimal.Zero, MaximumSlippageRate: decimal.NewFromInt(1), } e := Exchange{ CurrencySettings: []Settings{cs}, } ev := event.Base{ Exchange: testExchange, Time: time.Now(), Interval: gctkline.FifteenMin, CurrencyPair: p, AssetType: a, } o := &order.Order{ Base: ev, Direction: gctorder.Buy, Amount: decimal.NewFromInt(10), AllocatedFunds: decimal.NewFromInt(1337), } d := &kline.DataFromKline{ Item: gctkline.Item{ Exchange: "", Pair: currency.Pair{}, Asset: "", Interval: 0, Candles: []gctkline.Candle{ { Close: 1, High: 1, Low: 1, Volume: 1, }, }, }, } err = d.Load() if err != nil { t.Error(err) } d.Next() _, err = e.ExecuteOrder(o, d, bot.OrderManager, &fakeFund{}) if err != nil { t.Error(err) } cs.UseRealOrders = true cs.CanUseExchangeLimits = true o.Direction = gctorder.Sell e.CurrencySettings = []Settings{cs} _, err = e.ExecuteOrder(o, d, bot.OrderManager, &fakeFund{}) if err != nil && !strings.Contains(err.Error(), "unset/default API keys") { t.Error(err) } } func TestExecuteOrderBuySellSizeLimit(t *testing.T) { t.Parallel() bot := &engine.Engine{} var err error em := engine.SetupExchangeManager() exch, err := em.NewExchangeByName(testExchange) if err != nil { t.Fatal(err) } exch.SetDefaults() cfg, err := exch.GetDefaultConfig() if err != nil { t.Fatal(err) } err = exch.Setup(cfg) if err != nil { t.Fatal(err) } em.Add(exch) bot.ExchangeManager = em bot.OrderManager, err = engine.SetupOrderManager(em, &engine.CommunicationManager{}, &bot.ServicesWG, false) if err != nil { t.Error(err) } err = bot.OrderManager.Start() if err != nil { t.Error(err) } p := currency.NewPair(currency.BTC, currency.USDT) a := asset.Spot _, err = exch.FetchOrderbook(context.Background(), p, a) if err != nil { t.Fatal(err) } err = exch.UpdateOrderExecutionLimits(context.Background(), asset.Spot) if err != nil { t.Fatal(err) } limits, err := exch.GetOrderExecutionLimits(a, p) if err != nil { t.Fatal(err) } cs := Settings{ Exchange: testExchange, UseRealOrders: false, Pair: p, Asset: a, ExchangeFee: decimal.NewFromFloat(0.01), MakerFee: decimal.NewFromFloat(0.01), TakerFee: decimal.NewFromFloat(0.01), BuySide: MinMax{ MaximumSize: decimal.NewFromFloat(0.01), MinimumSize: decimal.Zero, }, SellSide: MinMax{ MaximumSize: decimal.NewFromFloat(0.1), MinimumSize: decimal.Zero, }, Leverage: Leverage{}, MinimumSlippageRate: decimal.Zero, MaximumSlippageRate: decimal.NewFromInt(1), Limits: limits, } e := Exchange{ CurrencySettings: []Settings{cs}, } ev := event.Base{ Exchange: testExchange, Time: time.Now(), Interval: gctkline.FifteenMin, CurrencyPair: p, AssetType: a, } o := &order.Order{ Base: ev, Direction: gctorder.Buy, Amount: decimal.NewFromInt(10), AllocatedFunds: decimal.NewFromInt(1337), } d := &kline.DataFromKline{ Item: gctkline.Item{ Exchange: "", Pair: currency.Pair{}, Asset: "", Interval: 0, Candles: []gctkline.Candle{ { Close: 1, High: 1, Low: 1, Volume: 1, }, }, }, } err = d.Load() if err != nil { t.Error(err) } d.Next() _, err = e.ExecuteOrder(o, d, bot.OrderManager, &fakeFund{}) if !errors.Is(err, errExceededPortfolioLimit) { t.Errorf("received %v expected %v", err, errExceededPortfolioLimit) } o = &order.Order{ Base: ev, Direction: gctorder.Buy, Amount: decimal.NewFromInt(10), AllocatedFunds: decimal.NewFromInt(1337), } cs.BuySide.MaximumSize = decimal.Zero cs.BuySide.MinimumSize = decimal.NewFromFloat(0.01) e.CurrencySettings = []Settings{cs} _, err = e.ExecuteOrder(o, d, bot.OrderManager, &fakeFund{}) if err != nil && !strings.Contains(err.Error(), "exceed minimum size") { t.Error(err) } if err != nil { t.Error("limitReducedAmount adjusted to 0.99999999, direction BUY, should fall in buyside {MinimumSize:0.01 MaximumSize:0 MaximumTotal:0}") } o = &order.Order{ Base: ev, Direction: gctorder.Sell, Amount: decimal.NewFromInt(10), AllocatedFunds: decimal.NewFromInt(1337), } cs.SellSide.MaximumSize = decimal.Zero cs.SellSide.MinimumSize = decimal.NewFromFloat(0.01) e.CurrencySettings = []Settings{cs} _, err = e.ExecuteOrder(o, d, bot.OrderManager, &fakeFund{}) if err != nil && !strings.Contains(err.Error(), "exceed minimum size") { t.Error(err) } if err != nil { t.Error("limitReducedAmount adjust to 0.99999999, should fall in sell size {MinimumSize:0.01 MaximumSize:0 MaximumTotal:0}") } o = &order.Order{ Base: ev, Direction: gctorder.Sell, Amount: decimal.NewFromFloat(0.5), AllocatedFunds: decimal.NewFromInt(1337), } cs.SellSide.MaximumSize = decimal.Zero cs.SellSide.MinimumSize = decimal.NewFromInt(1) e.CurrencySettings = []Settings{cs} _, err = e.ExecuteOrder(o, d, bot.OrderManager, &fakeFund{}) if !errors.Is(err, errExceededPortfolioLimit) { t.Errorf("received %v expected %v", err, errExceededPortfolioLimit) } o = &order.Order{ Base: ev, Direction: gctorder.Sell, Amount: decimal.NewFromFloat(0.02), AllocatedFunds: decimal.NewFromFloat(0.01337), } cs.SellSide.MaximumSize = decimal.Zero cs.SellSide.MinimumSize = decimal.NewFromFloat(0.01) cs.UseRealOrders = true cs.CanUseExchangeLimits = true o.Direction = gctorder.Sell e.CurrencySettings = []Settings{cs} _, err = e.ExecuteOrder(o, d, bot.OrderManager, &fakeFund{}) if !errors.Is(err, exchange.ErrAuthenticatedRequestWithoutCredentialsSet) { t.Errorf("received %v expected %v", err, exchange.ErrAuthenticatedRequestWithoutCredentialsSet) } } func TestApplySlippageToPrice(t *testing.T) { t.Parallel() resp := applySlippageToPrice(gctorder.Buy, decimal.NewFromInt(1), decimal.NewFromFloat(0.9)) if !resp.Equal(decimal.NewFromFloat(1.1)) { t.Errorf("received: %v, expected: %v", resp, decimal.NewFromFloat(1.1)) } resp = applySlippageToPrice(gctorder.Sell, decimal.NewFromInt(1), decimal.NewFromFloat(0.9)) if !resp.Equal(decimal.NewFromFloat(0.9)) { t.Errorf("received: %v, expected: %v", resp, decimal.NewFromFloat(0.9)) } } func TestReduceAmountToFitPortfolioLimit(t *testing.T) { t.Parallel() initialPrice := decimal.NewFromInt(100) initialAmount := decimal.NewFromInt(10).Div(initialPrice) portfolioAdjustedTotal := initialAmount.Mul(initialPrice) adjustedPrice := decimal.NewFromInt(1000) amount := decimal.NewFromInt(2) finalAmount := reduceAmountToFitPortfolioLimit(adjustedPrice, amount, portfolioAdjustedTotal, gctorder.Buy) if !finalAmount.Mul(adjustedPrice).Equal(portfolioAdjustedTotal) { t.Errorf("expected value %v to match portfolio total %v", finalAmount.Mul(adjustedPrice), portfolioAdjustedTotal) } finalAmount = reduceAmountToFitPortfolioLimit(adjustedPrice, decimal.NewFromInt(133333333337), portfolioAdjustedTotal, gctorder.Sell) if finalAmount != portfolioAdjustedTotal { t.Errorf("expected value %v to match portfolio total %v", finalAmount, portfolioAdjustedTotal) } finalAmount = reduceAmountToFitPortfolioLimit(adjustedPrice, decimal.NewFromInt(1), portfolioAdjustedTotal, gctorder.Sell) if !finalAmount.Equal(decimal.NewFromInt(1)) { t.Errorf("expected value %v to match portfolio total %v", finalAmount, portfolioAdjustedTotal) } } func TestVerifyOrderWithinLimits(t *testing.T) { t.Parallel() err := verifyOrderWithinLimits(nil, decimal.Zero, nil) if !errors.Is(err, common.ErrNilEvent) { t.Errorf("received %v expected %v", err, common.ErrNilEvent) } err = verifyOrderWithinLimits(&fill.Fill{}, decimal.Zero, nil) if !errors.Is(err, errNilCurrencySettings) { t.Errorf("received %v expected %v", err, errNilCurrencySettings) } err = verifyOrderWithinLimits(&fill.Fill{}, decimal.Zero, &Settings{}) if !errors.Is(err, errInvalidDirection) { t.Errorf("received %v expected %v", err, errInvalidDirection) } f := &fill.Fill{ Direction: gctorder.Buy, } err = verifyOrderWithinLimits(f, decimal.Zero, &Settings{}) if !errors.Is(err, nil) { t.Errorf("received %v expected %v", err, nil) } s := &Settings{ BuySide: MinMax{ MinimumSize: decimal.NewFromInt(1), MaximumSize: decimal.NewFromInt(1), }, } err = verifyOrderWithinLimits(f, decimal.NewFromFloat(0.5), s) if !errors.Is(err, errExceededPortfolioLimit) { t.Errorf("received %v expected %v", err, errExceededPortfolioLimit) } f.Direction = gctorder.Buy err = verifyOrderWithinLimits(f, decimal.NewFromInt(2), s) if !errors.Is(err, errExceededPortfolioLimit) { t.Errorf("received %v expected %v", err, errExceededPortfolioLimit) } f.Direction = gctorder.Sell s.SellSide = MinMax{ MinimumSize: decimal.NewFromInt(1), MaximumSize: decimal.NewFromInt(1), } err = verifyOrderWithinLimits(f, decimal.NewFromFloat(0.5), s) if !errors.Is(err, errExceededPortfolioLimit) { t.Errorf("received %v expected %v", err, errExceededPortfolioLimit) } f.Direction = gctorder.Sell err = verifyOrderWithinLimits(f, decimal.NewFromInt(2), s) if !errors.Is(err, errExceededPortfolioLimit) { t.Errorf("received %v expected %v", err, errExceededPortfolioLimit) } } <file_sep>package dispatch import ( "errors" "reflect" "github.com/gofrs/uuid" ) // GetNewMux returns a new multiplexer to track subsystem updates func GetNewMux() *Mux { return &Mux{d: dispatcher} } // Subscribe takes in a package defined signature element pointing to an ID set // and returns the associated pipe func (m *Mux) Subscribe(id uuid.UUID) (Pipe, error) { if m == nil { return Pipe{}, errors.New("mux is nil") } if id == (uuid.UUID{}) { return Pipe{}, errors.New("id not set") } ch, err := m.d.subscribe(id) if err != nil { return Pipe{}, err } return Pipe{C: ch, id: id, m: m}, nil } // Unsubscribe returns channel to the pool for the full signature set func (m *Mux) Unsubscribe(id uuid.UUID, ch chan interface{}) error { if m == nil { return errors.New("mux is nil") } return m.d.unsubscribe(id, ch) } // Publish takes in a persistent memory address and dispatches changes to // required pipes. Data should be of *type. func (m *Mux) Publish(ids []uuid.UUID, data interface{}) error { if m == nil { return errors.New("mux is nil") } if data == nil { return errors.New("data payload is nil") } cpy := reflect.ValueOf(data).Elem().Interface() for i := range ids { // Create copy to not interfere with stored value err := m.d.publish(ids[i], &cpy) if err != nil { return err } } return nil } // GetID a new unique ID to track routing information in the dispatch system func (m *Mux) GetID() (uuid.UUID, error) { if m == nil { return uuid.UUID{}, errors.New("mux is nil") } return m.d.getNewID() } // Release returns the channel to the communications pool to be reused func (p *Pipe) Release() error { return p.m.Unsubscribe(p.id, p.C) } <file_sep>package gct // AllModuleNames returns a list of all default module names. func AllModuleNames() []string { var names []string for name := range Modules { names = append(names, name) } return names } <file_sep>package backtest import ( "errors" "os" "strings" "testing" "time" "github.com/idoall/gocryptotrader/backtester/common" "github.com/idoall/gocryptotrader/backtester/config" "github.com/idoall/gocryptotrader/backtester/data" "github.com/idoall/gocryptotrader/backtester/data/kline" "github.com/idoall/gocryptotrader/backtester/eventhandlers/eventholder" "github.com/idoall/gocryptotrader/backtester/eventhandlers/exchange" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/risk" "github.com/idoall/gocryptotrader/backtester/eventhandlers/portfolio/size" "github.com/idoall/gocryptotrader/backtester/eventhandlers/statistics" "github.com/idoall/gocryptotrader/backtester/eventhandlers/strategies" "github.com/idoall/gocryptotrader/backtester/eventhandlers/strategies/base" "github.com/idoall/gocryptotrader/backtester/eventhandlers/strategies/dollarcostaverage" "github.com/idoall/gocryptotrader/backtester/funding" "github.com/idoall/gocryptotrader/backtester/report" gctcommon "github.com/idoall/gocryptotrader/common" "github.com/idoall/gocryptotrader/common/convert" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/database" "github.com/idoall/gocryptotrader/database/drivers" "github.com/idoall/gocryptotrader/engine" gctexchange "github.com/idoall/gocryptotrader/exchanges" "github.com/idoall/gocryptotrader/exchanges/asset" gctkline "github.com/idoall/gocryptotrader/exchanges/kline" "github.com/shopspring/decimal" ) const testExchange = "Bitstamp" var leet *decimal.Decimal func TestMain(m *testing.M) { oneThreeThreeSeven := decimal.NewFromInt(1337) leet = &oneThreeThreeSeven os.Exit(m.Run()) } func TestNewFromConfig(t *testing.T) { t.Parallel() _, err := NewFromConfig(nil, "", "") if !errors.Is(err, errNilConfig) { t.Errorf("received %v, expected %v", err, errNilConfig) } cfg := &config.Config{} _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, base.ErrStrategyNotFound) { t.Errorf("received: %v, expected: %v", err, base.ErrStrategyNotFound) } cfg.CurrencySettings = []config.CurrencySettings{ { ExchangeName: "test", Base: "test", Quote: "test", }, } _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, engine.ErrExchangeNotFound) { t.Errorf("received: %v, expected: %v", err, engine.ErrExchangeNotFound) } cfg.CurrencySettings[0].ExchangeName = testExchange _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, errInvalidConfigAsset) { t.Errorf("received: %v, expected: %v", err, errInvalidConfigAsset) } cfg.CurrencySettings[0].Asset = asset.Spot.String() _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, currency.ErrPairNotFound) { t.Errorf("received: %v, expected: %v", err, currency.ErrPairNotFound) } cfg.CurrencySettings[0].Base = "btc" cfg.CurrencySettings[0].Quote = "usd" _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, base.ErrStrategyNotFound) { t.Errorf("received: %v, expected: %v", err, base.ErrStrategyNotFound) } cfg.StrategySettings = config.StrategySettings{ Name: dollarcostaverage.Name, CustomSettings: map[string]interface{}{ "hello": "moto", }, } cfg.CurrencySettings[0].Base = "BTC" cfg.CurrencySettings[0].Quote = "USD" cfg.DataSettings.APIData = &config.APIData{ StartDate: time.Time{}, EndDate: time.Time{}, } _, err = NewFromConfig(cfg, "", "") if err != nil && !strings.Contains(err.Error(), "unrecognised dataType") { t.Error(err) } cfg.DataSettings.DataType = common.CandleStr _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, errIntervalUnset) { t.Errorf("received: %v, expected: %v", err, errIntervalUnset) } cfg.DataSettings.Interval = gctkline.OneMin.Duration() cfg.CurrencySettings[0].MakerFee = decimal.Zero cfg.CurrencySettings[0].TakerFee = decimal.Zero _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, gctcommon.ErrDateUnset) { t.Errorf("received: %v, expected: %v", err, gctcommon.ErrDateUnset) } cfg.DataSettings.APIData.StartDate = time.Now().Add(-time.Minute) cfg.DataSettings.APIData.EndDate = time.Now() cfg.DataSettings.APIData.InclusiveEndDate = true _, err = NewFromConfig(cfg, "", "") if !errors.Is(err, nil) { t.Errorf("received: %v, expected: %v", err, nil) } } func TestLoadDataAPI(t *testing.T) { t.Parallel() bt := BackTest{ Reports: &report.Data{}, } cp := currency.NewPair(currency.BTC, currency.USDT) cfg := &config.Config{ CurrencySettings: []config.CurrencySettings{ { ExchangeName: "Binance", Asset: asset.Spot.String(), Base: cp.Base.String(), Quote: cp.Quote.String(), InitialQuoteFunds: leet, Leverage: config.Leverage{}, BuySide: config.MinMax{}, SellSide: config.MinMax{}, MakerFee: decimal.Zero, TakerFee: decimal.Zero, }, }, DataSettings: config.DataSettings{ DataType: common.CandleStr, Interval: gctkline.OneMin.Duration(), APIData: &config.APIData{ StartDate: time.Now().Add(-time.Minute), EndDate: time.Now(), }}, StrategySettings: config.StrategySettings{ Name: dollarcostaverage.Name, CustomSettings: map[string]interface{}{ "hello": "moto", }, }, } em := engine.ExchangeManager{} exch, err := em.NewExchangeByName("Binance") if err != nil { t.Fatal(err) } exch.SetDefaults() b := exch.GetBase() b.CurrencyPairs.Pairs = make(map[asset.Item]*currency.PairStore) b.CurrencyPairs.Pairs[asset.Spot] = &currency.PairStore{ Available: currency.Pairs{cp}, Enabled: currency.Pairs{cp}, AssetEnabled: convert.BoolPtr(true), ConfigFormat: &currency.PairFormat{Uppercase: true}, RequestFormat: &currency.PairFormat{Uppercase: true}} _, err = bt.loadData(cfg, exch, cp, asset.Spot, false) if err != nil { t.Error(err) } } func TestLoadDataDatabase(t *testing.T) { t.Parallel() bt := BackTest{ Reports: &report.Data{}, } cp := currency.NewPair(currency.BTC, currency.USDT) cfg := &config.Config{ CurrencySettings: []config.CurrencySettings{ { ExchangeName: "Binance", Asset: asset.Spot.String(), Base: cp.Base.String(), Quote: cp.Quote.String(), InitialQuoteFunds: leet, Leverage: config.Leverage{}, BuySide: config.MinMax{}, SellSide: config.MinMax{}, MakerFee: decimal.Zero, TakerFee: decimal.Zero, }, }, DataSettings: config.DataSettings{ DataType: common.CandleStr, Interval: gctkline.OneMin.Duration(), DatabaseData: &config.DatabaseData{ Config: database.Config{ Enabled: true, Driver: "sqlite3", ConnectionDetails: drivers.ConnectionDetails{ Database: "gocryptotrader.db", }, }, StartDate: time.Now().Add(-time.Minute), EndDate: time.Now(), InclusiveEndDate: true, }}, StrategySettings: config.StrategySettings{ Name: dollarcostaverage.Name, CustomSettings: map[string]interface{}{ "hello": "moto", }, }, } em := engine.ExchangeManager{} exch, err := em.NewExchangeByName("Binance") if err != nil { t.Fatal(err) } exch.SetDefaults() b := exch.GetBase() b.CurrencyPairs.Pairs = make(map[asset.Item]*currency.PairStore) b.CurrencyPairs.Pairs[asset.Spot] = &currency.PairStore{ Available: currency.Pairs{cp}, Enabled: currency.Pairs{cp}, AssetEnabled: convert.BoolPtr(true), ConfigFormat: &currency.PairFormat{Uppercase: true}, RequestFormat: &currency.PairFormat{Uppercase: true}} bt.databaseManager, err = engine.SetupDatabaseConnectionManager(&cfg.DataSettings.DatabaseData.Config) if err != nil { t.Fatal(err) } _, err = bt.loadData(cfg, exch, cp, asset.Spot, false) if err != nil && !strings.Contains(err.Error(), "unable to retrieve data from GoCryptoTrader database") { t.Error(err) } } func TestLoadDataCSV(t *testing.T) { t.Parallel() bt := BackTest{ Reports: &report.Data{}, } cp := currency.NewPair(currency.BTC, currency.USDT) cfg := &config.Config{ CurrencySettings: []config.CurrencySettings{ { ExchangeName: "Binance", Asset: asset.Spot.String(), Base: cp.Base.String(), Quote: cp.Quote.String(), InitialQuoteFunds: leet, Leverage: config.Leverage{}, BuySide: config.MinMax{}, SellSide: config.MinMax{}, MakerFee: decimal.Zero, TakerFee: decimal.Zero, }, }, DataSettings: config.DataSettings{ DataType: common.CandleStr, Interval: gctkline.OneMin.Duration(), CSVData: &config.CSVData{ FullPath: "test", }}, StrategySettings: config.StrategySettings{ Name: dollarcostaverage.Name, CustomSettings: map[string]interface{}{ "hello": "moto", }, }, } em := engine.ExchangeManager{} exch, err := em.NewExchangeByName("Binance") if err != nil { t.Fatal(err) } exch.SetDefaults() b := exch.GetBase() b.CurrencyPairs.Pairs = make(map[asset.Item]*currency.PairStore) b.CurrencyPairs.Pairs[asset.Spot] = &currency.PairStore{ Available: currency.Pairs{cp}, Enabled: currency.Pairs{cp}, AssetEnabled: convert.BoolPtr(true), ConfigFormat: &currency.PairFormat{Uppercase: true}, RequestFormat: &currency.PairFormat{Uppercase: true}} _, err = bt.loadData(cfg, exch, cp, asset.Spot, false) if err != nil && !strings.Contains(err.Error(), "The system cannot find the file specified.") && !strings.Contains(err.Error(), "no such file or directory") { t.Error(err) } } func TestLoadDataLive(t *testing.T) { t.Parallel() bt := BackTest{ Reports: &report.Data{}, shutdown: make(chan struct{}), } cp := currency.NewPair(currency.BTC, currency.USDT) cfg := &config.Config{ CurrencySettings: []config.CurrencySettings{ { ExchangeName: "Binance", Asset: asset.Spot.String(), Base: cp.Base.String(), Quote: cp.Quote.String(), InitialQuoteFunds: leet, Leverage: config.Leverage{}, BuySide: config.MinMax{}, SellSide: config.MinMax{}, MakerFee: decimal.Zero, TakerFee: decimal.Zero, }, }, DataSettings: config.DataSettings{ DataType: common.CandleStr, Interval: gctkline.OneMin.Duration(), LiveData: &config.LiveData{ APIKeyOverride: "test", APISecretOverride: "test", APIClientIDOverride: "test", API2FAOverride: "test", RealOrders: true, }}, StrategySettings: config.StrategySettings{ Name: dollarcostaverage.Name, CustomSettings: map[string]interface{}{ "hello": "moto", }, }, } em := engine.ExchangeManager{} exch, err := em.NewExchangeByName("Binance") if err != nil { t.Fatal(err) } exch.SetDefaults() b := exch.GetBase() b.CurrencyPairs.Pairs = make(map[asset.Item]*currency.PairStore) b.CurrencyPairs.Pairs[asset.Spot] = &currency.PairStore{ Available: currency.Pairs{cp}, Enabled: currency.Pairs{cp}, AssetEnabled: convert.BoolPtr(true), ConfigFormat: &currency.PairFormat{Uppercase: true}, RequestFormat: &currency.PairFormat{Uppercase: true}} _, err = bt.loadData(cfg, exch, cp, asset.Spot, false) if err != nil { t.Error(err) } bt.Stop() } func TestLoadLiveData(t *testing.T) { t.Parallel() err := loadLiveData(nil, nil) if !errors.Is(err, common.ErrNilArguments) { t.Error(err) } cfg := &config.Config{} err = loadLiveData(cfg, nil) if !errors.Is(err, common.ErrNilArguments) { t.Error(err) } b := &gctexchange.Base{ Name: testExchange, API: gctexchange.API{ AuthenticatedSupport: false, AuthenticatedWebsocketSupport: false, PEMKeySupport: false, Credentials: struct { Key string Secret string ClientID string PEMKey string Subaccount string }{}, CredentialsValidator: struct { RequiresPEM bool RequiresKey bool RequiresSecret bool RequiresClientID bool RequiresBase64DecodeSecret bool }{ RequiresPEM: true, RequiresKey: true, RequiresSecret: true, RequiresClientID: true, RequiresBase64DecodeSecret: true, }, }, } err = loadLiveData(cfg, b) if !errors.Is(err, common.ErrNilArguments) { t.Error(err) } cfg.DataSettings.LiveData = &config.LiveData{ RealOrders: true, } cfg.DataSettings.Interval = gctkline.OneDay.Duration() cfg.DataSettings.DataType = common.CandleStr err = loadLiveData(cfg, b) if err != nil { t.Error(err) } cfg.DataSettings.LiveData.APIKeyOverride = "1234" cfg.DataSettings.LiveData.APISecretOverride = "1234" cfg.DataSettings.LiveData.APIClientIDOverride = "1234" cfg.DataSettings.LiveData.API2FAOverride = "1234" cfg.DataSettings.LiveData.APISubAccountOverride = "1234" err = loadLiveData(cfg, b) if err != nil { t.Error(err) } } func TestReset(t *testing.T) { t.Parallel() f := funding.SetupFundingManager(true, false) bt := BackTest{ shutdown: make(chan struct{}), Datas: &data.HandlerPerCurrency{}, Strategy: &dollarcostaverage.Strategy{}, Portfolio: &portfolio.Portfolio{}, Exchange: &exchange.Exchange{}, Statistic: &statistics.Statistic{}, EventQueue: &eventholder.Holder{}, Reports: &report.Data{}, Funding: f, } bt.Reset() if bt.Funding.IsUsingExchangeLevelFunding() { t.Error("expected false") } } func TestFullCycle(t *testing.T) { t.Parallel() ex := testExchange cp := currency.NewPair(currency.BTC, currency.USD) a := asset.Spot tt := time.Now() stats := &statistics.Statistic{} stats.ExchangeAssetPairStatistics = make(map[string]map[asset.Item]map[currency.Pair]*statistics.CurrencyPairStatistic) stats.ExchangeAssetPairStatistics[ex] = make(map[asset.Item]map[currency.Pair]*statistics.CurrencyPairStatistic) stats.ExchangeAssetPairStatistics[ex][a] = make(map[currency.Pair]*statistics.CurrencyPairStatistic) port, err := portfolio.Setup(&size.Size{ BuySide: exchange.MinMax{}, SellSide: exchange.MinMax{}, }, &risk.Risk{}, decimal.Zero) if err != nil { t.Error(err) } _, err = port.SetupCurrencySettingsMap(&exchange.Settings{Exchange: ex, Asset: a, Pair: cp}) if err != nil { t.Error(err) } f := funding.SetupFundingManager(false, true) b, err := funding.CreateItem(ex, a, cp.Base, decimal.Zero, decimal.Zero) if err != nil { t.Error(err) } quote, err := funding.CreateItem(ex, a, cp.Quote, decimal.NewFromInt(1337), decimal.Zero) if err != nil { t.Error(err) } pair, err := funding.CreatePair(b, quote) if err != nil { t.Error(err) } err = f.AddPair(pair) if err != nil { t.Error(err) } bt := BackTest{ shutdown: nil, Datas: &data.HandlerPerCurrency{}, Strategy: &dollarcostaverage.Strategy{}, Portfolio: port, Exchange: &exchange.Exchange{}, Statistic: stats, EventQueue: &eventholder.Holder{}, Reports: &report.Data{}, Funding: f, } bt.Datas.Setup() k := kline.DataFromKline{ Item: gctkline.Item{ Exchange: ex, Pair: cp, Asset: a, Interval: gctkline.FifteenMin, Candles: []gctkline.Candle{{ Time: tt, Open: 1337, High: 1337, Low: 1337, Close: 1337, Volume: 1337, }}, }, Base: data.Base{}, RangeHolder: &gctkline.IntervalRangeHolder{ Start: gctkline.CreateIntervalTime(tt), End: gctkline.CreateIntervalTime(tt.Add(gctkline.FifteenMin.Duration())), Ranges: []gctkline.IntervalRange{ { Start: gctkline.CreateIntervalTime(tt), End: gctkline.CreateIntervalTime(tt.Add(gctkline.FifteenMin.Duration())), Intervals: []gctkline.IntervalData{ { Start: gctkline.CreateIntervalTime(tt), End: gctkline.CreateIntervalTime(tt.Add(gctkline.FifteenMin.Duration())), HasData: true, }, }, }, }, }, } err = k.Load() if err != nil { t.Error(err) } bt.Datas.SetDataForCurrency(ex, a, cp, &k) err = bt.Run() if err != nil { t.Error(err) } } func TestStop(t *testing.T) { t.Parallel() bt := BackTest{shutdown: make(chan struct{})} bt.Stop() } func TestFullCycleMulti(t *testing.T) { t.Parallel() ex := testExchange cp := currency.NewPair(currency.BTC, currency.USD) a := asset.Spot tt := time.Now() stats := &statistics.Statistic{} stats.ExchangeAssetPairStatistics = make(map[string]map[asset.Item]map[currency.Pair]*statistics.CurrencyPairStatistic) stats.ExchangeAssetPairStatistics[ex] = make(map[asset.Item]map[currency.Pair]*statistics.CurrencyPairStatistic) stats.ExchangeAssetPairStatistics[ex][a] = make(map[currency.Pair]*statistics.CurrencyPairStatistic) port, err := portfolio.Setup(&size.Size{ BuySide: exchange.MinMax{}, SellSide: exchange.MinMax{}, }, &risk.Risk{}, decimal.Zero) if err != nil { t.Error(err) } _, err = port.SetupCurrencySettingsMap(&exchange.Settings{Exchange: ex, Asset: a, Pair: cp}) if err != nil { t.Error(err) } f := funding.SetupFundingManager(false, true) b, err := funding.CreateItem(ex, a, cp.Base, decimal.Zero, decimal.Zero) if err != nil { t.Error(err) } quote, err := funding.CreateItem(ex, a, cp.Quote, decimal.NewFromInt(1337), decimal.Zero) if err != nil { t.Error(err) } pair, err := funding.CreatePair(b, quote) if err != nil { t.Error(err) } err = f.AddPair(pair) if err != nil { t.Error(err) } bt := BackTest{ shutdown: nil, Datas: &data.HandlerPerCurrency{}, Portfolio: port, Exchange: &exchange.Exchange{}, Statistic: stats, EventQueue: &eventholder.Holder{}, Reports: &report.Data{}, Funding: f, } bt.Strategy, err = strategies.LoadStrategyByName(dollarcostaverage.Name, true) if err != nil { t.Error(err) } bt.Datas.Setup() k := kline.DataFromKline{ Item: gctkline.Item{ Exchange: ex, Pair: cp, Asset: a, Interval: gctkline.FifteenMin, Candles: []gctkline.Candle{{ Time: tt, Open: 1337, High: 1337, Low: 1337, Close: 1337, Volume: 1337, }}, }, Base: data.Base{}, RangeHolder: &gctkline.IntervalRangeHolder{ Start: gctkline.CreateIntervalTime(tt), End: gctkline.CreateIntervalTime(tt.Add(gctkline.FifteenMin.Duration())), Ranges: []gctkline.IntervalRange{ { Start: gctkline.CreateIntervalTime(tt), End: gctkline.CreateIntervalTime(tt.Add(gctkline.FifteenMin.Duration())), Intervals: []gctkline.IntervalData{ { Start: gctkline.CreateIntervalTime(tt), End: gctkline.CreateIntervalTime(tt.Add(gctkline.FifteenMin.Duration())), HasData: true, }, }, }, }, }, } err = k.Load() if err != nil { t.Error(err) } bt.Datas.SetDataForCurrency(ex, a, cp, &k) err = bt.Run() if err != nil { t.Error(err) } } <file_sep>package orderbook import ( "testing" "github.com/gofrs/uuid" ) var unsafeID, _ = uuid.NewV4() type externalBook struct{} func (e *externalBook) Lock() {} func (e *externalBook) Unlock() {} func TestUnsafe(t *testing.T) { d := newDepth(unsafeID) ob := d.GetUnsafe() if ob.AskHead == nil || ob.BidHead == nil || ob.m == nil { t.Fatal("these items should not be nil") } ob2 := &externalBook{} ob.Lock() ob.Unlock() // nolint:staticcheck, gocritic // Not needed in test ob.LockWith(ob2) ob.UnlockWith(ob2) } <file_sep>package data import ( "testing" "time" "github.com/idoall/gocryptotrader/currency" "github.com/idoall/gocryptotrader/exchanges/asset" "github.com/idoall/gocryptotrader/exchanges/kline" "github.com/shopspring/decimal" ) const testExchange = "binance" type fakeDataHandler struct { time int } func TestBaseDataFunctions(t *testing.T) { t.Parallel() var d Base if latest := d.Latest(); latest != nil { t.Error("expected nil") } d.Next() o := d.Offset() if o != 0 { t.Error("expected 0") } d.AppendStream(nil) d.AppendStream(nil) d.AppendStream(nil) d.Next() o = d.Offset() if o != 0 { t.Error("expected 0") } if list := d.List(); list != nil { t.Error("expected nil") } if history := d.History(); history != nil { t.Error("expected nil") } d.SetStream(nil) if st := d.GetStream(); st != nil { t.Error("expected nil") } d.Reset() d.GetStream() d.SortStream() } func TestSetup(t *testing.T) { t.Parallel() d := HandlerPerCurrency{} d.Setup() if d.data == nil { t.Error("expected not nil") } } func TestStream(t *testing.T) { var d Base var f fakeDataHandler // shut up coverage report f.GetOffset() f.SetOffset(1) f.IsEvent() f.Pair() f.GetExchange() f.GetInterval() f.GetAssetType() f.GetReason() f.AppendReason("fake") f.GetClosePrice() f.GetHighPrice() f.GetLowPrice() f.GetOpenPrice() d.AppendStream(fakeDataHandler{time: 1}) d.AppendStream(fakeDataHandler{time: 4}) d.AppendStream(fakeDataHandler{time: 10}) d.AppendStream(fakeDataHandler{time: 2}) d.AppendStream(fakeDataHandler{time: 20}) d.SortStream() f, ok := d.Next().(fakeDataHandler) if f.time != 1 || !ok { t.Error("expected 1") } f, ok = d.Next().(fakeDataHandler) if f.time != 2 || !ok { t.Error("expected 2") } f, ok = d.Next().(fakeDataHandler) if f.time != 4 || !ok { t.Error("expected 4") } f, ok = d.Next().(fakeDataHandler) if f.time != 10 || !ok { t.Error("expected 10") } f, ok = d.Next().(fakeDataHandler) if f.time != 20 || !ok { t.Error("expected 20") } } func TestSetDataForCurrency(t *testing.T) { t.Parallel() d := HandlerPerCurrency{} exch := testExchange a := asset.Spot p := currency.NewPair(currency.BTC, currency.USDT) d.SetDataForCurrency(exch, a, p, nil) if d.data == nil { t.Error("expected not nil") } if d.data[exch][a][p] != nil { t.Error("expected nil") } } func TestGetAllData(t *testing.T) { t.Parallel() d := HandlerPerCurrency{} exch := testExchange a := asset.Spot p := currency.NewPair(currency.BTC, currency.USDT) d.SetDataForCurrency(exch, a, p, nil) d.SetDataForCurrency(exch, a, currency.NewPair(currency.BTC, currency.DOGE), nil) result := d.GetAllData() if len(result) != 1 { t.Error("expected 1") } if len(result[exch][a]) != 2 { t.Error("expected 2") } } func TestGetDataForCurrency(t *testing.T) { t.Parallel() d := HandlerPerCurrency{} exch := testExchange a := asset.Spot p := currency.NewPair(currency.BTC, currency.USDT) d.SetDataForCurrency(exch, a, p, nil) d.SetDataForCurrency(exch, a, currency.NewPair(currency.BTC, currency.DOGE), nil) result := d.GetDataForCurrency(exch, a, p) if result != nil { t.Error("expected nil") } } func TestReset(t *testing.T) { t.Parallel() d := HandlerPerCurrency{} exch := testExchange a := asset.Spot p := currency.NewPair(currency.BTC, currency.USDT) d.SetDataForCurrency(exch, a, p, nil) d.SetDataForCurrency(exch, a, currency.NewPair(currency.BTC, currency.DOGE), nil) d.Reset() if d.data != nil { t.Error("expected nil") } } // methods that satisfy the common.DataEventHandler interface func (t fakeDataHandler) GetOffset() int64 { return 0 } func (t fakeDataHandler) SetOffset(int64) { } func (t fakeDataHandler) IsEvent() bool { return false } func (t fakeDataHandler) GetTime() time.Time { return time.Now().Add(time.Hour * time.Duration(t.time)) } func (t fakeDataHandler) Pair() currency.Pair { return currency.NewPair(currency.BTC, currency.USD) } func (t fakeDataHandler) GetExchange() string { return "fake" } func (t fakeDataHandler) GetInterval() kline.Interval { return kline.Interval(time.Minute) } func (t fakeDataHandler) GetAssetType() asset.Item { return asset.Spot } func (t fakeDataHandler) GetReason() string { return "fake" } func (t fakeDataHandler) AppendReason(string) { } func (t fakeDataHandler) GetClosePrice() decimal.Decimal { return decimal.Zero } func (t fakeDataHandler) GetHighPrice() decimal.Decimal { return decimal.Zero } func (t fakeDataHandler) GetLowPrice() decimal.Decimal { return decimal.Zero } func (t fakeDataHandler) GetOpenPrice() decimal.Decimal { return decimal.Zero }
2d909edfbb447570dd6b7045bbe955914538d902
[ "Go Module", "Go", "Shell" ]
75
Go
idoall/gocryptotrader
afb2b8d045f245bc879906ec0b0f1e455633df32
16eab554ac34e4fa9c05cbddf2ef351dc1cd6d87
refs/heads/master
<file_sep>const getIterator = require('get-iterator') // Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort module.exports = function createAbortable (iterator, signal, options) { iterator = getIterator(iterator) options = options || {} const onAbort = options.onAbort || (() => {}) const abortMessage = options.abortMessage || 'operation aborted' const abortCode = options.abortCode || 'ERR_ABORTED' const errAborted = () => Object.assign(new Error(abortMessage), { code: abortCode }) async function * abortable () { while (true) { let result try { if (signal.aborted) throw errAborted() const abort = new Promise((resolve, reject) => { signal.onabort = () => reject(errAborted()) }) // Race the iterator and the abort signal result = await Promise.race([abort, iterator.next()]) } catch (err) { if (err.code === abortCode) { // Do any custom abort handling for the iterator await onAbort(iterator) // End the iterator if it is a generator if (typeof iterator.return === 'function') { iterator.return() } } throw err } if (result.done) return yield result.value } } return abortable() }
1fcbadf508120a717e60dae20bc51776cff0c5db
[ "JavaScript" ]
1
JavaScript
Happy-Ferret/abortable-iterator
ef1c2816f4674ea357ae3cda727ccf1dce626e12
4e22923eec829d602e978f5811ab2beae0a3b9fb
refs/heads/master
<file_sep>#include<iostream> #include<stdlib.h> #include<math.h> using namespace std; void convert(int, int, int[][5]); int main(void){ int digits[102][5]; int test, input, counter; for(int i=0;i<5;i++) digits[1][i]=0; for(int i=1;i<=100;i++){ test = i; counter = 0; while(test>0){ convert((test%10)*(int)pow(10,counter),i,digits); test/=10; counter++; } for(int j=0;j<5;j++) digits[i+1][j] = digits[i][j]; } while(true){ cin>>input; if(input == 0) return 0; cout<<input<<": "<<digits[input][0]<<" i, "<<digits[input][1]; cout<<" v, "<<digits[input][2]<<" x, "<<digits[input][3]<<" l, "<<digits[input][4]<<" c"<<endl; } return 0; } void convert(int num, int testnum, int digits[][5]){ switch (num){ case 1: digits[testnum][0]++; break; case 2: digits[testnum][0]+=2; break; case 3: digits[testnum][0]+=3; break; case 4: digits[testnum][0]++; digits[testnum][1]++; break; case 5: digits[testnum][1]++; break; case 6: digits[testnum][0]++; digits[testnum][1]++; break; case 7: digits[testnum][0]+=2; digits[testnum][1]++; break; case 8: digits[testnum][0]+=3; digits[testnum][1]++; break; case 9: digits[testnum][0]++; digits[testnum][2]++; break; case 10: digits[testnum][2]++; break; case 20: digits[testnum][2]+=2; break; case 30: digits[testnum][2]+=3; break; case 40: digits[testnum][2]++; digits[testnum][3]++; break; case 50: digits[testnum][3]++; break; case 60: digits[testnum][2]++; digits[testnum][3]++; break; case 70: digits[testnum][2]+=2; digits[testnum][3]++; break; case 80: digits[testnum][2]+=3; digits[testnum][3]++; break; case 90: digits[testnum][2]++; digits[testnum][4]++; break; case 100: digits[testnum][4]++; break; } } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int score[1000]; int test, n, counter; double sum, percentage; cin>>test; for(int i=0;i<test;i++){ cin>>n; sum = 0; counter = 0; for(int j=0;j<n;j++){ cin>>score[j]; sum+=score[j]; } sum/=n; for(int j=0;j<n;j++){ if(score[j]>sum) counter++; } percentage = (double)counter/n * 100; printf("%.3lf%%\n",percentage); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int num[11][11]; int input,counter,count,casec=1; long long sum; while(cin>>input&&input){ for(int i=0;i<input;i++) for(int j=0;j<input;j++) cin>>num[i][j]; cout<<"Case "<<casec<<": "; if(input==1) cout<<num[0][0]<<endl; else{ counter = (input+1)/2; count = 0; while(counter--){ sum = 0; for(int i=count;i<input-count;i++) sum+=num[count][i]+num[input-count-1][i]; for(int i=count+1;i<input-count-1;i++) sum+=num[i][count]+num[i][input-count-1]; if(counter==0 && input%2==1) sum/=2; cout<<sum<<" "; count++; } cout<<endl; } } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<map> #include<algorithm> using namespace std; int main(void){ int N,Q,input; int arr[51000]; scanf("%d",&N); map<int,int> in; map<int,int>::iterator it; for(int i=0;i<N;i++){ scanf("%d",&arr[i]); in[arr[i]]=1; } scanf("%d",&Q); for(int i=0;i<Q;i++){ scanf("%d",&input); if(input==arr[0]){ it = in.begin(); it++; printf("X %d\n",it->first); } else if(input<arr[0]) printf("X %d\n",arr[0]); else if(input==arr[N-1]){ it = in.end(); it--; it--; printf("%d X\n",it->first); } else if(input>arr[N-1]) printf("%d X\n",arr[N-1]); else{ it = in.lower_bound(input); while(it->first>=input) it--; printf("%d %d\n",it->first,in.upper_bound(input)->first); } } return 0; } <file_sep>#include<iostream> using namespace std; void countdigit(int, int[]); int main(void){ int test,digit; int digitcounter[10]; cin>>test; for(int i=0;i<test;i++){ cin>>digit; for(int j=0;j<10;j++) digitcounter[j] = 0; for(int j=1;j<=digit;j++) countdigit(j,digitcounter); for(int j=0;j<9;j++) cout<<digitcounter[j]<<" "; cout<<digitcounter[9]<<endl; } return 0; } void countdigit(int number,int digitcounter[]){ while(number>0){ digitcounter[number%10]++; number/=10; } } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int test; string dummy; long long mtx[100][100]; int dimension; bool negative; scanf("%d\n",&test); for(int i=1;i<=test;i++){ negative = false; scanf("N = %d",&dimension); for(int j=0;j<dimension;j++){ for(int k=0;k<dimension;k++){ cin>>mtx[j][k]; if(mtx[j][k]<0) negative = true; } } getline(cin,dummy); cout<<"Test #"<<i<<": "; if(!negative){ for(int j=0;j<dimension;j++) for(int k=0;k<dimension;k++) if(mtx[dimension-1-j][dimension-1-k]!=mtx[j][k]){ negative = true; break; } if(negative) cout<<"Non-symmetric."<<endl; else cout<<"Symmetric."<<endl; } else cout<<"Non-symmetric."<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int arr[13] = {2,7,5,30,169,441,1872,7632,1740,93313,459901,1358657,2504881}; int k; while(cin>>k && k){ cout<<arr[k-1]<<endl; } } <file_sep>#include<iostream> using namespace std; int main(void){ long long input; int counter; while(cin>>input){ if(input<=3) cout<<input; else{ counter = 0; while(input!=1){ if(input%2==0) input/=2; else{ if(((input-1) %4 == 0) || input == 3) input--; else input++; } counter++; } cout<<++counter; } cout<<endl; } return 0; } <file_sep>#include<stdio.h> #include<iostream> #include<vector> #include<string.h> using namespace std; int main(void){ string unsort[55],sorted[55],in; int test,take; vector<int> tes; vector<int>::iterator it; bool taken[55]; int length[55]; while(cin>>test && test){ for(int i=0;i<test;i++){ cin>>unsort[i]>>in; length[i] = in.length() - 1; tes.push_back(i); } for(int i=0;i<test;i++) taken[i]=false; int current = 0, counter; for(int i=0;i<test;i++){ counter = 0; while(counter<length[i]){ current++; counter++; if(current == tes.size()) current = 0; } sorted[tes[current]] = unsort[i]; tes.erase(tes.begin()+current-1); } for(int i=0;i<test-1;i++) cout<<sorted[i]<<" "; cout<<sorted[test-1]<<endl; } return 0; } <file_sep>#include<queue> #include<iostream> #include<stdio.h> using namespace std; int main(void){ priority_queue<int> pq; int length; int dummy, sum, cost; while(scanf("%d",&length) && length){ for(int i=0;i<length;i++){ scanf("%d",&dummy); dummy*=-1; pq.push(dummy); } sum = 0; while(pq.size()>1){ dummy = -1*pq.top(); pq.pop(); dummy+=-1*pq.top(); pq.pop(); sum+=dummy; dummy*=-1; pq.push(dummy); } printf("%d\n",sum); pq.pop(); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ string hortop[10] = {"-"," ","-","-"," ","-","-","-","-","-"}; string verfronttop[10] = {"|"," "," "," ","|","|","|"," ","|","|"}; string verbacktop[10] = {"|","|","|","|","|"," "," ","|","|","|"}; string hormid[10] = {" "," ","-","-","-","-","-"," ","-","-"}; string verfrontbot[10] = {"|"," ","|"," "," "," ","|"," ","|"," "}; string verbackbot[10] = {"|","|"," ","|","|","|","|","|","|","|"}; string horbot[10] = {"-"," ","-","-"," ","-","-"," ","-","-"}; int dimension; string in; while(cin>>dimension>>in && dimension){ for(int i=0;i<in.length();i++){ cout<<" "; for(int j=0;j<dimension;j++) cout<<hortop[in.at(i)-'0']; cout<<" "; if(i!=in.length()-1) cout<<" "; } cout<<endl; for(int j=0;j<dimension;j++){ for(int i=0;i<in.length();i++){ cout<<verfronttop[in.at(i)-'0']; for(int k=0;k<dimension;k++) cout<<" "; cout<<verbacktop[in.at(i)-'0']; if(i!=in.length()-1) cout<<" "; } cout<<endl; } for(int i=0;i<in.length();i++){ cout<<" "; for(int j=0;j<dimension;j++) cout<<hormid[in.at(i)-'0']; cout<<" "; if(i!=in.length()-1) cout<<" "; } cout<<endl; for(int j=0;j<dimension;j++){ for(int i=0;i<in.length();i++){ cout<<verfrontbot[in.at(i)-'0']; for(int k=0;k<dimension;k++) cout<<" "; cout<<verbackbot[in.at(i)-'0']; if(i!=in.length()-1) cout<<" "; } cout<<endl; } for(int i=0;i<in.length();i++){ cout<<" "; for(int j=0;j<dimension;j++) cout<<horbot[in.at(i)-'0']; cout<<" "; if(i!=in.length()-1) cout<<" "; } cout<<endl<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> #include<map> #include<algorithm> using namespace std; map<int,int>mapper; int AdjMat[102][102]; int main(void){ int a,b,counter,casecounter=1; while(true){ for(int i=0;i<102;i++) for(int j=0;j<102;j++){ if(i!=j) AdjMat[i][j] = 10000000; else AdjMat[i][j] = 0; } scanf("%d %d",&a,&b); if(!a && !b) return 0; counter = 0; mapper.clear(); if(mapper.find(a)==mapper.end()) mapper[a]=counter++; if(mapper.find(b)==mapper.end()) mapper[b]=counter++; AdjMat[mapper[a]][mapper[b]] = 1; while(scanf("%d %d",&a,&b) && a && b){ if(mapper.find(a)==mapper.end()) mapper[a]=counter++; if(mapper.find(b)==mapper.end()) mapper[b]=counter++; AdjMat[mapper[a]][mapper[b]] = 1; } for(int k=0;k<counter;k++) for(int i=0;i<counter;i++) for(int j=0;j<counter;j++) AdjMat[i][j] = min(AdjMat[i][j],AdjMat[i][k]+AdjMat[k][j]); double total = 0,div; for(int i=0;i<counter;i++){ for(int j=0;j<counter;j++) total+=AdjMat[i][j]; } div = counter*counter - counter; printf("Case %d: average length between pages = %.3lf clicks\n",casecounter++,total/div); } return 0; } <file_sep>#include<iostream> #include<string.h> #include<algorithm> #include<stdlib.h> #include<stdio.h> using namespace std; struct country_t{ char name[100]; int girls; }; bool compare(string,string); int main(void){ int test,counter; char dummy[100]; string testing; bool written; counter = 0; cin>>test; country_t country[2000]; for(int i=0;i<test;i++){ scanf("%s",dummy); written = false; for(int j=0;j<counter;j++){ if(strcmp(country[j].name,dummy)==0){ country[j].girls++; written = true; break; } } if(!written){ strcpy(country[counter].name , dummy); country[counter].girls = 1; counter++; } getline(cin,testing); } for (int j = 1; j < counter; j++) { bool is_sorted = true; for (int k = 0; k < counter-j; k++) { if (strcmp(country[k].name,country[k+1].name)>0) { country_t temp = country[k]; country[k] = country[k+1]; country[k+1] = temp; is_sorted = false; } } if (is_sorted) break; } for(int j=0;j<counter;j++){ cout<<country[j].name<<" "<<country[j].girls<<endl; } return 0; } bool compare(string test1, string test2){ int max = (test1.length(), test2.length()); for(int i=0;i<max;i++){ if(test1.at(i)!=test2.at(i)) if((int)test2.at(i)<(int)test1.at(i)) return false; } return true; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) class UnionFind { // OOP style private: vi p, rank, setSize; // remember: vi is vector<int> int numSets; public: UnionFind(int N) { setSize.assign(N, 1); numSets = N; rank.assign(N, 0); p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { if (!isSameSet(i, j)) { numSets--; int x = findSet(i), y = findSet(j); // rank is used to keep the tree short if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } } int numDisjointSets() { return numSets; } int sizeOfSet(int i) { return setSize[findSet(i)]; } }; vector<vii> AdjList; int fr, to, cost; int main(void){ //freopen("in.txt","r",stdin); int c,s,q, casecounter = 1; int AdjMat[101][101]; bool first = true; while(scanf("%d %d %d",&c,&s,&q), (c||s||q)){ if(!first) printf("\n"); first = false; for(int i=0;i<c;i++) for(int j=0;j<c;j++) AdjMat[i][j] = AdjMat[j][i] = INF; for(int i=0;i<s;i++){ scanf("%d %d %d",&fr,&to,&cost); AdjMat[fr-1][to-1] = AdjMat[to-1][fr-1] = cost; } for(int k=0;k<c;k++) for(int i=0;i<c;i++) for(int j=0;j<c;j++) AdjMat[i][j] = min(AdjMat[i][j], max(AdjMat[i][k], AdjMat[k][j])); printf("Case #%d\n",casecounter++); for(int i=0;i<q;i++){ scanf("%d %d",&fr,&to); fr--,to--; if(AdjMat[fr][to] == INF)printf("no path\n"); else printf("%d\n",AdjMat[fr][to]); } } return 0; } <file_sep>#include<iostream> #include<map> #include<algorithm> using namespace std; typedef struct{ int users; string name; }source; bool sort_comp(source a, source b){ if(a.users!=b.users) return a.users>b.users; return a.name.compare(b.name)<0; } int main(void){ string input,remname; map<string,int> developer; map<string,int> user; map<string,string> develuser; source open[1000]; while(true){ developer.clear(); user.clear(); getline(cin,input); if(input=="0") break; else{ remname = input; developer[remname]=0; } while(true){ getline(cin,input); if(input=="1") break; if(input.at(0)>='A' && input.at(0)<='Z'){ remname = input; developer[remname]=0; } else{ if(!user[input]){ user[input]=1; developer[remname]++; develuser[input]=remname; } else if(user[input]==1 && develuser[input]!=remname){ developer[develuser[input]]--; user[input]=2; } } } int counter; counter = 0; for(map<string,int>::iterator it=developer.begin();it!=developer.end();it++){ open[counter].name = it->first; open[counter].users = it->second; counter++; } sort(open,open+counter,sort_comp); for(int i=0;i<counter;i++) cout<<open[i].name<<" "<<open[i].users<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ int high[10001],low[10001]; memset(high,0,sizeof high); memset(low,0,sizeof low); int i,j,diff; i = 2; diff = 0; while(i<=58){ j=1; while(j<i){ diff = i*i*i-j*j*j; if(diff<=10000){ if(low[diff]==0 && high[diff]==0){ low[diff]=j; high[diff]=i; } else if(low[diff]>0 && low[diff]>j){ low[diff]=j; high[diff]=i; } } j++; } i++; } int input; while(cin>>input && input){ if(!low[input]) cout<<"No solution"<<endl; else cout<<high[input]<<" "<<low[input]<<endl; } return 0; } <file_sep>import java.util.*; class Three{ public static void main(String[] args){ boolean found = false; int asdf; for(int i=1;i<=50000;i++){ found = false; if(i%8!=7){ asdf = (int)Math.sqrt(i); for(int j=0;j<=asdf;j++){ for(int k=j;k<=asdf;k++){ for(int l=k;l<=asdf;l++){ if(j*j + k*k + l*l == i){ System.out.print("\""+j+" "+k+" "+l+"\""); found = true; break; } } if(found) break; } if(found) break; } } if(!found) System.out.print("\"-1\""); System.out.print(","); } } } <file_sep>#include<iostream> using namespace std; int main(void){ int height[10002] = {0}; int left, h, right,start,max; max = -1000; start = 10000; while(cin>>left>>h>>right){ if(start>left) start = left; if(max<right) max = right; for(int i=left;i<right;i++){ if(height[i] == 0) height[i] = h; else if(height[i]<h) height[i] = h; } } height[max] = 0; cout<<start<<" "<<height[start]<<" "; for(int i=start+1;i<=max;i++){ if(height[i]!=height[i-1] && i !=max) cout<<i<<" "<<height[i]<<" "; else if(i==max) cout<<i<<" "<<height[i]; } cout<<endl; return 0; } <file_sep>#include<set> #include<map> #include<algorithm> #include<string.h> #include<iostream> using namespace std; int main(void){ string input, sorted; set<string> dict; map<string,string> in; while(true){ getline(cin,input); if(input == "XXXXXX") break; sorted = input; sort(input.begin(), input.end()); in[sorted] = input; dict.insert(input); } bool found; while(true){ getline(cin,input); if(input == "XXXXXX") break; found = false; sort(input.begin(),input.end()); for(map<string,string>::iterator it = in.begin();it!=in.end();it++) if(it->second == input){ cout<<it->first<<endl; found = true; } if(!found) cout<<"NOT A VALID WORD"<<endl; cout<<"******"<<endl; } return 0; } <file_sep>#include <iostream> using namespace std; int main(){ int i,j, carry, tempi, tempj, hascarry; while(true){ cin>>i>>j; if(i==0 && j==0) return 0; carry = 0; hascarry = 0; while(i!=0 || j!=0){ tempi = i%10; tempj = j%10; if(i!=0) i/=10; if(j!=0) j/=10; if((hascarry==0 && (tempi+tempj)>9) ||(hascarry==1 && tempi + tempj>8)){ carry++; hascarry = 1; } else hascarry = 0; } if(carry==0){ cout << "No carry operation."; } else if(carry==1){ cout << "1 carry operation."; } else cout<< carry<<" carry operations."; cout<<endl; } } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> using namespace std; short divide[1000001]; int most[1000001]; int main(void){ for(int i=2;i<=1000000;i++) divide[i]=1; divide[1]=0; for(int i=2;i<500001;i++) for(int j=i;j<=1000000;j+=i) divide[j]++; most[1]=1; for(int i=2;i<=1000000;i++){ if(divide[most[i-1]]<=divide[i]) most[i]=i; else most[i]=most[i-1]; } int test,in; scanf("%d",&test); for(int i=0;i<test;i++){ scanf("%d",&in); printf("%d\n",most[in]); } return 0; } <file_sep>#include<stdio.h> #include<algorithm> using namespace std; int main(void){ int test, dummy; int countneg, countpos, countpos2, countneg2; int building, built; int sizepos[500000], sizeneg[500000]; bool taken; scanf("%d",&test); for(int i=0;i<test;i++){ scanf("%d",&building); countneg = countpos = 0; for(int j=0;j<building;j++){ scanf("%d",&dummy); if(dummy>0) sizepos[countpos++] = dummy; else sizeneg[countneg++] = (dummy*-1); } if(building == 0) printf("0\n"); else if(countneg == 0 || countpos == 0) printf("1\n"); else{ built = countpos2 = countneg2 = 0; sort(sizepos,sizepos+countpos); sort(sizeneg,sizeneg+countneg); if(sizepos[countpos2]<sizeneg[countneg2]){ countpos2++; taken = true; } else{ countneg2++; taken = false; } built++; while(countpos2<countpos && countneg2<countneg){ if(taken){ if(sizeneg[countneg2]<sizepos[countpos2]) countneg2++; else if(sizeneg[countneg2]>sizepos[countpos2]){ countpos2++; built++; taken = false; } } else{ if(sizepos[countpos2]<sizeneg[countneg2]) countpos2++; else if(sizepos[countpos2]>sizeneg[countneg2]){ countneg2++; built++; taken = true; } } } printf("%d\n",built); } } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ string input; char rem; int in1, in2, res; int track, right = 0; while(cin>>input){ track = in1 = in2 = res = 0; while(input.at(track)>='0' && input.at(track)<='9'){ in1*=10; in1+=input.at(track) -'0'; track++; } rem = input.at(track); track++; while(input.at(track)>='0' && input.at(track)<='9'){ in2*=10; in2+=input.at(track) -'0'; track++; } track++; for(int i=track;i<input.length();i++){ if(input.at(track)=='?') res = -10000000l; else{ res*=10; res+=input.at(i)-'0'; } } if(rem=='+') in1+=in2; if(rem=='-') in1-=in2; if(in1==res) right++; } cout<<right<<endl; return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int test; int length[3]; cin>>test; for(int i=0;i<test;i++){ for(int j=0;j<3;j++) cin>>length[j]; sort(length,length+3); if(length[0]+length[1]>length[2]) cout<<"OK"; else cout<<"Wrong!!"; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ string input; int sum[2]; int length; while(cin>>input){ if(input.length()==1 && input=="0") break; sum[0] = sum[1] = 0; length = input.length(); for(int i=0;i<length;i++){ if(i%2==0) sum[0]+=input.at(i)-'0'; else sum[1]+=input.at(i)-'0'; } cout<<input<<" is "; if(sum[0]%11 == sum[1]%11) cout<<"a multiple of 11."<<endl; else cout<<"not a multiple of 11."<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int main(void){ freopen("in.txt","r",stdin); map<string,int> mapper; string str,str2; while(cin>>str){ mapper.clear(); int len = str.length(); FOR(i,len){ REPN(j,1,len-i){ str2 = str.substr(i,j); int leng = str2.length(); if(mapper.find(str2)==mapper.end()){ bool found = true; FOR(k,leng){ if(str2.at(k)!=str2.at(leng-1-k)){ found = false; break; } } if(found)mapper[str2]++; } } } printf("The %d unique palindromes in '%s' are ",mapper.size(),str.c_str()); mapper<string,int>::iterator it = mapper.begin(); int counter = for(;it!=mapper.end();it++){ printf("'%s'",it->first.c_str()); } } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string burger; int length,distr, distd,min; bool r,d; while(cin>>length && length){ cin>>burger; r = d = false; min = 20000000; for(int i=0;i<length;i++){ if(burger.at(i)=='Z'){ min = 0; break; } if(burger.at(i)=='R'){ if(!r){ r = true; distr = 0; } else if(r){ distr = 0; } if(d){ distd++; if(min>distd) min = distd; d = false; } } else if(burger.at(i)=='D'){ if(!d){ d = true; distd = 0; } else if(d){ distd = 0; } if(r){ distr++; if(min>distr) min = distr; r = false; } } else if(burger.at(i)=='.'){ if(r) distr++; if(d) distd++; } } cout<<min<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int signal[100]; int min,i; while(cin>>signal[0] && signal[0]){ i=1; int lights[18000] = {0}; min = signal[0]; while(cin>>signal[i] && signal[i]){ if(min>signal[i]) min = signal[i]; i++; } while(true){ for(int j=0;j<i;j++){ for(int k=) } } } cin>>signal[0]>>signal[0]; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> #include<sstream> using namespace std; char dimension[101][101]; int counter; int maxcol,maxrow; int dr[]={-1,-1,-1,0,0,1,1,1}; int dc[]={-1,0,1,-1,1,-1,0,1}; int floodfill(int row, int col, char c1, char c2){ //cout<<row<<col<<dimension[row][col]; if(row<0||col<0||row>=maxrow||col>=maxcol) return 0; if(dimension[row][col]!=c1) return 0; dimension[row][col] = c2; int ans = 1; for(int i=0;i<8;i++) ans+=floodfill(row+dr[i],col+dc[i],c1,c2); return ans; } int main(void){ int test,row,col; scanf("%d",&test); string in; getline(cin,in); getline(cin,in); while(test--){ counter = 0; while(true){ getline(cin,in); if(in.at(0)!='W' && in.at(0)!='L'){ stringstream(in)>>row>>col; break; } for(int i=0;i<in.length();i++) dimension[counter][i]=in.at(i); counter++; maxcol = in.length(); } maxrow = counter; cout<<floodfill(row-1,col-1,'W','.')<<endl; while(getline(cin,in)){ if(in.empty()) break; stringstream(in)>>row>>col; if(dimension[row-1][col-1]=='.') cout<<floodfill(row-1,col-1,',','W')<<endl; else cout<<floodfill(row-1,col-1,'W','.')<<endl; } if(test) cout<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<vector> #include<map> #include<algorithm> using namespace std; map<vector<int>,int> result; long long t,n; int arr[1000]; typedef vector<int> vectorint; typedef vector<vectorint> vi; void comb(vector<int> v,int now, long long sum){ if(sum>t){ return; } if(sum==t){ sort(v.begin(),v.end()); reverse(v.begin(),v.end()); result[v]++; } if(now == n) return; for(int i=now;i<n;i++){ v.push_back(arr[i]); comb(v,i+1,sum+arr[i]); v.pop_back(); } } bool sort_cmp(vector<int> a, vector<int> b){ int mini; if(a.size()<b.size()) mini = a.size(); else mini = b.size(); for(int i=0;i<mini;i++){ if(a[i]!=b[i]) return a[i]>b[i]; } return mini == a.size(); } int main(void){ vi res; vector<int> v; while(scanf("%d %d",&t,&n) && n){ for(int i=0;i<n;i++) scanf("%d",&arr[i]); result.clear(); comb(v,0,0); printf("Sum of %d:\n",t); if(result.size()==0) printf("NONE\n"); else{ res.clear(); for(map<vector<int>,int>::iterator it = result.begin();it!=result.end();it++){ res.push_back(it->first); } sort(res.begin(),res.end(),sort_cmp); for(int i=0;i<res.size();i++){ printf("%d",res[i][0]); for(int j=1;j<res[i].size();j++) printf("+%d",res[i][j]); printf("\n"); } } } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) typedef struct{ string name,compname; int mins, sec, ms; }racer; bool sort_cmp(racer a, racer b){ if(a.mins != b.mins)return a.mins<b.mins; if(a.sec != b.sec) return a.sec<b.sec; if(a.ms != b.ms) return a.ms<b.ms; return a.compname.compare(b.compname) < 0; } int main(void){ //freopen("in.txt","r",stdin); int n; racer race[102]; while(scanf("%d",&n)!=EOF){ string dummy; FOR(i,n){ cin>>race[i].name>>dummy>>race[i].mins>>dummy>>race[i].sec>>dummy>>race[i].ms>>dummy; string x = ""; FOR(j,race[i].name.length()){ x += tolower(race[i].name.at(j)); } race[i].compname = x; //scanf("%s : %d min %d sec %d ms",race[i].name,race[i].mins,race[i].sec,race[i].ms); } sort(race,race+n,sort_cmp); int counter = 0; FOR(i,n){ if(i%2 == 0){ counter++; printf("Row %d\n",counter); } cout<<race[i].name<<endl; //printf("%s\n",race[i].name); } printf("\n"); } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int street[50001], avenue[50001]; int test, str, ave,friends; cin>>test; for(int i=0;i<test;i++){ cin>>str>>ave>>friends; for(int j=0;j<friends;j++) cin>>street[j]>>avenue[j]; sort(street,street+friends); sort(avenue,avenue+friends); if(friends%2==1){ str = street[friends/2]; ave = avenue[friends/2]; } else{ str = street[friends/2-1]; ave = avenue[friends/2-1]; } cout<<"(Street: "<<str<<", Avenue: "<<ave<<")"<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string> using namespace std; int main(void){ string test; int quote = 0; while(getline(cin,test)){ for(int i=0;i<test.length();i++){ if(test.at(i)=='"' && quote == 0){ cout<<"``"; quote = 1; } else if(test.at(i) == '"' && quote == 1){ cout<<"''"; quote = 0; } else cout<<test.at(i); } cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ int num, remember, temp, testcase; int rem[1000]; cin>>testcase; for(int i=1;i<=testcase;i++){ cin>>num; temp = 0; memset(rem,0,sizeof rem); cout<<"Case #"<<i<<": "<<num<<" is "; while(true){ while(num>0){ temp+=(num%10)*(num%10); num/=10; } num = temp; temp = 0; rem[num]++; if(num==1){ cout<<"a Happy number."<<endl; break; } if(rem[num]>1){ cout<<"an Unhappy number."<<endl; break; } } } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC(tc) while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) ll _sieve_size; vi primes; bitset<10000010> bs; // 10^7 should be enough for most cases void sieve(ll upperbound) { // create list of primes in [0..upperbound] _sieve_size = upperbound + 1; // add 1 to include upperbound bs.set(); // set all bits to 1 bs[0] = bs[1] = 0; // except index 0 and 1 for (ll i = 2; i <= _sieve_size; i++) if (bs[i]) { // cross out multiples of i starting from i * i! for (ll j = i * i; j <= _sieve_size; j += i) bs[j] = 0; primes.push_back((int)i); // also add this vector containing list of primes } } vi primeFactors(ll N) { // remember: vi is vector of integers, ll is long long vi factors; // vi `primes' (generated by sieve) is optional ll PF_idx = 0, PF = primes[PF_idx]; // using PF = 2, 3, 4, ..., is also ok while (N != 1 && (PF * PF <= N)) { // stop at sqrt(N), but N can get smaller while (N % PF == 0) { N /= PF; factors.push_back(PF); } // remove this PF PF = primes[++PF_idx]; // only consider primes! } if (N != 1) factors.push_back(N); // special case if N is actually a prime return factors; // if pf exceeds 32-bit integer, you have to change vi } int main(void){ int tc; sieve(1000000); scanf("%d",&tc); map<int,int> mA,mB; TC(tc){ int a,b; scanf("%d%d",&a,&b); if(a>b) printf("NO SOLUTION\n"); else if(a==b) printf("1\n"); else{ mA.clear(); mB.clear(); vi A = primeFactors(a); vi B = primeFactors(b); for(int i=0;i<A.size();i++) mA[A[i]]++; for(int i=0;i<B.size();i++) mB[B[i]]++; bool valid = true; for(map<int,int>::iterator it = mA.begin();it!=mA.end();it++){ // printf("faktor:%d^ %d\n",it->first,it->second); if(mB[it->first]<it->second) {valid = false;break;} } /* for(map<int,int>::iterator it = mB.begin();it!=mB.end();it++){ printf("faktor:%d^ %d\n",it->first,it->second); }*/ ll total = 1; if(valid) for(map<int,int>::iterator it = mB.begin();it!=mB.end();it++){ if(it->second > mA[it->first]){ //printf("%d %d %d\n",it->first,it->second, mA[it->second]); for(int i=0;i<it->second;i++) total*=it->first; //total*= pow((double)it->first, (double)it->second); // printf("total = %lld\n",total); } } if(total > b || !valid)printf("NO SOLUTION\n"); else printf("%lld\n",total); } } return 0; } <file_sep>#include<stdio.h> #include<iostream> #include<map> using namespace std; int GCD(int,int); int main(void){ int x,total; for(int x=2;x<501;x++){ total=0; for(int i=1;i<x;i++) for(int j=i+1;j<=x;j++){ total+=GCD(i,j); } printf("%d\n",total); } return 0; } int GCD(int i, int j){ if(!j) return i; else return GCD(j,i % j); } <file_sep>#include<iostream> #include<string> using namespace std; struct web{ string nama; int relevance; }; int main(void){ int testcase, max; web nyoba[10]; cin>>testcase; for(int i=1;i<=testcase;i++){ max = 0; cout<<"Case #"<<i<<":"<<endl; for(int j=0;j<10;j++){ cin>>nyoba[j].nama >>nyoba[j].relevance; if(max<nyoba[j].relevance) max = nyoba[j].relevance; } for(int j=0;j<10;j++){ if( nyoba[j].relevance == max) cout<<nyoba[j].nama<<endl; } } } <file_sep>#include<iostream> #include<stdio.h> #include<math.h> using namespace std; int main(void){ int prime[10001] = {1}; int a,b,j, k, counter; long long test; for(int i=1;i<=10000;i++){ test = i*i + i + 41; if(test%2!=0){ k=sqrt(test); for(j=3;j<=k;j++) if(test%j == 0) break; if(j>k) prime[i] = 1; else prime[i] = 0; } else{ prime[i] = 0; } } while(cin>>a>>b){ counter = 0; for(int i=a;i<=b;i++) counter+=prime[i]; printf("%.2lf\n",100.0*counter/(b-a+1)+1e-8); } return 0; } <file_sep>#include<map> #include<iostream> #include<string.h> #include<algorithm> using namespace std; typedef struct{ int ascii; int freq; }iden; bool sort_cmp(iden a, iden b){ if(a.freq!=b.freq) return a.freq<b.freq; else return a.ascii>b.ascii; } int main(void){ map<char,int> store; string input; iden id[250]; int counter; bool first = true; while(getline(cin,input)){ store.clear(); counter = 0; if(first) first = false; else cout<<endl; for(int i=0;i<input.length();i++) store[input.at(i)]++; for(map<char,int>::iterator it=store.begin();it!=store.end();it++){ id[counter].ascii = (int)it->first; id[counter].freq = it->second; counter++; } sort(id,id+counter,sort_cmp); for(int i=0;i<counter;i++) cout<<id[i].ascii<<" "<<id[i].freq<<endl; } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class FindTheWays{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n,r; String result; while(sc.hasNext()){ n = sc.nextInt(); r = sc.nextInt(); BigInteger com = BigInteger.ONE; if(r>(n-r)) r = n-r; BigInteger temp; for(int i=n;i>(n-r);i--){ temp = BigInteger.valueOf(i); com = com.multiply(temp); } for(int i=2;i<=r;i++){ temp = BigInteger.valueOf(i); com = com.divide(temp); } result = com.toString(); System.out.println(result.length()); } return; } } <file_sep>#include<iostream> #include<string> #include<stdio.h> using namespace std; int main(void){ int test, hour, min; string input; cin>>test; for(int i=0;i<test;i++){ scanf("%d:%d",&hour,&min); min = 60 - min; if(min == 60) min = 0; hour = 12-hour - 1; if(min==0) hour++; if(hour <= 0) hour = 12+hour; if(hour<10) cout<<"0"<<hour<<":"; else cout<<hour<<":"; if(min<10) cout<<"0"<<min; else cout<<min; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> #include<map> #include<stdio.h> using namespace std; string T[30][2]; int sizes,vol; bool finish; void trycomb(int now, map<string,int> avail){ if(now==vol) finish = true; else{ for(int i=0;i<2;i++){ if(finish) return; if(avail[T[now][i]]>0){ avail[T[now][i]]--; trycomb(now+1,avail); avail[T[now][i]]++; } } } } int main(void){ int test, maxshirt; string size; map<string, int> avail; scanf("%d",&test); for(int i=0;i<test;i++){ scanf("%d %d",&sizes,&vol); maxshirt = sizes/6; avail.clear(); avail["S"]=maxshirt; avail["XS"]=maxshirt; avail["M"]=maxshirt; avail["L"]=maxshirt; avail["XL"]=maxshirt; avail["XXL"]=maxshirt; for(int j=0;j<vol;j++){ cin>>T[j][0]>>T[j][1]; } finish = false; trycomb(0,avail); if(finish) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int arr[3]; while(true){ cin>>arr[0]>>arr[1]>>arr[2]; if(arr[0] == arr[1] && arr[1] == arr[2] && arr[2] == 0) return 0; sort(arr,arr+3); if((arr[0] * arr[0] + arr[1] * arr[1]) == arr[2] * arr[2]) cout<<"right"<<endl; else cout<<"wrong"<<endl; } return 0; } <file_sep>#include<iostream> #include<algorithm> #include<stdlib.h> using namespace std; typedef struct{ int input; int mods; }data; bool sort_comp(data a, data b){ if(a.mods!=b.mods) return a.mods<b.mods; else if(abs(a.input%2)!=abs(b.input%2)) return abs(a.input%2)>abs(b.input%2); else if(a.input%2==0) return a.input<b.input; else return a.input>b.input; } int main(void){ int n,m; data num[10001]; while(cin>>n>>m && (n || m)){ for(int i=0;i<n;i++){ cin>>num[i].input; num[i].mods = num[i].input%m; } cout<<n<<" "<<m<<endl; sort(num,num+n,sort_comp); for(int i=0;i<n;i++){ cout<<num[i].input<<endl; } } cout<<"0 0"<<endl; return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> using namespace std; long long changes(int, int); int coins[]={5,10,20,50,100,200,500,1000,2000,5000,10000}; long long change[13][30100]; int main(void){ memset(change,-1,sizeof change); int inputd, inputc; double writing; while(scanf("%d.%d",&inputd,&inputc)){ if(inputd==0 && inputc == 0) return 0; inputd = inputd*100 + inputc; writing = inputd/100.0; printf("%6.2lf%17llu\n",writing,changes(inputd,0)); } return 0; } long long changes(int money, int value){ if(money==0) return 1; if(money<0 || value>10) return 0; if(change[value][money]!=-1) return change[value][money]; return change[value][money] = changes(money-coins[value],value) + changes(money,value+1); } <file_sep>#include<iostream> using namespace std; int main(void){ int test, numcall, interval; int sum[2]; cin>>test; for(int i=1;i<=test;i++){ cin>>numcall; sum[0] = sum[1] = 0; for(int j=0;j<numcall;j++){ cin>>interval; sum[0] +=(interval/30 + 1)*10; sum[1] +=(interval/60 + 1)*15; } cout<<"Case "<<i<<": "; if(sum[0]==sum[1]) cout<<"Mile Juice "<<sum[1]<<endl; else if(sum[0]<sum[1]) cout<<"Mile "<<sum[0]<<endl; else cout<<"Juice "<<sum[1]<<endl; } return 0; } <file_sep> class UglyNumber{ public static void main(String[] args){ int ugly = 2; int counter = 1, i; boolean isugly = true; while(true){ i=2; while(ugly>=i){ if((ugly%i==0) && (i%2!=0 && i%3!=0 && i%5!=0)){ isugly = false; break; } i++; } if(isugly){ counter++; } if(counter==1500) break; ugly++; isugly = true; } System.out.println(ugly); } } <file_sep>#include<stdio.h> #include<string.h> bool sieve[1000000]; int digit[1000000]; void sieves(){ memset(sieve,true,sizeof sieve); sieve[0]=sieve[1]=false; for(int i=2;i<1000;i++) if(sieve[i]) for(int j=i*i;j<1000000;j+=i) sieve[j]=false; } void generate(){ digit[0]=digit[1]=0; int temp,num; for(int i=2;i<1000000;i++){ if(sieve[i]){ num = i; temp = 0; while(num>0){ temp+=num%10; num/=10; } if(sieve[temp]) digit[i]=digit[i-1]+1; else digit[i]=digit[i-1]; } else digit[i]=digit[i-1]; } } int main(void){ sieves(); generate(); int test,low,high; int temp,result,num; scanf("%d",&test); for(int i=0;i<test;i++){ scanf("%d %d",&low,&high); num = low; temp = 0; while(num>0){ temp+=num%10; num/=10; } result = digit[high]-digit[low]; if(sieve[temp] && sieve[low]) result++; printf("%d\n",result); } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int test; int array[4]; cin>>test; for(int i=0;i<test;i++){ for(int j=0;j<4;j++) cin>>array[j]; sort(array,array+4); if(array[0] == array[1] && array[1] == array[2] && array[2]==array[3] && array[3]==array[0]) cout<<"square"; else if(array[0]==array[1] && array[2]==array[3]) cout<<"rectangle"; else if(array[3] >= array[0] + array[1] + array[2]) cout<<"banana"; else cout<<"quadrangle"; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> #include<algorithm> using namespace std; int main(void){ string input1, input2; int test, counter1, counter2; bool same; cin>>test; getline(cin,input1); for(int i=1;i<=test;i++){ getline(cin,input1); getline(cin,input2); cout<<"Case "<<i<<": "; if(input1==input2) cout<<"Yes"<<endl; else{ same = true; counter1 = counter2 = 0; for(int i=0;i<input1.length();i++) if(input1.at(i)==' '){ input1.erase(i,1); i--; } for(int i=0;i<input2.length();i++) if(input2.at(i)==' '){ input2.erase(i,1); i--; } if(input1==input2) cout<<"Output Format Error"<<endl; else cout<<"Wrong Answer"<<endl; } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ long long A, L; int counter; int i = 1; while(cin>>A>>L && A>0 && L>0){ counter = 0; cout<<"Case "<<i<<": A = "<<A<<", limit = "<<L<<", number of terms = "; while(A!=1 && A<=L){ counter++; if(A%2==1) A = A*3 + 1; else A/=2; } if(A==1) counter++; cout<<counter<<endl; i++; } } <file_sep>#include<iostream> using namespace std; int main(void){ long long available, madenew[12], needed[12], counter = 1; while(cin>>available && available>-1){ for(int i=0;i<12;i++) cin>>madenew[i]; for(int i=0;i<12;i++) cin>>needed[i]; cout<<"Case "<<counter<<":"<<endl; for(int i=0;i<12;i++){ if(available>=needed[i]){ cout<<"No problem! :D"<<endl; available-=needed[i]; } else cout<<"No problem. :("<<endl; available+=madenew[i]; } counter++; available = 0; } return 0; } <file_sep>#include<stdio.h> int main(void){ int result[10000]; result[0]=result[1]=1; int temp=1; for(int i=2;i<10000;i++){ temp*=i; while(temp%10==0) temp/=10; temp%=100000; result[i]=temp%10; } int input; while(scanf("%d",&input)==1){ printf("%5d -> %d\n",input,result[input]); } return 0; } <file_sep>#include<string> #include<iostream> using namespace std; int main(void){ string input1, input2; int counter1,counter2; while(cin>>input1>>input2){ counter1 = counter2 = 0; while(counter1<input1.length() && counter2<input2.length()){ while(input1.at(counter1)!=input2.at(counter2)){ counter2++; if(counter2 == input2.length()) break; } if(counter2 == input2.length()) break; counter1++; counter2++; } if(counter1 == input1.length()) cout<<"Yes"<<endl; else{ cout<<"No"<<endl; } } return 0; } <file_sep>#include<iostream> #include<stdlib.h> using namespace std; int main(void){ int x1,y1,x2,y2, move; while(cin>>x1>>y1>>x2>>y2){ if(x1 == 0 && x2 == 0 && y1 == 0 && y2 == 0) return 0; if(x1==x2 && y1 == y2) move = 0; else if(x1==x2 || y1==y2) move = 1; else if(abs(x1-x2) == abs(y1-y2)) move = 1; else move = 2; cout<<move<<endl; } return 0; } <file_sep>#include<stdio.h> #include<math.h> #include<iostream> using namespace std; bool isPrime[100010042]; short prime[10001]; int main(void){ for(int i=0;i<=100010041;i++) isPrime[i] = true; for(int i=2;i<=100010041;i++) if(isPrime[i]) for(int j=i+i;j<=100010041;j+=i) isPrime[j] = false; int a,b; for(int i=1;i<=10000;i++) prime[i] = 0; prime[0] = 1; for(int i=1;i<=10000;i++){ if(isPrime[(int) i*i + i + 41]) prime[i] = prime[i-1]+1; else prime[i] = prime[i-1]; } while(cin>>a>>b){ printf("%.2lf\n",(double)(prime[b] - prime[a]+1)*100/(b-a+1)); } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ long long x, y, res, count; int test, counter; cin>>test; for(int i=0;i<test;i++){ cin>>x>>y; y = y-x; if(y==0) cout<<"0"<<endl; else if(y==1) cout<<"1"<<endl; else{ counter = 2; count = counter*counter; while(count<y){ counter++; count = counter*counter; } if(y<=count-counter){ counter = counter*2-2; } else counter = counter*2-1; cout<<counter<<endl; } } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int a,b,res; while(cin>>a>>b && a!=-1 && b!=-1){ res = b-a; if(res<0) res=-res; if(res>50) res = 100-res; cout<<res<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) int main(void){ //freopen("in.txt","r",stdin); int V, x[202],y[202]; double AdjMatrix[300][300]; int casecounter = 1; while(scanf("%d",&V) && V){ //printf("V = %d\n",V); for(int i=0;i<V;i++){ AdjMatrix[i][i] = 0; //printf("%d\n",i); scanf("%d %d",&x[i], &y[i]); } for(int i=0;i<V;i++){ for(int j=i+1;j<V;j++) AdjMatrix[i][j] = AdjMatrix[j][i] = hypot((x[i]-x[j]),(y[i]-y[j])); } for (int k = 0; k < V; k++) for (int i = 0; i < V; i++) for (int j = 0; j < V; j++) AdjMatrix[i][j] = min(AdjMatrix[i][j], max(AdjMatrix[i][k], AdjMatrix[k][j])); printf("Scenario #%d\n",casecounter++); printf("Frog Distance = %.3lf\n\n",AdjMatrix[0][1]); } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int input; while(cin>>input){ if(input == 2){ printf("00\n01\n81\n"); } else if(input == 4){ printf("0000\n0001\n2025\n3025\n9801\n"); } else if(input == 6){ printf("000000\n000001\n088209\n494209\n998001\n"); } else if(input == 8){ printf("00000000\n00000001\n04941729\n07441984\n24502500\n25502500\n52881984\n60481729\n99980001\n"); } } return 0; } <file_sep> #include <algorithm> #include <cstdio> #include <vector> #include <queue> using namespace std; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; #define INF 1000000000 int main() { int tc,V, E, s, u, v, w; vector<vii> AdjList; scanf("%d",&tc); while(tc--){ scanf("%d %d", &V, &E); AdjList.assign(V, vii()); // assign blank vectors of pair<int, int>s to AdjList for (int i = 0; i < E; i++) { scanf("%d %d %d", &u, &v, &w); AdjList[u].push_back(ii(v, w)); } // Bellman Ford routine vi dist(V, INF); dist[0] = 0; for (int i = 0; i < V - 1; i++) // relax all E edges V-1 times, overall O(VE) for (int u = 0; u < V; u++) // these two loops = O(E) for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; // we can record SP spanning here if needed dist[v.first] = min(dist[v.first], dist[u] + v.second); // relax } bool hasNegativeCycle = false; for (int u = 0; u < V; u++) // one more pass to check for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (dist[v.first] > dist[u] + v.second) // should be false hasNegativeCycle = true; // but if true, then negative cycle exists! } printf("%s\n", hasNegativeCycle ? "possible" : "not possible"); } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int input; int counter; int money[1001]; int day; scanf("%d",&input); for(int i=0;i<input;i++){ counter = 0; scanf("%d",&day); scanf("%d",&money[0]); for(int j=1;j<day;j++){ scanf("%d",&money[j]); for(int k=0;k<j;k++){ if(money[j]>=money[k]) counter++; } } printf("%d\n",counter); } } <file_sep>import java.util.*; class DecodingTheMessage{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String input, temp; StringTokenizer st; int test = sc.nextInt(); int counter; sc.nextLine(); sc.nextLine(); for(int i=1;i<=test;i++){ System.out.println("Case #"+i+":"); while(true){ counter = 0; input = sc.nextLine(); if(input.isEmpty()) break; st = new StringTokenizer(input); while(st.hasMoreTokens()){ temp = st.nextToken(); if(temp.length()>counter){ System.out.print(temp.charAt(counter)); counter++; } } System.out.println(); } if(i!=test) System.out.println(); } } }<file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ int test, length, counter, crow; string in; cin>>test; for(int i=1;i<=test;i++){ cin>>length; getline(cin,in); getline(cin,in); counter = crow = 0; while(counter<length){ if(in.at(counter)=='.'){ crow++; counter+=3; } else counter++; } cout<<"Case "<<i<<": "<<crow<<endl; } } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int input; long long res; while(scanf("%d",&input)==1){ res = input/2+1; res = res*(res+1)/2.0; printf("%lld\n",res); } return 0; } <file_sep>#include<iostream> #include<map> using namespace std; int main(void){ map<string,int> scale; map<int,string> scaleinv; scale["C"] = 0; scale["C#"] = 1; scale["D"] = 2; scale["D#"] = 3; scale["E"] = 4; scale["E#"] = 5; scale["F"] = 5; scale["F#"] = 6; scale["G"] = 7; scale["G#"] = 8; scale["A"] = 9; scale["A#"] = 10; scale["B"] = 11; scale["B#"] = 0; scaleinv[0] = "C"; scaleinv[1] = "C#"; scaleinv[2] = "D"; scaleinv[3] = "D#"; scaleinv[4] = "E"; scaleinv[5] = "F"; scaleinv[6] = "F#"; scaleinv[7] = "G"; scaleinv[8] = "G#"; scaleinv[9] = "A"; scaleinv[10] = "A#"; scaleinv[11] = "B"; int notes[12][12] = { 1,0,1,0,1,1,0,1,0,1,0,1, 1,1,0,1,0,1,1,0,1,0,1,0, 0,1,1,0,1,0,1,1,0,1,0,1,//d 1,0,1,1,0,1,0,1,1,0,1,0,//eb 0,1,0,1,1,0,1,0,1,1,0,1,//e 1,0,1,0,1,1,0,1,0,1,1,0,//f 0,1,0,1,0,1,1,0,1,0,1,1,//f# 1,0,1,0,1,0,1,1,0,1,0,1,//g 1,1,0,1,0,1,0,1,1,0,1,0,//as 0,1,1,0,1,0,1,0,1,1,0,1,//a 1,0,1,1,0,1,0,1,0,1,1,0,//bes 0,1,0,1,1,0,1,0,1,0,1,0,//b }; string input, newstr; int len, value; bool valid[12], first; while(getline(cin,input)){ if(input == "END") return 0; for(int i=0;i<12;i++) valid[i] = true; len = input.length(); for(int i=0;i<len;i++){ if(input.at(i)!=' ') newstr = newstr + input.at(i); else if(input.at(i)==' '){ value = scale[newstr]; newstr.clear(); for(int j=0;j<12;j++) if(notes[j][value]==0) valid[j] = false; } if(i==len-1 && newstr.size()>0){ value = scale[newstr]; newstr.clear(); for(int j=0;j<12;j++) if(notes[j][value]==0) valid[j] = false; } } first = true; for(int i=0;i<12;i++) if(valid[i]){ cout<<scaleinv[i]<<" "; } cout<<endl; } return 0; } <file_sep>#include<stdio.h> using namespace std; int main(void){ int salute[] = {1,2,5,14,42,132,429,1430,4862,16796}; int in; bool first = true; while(scanf("%d",&in)==1){ if(!first) printf("\n"); first = false; printf("%d\n",salute[in-1]); } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class BrickWallPatterns{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger[] fib = new BigInteger[51]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE.add(BigInteger.ONE); for(int i=2;i<=50;i++){ fib[i] = fib[i-1].add(fib[i-2]); } int input; while(true){ input = sc.nextInt(); if(input == 0) break; System.out.println(fib[input - 1]); } } }<file_sep>#include<iostream> using namespace std; void parity(int); int par(int); int main(){ int i; while(cin>>i){ if(i==0) break; cout<<"The parity of "; parity(i); cout<<" is "<<par(i)<<" (mod 2)."<<endl; } return 0; } void parity(int num){ if(num>0){ parity(num/2); cout<<num%2; } } int par(int num){ int counter = 0; while(num>0){ if(num%2==1) counter++; num/=2; } return counter; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define LSOne(k) (k & (~k)) ll tree[501][501]; int max_x, max_y; void update(int x, int y, ll value){ int y1 = y; //printf("%d\n",LSOne(x)); //scanf("%d",&x); while(x<=max_x){ y = y1; while(y<=max_y){ tree[x][y]+=value; y+=LSOne(y); //printf("x: %d y: %d\n",x,y); }x+=LSOne(x); } } ll query(int x, int y){ ll sum = 0;int y1 = y; while(x>0){ y = y1; while(y>0){ sum+=tree[x][y]; y-=LSOne(y); }x-=LSOne(x); }return sum; } ll query(int x1, int x2, int y1, int y2){ return query(x2,y2) - ((x1==0)?0:query(x1-1,y2)) - ((y1==0)?0:query(x2,y1-1)) + ((x1==0||y1==0)?0:query(x1-1,y1-1)); } int main(void){ //freopen("in.txt","r",stdin); scanf("%d %d",&max_x,&max_y); //printf("%d %d\n",max_x,max_y); reset(tree,0); ll num; int x1,y1,x2,y2; ll val; REPN(i,1,max_x){ REPN(j,1,max_y){ scanf("%lld",&num); update(i,j,num); } } int query; char input; FOR(i,query){ scanf("%c",&input); printf("%c",input); if(input == 'q'){ scanf("%d %d %d %d",&x1,&y1,&x2,&y2); }else{ scanf("%d %d %lld",&x1,&y1,&val); } } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; typedef pair<int,ii> pii; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) int dx[] = {-1,0,1,0}; int dy[] = {0,-1,0,1}; int main(void){ //freopen("in.txt","r",stdin); int tc; int arr[1000][1000]; scanf("%d",&tc); TC(){ int row, col; scanf("%d %d",&row,&col); for(int i=0;i<row;i++) for(int j=0;j<col;j++) scanf("%d",&arr[i][j]); int V = row*col; vi dist(V, INF); dist[0] = arr[0][0]; // INF = 1B to avoid overflow , ii(weight,node). priority_queue< pii, vector< pii>, greater<pii> > pq; pq.push(pii(dist[0],ii(0, 0))); // ^to sort the pairs by increasing distance from s while (!pq.empty()) { // main loop pii front = pq.top(); pq.pop(); // greedy: pick shortest unvisited vertex int d = front.first, u = front.second.first*col + front.second.second; if (d > dist[u]) continue; // this check is important, see the explanation int x = front.second.first, y = front.second.second; for (int j = 0; j < 4; j++) { int x2 = x+dx[j], y2 = y+dy[j]; // all outgoing edges from u if(x2>=0 && x2 < row && y2 >= 0 && y2 < col){ int comb = x2*col + y2; if (dist[u] + arr[x2][y2] < dist[comb]) { dist[x2*col + y2] = dist[u] + arr[x2][y2]; // relax operation pq.push(pii(dist[comb], ii(x2,y2))); } } } } // note: this variant can cause duplicate items in the priority queue printf("%d\n",dist[(row-1)*col + col-1]); } return 0; } <file_sep>#include<iostream> #include<map> #include<string.h> using namespace std; bool prime[2100]; void sieve(){ memset(prime,true,sizeof prime); prime[0]=prime[1]=false; for(int i=2;i<=2100;i++) if(prime[i]) for(int j=i+i;j<=2100;j+=i) prime[j]=false; } int main(void){ sieve(); int test; cin>>test; string input; getline(cin,input); map<char,int> parse; bool printed; for(int i=1;i<=test;i++){ getline(cin,input); parse.clear(); printed = false; for(int j=0;j<input.length();j++){ parse[input.at(j)]++; } cout<<"Case "<<i<<": "; for(map<char,int>::iterator it=parse.begin();it!=parse.end();it++){ if(prime[it->second]){ printed = true; cout<<it->first; } } if(!printed) cout<<"empty"<<endl; else cout<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<bitset> #include<vector> using namespace std; vector<int> primes; bitset<4000> bs; void sieve(){ bs.set(); bs[0] = bs[1] = 0; for(int i=2;i<4000;i++) if(bs[i]){ for(int j=i*i;j<4000;j*=i) bs[j] = 0; primes.push_back(i); } } int main(void){ sieve(); int num, TC; cin>>TC; for(int z=1;z<=TC;z++){ cin>>num; int last = 0; int counter = 0; cout<<"Case #"<<z<<": "<<num<<" = "; for(int i=0;i<(int)primes.size();i++) if(num%primes[i]==0){ last = primes[i]; counter++; cout<<primes[i]<<" * "<<num/primes[i]; if(counter==2) break; cout<<" = "; } if(counter == 1){ for(int i=last+1;i<num;i++) if(num%i==0){ cout<<i<<" * "<<num/i; break; } } cout<<endl; } return 0; } <file_sep> #include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) int p[110][110]; string name,fr,to; map<string,int> mapper; map<int,string> rev; void printPath(int i, int j){ if(i!=j)printPath(i,p[i][j]); if(j == mapper[fr])cout<<rev[j]; else cout<<" "<<rev[j]; } int main(void){ //freopen("in.txt","r",stdin); int tc; scanf("%d",&tc); int dist[110][110]; TC(){ int V; mapper.clear(); rev.clear(); string str; scanf("%d",&V); for(int i=0;i<V;i++){ cin>>str; mapper[str] = i; rev[i] = str; } for(int i=0;i<V;i++) for(int j=0;j<V;j++){ scanf("%d",&dist[i][j]); dist[i][j] = (dist[i][j]==-1?INF:dist[i][j]); p[i][j] = i; } for (int k = 0; k < V; k++) for (int i = 0; i < V; i++) for (int j = 0; j < V; j++) if(dist[i][j]>dist[i][k]+dist[k][j]){ dist[i][j] = dist[i][k]+dist[k][j]; p[i][j] = p[k][j]; } int Q; scanf("%d",&Q); for(int i=0;i<Q;i++){ cin>>name>>fr>>to; if(dist[mapper[fr]][mapper[to]] == INF){ cout<<"Sorry Mr "<<name<<" you can not go from "<<fr<<" to "<<to<<endl; } else{ cout<<"Mr "<<name<<" to go from "<<fr<<" to "<<to<<", you will receive "<<dist[mapper[fr]][mapper[to]]<<" euros"<<endl; if(fr==to) cout<<"Path:"<<fr<<" "<<fr<<endl; else{ printf("Path:"); printPath(mapper[fr],mapper[to]); printf("\n"); } } } } return 0; } <file_sep>#include<stdio.h> #include<iostream> using namespace std; int main(void){ int x,y; while(cin>>x>>y){ cout<<"["; bool first = true; while(true){ if(first){ cout<<x/y; cout<<";"; first = false; } else{ cout<<x/y; cout<<","; } int z = x%y; if(z==1){ cout<<y<<"]"<<endl; break; } else{ x = y; y = z; } } } return 0; } <file_sep>#include<stdio.h> #include<string> #include<iostream> using namespace std; int main(void){ int input,counter; string in; counter = 1; while(scanf("%d",&input) && input){ printf("Case %d:\n",counter++); printf("#include<string.h>\n#include<stdio.h>\nint main()\n{\n"); for(int i=0;i<input;i++){ getline(cin,in); if(in.empty()) i--; else{ printf("printf(\""); for(int j=0;j<in.length();j++){ if(in.at(j)=='\\' || in.at(j)=='\"') printf("\\"); printf("%c",in.at(j)); } printf("\\n\");\n"); } } printf("printf(\"\\n\");\nreturn 0;\n}\n"); } return 0; } <file_sep>#include<algorithm> #include<iostream> using namespace std; int main(void){ int goods[20000]; int test, numgood,disc; cin>>test; for(int i=0;i<test;i++){ cin>>numgood; disc = 0; for(int j=0;j<numgood;j++) cin>>goods[j]; sort(goods,goods+numgood); for(int j=numgood-3;j>=0;j-=3) disc+=goods[j]; cout<<disc<<endl; } return 0; } <file_sep>#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; bool isPrime[1000001]; int main(void){ int input, counter,mustfind,remember,count1; bool found; for(int i=2;i<=1000000;i++) isPrime[i] = true; for(int i=2;i<=999990;i++){ if(isPrime[i]){ for(int j=i+i;j<=1000000;j+=i) isPrime[j]=false; } } while(cin>>input && input){ found = false; count1 = 0; for(int i=2;i<input;i++){ if(isPrime[i] && isPrime[input - i]){ found = true; count1 = i; break; } } if(found) printf("%d:\n%d+%d\n",input,count1,input - count1); else printf("%d:\nNO WAY!\n",input); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int main(void){ //freopen("in.txt","r",stdin); int n,m; vi out; vector<vi> AdjList; while(scanf("%d %d",&n,&m),(n||m)){ out.assign(n+1,0); int a,b; AdjList.assign(n+1,vi()); FOR(i,m){ scanf("%d %d",&a,&b); AdjList[a].pb(b); out[b]++; } queue<int> q; REPN(i,1,n){ if(out[i] == 0){ q.push(i); } } vi toposort; bool valid = true; while(!q.empty()){ int v = q.front();q.pop(); toposort.pb(v); FOR(i,AdjList[v].size()){ int x = AdjList[v][i]; out[x]--; if(!out[x]){ q.push(x); } } } if(valid){ FOR(i,toposort.size()){ printf("%d\n",toposort[i]); }} else printf("IMPOSSIBLE\n"); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ int test,counter; int value[26]={1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,4,1,2,3,1,2,3,4}; string sms; cin>>test; getline(cin,sms); for(int i=1;i<=test;i++){ counter = 0; cout<<"Case #"<<i<<": "; getline(cin,sms); for(int j=0;j<sms.length();j++){ if(sms.at(j)==' ') counter++; else{ counter+=value[(int)sms.at(j) - 97]; } } cout<<counter<<endl; } return 0; } <file_sep>#include<map> #include<stdio.h> #include<iostream> #include<algorithm> #include<math.h> #include<vector> using namespace std; int main(void){ long long test,tobetested; long long arr[1001]; vector<long long> dist; int casecounter = 1; vector<long long>::iterator it; while(cin>>test&&test){ dist.clear(); for(int i=0;i<test;i++){ cin>>arr[i]; for(int j=0;j<i;j++) dist.push_back(arr[i]+arr[j]); } printf("Case %d:\n",casecounter++); cin>>test; for(int i=0;i<test;i++){ cin>>tobetested; printf("Closest sum to %lld is ",tobetested); if(!dist[tobetested]){ long long temp,temp2; it = lower_bound(dist.begin(),dist.end(),tobetested); temp = abs(*it - tobetested); temp2 = *it; it--; if(temp>abs(*it - tobetested)){ cout<<*it<<".\n"; } else cout<<temp2<<".\n"; } else{ cout<<tobetested<<".\n"; } } } return 0; } <file_sep>#include<stdio.h> #include<iostream> #include<queue> using namespace std; int main(void){ int L, U, R,casenum=0; int verify[10000]; bool arr[10000]; bool found; int adder[10]; while(cin>>L>>U>>R && (L||U||R)){ found = false; for(int i=0;i<R;i++) cin>>adder[i]; for(int i=0;i<10000;i++){ verify[i] = 0; arr[i] = false; } queue<int> q; q.push(L); verify[L] = 0; while(!q.empty()){ int x = q.front(); q.pop(); if(x==U){ found = true; printf("Case %d: %d\n",++casenum,verify[U]); break; } for(int i=0;i<R;i++){ int y = (x+adder[i])%10000; if(!arr[y]){ arr[y] = true; verify[y]=verify[x]+1; q.push(y); } } } if(!found) printf("Case %d: Permanently Locked\n",++casenum); } } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define EPS 1e-9 #define PI acos(-1.0) double DEG_to_RAD(double d) { return d * PI / 180.0; } double RAD_to_DEG(double r) { return r * 180.0 / PI; } struct point { double x, y; // only used if more precision is needed point() { x = y = 0.0; } // default constructor point(double _x, double _y) : x(_x), y(_y) {} // user-defined bool operator == (point other) const { return (fabs(x - other.x) < EPS && (fabs(y - other.y) < EPS)); } }; struct vec { double x, y; // name: `vec' is different from STL vector vec(double _x, double _y) : x(_x), y(_y) {} }; vec toVec(point a, point b) { // convert 2 points to vector a->b return vec(b.x - a.x, b.y - a.y); } double cross(vec a, vec b) { return a.x * b.y - a.y * b.x; } double cross(point p, point q, point r) { return (r.x - q.x) * (p.y - q.y) - (r.y - q.y) * (p.x - q.x); } // note: to accept collinear points, we have to change the `> 0' // returns true if point r is on the left side of line pq bool ccw(point p, point q, point r) { return cross(toVec(p, q), toVec(p, r)) > 0; } double dot(vec a, vec b) { return (a.x * b.x + a.y * b.y); } double norm_sq(vec v) { return v.x * v.x + v.y * v.y; } double angle(point a, point o, point b) { // returns angle aob in rad vec oa = toVec(o, a), ob = toVec(o, b); return acos(dot(oa, ob) / sqrt(norm_sq(oa) * norm_sq(ob))); } bool inPolygon(point pt, const vector<point> &P) { if ((int)P.size() == 0) return false; double sum = 0; // assume the first vertex is equal to the last vertex for (int i = 0; i < (int)P.size()-1; i++) { if (ccw(pt, P[i], P[i+1])) sum += angle(P[i], pt, P[i+1]); // left turn/ccw else sum -= angle(P[i], pt, P[i+1]); } // right turn/cw return fabs(fabs(sum) - 2*PI) < EPS; } bool PointInPolygon(const vector<point> &p, point q) { bool c = 0; for (int i = 0; i < p.size()-1; i++){ int j = (i+1); if ((p[i].y <= q.y && q.y < p[j].y || p[j].y <= q.y && q.y < p[i].y) && q.x < p[i].x + (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y)) c = !c; } return c; } bool AM_cmp(point a, point b){ if(!(fabs(a.x - b.x)<EPS)) return a.x < b.x; return a.y < b.y; } vector<point> AMH(vector<point> P){ vector<point> res; res.assign(2*(int)P.size(),point(0,0)); int counter = 0; for(int i=0;i<(int)P.size();i++){ while (counter >= 2 && cross(res[counter-2], res[counter-1], P[i]) <= 0) counter--; res[counter++] = P[i]; } for(int i=(int)P.size()-2,t=counter+1;i>=0;i--){ while (counter >= t && cross(res[counter-2], res[counter-1], P[i]) <= 0) counter--; res[counter++] = P[i]; } res.resize(counter,point(0,0)); return res; } int main(void){ //freopen("in.txt","r",stdin); vector<point> P; int n; double x,y; while(scanf("%d",&n),n){ P.clear(); FOR(i,n){ scanf("%lf %lf",&x,&y); P.push_back(point(x,y)); } P.push_back(P[0]); //sort(P.begin(),P.end(),AM_cmp); //P = AMH(P); //FOR(i,P.size()){ // printf("%lf %lf\n",P[i].x,P[i].y); //} scanf("%lf %lf",&x,&y); if(PointInPolygon(P,point(x,y))){ printf("T\n"); }else printf("F\n"); } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; bool vowel(char a){ return (a=='a' || a=='e' || a=='i' || a=='o' || a=='u'); } int main(void){ int test; bool mut; string name1,name2; cin>>test; for(int i=0;i<test;i++){ cin>>name1>>name2; mut = true; if(name1.length()!=name2.length()) mut = false; else{ for(int j=0;j<name1.length();j++){ if(!vowel(name1.at(j))){ if(name1.at(j)!=name2.at(j) || vowel(name2.at(j))){ mut = false; break; } } if(vowel(name1.at(j)) && !vowel(name2.at(j))) mut = false; } } if(mut) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> using namespace std; int main(void){ char token[2500]; char * pch; int input, numneighbor; cin>>input; for(int i=0;i<input;i++){ cin>>numneighbor; for(int j=0;j<numneighbor;j++){ getline(cin,token); pch = strtok(token," "); } } } <file_sep>#include<string> #include<iostream> using namespace std; int main(void){ string base; while(cin>>base){ if(base.length()>1 || base.length() == 0) cout<<"such number is impossible!"<<endl; else if((int)base.at(0)<58 && (int) base.at(0)>47) cout<<(int) base.at(0) - 47<<endl; else if((int)base.at(0)<91 && (int)base.at(0)>64) cout<<(int) base.at(0) - 54<<endl; else if((int) base.at(0)<123 && (int)base.at(0)>96) cout<<(int)base.at(0) - 60<<endl; else cout<<"such number is impossible!"<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int sum, dif, n, x, y, temp; cin>>n; for(int i=0;i<n;i++){ cin>>sum>>dif; x = (sum+dif)/2; y = sum-x; if(x<0 || y<0 || (sum+dif)%2==1) cout<<"impossible"<<endl; else cout<<x<<" "<<y<<endl; } return 0; }<file_sep>#include<stdio.h> #include<string> #include<iostream> #include<map> using namespace std; int main(void){ int test; int brand; int min,max,count; int absmin,absmax,query,number; string name,remname; map<string,int> low; map<string,int> high; map<string,int>::iterator it,it1; it = low.begin(); it1 = high.begin(); scanf("%d",&test); for(int i=0;i<test;i++){ scanf("%d",&brand); absmin = 1000000; absmax = 0; for(int j=0;j<brand;j++){ cin>>name; scanf("%d %d",&min,&max); if(min<absmin) absmin = min; if(max>absmax) absmax = max; low[name] = min; high[name] = max; } scanf("%d",&query); for(int j=0;j<query;j++){ scanf("%d",&number); if(number<absmin || number>absmax){ printf("UNDETERMINED\n"); } else{ count = 0; it1 = high.begin(); for(it=low.begin();it!=low.end();it++,it1++){ if(it->second<=number && it1->second>=number){ count++; remname = it->first; } if(count>1) break; } if(count>1) printf("UNDETERMINED\n"); else cout<<remname<<endl; } } low.clear(); high.clear(); printf("\n"); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string input; int row, col, important, notimportant, test; int max; int counter; cin>>test; for(int i=1;i<=test;i++){ max = counter = 0; cin>>row>>col>>important>>notimportant; int value[26] = {0}; for(int j=0;j<row;j++){ cin>>input; for(int k=0;k<col;k++){ value[(int)input.at(k) - 'A']++; if(value[(int)input.at(k) - 'A']>max) max = value[(int)input.at(k) - 'A']; } } for(int j=0;j<26;j++){ if(value[j]==max) counter+=important*value[j]; else if(value[j]>=1) counter+=notimportant*value[j]; } cout<<"Case "<<i<<": "<<counter<<endl; } return 0; } <file_sep>import java.util.*; import java.math.BigDecimal; class Exponentiation{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigDecimal x; int n,zero; String check; while(sc.hasNext()){ x = sc.nextBigDecimal(); n = sc.nextInt(); x = x.pow(n); check = x.toPlainString(); int i = 0; while(check.charAt(check.length()-i-1)=='0') i++; if(x.compareTo(BigDecimal.ONE)==-1){ for(int j=1;j<check.length()-i;j++) System.out.print(check.charAt(j)); } else{ for(int j=0;j<check.length()-i;j++) System.out.print(check.charAt(j)); } System.out.println(); } } }<file_sep>#include<iostream> using namespace std; int main(void){ double height, up, down, fatigue, decrease, distance; int day; while(cin>>height>>up>>down>>fatigue && height){ decrease = fatigue/100*up; distance = 0; day = 1; while(day==1 || distance>0 && distance<=height){ distance+=up; up-=decrease; if(up<=0) up = 0; if(distance>height) break; distance-=down; if(distance<0) break; day++; } if(distance>=height) cout<<"success on day "<<day<<endl; else cout<<"failure on day "<<day<<endl; } } <file_sep>#include<iostream> #include<stdio.h> #include<map> #include<stdlib.h> #include<math.h> using namespace std; int main(void){ map<int,int> mapper; mapper.clear(); int TC,low,high,mindiv,minnum; scanf("%d",&TC); while(TC--){ minnum = -1; scanf("%d %d",&low,&high); mindiv = 0; for(int i=low;i<=high;i++){ int x = (int)floor(sqrt(i)); int sum = 2; for(int j=2;j<=x;j++){ if(!(i%j)){ sum+=2; if(j==x && x*x == i) sum--; } } if(i==1) sum--; if(mindiv<sum){ mindiv = sum; minnum = i; } } printf("Between %d and %d, %d has a maximum of %d divisors.\n",low,high,minnum,mindiv); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int price[10], n; int combo; int deal[12][12]; int memo[1000000]; int demand(int demand[]){ int num = 0; FOR(i,n){ num = num*10 + demand[i]; } if(memo[num]!=-1)return memo[num]; int ans = INF; FOR(i,combo){ } FOR(i,n){ } return memo[num] = ans; } int main(void){ // #ifndef DEBUG freopen("in.txt","r",stdin); // #endif int demand[10]; while(scanf("%d",&n)!=EOF){ FOR(i,n){ scanf("%d",&price[i]); } //demand.assign(n,0); scanf("%d",&combo); FOR(i,combo){ FOR(j,n){ scanf("%d",&deal[i][j]); } scanf("%d",&deal[i][n]); } int tc; memset(memo,-1,sizeof memo); scanf("%d",&tc); TC(){ FOR(i,n){ scanf("%d",&demand[i]); } printf("%d\n",dp(demand)); } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ long long int n; while(cin>>n){ if(n<0){ if((-n)%2==0) cout<<"Underflow!"<<endl; else cout<<"Overflow!"<<endl; } else{ if(n<8) cout<<"Underflow!"<<endl; else if(n>13) cout<<"Overflow!"<<endl; else{ switch(n){ case 8: cout<<"40320"<<endl; break; case 9: cout<<"362880"<<endl; break; case 10: cout<<"3628800"<<endl; break; case 11: cout<<"39916800"<<endl; break; case 12: cout<<"479001600"<<endl; break; case 13: cout<<"6227020800"<<endl; break; } } } } return 0; } <file_sep>#include<map> #include<iostream> #include<stdio.h> #include<string.h> using namespace std; int main(void){ string m, n; int m1,n1; while(true){ cin>>m; cin>>n; if(m=="0" && n=="0") return 0; if(n=="0") cout<<"1"; else{ m1 = m.at(m.length()-1)-'0'; n1 = n.at(n.length()-1)-'0'; if(n.length()>1) n1+=(n.at(n.length()-2)-'0')*10; if(m1==1 || m1 == 5 || m1 == 6 || m1 == 0) cout<<m1; else if(m1==2){ switch(n1%4){ case 0: cout<<"6";break; case 1: cout<<"2";break; case 2: cout<<"4";break; case 3: cout<<"8";break; } } else if(m1==3){ switch(n1%4){ case 0: cout<<"1";break; case 1: cout<<"3";break; case 2: cout<<"9";break; case 3: cout<<"7";break; } } else if(m1==4){ switch(n1%2){ case 0: cout<<"6";break; case 1: cout<<"4";break; } } else if(m1==7){ switch(n1%4){ case 0: cout<<"1";break; case 1: cout<<"7";break; case 2: cout<<"9";break; case 3: cout<<"3";break; } } else if(m1==8){ switch(n1%4){ case 0: cout<<"6";break; case 1: cout<<"8";break; case 2: cout<<"4";break; case 3: cout<<"2";break; } } else if(m1==9){ switch(n1%2){ case 0: cout<<"1";break; case 1: cout<<"9";break; } } } cout<<endl; } return 0; } <file_sep>#include<string> #include<iostream> #include<stdio.h> using namespace std; int main(void){ string input; char now; int counter, start,end,query,temp; short zero[1000000]; bool dif; counter = 1; while(getline(cin,input)){ if(input.length()==0) break; printf("Case %d:\n",counter); scanf("%d",&query); zero[0] = 0; now = input.at(0); for(int i=1;i<input.length();i++){ if(input.at(i)==now) zero[i] = zero[i-1]; else{ now = input.at(i); zero[i] = zero[i-1]+1; } } for(int i=0;i<query;i++){ scanf("%d %d",&start,&end); if(zero[start]==zero[end]) printf("Yes\n"); else printf("No\n"); } counter++; getline(cin,input); } return 0; } <file_sep>#include<iostream> //UVa11059 #include<algorithm> #include<stdio.h> #include<string.h> using namespace std; int main(void){ int test, dummy, counter, z; int input[20]; bool first; long long pos[20]; double product; z=0; while(cin>>test){ z++; product = 0; counter = 0; memset(pos,0,sizeof pos); for(int i=0;i<test;i++){ cin>>input[i]; pos[i]=input[i]; if(pos[i]>product) product = pos[i]; for(int j=0;j<i;j++){ pos[j]*=input[i]; if(pos[j]>product) product=pos[j]; } } printf("Case #%d: The maximum product is %.0lf.\n\n",z,product); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ int counter; string input; counter = 1; while(true){ cin>>input; if(input == "#") return 0; cout<<"Case "<<counter<<": "; if(input == "HELLO") cout<<"ENGLISH"<<endl; else if(input == "HOLA") cout<<"SPANISH"<<endl; else if(input == "HALLO") cout<<"GERMAN"<<endl; else if(input == "BONJOUR") cout<<"FRENCH"<<endl; else if(input == "CIAO") cout<<"ITALIAN"<<endl; else if(input == "ZDRAVSTVUJTE") cout<<"RUSSIAN"<<endl; else cout<<"UNKNOWN"<<endl; counter++; } return 0; } <file_sep>#include<string> #include<iostream> using namespace std; int main(void){ string input; int repeating; while(cin>>input){ repeating = 0; for(int i=0;i<input.length();i++){ switch(input.at(i)){ case 'B': case'F': case'P': case'V':{ if(repeating!=1) cout<<"1"; repeating = 1; break; } case 'C': case 'G': case 'J': case 'K': case 'Q': case 'S': case 'X': case 'Z':{ if(repeating!=2) cout<<"2"; repeating = 2; break; } case 'D': case 'T':{ if(repeating!=3) cout<<"3"; repeating = 3; break; } case 'L':{ if(repeating!=4) cout<<"4"; repeating = 4; break; } case 'M': case 'N':{ if(repeating!=5) cout<<"5"; repeating = 5; break; } case 'R':{ if(repeating!=6) cout<<"6"; repeating = 6; break; } default:{ repeating = 0; break; } } } cout<<endl; } return 0; } <file_sep>#include <stdio.h> #include <string.h> #define MINE 'x' // a mine-filled cell #define FREE '.' // a mine-free cell #define MAX_ROWS 1000 // maximum rows of a minefield #define MAX_COLS 1000 // maximum columns of a minefield #include<iostream> using namespace std; void scan_minefield(char [][MAX_COLS+1], int *, int *); void count_minefield(char [][MAX_COLS+1], int, int); int main(void) { char minefield[MAX_ROWS][MAX_COLS+1]; int row_size, col_size; // actual size of minefield read int counter,i,j; int test; cin>>test; for(int z=1;z<=test;z++){ scan_minefield(minefield,&row_size,&col_size); counter=0; for(i=0;i<row_size;i++) for(j=0;j<row_size;j++) { if(minefield[i][j] == MINE) { count_minefield(minefield, i, j); counter++; } } printf("Case %d: %d\n",z,counter); } return 0; } // To read in the minefield void scan_minefield(char mines[][MAX_COLS+1], int *row_size_p, int *col_size_p) { int r; scanf("%d",row_size_p); getchar(); // to catch the newline for (r=0; r<*row_size_p; r++) gets(mines[r]); } //To read where the minecluster is. void count_minefield(char minefield[][MAX_COLS+1], int row, int col) { int i,j; minefield[row][col]=FREE; if(minefield[row-1][col]==MINE || minefield[row-1][col]=='@') count_minefield(minefield,row-1,col); if(minefield[row+1][col]==MINE || minefield[row+1][col]=='@') count_minefield(minefield,row+1,col); if(minefield[row][col-1]==MINE || minefield[row][col-1]=='@') count_minefield(minefield,row,col-1); if(minefield[row][col+1]==MINE || minefield[row][col+1]=='@') count_minefield(minefield,row,col+1); } <file_sep> #include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int main(void){ //freopen("in.txt","r",stdin); int tc; ll box[102][102]; int n,m; while(scanf("%d %d",&n,&m),(n||m)){ reset(box,0); int counter = 0; FOR(i,n){ FOR(j,m){ scanf("%lld",&box[i][j]); if(box[i][j] == 1) box[i][j] = -INF; else box[i][j] = 1; if(i>0) box[i][j] += box[i-1][j]; if(j>0) box[i][j] += box[i][j-1]; if(i>0 && j>0) box[i][j] -= box[i-1][j-1]; } } /*FOR(i,counter){ FOR(j,len) printf("%lld ",box[i][j]); printf("\n"); }*/ ll optimum = 0, subRect; FOR(i,n){ FOR(j,m){ REP(k,i,n){ REP(l,j,m){ subRect = box[k][l]; if(i>0) subRect -= box[i-1][l]; if(j>0) subRect -= box[k][j-1]; if(i>0 && j>0) subRect += box[i-1][j-1]; optimum = max(optimum, subRect); } } } } printf("%lld\n",optimum); } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int n,r,d, total, count; int morn[100]; int noon[100]; while(cin>>n>>d>>r && n && r && d){ for(int i=0;i<n;i++){ cin>>morn[i]; } for(int i=0;i<n;i++){ cin>>noon[i]; } sort(morn,morn+n); sort(noon,noon+n); total = 0; for(int i=0;i<n;i++){ count = morn[i] + noon[n-i-1]; if(count>d){ total += (count - d)*r; } } cout<<total<<endl; } return 0; } <file_sep>#include<math.h> #include<iostream> #include<stdio.h> using namespace std; int gcd(int,int); int main(void){ int array[50]; int test, counter; double pi; while(true){ cin>>test; if(test == 0) break; for(int i=0;i<test;i++) cin>>array[i]; counter = 0; for(int i=0;i<test-1;i++) for(int j=i+1;j<test;j++) if(gcd(array[i],array[j])==1) counter++; if(counter == 0) cout<<"No estimate for this data set."<<endl; else{ pi = 6*test*(test-1)*0.5/counter; pi = sqrt(pi); printf("%.6lf\n",pi); } } return 0; } int gcd(int a, int b){ if(b == 0) return a; else return gcd(b, a%b); } <file_sep>#include<iostream> using namespace std; int main(void){ int test; unsigned long int permutation; int freq[26]; string input; cin>>test; for(int i=1;i<=test;i++){ cin>>input; for(int j=0;j<26;j++) freq[j]=0; for(int j=0;j<input.length();j++) freq[(int) input.at(j) - 65]++; permutation = 1; if(input.length()<=12) for(int j=2;j<=input.length();j++) permutation*=j; else for(int j=2;j<=12;j++) permutation*=j; cout<<permutation<<"<<Permutation"; for(int j=0;j<26;j++){ while(freq[j]>1){ permutation/=freq[j]; freq[j]--; } } for(int j=13;j<=input.length();j--){ permutation*=j; } cout<<"Data set "<<i<<": "; cout<<permutation<<endl; } } <file_sep>#include<cstdio> #include<vector> #include<cstdlib> #include<cstring> using namespace std; typedef vector<int> vi; int AdjList[50000]; int arr[50000]; vi topoSort; void dfs(int u) { //printf(" %d", u); arr[u] = 1; int v = AdjList[u]; if (arr[v] == 0) dfs(v); topoSort.push_back(u); } int main(void){ int tc; scanf("%d",&tc); int casecounter = 1; //int arr[50000]; while(tc--){ topoSort.clear(); int total = 0; int n; scanf("%d",&n); int fr,to; //AdjList.assign(n,vi()); for(int i=0;i<n;i++){ scanf("%d %d",&fr,&to); AdjList[fr-1] = to-1; } int maxi; memset(arr,0,sizeof arr); for(int i=0;i<n;i++){ int temptot = 1; int now = i; //arr[i] = 1; //printf("NOW: %d\n",now); //printf("%d\n",i); if(arr[i]==0) dfs(i); } //for(int i=0;i<topoSort.size();i++) // printf("%d ",topoSort[i]); printf("Case %d: %d\n",casecounter++,topoSort[topoSort.size()-1]+1); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; struct people{ string name; int gold; }; int main(void){ bool first = true; int num, give,howmany,remember; string search; people peeps[10]; while(cin>>num){ if(!first) cout<<endl; first = false; for(int i=0;i<num;i++){ cin>>peeps[i].name; peeps[i].gold = 0; } for(int i=0;i<num;i++){ cin>>search>>give>>howmany; for(int j=0;j<num;j++){ if(search == peeps[j].name){ if(howmany){ peeps[j].gold -= give; peeps[j].gold+=give%howmany; } } } for(int j=0;j<howmany;j++){ cin>>search; for(int k=0;k<num;k++) if(search == peeps[k].name) peeps[k].gold+=give/howmany; } } for(int i=0;i<num;i++) cout<<peeps[i].name<<" "<<peeps[i].gold<<endl; } return 0; } <file_sep>//Template for Dev-C++ 5.3.0.4 by unlimitedsky #include<iostream> #include<cstdio> #include<string> #include<string> #include<cstdlib> #include<algorithm> #include<cmath> #include<climits> #include<vector> #include<stack> #include<queue> #include<map> #include<utility> using namespace std; #define FOR(i,a,b,c) for (int i = a; i <= b; i+=c) #define FORR(i,a,b,c) for (int i = a; i >= b; i-=c) #define INC(i,a,b) for (int i = a; i <= b; i++) #define DEC(i,a,b) for (int i = a; i >= b; i--) #define MP make_pair #define pb push_back #define fi first #define se second #define reset(a,b) memset(a,b,sizeof a) typedef long long int LL; typedef pair<int,int> PII; typedef vector<PII> vii; int tc, n, q, a; map<string,PII>car; char dummy; string str, ans; int main(){ scanf("%d", &tc); while(tc--){ car.clear(); scanf("%d", &n); while(n--){ cin >> str; int x,y; scanf("%d %d", &x, &y); car[str] = PII(x,y); } scanf("%d", &q); while(q--){ ans = "----"; scanf("%d", &a); for (map<string,PII>::iterator it = car.begin(); it!=car.end(); ++it){ PII ii = it->second; if (a >= ii.fi && a <= ii.se){ if (ans == "----") ans = it->fi; else{ ans = "----"; break; } } } if (ans != "----") cout << ans << endl; else printf("UNDETERMINED\n"); } if (tc) printf("\n"); } return 0; } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> using namespace std; int main(void){ int player, games, pl1, pl2; string move1, move2; int win[200]; int lose[200]; bool first = true; while(cin>>player && player){ cin>>games; if(!first) cout<<endl; else first = false; memset(win,0,sizeof win); memset(lose,0,sizeof lose); games = games*player*(player-1)/2.0; for(int i=0;i<games;i++){ cin>>pl1>>move1>>pl2>>move2; if(move1=="scissors" && move2=="rock"){ lose[pl1]++; win[pl2]++; } else if(move1=="rock" && move2=="scissors"){ lose[pl2]++; win[pl1]++; } else if(move1=="scissors" && move2=="paper"){ lose[pl2]++; win[pl1]++; } else if(move1=="paper" && move2=="scissors"){ lose[pl1]++; win[pl2]++; } else if(move1=="paper" && move2=="rock"){ lose[pl2]++; win[pl1]++; } else if(move1=="rock" && move2=="paper"){ lose[pl1]++; win[pl2]++; } } for(int i=1;i<=player;i++){ if(lose[i]==0 && win[i]==0) cout<<"-"<<endl; else{ printf("%.3lf\n",(double)win[i]/(win[i]+lose[i])); } } } return 0; } <file_sep>import java.util.*; class DoomDay{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int date, month; int day; Calendar cal = Calendar.getInstance(); int testcase = sc.nextInt(); for(int i=0;i<testcase;i++){ month = sc.nextInt() - 1; date = sc.nextInt(); cal.set(2011,month,date); day = cal.get(Calendar.DAY_OF_WEEK); if(day == 1) System.out.println("Sunday"); else if(day == 2) System.out.println("Monday"); else if(day == 3) System.out.println("Tuesday"); else if(day == 4) System.out.println("Wednesday"); else if(day == 5) System.out.println("Thursday"); else if(day == 6) System.out.println("Friday"); else if(day == 7) System.out.println("Saturday"); } } }<file_sep>#include<iostream> #include<stdio.h> #include<string> using namespace std; int main(){ string input; int i; bool haskutip = false; while(getline(cin, input)){ for(i = 0;i < input.size();i++){ if(input[i] == '"'){ if(haskutip){ haskutip = false; cout<<"``"; } else{ haskutip = true; cout<< } } else cout<<input[i]; } cout<<endl; } return 0; }<file_sep>#include<iostream> #include<stdio.h> #include<math.h> #include<cmath> using namespace std; int low, high, total,fairness, maxppl; int weight[102]; void compute(int now, int tot){ if(now==maxppl || tot>=total/2){ int x = total-tot; if(fairness>abs((double)(x-tot))){ fairness = (int)abs((double)(x-tot)); if(tot<x){ low = tot; high = x; } else{ low = x; high = tot; } } return; } else{ for(int i=now;i<maxppl;i++){ compute(i+1, tot+weight[i]); } } return; } int main(void){ int TC; scanf("%d",&TC); low = high = 0; while(TC--){ scanf("%d",&maxppl); total = 0; fairness = 100000000; for(int i=0;i<maxppl;i++){ scanf("%d",&weight[i]); total+=weight[i]; } compute(0,0); printf("%d %d\n",low, high); if(TC) printf("\n"); } } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) double memo2d[500][500]; double d[500][500]; int n; double dp(int p1, int p2){ //called with dp(0,0) int v = 1 + max(p1, p2); if(v == n-1){ return d[p1][v] + d[v][p2]; } if(memo2d[p1][p2] > -0.5){ return memo2d[p1][p2]; }return memo2d[p1][p2] = min( d[p1][v] + dp(v,p2),d[v][p2]+dp(p1,v)); } int main(void){ //freopen("in.txt","r",stdin); vi xi, yi; int x,y; while(scanf("%d",&n)!=EOF){ memset(memo2d,-1,sizeof memo2d); xi.clear();yi.clear(); FOR(i,n){ scanf("%d %d",&x,&y); xi.pb(x); yi.pb(y); } FOR(i,n){ d[i][i] = 0; REP(j,i+1,n){ d[i][j] = d[j][i] = hypot(abs(xi[i]-xi[j]),abs(yi[i]-yi[j])); } } printf("%.2lf\n",dp(0,0)); } return 0; } <file_sep>#include<algorithm> #include<stdio.h> #include<iostream> #include<vector> using namespace std; int main(void){ int N,Q,input,casecounter = 1; vector<int> marble; while(scanf("%d %d",&N,&Q) && N && Q){ marble.clear(); for(int i=1;i<=N;i++){ scanf("%d",&input); marble.push_back(input); } sort(marble.begin(),marble.end()); printf("CASE# %d:\n",casecounter++); for(int i=0;i<Q;i++){ scanf("%d",&input); if(binary_search(marble.begin(),marble.end(),input)){ printf("%d found at ",input); cout<<int(lower_bound(marble.begin(),marble.end(),input)-marble.begin())+1<<endl; } else printf("%d not found\n",input); } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) vi S, visited; vector<vi> AdjList; int dfsNumberCounter; int numSCC; //strongly connected Component vi dfs_low, dfs_num; void tarjanSCC(int u) { dfs_low[u] = dfs_num[u] = dfsNumberCounter++; S.push_back(u); visited[u] = 1; for (int j = 0; j < (int)AdjList[u].size(); j++) { int v = AdjList[u][j]; if (dfs_num[v] == -1) tarjanSCC(v); if (visited[v]) dfs_low[u] = min(dfs_low[u], dfs_low[v]); } if (dfs_low[u] == dfs_num[u]) { printf("SCC %d:", ++numSCC); while (1) { int v = S.back(); S.pop_back(); visited[v] = 0; printf(" %d", v); if (u == v) break; } printf("\n"); } } int main(void){ #ifdef ccsnoopy freopen("D:/Code/in.txt","r",stdin); #endif //to compile: g++ -o foo filename.cpp -lm -Dccsnoopy for debug. int m,n; int fr,to,way; while(scanf("%d %d",&m,&n) && (m||n)){ AdjList.assign(m,vi()); FOR(i,n){ sc(fr);sc(to);sc(way); fr--;to--; AdjList[fr].pb(to); if(way == 2)AdjList[to].pb(fr); } dfsNumberCounter = numSCC = 0; visited.assign(m,0);dfs_num.assign(m, -1); dfs_low.assign(m, 0); tarjanSCC(0); bool valid = true; FOR(i,m){ if(visited[i] == 0){valid = false;printf("%d\n",i);} } if(valid && numSCC == 1){ printf("1\n"); }else printf("0\n"); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<vector> #include<map> using namespace std; map<unsigned long long, long long> mapper; unsigned long long func(unsigned long long x){ if(mapper.find(x)!=mapper.end()) return mapper[x]; if(!(x%2)) return mapper[x] = func(x/2) + 1; return mapper[x] = func(3*x + 1) + 1; } int main(void){ mapper.clear(); long long min; long long x,y,minnum; mapper[1] = 1; while(cin>>x>>y){ minnum = -1; for(long long i=x;i<=y;i++){ if(mapper.find(i)==mapper.end()) func(i); if(minnum<mapper[i]){ minnum = mapper[i]; } } cout<<x<<" "<<y<<" "<<minnum<<endl; } return 0; } <file_sep>#include<string.h> #include<stdio.h> #include<iostream> using namespace std; bool painted[100][100]; char grid[100][100]; int dr[]={0,-1,0,1}; int dc[]={-1,0,1,0}; void floodfill(int row, int col, char c1){ if(row<0 || col<0) return; if(grid[row][col]=='X' || grid[row][col]=='\0') return; if(painted[row][col]) return; grid[row][col] = c1; painted[row][col]= true; for(int i=0;i<4;i++) floodfill(row+dr[i],col+dc[i],c1); } int main(void){ int counter; int testcase; cin>>testcase; getchar(); while(testcase--){ counter = 0; for(int i=0;i<100;i++) for(int j=0;j<100;j++) painted[i][j] = false; while(gets(grid[counter++])){ if(grid[counter-1][0]=='_') break; } for(int i=0;i<counter-1;i++) for(int j=0;grid[i][j]!='\0';j++) if(grid[i][j]=='*') floodfill(i,j,'#'); for(int i=0;i<counter;i++){ printf("%s\n",grid[i]); } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ for(int i=6;i<=200;i++) for(int j=2;j<i;j++) for(int k=j+1;k<i-1;k++) for(int l=k+1;l<i-2;l++) if(i*i*i == (j*j*j + k*k*k + l*l*l)) cout<<"Cube = "<<i<<", Triple = ("<<j<<","<<k<<","<<l<<")"<<endl; return 0; } <file_sep>#include<string.h> #include<map> #include<stdio.h> #include<iostream> using namespace std; int main(void){ char lines[2][1000]; int test; map<char,char> cipher; scanf("%d",&test); getchar(); getchar(); for(int i=0;i<test;i++){ cipher.clear(); gets(lines[0]); gets(lines[1]); for(int j=0;j<strlen(lines[0]);j++) cipher[lines[0][j]]=lines[1][j]; printf("%s\n%s\n",lines[1],lines[0]); while(true){ gets(lines[0]); if(strlen(lines[0])==0) break; for(int j=0;j<strlen(lines[0]);j++){ if(cipher.find(lines[0][j])==cipher.end()) printf("%c",lines[0][j]); else printf("%c",cipher[lines[0][j]]); } printf("\n"); } if(i!=test-1) printf("\n"); } return 0; } <file_sep>#include<stack> #include<queue> #include<iostream> using namespace std; int main(void){ stack<int> st; queue<int> q; priority_queue<int> pq; bool isStack, isQueue, isPQ; int command, pushpop, num, sum; while(cin>>command){ isStack = isQueue = isPQ = true; for(int i=0;i<command;i++){ cin>>pushpop>>num; if(pushpop == 1){ if(isStack) st.push(num); if(isQueue) q.push(num); if(isPQ) pq.push(num); } else if(pushpop == 2){ if(isStack){ if(!st.empty() && num == st.top()) st.pop(); else isStack = false; } if(isQueue){ if(!q.empty() && num == q.front()) q.pop(); else isQueue = false; } if(isPQ){ if(!pq.empty() && num == pq.top()) pq.pop(); else isPQ = false; } } } while(!st.empty()) st.pop(); while(!q.empty()) q.pop(); while(!pq.empty()) pq.pop(); sum = 0; if(isStack) sum++; if(isQueue) sum++; if(isPQ) sum++; if(sum==0) cout<<"impossible"; else if(sum>1) cout<<"not sure"; else if(sum == 1){ if(isStack) cout<<"stack"; else if(isQueue) cout<<"queue"; else if(isPQ) cout<<"priority queue"; } cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string command1, command2; int numblock; cin>>numblock; int while(true){ } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int xl1,yl1,xl2,yl2,xu1,xu2,yu1,yu2; int test; cin>>test; for(int i=0;i<test;i++){ cin>>xl1>>yl1>>xu1>>yu1; cin>>xl2>>yl2>>xu2>>yu2; if(xl1<xu2 && yl1<yu2 && xu2>xl1 && yu2>yl1){ if(xl1<xl2) cout<<xl2; else cout<<xl1; cout<<" "; if(yl1<yl2) cout<<yl2; else cout<<yl1; cout<<" "; if(xu1<xu2) cout<<xu1; else cout<<xu2; cout<<" "; if(yu1<yu2) cout<<yu1; else cout<<yu2; cout<<endl; } else cout<<"No overlap"<<endl; } return 0; } <file_sep>#include<stdio.h> #include<map> #include<queue> #include<iostream> #include<string> #include<vector> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; int main(void){ int test; scanf("%d",&test); printf("SHIPPING ROUTES OUTPUT\n\n"); for(int z=1;z<=test;z++){ printf("DATA SET %d\n\n",z); map<string,int> mapper; mapper.clear(); vector<vii> AdjList; AdjList.clear(); string in,fr,to; int numwarehouse, numroute, numquery,counter = 0; scanf("%d %d %d",&numwarehouse,&numroute, &numquery); AdjList.assign(numwarehouse,vii()); for(int i=0;i<numwarehouse;i++){ cin>>in; mapper[in] = counter++; } while(numroute--){ cin>>fr>>to; AdjList[mapper[fr]].push_back(ii(mapper[to],0)); AdjList[mapper[to]].push_back(ii(mapper[fr],0)); } while(numquery--){ int size; scanf("%d",&size); cin>>fr>>to; queue<int> q; map<int,int> dist; dist.clear(); dist[mapper[fr]] = 1; q.push(mapper[fr]); while(!q.empty()){ int u = q.front();q.pop(); for(int i=0;i<(int) AdjList[u].size();i++){ ii v = AdjList[u][i]; if(!dist.count(v.first)){ dist[v.first] = dist[u]+1; q.push(v.first); } } } dist[mapper[to]]--; if(dist[mapper[to]]==-1) printf("NO SHIPMENT POSSIBLE\n"); else printf("$%d\n",dist[mapper[to]]*size*100); } printf("\n"); } printf("END OF OUTPUT\n"); return 0; } <file_sep>#include<iostream> #include<stdlib.h> #include<algorithm> using namespace std; int main(void){ int test, array[20],stores; int median, total; cin>>test; for(int i=0;i<test;i++){ cin>>stores; for(int j=0;j<stores;j++) cin>>array[j]; total = 0; sort(array,array+stores); for(int j=0;j<stores-1;j++) total += array[j+1]-array[j]; total+=array[stores-1]-array[0]; cout<<(int)total<<endl; } return 0; } <file_sep>import java.util.*; class WalkingOnTheSafeSide{ public static int W,N; public static Boolean valid[][]; public static long memo[][]; public static void calculate(int x, int y){ if(x>W || y>N) return; if(valid[x][y]){ memo[x][y] = memo[x-1][y] + memo[x][y-1]; calculate(x+1,y); calculate(x,y+1); } return; } public static void main(String[] args){ StringTokenizer st; String str; Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while(tc-->0){ W = sc.nextInt();N = sc.nextInt(); valid = new Boolean[W+1][N+1]; memo = new long[W+1][N+1]; for(int i=1;i<=W;i++){ for(int j=1;j<=N;j++){ memo[i][j] = 0; valid[i][j] = true; } } memo[0][1] = 1; for(int i=1;i<=W;i++){ sc.nextInt(); str = sc.nextLine(); st = new StringTokenizer(str); while(st.hasMoreTokens()){ valid[i][Integer.valueOf(st.nextToken())] = false; } } calculate(1,1); System.out.println(memo[W][N]); if(tc!=0) System.out.println(); } } }<file_sep>#include<iostream> #include<string.h> #include<map> #include<stdio.h> using namespace std; int main(void){ char recipe[1000]; int printed; map<string,int> made; string input,remember,used,rem2; int p,ing,quan,min; map<string, int> menu; int total, test,price,cake,budget; cin>>test; for(int i=0;i<test;i++){ getchar(); made.clear(); gets(recipe); for(int j=0;j<strlen(recipe);j++) cout<<(char)toupper(recipe[j]); cout<<endl; cin>>price>>cake>>budget; menu.clear(); for(int j=0;j<price;j++){ cin>>input>>p; menu[input]=p; } printed = 0; for(int j=0;j<cake;j++){ getchar(); getline(cin,remember); cin>>ing; total = 0; for(int k=0;k<ing;k++){ cin>>used>>quan; total+=menu[used]*quan; } if(total<=budget){ printed++; made[remember]=total; } } if(!printed) cout<<"Too expensive!"<<endl; else for(int k=0;k<printed;k++){ min = budget+1; for(map<string,int>::iterator it=made.begin();it!=made.end();it++){ if(min>it->second){ min = it->second; rem2 = it->first; } } cout<<rem2<<endl; made[rem2]=1000000; } cout<<endl; } return 0; } <file_sep> #include<string.h> #include<stdio.h> #include<stdlib.h> #include<algorithm> #include<iostream> using namespace std; bool comp_ana(char a, char b){ if(a>='a' && a<='z' && b>='a' && b<='z') return a<b; if(a>='A' && a<='Z' && b>='A' && b<='Z') return a<b; if(a>='A' && a<='Z' && b>='a' && b<='z' && tolower(a)!=b) return tolower(a)<b; if(a>='A' && a<='Z' && b>='a' && b<='z' && tolower(a)==b) return true; if(a>='a' && a<='z' && b>='A' && b<='Z' && tolower(b)!=a) return a<tolower(b); if(a>='a' && a<='z' && b>='A' && b<='Z' && tolower(b)==a) return false; } int main(void){ int test, length; char input[10000]; scanf("%d\n",&test); for(int i=0;i<test;i++){ scanf("%s",input); length = strlen(input); sort(input,input+length,comp_ana); do{ printf("%s\n",input); }while(next_permutation(input,input+length, comp_ana)); } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; char str[27][27]; int dr[] = {1,1,0,-1,-1,0,1}; int dc[] = {0,1,1,1,0,-1,-1,-1}; int count; int floodfill(int, int, char, char); int main(void){ int test; cin>>test; string input; int counter, max, temp; getline(cin,input); getline(cin,input); for(int i=0;i<test;i++){ counter = 0; while(getline(cin,input)){ if(input.empty()) break; for(int j=0;j<input.length();j++) str[counter][j] = input.at(j); counter++; } count = counter; max = 0; for(int j=0;j<counter;j++){ for(int k=0;k<counter;k++){ if(str[j][k]=='1'){ temp = floodfill(j,k,'1','0'); if(temp>max) max = temp; } } } cout<<max<<endl; if(i!=test-1) cout<<endl; } return 0; } int floodfill(int r, int c, char c1, char c2){ if(r<0 || r>=count || c<0 || c>=count) return 0; if(str[r][c]!=c1) return 0; int ans = 1; str[r][c] = c2; for(int d=0;d<8;d++) ans+=floodfill(r+dr[d],c+dc[d],c1,c2); return ans; } <file_sep>#include<iostream> #include<stdio.h> #include<map> #include<algorithm> #include<vector> #include<sstream> using namespace std; typedef struct{ int id; int probsolved; int penalty; int problem[11]; bool done[11]; }contestant_t; contestant_t contestant[101]; void init(int index){ contestant[index].probsolved = contestant[index].penalty = 0; for(int i=0;i<11;i++){ contestant[index].problem[i] = 0; contestant[index].done[i] = false; } } bool sort_cmp(contestant_t a, contestant_t b){ if(a.probsolved!=b.probsolved) return a.probsolved>b.probsolved; if(a.penalty!=b.penalty) return a.penalty<b.penalty; return a.id<b.id; } int main(void){ int test,id,prob,time; char verdict; scanf("%d",&test); string input; getline(cin,input); getline(cin,input); map<int,int> mapper; int counter; while(test--){ counter = 0; mapper.clear(); while(getline(cin,input)){ if(input.empty()) break; stringstream(input)>>id>>prob>>time>>verdict; if(mapper.find(id)==mapper.end()){ mapper[id]=counter++; init(mapper[id]); contestant[mapper[id]].id = id; } switch(verdict){ case 'C':{ if(!contestant[mapper[id]].done[prob]){ contestant[mapper[id]].probsolved++; contestant[mapper[id]].penalty+=time+contestant[mapper[id]].problem[prob]*20; contestant[mapper[id]].done[prob] = true; } break; } case 'I':{ contestant[mapper[id]].problem[prob]++; break; } } // for(int i=0;i<counter;i++){ // printf("%d %d %d\n",contestant[i].id,contestant[i].probsolved,contestant[i].penalty); //} } sort(contestant,contestant+counter,sort_cmp); for(int i=0;i<counter;i++){ printf("%d %d %d\n",contestant[i].id,contestant[i].probsolved,contestant[i].penalty); } if(test) printf("\n"); } return 0; } <file_sep>import java.util.*; import java.io.*; import java.math.BigInteger; class uva10229{ static Matrix matMul(Matrix a, Matrix b){ Matrix ans; int i,j,k; ans = new Matrix(); for(i=0;i<2;i++){ for(j=0;j<2;j++){ ans.mat[i][j] = BigInteger.ZERO; for(k = 0;k<2; k++) ans.mat[i][j] = ans.mat[i][j].add(a.mat[i][k].multiply(b.mat[k][j])); } } return ans; } static Matrix matPow(Matrix base, int p){ Matrix ans; int i,j; ans = new Matrix(); for(i=0;i<2;i++) for(j=0;j<2;j++) ans.mat[i][j] = (i==j)?BigInteger.ONE:BigInteger.ZERO; while(p!=0){ if(p%2== 1) ans = matMul(ans,base); base = matMul(base,base); p>>=1; System.out.println(p); } return ans;} public static void main(String[] args){ PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Matrix mat = new Matrix(); mat.mat[0][0] = mat.mat[0][1] = mat.mat[1][0] = BigInteger.ONE; mat.mat[1][1] = BigInteger.ZERO; while(sc.hasNext()){ int x, mod; x = sc.nextInt(); mod = sc.nextInt(); Matrix res = new Matrix(); res = matPow(mat,x); BigInteger result = res.mat[0][1]; pr.println(result.mod(BigInteger.valueOf(2).pow(mod))); } pr.close(); } } class Matrix{ BigInteger[][] mat; public Matrix(){ mat = new BigInteger[2][2]; } }<file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ long long value[10002]; int counter, test; counter = 0; while(cin>>value[counter]){ counter++; stable_sort(value, value+counter); if(counter%2==1) cout<<value[counter/2]; else cout<<(value[counter/2]+value[counter/2-1])/2; cout<<endl; //for(int i=0;i<counter;i++) // cout<<" "<<value[i]<<" "; } } <file_sep>import java.util.Scanner; import java.math.BigDecimal; class BigBigRealNumbers{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int test = sc.nextInt(); String check; BigDecimal bigdec1, bigdec2; while(test-->0){ bigdec1 = new BigDecimal(sc.next()); bigdec2 = new BigDecimal(sc.next()); check = bigdec1.add(bigdec2).toPlainString(); int i = 0; while(check.charAt(check.length()-i-1)=='0') i++; for(int j=0;j<check.length()-i;j++) System.out.print(check.charAt(j)); if(check.charAt(check.length()-i-1) == '.') System.out.print("0"); System.out.println(); } } }<file_sep>#include<cstdio> #include<map> using namespace std; int main(void){ int n; map<int,int>mapper; int arr[1000000]; while(scanf("%d",&n) && n){ mapper.clear(); int a,b, counter = 0; for(int i=0;i<2*n;i++) arr[i] = 0; for(int i=0;i<n;i++){ scanf("%d%d",&a,&b); if(mapper.find(a)==mapper.end()){ mapper[a] = counter++; } if(mapper.find(b)==mapper.end()) mapper[b] = counter++; arr[mapper[a]]--; arr[mapper[b]]++; } bool valid = true; for(int i=0;i<counter;i++) if(arr[i]){valid = false;break;} if(valid) printf("YES\n"); else printf("NO\n"); } return 0; } <file_sep>#include<map> #include<iostream> using namespace std; int main(void){ string input, inputnum; int numcom; int numquery; map<string, int> value; double val; int ans, realans; bool guess; cin>>numcom>>numquery; for(int i=0;i<numcom;i++){ cin>>input>>inputnum; if(inputnum.length()==3) val = (inputnum.at(0)-'0')*10 + inputnum.at(2)-'0'; if(inputnum.length()==4) val = (inputnum.at(0)-'0')*100 + (inputnum.at(1)-'0')*10+ inputnum.at(3)-'0'; value[input] = val; } for(int i=1;i<=numquery;i++){ ans = 0; guess = false; while(true){ cin>>input; if(input == "="){ cin>>realans; if(ans == realans*10) guess = true; break; } else if(input == ">"){ cin>>realans; if(ans > realans*10) guess = true; break; } else if(input == ">="){ cin>>realans; if(ans >= realans*10) guess = true; break; } else if(input == "<"){ cin>>realans; if(ans<realans*10) guess = true; break; } else if(input == "<="){ cin>>realans; if(ans<=realans*10) guess = true; break; } else if(input !="+"){ ans +=value[input]; } } //cout<<ans<<" "<<realans<<endl<<endl; cout<<"Guess #"<<i<<" was "; if(guess) cout<<"correct."<<endl; else cout<<"incorrect."<<endl; } } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> #include<map> #include<math.h> #include<stdlib.h> #include<algorithm> #define INF 100000000 using namespace std; double AdjMat[205][205]; int main(void){ int K,M,temp1,temp2,temp3; double x[205],y[205],r[205]; while(cin>>K>>M){ for(int i=0;i<202;i++) for(int j=0;j<202;j++){ if(i!=j) AdjMat[i][j] = INF; else AdjMat[i][j] = 0; } int x[202],y[202],r[202],in; cin>>x[0]>>y[0]>>r[0]>>temp1>>temp2>>temp3; cin>>in; x[in+1] = temp1; y[in+1]=temp2; r[in+1] = temp3; for(int j=1;j<=in;j++) cin>>x[j]>>y[j]>>r[j]; for(int i=0;i<=in;i++) for(int j=i+1;j<=in+1;j++){ AdjMat[i][j] = sqrt(pow(abs(x[i]-x[j]),2) + pow(abs(y[i]-y[j]),2)) - r[i]-r[j]; if(AdjMat[i][j]<=K*M) AdjMat[j][i] = AdjMat[i][j]; else{ AdjMat[i][j] = AdjMat[j][i] = INF; } } for(int k=0;k<=in+1;k++) for(int i=0;i<=in+1;i++) for(int j=0;j<=in+1;j++) AdjMat[i][j] = min(AdjMat[i][j],AdjMat[i][k]+AdjMat[k][j]); if(AdjMat[0][in+1]==INF) cout<<"Larry and Ryan will be eaten to death."<<endl; else cout<<"Larry and Ryan will escape!"<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> using namespace std; int main(void){ int row, col, start,counter,rownow,colnow; int traversed[400][400]; char symbol[400][400]; while(cin>>row>>col>>start && row && col && start){ getchar(); for(int i=0;i<row;i++) gets(symbol[i]); for(int i=0;i<row;i++) for(int j=0;j<col;j++) traversed[i][j]=0; counter = 1; rownow = 0; colnow = start-1; while(true){ if(rownow<0||rownow>=row||colnow<0||colnow>=col){ //cout<<rownow<<" "<<row<<" "<<colnow<<" "<<col<<endl; cout<<counter-1<<" step(s) to exit"<<endl; break; } else if(traversed[rownow][colnow]!=0){ cout<<traversed[rownow][colnow]-1<<" step(s) before a loop of "<<counter-traversed[rownow][colnow]<<" step(s)"<<endl; break; } traversed[rownow][colnow]=counter; counter++; if(symbol[rownow][colnow]=='N') rownow--; else if(symbol[rownow][colnow]=='E') colnow++; else if(symbol[rownow][colnow]=='S') rownow++; else if(symbol[rownow][colnow]=='W') colnow--; } } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ int n, dif; int jump[3000]; int jump1[3000]; bool isJolly; while(cin>>n){ isJolly = true; for(int i=0;i<n;i++){ jump[i] = 0; cin>>jump1[i]; } for(int i=0;i<n-1;i++){ dif = fabs((double)(jump1[i]-jump1[i+1])); if(dif<n) jump[dif] = 1; } for(int i=1;i<n;i++){ if(jump[i]==0){ isJolly = false; break; } } if(isJolly) cout<<"Jolly"<<endl; else cout<<"Not jolly"<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int x,y,x1,y1,testcase; while(true){ cin>>testcase; if(testcase == 0) break; cin>>x>>y; for(int i=0;i<testcase;i++){ cin>>x1>>y1; if(x1==x || y1==y) cout<<"divisa"; else if(x1<x){ if(y1<y) cout<<"SO"; else cout<<"NO"; } else{ if(y1<y) cout<<"SE"; else cout<<"NE"; } cout<<endl; } } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) typedef struct{ int num, balance; string str; }trav; bool sort_cmp(trav a, trav b){ return a.balance>b.balance; } int main(void){ #ifdef ccsnoopy freopen("D:/Code/in.txt","r",stdin); #endif //to compile: g++ -o foo filename.cpp -lm -Dccsnoopy for debug. int n,t; string name,namez; map<string,int>mapper; trav traveller[24]; int tc = 1; while(scanf("%d %d",&n,&t) && (n||t)){ printf("Case #%d\n",tc++); FOR(i,n){ cin>>name; mapper[name] = i; traveller[i].num = i; traveller[i].balance = 0; traveller[i].str = name; } int amt; FOR(i,t){ cin>>name>>namez; sc(amt); traveller[mapper[name]].balance-=amt; traveller[mapper[namez]].balance+=amt; } sort(traveller,traveller+n,sort_cmp); int ptr = n-1; FOR(i,n){ while(traveller[i].balance!=0){ int sumbang = min(abs(traveller[i].balance),abs(traveller[ptr].balance)); traveller[i].balance-=sumbang; traveller[ptr].balance+=sumbang; cout<<traveller[i].str<<" "<<traveller[ptr].str<<" "<<sumbang<<endl; if(traveller[ptr].balance==0)ptr--; } } printf("\n"); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ //freopen("D:/Code/in.txt","r",stdin); int tc; bool arr[103]; int left[60],right[60]; sc(tc); bool first = true; char str[4]; TC(){ if(!first){ printf("\n"); }else first = false; int n,k; sc(n); sc(k); FORN(i,n)arr[i] = false; int test; FOR(i,k){ sc(test); FOR(j,test){ sc(left[j]); } FOR(j,test){ sc(right[j]); } scanf("%s",str); //printf("%s",str); if(str[0]=='='){ FOR(j,test){ //printf("%d %d\n",left[j],right[j]); arr[left[j]] = true; arr[right[j]] = true; } }else{ bool status[103]; reset(status,false); FOR(j,test){ status[left[j]] = status[right[j]] = true; } REPN(j,1,n){ if(!status[j])arr[j] = true; } } } int tot = 0; int idx; /*REPN(i,1,n){ if(!arr[i])printf("%d\n",i); }*/ REPN(i,1,n){ if(!arr[i]){ tot++; idx = i; } if(tot>1)break; } if(tot == 1){ printf("%d\n",idx); }else printf("0\n"); } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ double test; int cow, car, show; while(scanf("%d %d %d",&cow,&car,&show) == 3){ test = (double)cow/(cow+car)*(double)car/(cow+car-show-1) + (double)car/(car+cow)*(double)(car-1)/(cow+car-show-1); printf("%.5lf\n",test); } return 0; } <file_sep>#include<math.h> #include<iostream> #include<stdio.h> using namespace std; int main(void){ int test, counter = 1; double u,v,a,s,t; while(cin>>test && test){ if(test == 1){ cin>>u>>v>>t; a = (v-u)/t; s = (u+v)/2*t; printf("Case %d: %.3lf %.3lf\n",counter,s,a); } else if(test == 2){ cin>>u>>v>>a; t = (v-u)/a; s = (u+v)/2*t; printf("Case %d: %.3lf %.3lf\n",counter,s,t); } else if(test == 3){ cin>>u>>a>>s; v = sqrt(pow(u,2) + 2*a*s); t = (v-u)/a; printf("Case %d: %.3lf %.3lf\n",counter,v,t); } else if(test == 4){ cin>>v>>a>>s; u = sqrt(pow(v,2)-2*a*s); t = (v-u)/a; printf("Case %d: %.3lf %.3lf\n",counter,u,t); } counter++; } return 0; } <file_sep> #include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) #define PI 3.141592653589793 #define EARTH_RAD (6378000) // in meters double gcDistance(double pLat, double pLong, double qLat, double qLong, double radius) { pLat *= PI / 180; pLong *= PI / 180; qLat *= PI / 180; qLong *= PI / 180; return radius * acos(cos(pLat)*cos(pLong)*cos(qLat)*cos(qLong) + cos(pLat)*sin(pLong)*cos(qLat)*sin(qLong) + sin(pLat)*sin(qLat)); } double EucledianDistance(double pLat, double pLong, // 3D version double qLat, double qLong, double radius) { double phi1 = (90 - pLat) * PI / 180; double theta1 = (360 - pLong) * PI / 180; double x1 = radius * sin(phi1) * cos(theta1); double y1 = radius * sin(phi1) * sin(theta1); double z1 = radius * cos(phi1); double phi2 = (90 - qLat) * PI / 180; double theta2 = (360 - qLong) * PI / 180; double x2 = radius * sin(phi2) * cos(theta2); double y2 = radius * sin(phi2) * sin(theta2); double z2 = radius * cos(phi2); double dx = x1 - x2, dy = y1 - y2, dz = z1 - z2; return sqrt(dx * dx + dy * dy + dz * dz); } int main(void){ //freopen("in.txt","r",stdin); int counter = 0; string str; double x[1000],y[1000]; map<string,int> mapper; while(scanf("%d",&n)!=EOF){ for(int i=0;i<n;i++){ scanf("%lf %lf",&x[i],&y[i]); } double AdjMat[1000][1000]; memset(AdjMat,0,sizeof AdjMat); for(int i=0;i<n;i++) for(int j=i+1;j<n;j++){ AdjMat[i][j] = AdjMat[j][i] = gcDistance(x[i],y[i],x[j],y[j],EARTH_RAD); } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int bin[9]; int min; string mincomb; while(cin>>bin[0]>>bin[1]>>bin[2]>>bin[3]>>bin[4]>>bin[5]>>bin[6]>>bin[7]>>bin[8]){ min = bin[3]+bin[6] + bin[2] + bin[8] + bin[1] + bin[4]; mincomb = "BCG"; if(min>(bin[3]+bin[6] + bin[2] + bin[5] + bin[1] + bin[7])){ min = bin[3]+bin[6] + bin[2] + bin[5] + bin[1] + bin[7]; mincomb = "BGC"; } if(min>(bin[5]+bin[8] + bin[0] + bin[6] + bin[1] + bin[4])){ min = bin[5]+bin[8] + bin[0] + bin[6] + bin[1] + bin[4]; mincomb = "CBG"; } if(min>(bin[5]+bin[8] + bin[0] + bin[3] + bin[1] + bin[7])){ min = bin[5]+bin[8] + bin[0] + bin[3] + bin[1] + bin[7]; mincomb = "CGB"; } if(min>(bin[5]+bin[2] + bin[0] + bin[6] + bin[7] + bin[4])){ min = bin[5]+bin[2] + bin[0] + bin[6] + bin[7] + bin[4]; mincomb = "GBC"; } if(min>(bin[2]+bin[8] + bin[0] + bin[3] + bin[7] + bin[4])){ min = bin[2]+bin[8] + bin[0] + bin[3] + bin[7] + bin[4]; mincomb = "GCB"; } cout<<mincomb<<" "<<min<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; typedef pair<int,ii> pii; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define scan() scanf("%d",&tc); #define TC() while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) class UnionFind { // OOP style private: vi p, rank, setSize; // remember: vi is vector<int> int numSets; public: UnionFind(int N) { setSize.assign(N, 1); numSets = N; rank.assign(N, 0); p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { if (!isSameSet(i, j)) { numSets--; int x = findSet(i), y = findSet(j); // rank is used to keep the tree short if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } } int numDisjointSets() { return numSets; } int sizeOfSet(int i) { return setSize[findSet(i)]; } }; int main(void){ //freopen("in.txt","r",stdin); int tc, S, P; scanf("%d",&tc); TC(){ vector< pair<double, ii> > EdgeList; EdgeList.clear(); int x[501],y[501]; scanf("%d %d",&S,&P); for(int i=0;i<P;i++){ scanf("%d %d",&x[i],&y[i]); } for(int i=0;i<P;i++) for(int j=i+1;j<P;j++) EdgeList.push_back(make_pair(hypot((double)(x[i]-x[j]),(double)y[i]-y[j]),ii(i,j))); sort(EdgeList.begin(), EdgeList.end()); //for(int i=0;i<EdgeList.size();i++) //printf("%lf %d %d\n",EdgeList[i].first, EdgeList[i].second.first,EdgeList[i].second.second); double mst_cost = 0; UnionFind UF(P); // all V are disjoint sets initially for (int i = 0; i < EdgeList.size(); i++) { // for each edge, O(E) //printf("%lf %d\n",mst_cost,UF.numDisjointSets()); if(UF.numDisjointSets() == S) break; pair<double, ii> front = EdgeList[i]; if (!UF.isSameSet(front.second.first, front.second.second)) { // check mst_cost = front.first; // add the weight of e to MST UF.unionSet(front.second.first, front.second.second); // link them } } // note: the runtime cost of UFDS is very light printf("%.2lf\n",mst_cost); } return 0; } <file_sep>#include<string> #include<iostream> using namespace std; int main(void){ int x,y, counter; int xy[102][102]; string test; char bomb[102][102]; counter = 1; cin>>x>>y; while(x!=0 && y!=0){ if(x==y && y == 0) break; int xy[102][102] = {0}; for(int i=1;i<=x;i++){ cin>>test; for(int j=1;j<=y;j++){ bomb[i][j] = test.at(j-1); if(bomb[i][j] == '*'){ for(int k = i-1;k<=i+1;k++) for(int l = j-1;l<=j+1;l++) xy[k][l]++; } } } cout<<"Field #"<<counter<<":"<<endl; for(int i=1;i<=x;i++){ for(int j=1;j<=y;j++){ if(bomb[i][j] == '*') cout<<"*"; else cout<<xy[i][j]; } cout<<endl; } counter++; cin>>x>>y; if(x!=0 && y!=0) cout<<endl; } return 0; } <file_sep>#include <iostream> using namespace std; int computeSinks(int [],int [], int); int computeHit(int [], int [], int); int main(void) { int counter, peg[1000],guess[1000]; int test, sink, hit; bool playing; counter = 1; while(true){ cin>>test; if(test == 0) return 0; playing = true; for(int i=0;i<test;i++){ cin>>peg[i]; } cout<<"Game "<<counter<<":"<<endl; while(playing){ for(int i=0;i<test;i++){ cin>>guess[i]; } for(int i=0;i<test;i++){ if(i==test-1 && guess[test-1]==0) playing = false; if(guess[i]!=0) break; } if(!playing) break; sink=computeSinks(peg, guess,test); hit=computeHit(peg, guess,test); cout<<" ("<<sink<<","<<hit<<")"<<endl; } counter++; } return 0; } //To compute how many sinks that a guess has.(sink:correct number and position) int computeSinks(int secret[], int guess[], int test) { int i, sink=0; for(i=0;i<test;i++) { if(secret[i]==guess[i]) sink++; } return sink; } //To compute how many hits that a guess has.(hit:correct number wrong position) int computeHit(int secret[], int guess[], int test) { int i,k,hit=0, temp[test]; for(int j=0;j<test;j++) temp[j] = secret[j]; for(i=0;i<test;i++) if(secret[i]==guess[i]) { secret[i]=0; guess[i]=0; } for(i=0;i<test;i++) { for(k=0;k<test;k++) { if(secret[i]==0) break; if(secret[i]==guess[k] && i!=k) { hit++; guess[k]=0; break; } } } for(int j=0;j<test;j++) secret[j] = temp[j]; return hit; } <file_sep>#include<map> #include<set> #include<iostream> using namespace std; int main(void){ map<int,int> did; set<int> set1; set<int> set2; set<int> set3; int max,test,input,num; cin>>test; for(int i=1;i<=test;i++){ cin>>input; for(int j=0;j<input;j++){ cin>>num; did[num]++; } cin>>input; for(int j=0;j<input;j++){ cin>>num; did[num]+=3; } cin>>input; for(int j=0;j<input;j++){ cin>>num; did[num]+=5; } for(map<int,int>::iterator it = did.begin();it!=did.end();it++){ if(it->second == 1) set1.insert(it->first); else if(it->second == 3) set2.insert(it->first); else if(it->second == 5) set3.insert(it->first); } max = set1.size(); cout<<"Case #"<<i<<":"<<endl; if(max<set2.size()) max = set2.size(); if(max<set3.size()) max = set3.size(); if(set1.size() == max){ cout<<"1 "<<max; for(set<int>::iterator it1 = set1.begin();it1!=set1.end();it1++) cout<<" "<<*it1; cout<<endl; } if(set2.size() == max){ cout<<"2 "<<max; for(set<int>::iterator it1 = set2.begin();it1!=set2.end();it1++) cout<<" "<<*it1; cout<<endl; } if(set3.size() == max){ cout<<"3 "<<max; for(set<int>::iterator it1 = set3.begin();it1!=set3.end();it1++) cout<<" "<<*it1; cout<<endl; } set1.clear(); set2.clear(); set3.clear(); did.clear(); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int people[101]; int start, count, num, counter, countdead, countadd, remember; bool fail; while(cin>>num>>count && num && count){ start = 1; fail = true; while(fail){ counter = start; countdead = 0; countadd = 1; for(int i=1;i<=num;i++) people[i] = 1; while(true){ while(countadd<(count)){ if(people[counter]==1){ counter++; countadd++; } else counter++; if(counter>num) counter = 1; } if(people[counter]){ people[counter] = 0; } else{ while(!people[counter]){ counter++; if(counter>num) counter = 1; } people[counter] = 0; } remember = counter; countadd = 0; while(countadd<(count)){ if(people[counter]==1){ counter++; countadd++; } else counter++; if(counter>num) counter = 1; } if(people[counter]){ people[counter] = 0; } else{ while(!people[counter]){ counter++; if(counter>num) counter = 1; } people[counter] = 0; } people[remember] = 1; countdead++; //for(int i=1;i<=num;i++) //cout<<" "<<people[i]; //cout<<endl; if(remember == 1 && countdead<num) break; if(remember == 1 && countdead==num){ fail = false; break; } counter = remember; } if(fail) start++; } cout<<start<<endl; } return 0; } <file_sep>#include<string.h> #include<map> #include<iostream> using namespace std; int main(void){ map<char,long long> dict; int test, len; long long max = 0; string in; cin>>test; getline(cin,in); for(int i=0;i<test;i++){ getline(cin,in); len = in.length(); for(int j=0;j<len;j++){ if(in.at(j)>='A' && in.at(j)<='Z' || in.at(j)>='a' && in.at(j)<='z') dict[toupper(in.at(j))]++; } } while(true){ max = 0; for(map<char,long long>::iterator it = dict.begin();it!=dict.end();it++) if(it->second > max) max = it->second; if(max == 0) break; for(map<char,long long>:: iterator it = dict.begin();it!=dict.end();it++){ if(it->second == max){ cout<<it->first<<" "<<it->second<<endl; it->second = 0; } } } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; typedef struct{ int brief; int comm; }soldier; bool comp(soldier a, soldier b){ if(a.comm != b.comm) return a.comm<b.comm; return a.brief<b.brief; } int main(void){ int test; int counter = 1; long long totalbrief, totalcomm; soldier sol[1001]; while(cin>>test && test){ totalbrief = totalcomm = 0; for(int i=0;i<test;i++){ cin>>sol[i].brief>>sol[i].comm; totalbrief+=sol[i].brief; totalcomm+=sol[i].comm; } cout<<"Case "<<counter++<<": "; sort(sol,sol+test); if(totalbrief>=(totalcomm-sol[test-1].brief)) cout<<totalbrief+sol[test-1].comm; else{ } cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string> int main(void){ string test[100]; int i = 0; int maxdigit; while(true){ cin>>test[i]; if(test[i].length()==1 && test[i] == "0") break; if(test[i].length()>maxdigit) maxdigit == test[i].length(); i++; } for(int k=maxdigit-1;k>=0;k++){ for(int j=0;j<=i;j++){ if(test[j].length()>k) } } return 0; } <file_sep>import java.util.Scanner; import java.util.StringTokenizer; class WordScramble{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); StringTokenizer st; String input; boolean first; while(sc.hasNextLine()){ input = sc.nextLine(); st = new StringTokenizer(input); first = true; while(st.hasMoreTokens()){ if(!first) System.out.print(" "); first = false; input = st.nextToken(); for(int i=0;i<input.length();i++){ System.out.print(input.charAt(input.length()-i-1)); } } System.out.println(); } } }<file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ #ifdef ccsnoopy freopen("D:/Code/in.txt","r",stdin); #endif //to compile: g++ -o foo filename.cpp -lm -Dccsnoopy for debug. string str; int dr[] = {-1,0,1,0}; int dc[] = {0,1,0,-1}; int arr[10]; int x,y,x1,y1; vector<vi>AdjList; AdjList.assign(9,vi()); FOR(j,9){ x = j/3; y = j%3; FOR(i,4){ x1 = x+dr[i]; y1 = y+dc[i]; if(x1>=0 && y1>=0 && x1<3 && y1<3){ //printf("%d %d with %d %d\n",x,y,x1,y1); AdjList[x*3+y].pb(x1*3+y1); } } } int tc = 1; while(getline(cin,str)){ reset(arr,0); int len = str.length(); int num; FOR(i,len){ num = str.at(i)-'a'; arr[num]++; //printf("%d\n",num); FOR(j,AdjList[num].size()){ arr[AdjList[num][j]]++; //printf("%d %d %d\n",num,AdjList[num][j],arr[AdjList[num][j]]); } } printf("Case #%d:\n",tc++); FOR(i,3){ FOR(j,3){ if(j<2)printf("%d ",arr[i*3+j]%10); else printf("%d",arr[i*3+j]%10); }printf("\n"); } } return 0; } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> using namespace std; int dr[] = {-1,0,1,-1,0,1}; int dc[] = {-1,-1,0,0,1,1}; char grid[210][210]; int input; bool white; void floodfill(int row, int col, char c1, char c2){ if(row<0||row>=input||col<0||col>=input) return; if(grid[row][col]!=c1) return; grid[row][col]=c2; for(int d=0;d<6;d++) floodfill(row+dr[d],col+dc[d],c1,c2); } int main(void){ int prob=1; while(cin>>input && input){ getchar(); for(int i=0;i<input;i++) gets(grid[i]); white = false; for(int i=0;i<input;i++) if(grid[i][0]=='w') floodfill(i,0,'w','.'); for(int i=0;i<input;i++) if(grid[i][input-1]=='.'){ white = true; break; } cout<<prob++<<" "; if(white) cout<<"W"<<endl; else cout<<"B"<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> #include<vector> #include<stdlib.h> using namespace std; int main(void){ vector<int> x1,x3,y1,y3; int length,length2,mintemp,temp,ans,dim; char num[1000][1000]; while(scanf("%d",&dim)==1){ getchar(); ans = 0; x1.clear(); x3.clear(); y1.clear(); y3.clear(); for(int i=0;i<dim;i++) gets(num[i]); for(int i=0;i<dim;i++) for(int j=0;j<dim;j++){ if(num[i][j]=='1'){ x1.push_back(i); y1.push_back(j); } else if(num[i][j]=='3'){ x3.push_back(i); y3.push_back(j); } } length = x1.size(); length2 = x3.size(); for(int i=0;i<length;i++){ mintemp = 1000; for(int j=0;j<length2;j++){ temp = abs(x1.at(i)-x3.at(j))+abs(y1.at(i)-y3.at(j)); if(temp<mintemp) mintemp = temp; } if(ans<mintemp) ans = mintemp; } printf("%d\n",ans); } return 0; } <file_sep>#include<iostream> #include<map> using namespace std; int main(void){ int test,testcase, price; cin>>test>>testcase; map<string,int> job; string input; for(int i=0;i<test;i++){ cin>>input; cin>>price; job[input] = price; } long long sum; for(int i=0;i<testcase;i++){ sum = 0; while(cin>>input){ if(input==".") break; if(job.find(input)!=job.end()) sum+=job[input]; } cout<<sum<<endl; } } <file_sep>#include<iostream> #include<string> #include<stdio.h> using namespace std; int main(void){ int test,startH[2],endH[2],startM[2],endM[2],start[2],end[2]; int min[1440]; scanf("%d",&test); for(int i=1;i<=test;i++){ for(int j=0;j<2;j++){ scanf("%d:%d %d:%d",&startH[j],&startM[j],&endH[j],&endM[j]); start[j] = startH[j]*60+startM[j]; end[j] = endH[j]*60 + endM[j]; if(end[j]<start[j]) end[j]+=1440; } cout<<"Case "<<i<<": "; if(start[0]<=start[1] && start[1]<=end[0] || start[1]<=start[0] && start[0]<=end[1]) cout<<"Mrs Meeting"<<endl; else cout<<"Hits Meeting"<<endl; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ int input, indicator[11]; bool honest, done; string response; while(true){ honest = true; done = false; for(int i=1;i<11;i++) indicator[i] = 0; while(true){ cin>>input; if(input == 0) return 0; getline(cin,response); getline(cin,response); if(response == "too high"){ if(indicator[input] == 0 || indicator[input] == 1) indicator[input] = 1; else honest = false; } else if(response == "too low"){ if(indicator[input] == 0 || indicator[input] == -1) indicator[input] = -1; else honest = false; } else if(response == "right on"){ for(int i=0;i<=input;i++){ if(indicator[i]==1) honest = false; } for(int i=input;i<=10;i++){ if(indicator[i]==-1) honest = false; } if(honest) cout<<"Stan may be honest"<<endl; else cout<<"Stan is dishonest"<<endl; done = true; } if(done) break; } } return 0; } <file_sep>#include<iostream> #include<string.h> #include<math.h> using namespace std; int gcd(int,int); int main(void){ string in; int len, test, test1,test2; cin>>test; for(int i=1;i<=test;i++){ cin>>in; len = in.length(); test1 = test2 = 0; for(int j=0;j<len;j++) test1+=(in.at(j)-'0')*(int)pow(2,len-j-1); cin>>in; len = in.length(); for(int j=0;j<len;j++) test2+=(in.at(j)-'0')*(int)pow(2,len-j-1); cout<<"Pair #"<<i<<": "; if(gcd(test1,test2)>1) cout<<"All you need is love!"<<endl; else cout<<"Love is not all you need!"<<endl; } return 0; } int gcd(int a, int b){ return (b == 0 ? a : gcd(b,a%b)); } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) typedef vector<int> VI; typedef vector<VI> VVI; typedef long long L; typedef vector<L> VL; typedef vector<VL> VVL; typedef pair<int, int> PII; typedef vector<PII> VPII; typedef vector<double> VD; struct MinCostMaxFlow { int N; vector<VD> cost; VVL cap, flow; VI found; VD dist, pi, width; VPII dad; MinCostMaxFlow(int N) : N(N), cap(N, VL(N)), flow(N, VL(N)), cost(N, VD(N)), found(N), dist(N), pi(N), width(N), dad(N) {} void AddEdge(int from, int to, L cap, double cost) { this->cap[from][to] = cap; this->cost[from][to] = cost; } void Relax(int s, int k, L cap, double cost, int dir) { double val = dist[s] + pi[s] - pi[k] + cost; if (cap && val < dist[k]) { dist[k] = val; dad[k] = make_pair(s, dir); width[k] = min((double)cap, width[s]); } } L Dijkstra(int s, int t) { fill(found.begin(), found.end(), false); fill(dist.begin(), dist.end(), INFLL); fill(width.begin(), width.end(), 0); dist[s] = 0; width[s] = INF; while (s != -1) { int best = -1; found[s] = true; for (int k = 0; k < N; k++) { if (found[k]) continue; Relax(s, k, cap[s][k] - flow[s][k], cost[s][k], 1); Relax(s, k, flow[k][s], -cost[k][s], -1); if (best == -1 || dist[k] < dist[best]) best = k; } s = best; } for (int k = 0; k < N; k++) pi[k] = min(pi[k] + dist[k], (double)INFLL); return width[t]; } pair<L, double> GetMaxFlow(int s, int t) { L totflow = 0; double totcost = 0; while (L amt = Dijkstra(s, t)) { totflow += amt; for (int x = t; x != s; x = dad[x].first) { if (dad[x].second == 1) { flow[dad[x].first][x] += amt; totcost += amt * cost[dad[x].first][x]; } else { flow[x][dad[x].first] -= amt; totcost -= amt * cost[x][dad[x].first]; } } } return make_pair(totflow, totcost); } }; int main(void){ //freopen("in.txt","r",stdin); int n,m; //MinCostMaxFlow mcmf; while(scanf("%d %d",&n,&m),(n||m)){ MinCostMaxFlow mcmf = MinCostMaxFlow(n+m+2); FOR(i,n){ mcmf.AddEdge(m+1+i,n+m+1,1,0); } FOR(i,m){ mcmf.AddEdge(0,i+1,1,0); } double cost; FOR(i,n){ FOR(j,m){ scanf("%lf",&cost); mcmf.AddEdge(j+1,i+m+1,1,cost); // mcmf.AddEdge(2+j+n,i+2,1,cost); } } pair<L,double> res = mcmf.GetMaxFlow(0,n+m+1); printf("%.2lf\n",res.second/n + 1e-6); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; char dice[100][100]; int maxrow, maxcol; int dr[] = {0,1,0,-1}; int dc[] = {-1,0,1,0}; void scan(){ getchar(); for(int i=0;i<maxrow;i++) gets(dice[i]); } void filldice(int row, int col, char c1, char c2){ if(row<0 || row>=maxrow || col<0 || col>=maxcol) return; if(dice[row][col]!=c1) return; dice[row][col]=c2; for(int d=0;d<4;d++) filldice(row+dr[d],col+dc[d],c1,c2); } int floodfill(int row, int col, char c1, char c2){ if(row<0 || row>=maxrow || col<0 || col>=maxcol) return 0; int ans = 0; if(dice[row][col]=='X') { filldice(row,col,'X','*'); ans++; } if(dice[row][col]!=c1) return 0; dice[row][col] = c2; for(int d=0;d<4;d++) ans+=floodfill(row+dr[d],col+dc[d],c1,c2); return ans; } int main(void){ int counter, countthrow = 1; int die[1000]; while(cin>>maxcol>>maxrow && maxrow && maxcol){ scan(); counter = 0; for(int i=0;i<maxrow;i++) for(int j=0;j<maxcol;j++){ if(dice[i][j]!='.'){ die[counter] = floodfill(i,j,'*','.'); counter++; } } sort(die,die+counter); cout<<"Throw "<<countthrow++<<endl; for(int i=0;i<counter-1;i++) cout<<die[i]<<" "; cout<<die[counter-1]<<endl<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) typedef struct{ int x,y; }dol; bool sort_cmp(dol a, dol b){ if(a.x != b.x)return a.x<b.x; return a.y<b.y; } int main(void){ int tc; dol doll[20010]; int L[20010], L_id[20010], P[20010]; scanf("%d",&tc); TC(){ int n; scanf("%d",&n); FOR(i,n){ scanf("%d %d",&doll[i].x,&doll[i].y); } sort(doll,doll+n,sort_cmp); int lis = 0, lis_end = 0; for (int i = 0; i < n; ++i) { int pos = lower_bound(L, L + lis, doll[i].y) - L; L[pos] = doll[i].y; L_id[pos] = i; P[i] = pos ? L_id[pos - 1] : -1; if (pos + 1 > lis) { lis = pos + 1; lis_end = i; } } printf("%d\n",lis); } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ int test,squarestring; string teststring; cin>>test; getline(cin,teststring); for(int i=0;i<test;i++){ getline(cin,teststring); if(sqrt(teststring.length())!=(int) sqrt(teststring.length())) cout<<"INVALID"<<endl; else{ squarestring = sqrt(teststring.length()); for(int j=0;j<squarestring;j++){ for(int k=j;k<teststring.length();k+=squarestring) cout<<teststring.at(k); } cout<<endl; } } return 0; } <file_sep>#include<iostream> #include<sstream> #include<map> #include<stdio.h> #include<string.h> #define INF 1000000 using namespace std; int main(void){ int test; string in; long long data[200][200]; long long total; while(cin>>test){ if(test==1){ cout<<"0"<<endl; } else{ total = 0; for(int i=2;i<=test;i++){ for(int j=1;j<=i-1;j++){ cin>>in; if(in=="x"){ data[i][j] = INF; data[j][i] = INF; } else{ stringstream(in)>>(data[i][j]); data[j][i] = data[i][j]; } } } for(int k=1;k<=test;k++) for(int i=1;i<=test;i++) for(int j=1;j<=test;j++) data[i][j] = min(data[i][j],data[i][k]+data[k][j]); for(int i=2;i<=test;i++) total = max(total,data[1][i]); cout<<total<<endl; } } return 0; } <file_sep>#include<stdio.h> #include<map> #include<iostream> using namespace std; int main(void){ map<long long, int> catalan; catalan[1] = 1; catalan[2] = 2; catalan[5] = 3; catalan[14] = 4; catalan[42] = 5; catalan[132] = 6; catalan[429] = 7; catalan[1430] = 8; catalan[4862] = 9; catalan[16796] = 10; catalan[58786] = 11; catalan[208012] = 12; catalan[742900] = 13; catalan[2674440] = 14; catalan[9694845] = 15; catalan[35357670] = 16; catalan[129644790] = 17; catalan[477638700] = 18; catalan[1767263190] = 19; long long input; while(cin>>input) cout<<catalan[input]<<endl; return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int convert(char); int main(void){ string telephone; while(getline(cin,telephone)){ for(int i=0;i<telephone.length();i++){ if((int)telephone.at(i)>=65 && (int)telephone.at(i)<=90){ cout<<convert(telephone.at(i)); } else cout<<telephone.at(i); } cout<<endl; } return 0; } int convert(char converted){ switch(converted){ case 'A': case 'B': case 'C': return 2; case 'D': case 'E': case 'F': return 3; case 'G': case 'H': case 'I': return 4; case 'J': case 'K': case 'L': return 5; case 'M': case 'N': case 'O': return 6; case 'P': case 'Q': case 'R': case'S': return 7; case 'T': case 'U': case 'V': return 8; case 'W': case 'X': case 'Y': case 'Z': return 9; } } <file_sep>#include<iostream> using namespace std; unsigned int rev(unsigned int); bool palindrome(unsigned int); int main(void){ unsigned int number, reversed, temp; int test, counter; cin>>test; for(int i=0;i<test;i++){ cin>>number; counter = 0; while(true){ if(palindrome(number)){ cout<<counter<<" "<<number<<endl; break; } else{ reversed = rev(number); number+=reversed; counter++; } } } } bool palindrome(unsigned int number){ unsigned int number2 = 0,temp; temp = number; while(number>0){ number2 = number2*10 + number%10; number/=10; } if(number2==temp) return true; else return false; } unsigned int rev(unsigned int number){ unsigned int reverse = 0; while(number>0){ reverse = reverse*10 + number%10; number/=10; } return reverse; } <file_sep>#include<iostream> #include<stdio.h> #include<queue> #include<map> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; vector<vii> AdjList; map<int,int> mapper; map<int,int> dist; map<int,int> boom; int main(void){ int numpeople,counter = 0,num,neigh; scanf("%d",&numpeople); AdjList.assign(numpeople,vii()); for(int i=0;i<numpeople;i++){ if(mapper.find(i)==mapper.end()) mapper[i] = counter++; scanf("%d",&num); for(int j=0;j<num;j++){ scanf("%d",&neigh); if(mapper.find(neigh)==mapper.end()) mapper[neigh] = counter++; AdjList[mapper[i]].push_back(ii(mapper[neigh], 0)); } } int test,fp; scanf("%d",&test); while(test--){ scanf("%d",&fp); if(AdjList[mapper[fp]].size()==0) printf("0\n"); else{ int maxi = 0, day; ii v; dist.clear(); boom.clear(); dist[mapper[fp]] = 0; queue<int> q; q.push(mapper[fp]); while(!q.empty()){ int u = q.front();q.pop(); for(int j=0;j<(int)AdjList[u].size();j++){ v = AdjList[u][j]; if(!dist.count(v.first)){ dist[v.first] = dist[u] + 1; boom[dist[v.first]]++; q.push(v.first); } } if(maxi<boom[dist[v.first]]){ maxi = boom[dist[v.first]]; day = dist[v.first]; } } //for(map<int,int>::iterator it = boom.begin();it!=boom.end();it++) //printf("%d %d\n",it->first,it->second); printf("%d %d\n",maxi, day); } } return 0; } <file_sep>#include<iostream> #include<math.h> #include<stdio.h> using namespace std; int main(void){ int hour, minute; double atHour, atMin, degree; string test; while(cin>>test){ if(test == "0:00") break; if(test.length() == 5){ hour = ((int) test.at(0) - 48) * 10 + ((int) test.at(1) - 48); minute = ((int) test.at(3) - 48) * 10 + ((int) test.at(4) - 48); } else if(test.length() == 4){ hour = (int) test.at(0) - 48; minute = ((int) test.at(2) - 48) * 10 + ((int) test.at(3) - 48); } if (hour == 12) hour = 0; atMin = minute*6; atHour = hour*30 + minute*0.5; degree = max(atMin,atHour) - min(atMin,atHour); if(degree>180) degree =360 - degree; printf("%.3f\n",degree); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<queue> using namespace std; int main(void){ int dx[]={0,-1,0,1,0,0}; int dy[]={-1,0,1,0,0,0}; int dz[]={0,0,0,0,-1,1}; int l,r,c,x,y,z,x1,y1,z1; char mapper[31][31][31]; int value[31][31][31]; while(cin>>l>>r>>c && (l||r||c)){ for(int i=0;i<l;i++) for(int j=0;j<r;j++) for(int k=0;k<c;k++){ value[i][j][k] = -1; cin>>mapper[i][j][k]; if(mapper[i][j][k]=='S'){ z=i,x=j,y=k; value[i][j][k] = 0; } else if(mapper[i][j][k]=='E') z1=i,x1=j,y1=k; } queue<int> q1,q2,q3; q1.push(x); q2.push(y); q3.push(z); bool found = false; while(!q1.empty()){ int x2 = q1.front(); q1.pop(); int y2 = q2.front(); q2.pop(); int z2 = q3.front(); q3.pop(); for(int i=0;i<6;i++){ int xdest = x2+dx[i]; int ydest = y2+dy[i]; int zdest = z2+dz[i]; if(xdest>=0 && xdest<r && ydest>=0 && ydest<c && zdest>=0 && zdest<l && mapper[zdest][xdest][ydest]!='#'){ value[zdest][xdest][ydest] = value[z2][x2][y2]+1; if(xdest == x1 && ydest == y1 && zdest == z1){ found = true; break; } mapper[zdest][xdest][ydest] = '#'; q1.push(xdest); q2.push(ydest); q3.push(zdest); } } if(found) break; } if(found) printf("Escaped in %d minute(s).\n",value[z1][x1][y1]); else printf("Trapped!\n"); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ //freopen("D:/Code/in.txt","r",stdin); int n; sc(n); string str[103]; FOR(i,n){ //scanf("%s",str[i]); cin>>str[i]; } FOR(i,n){ //printf("%s ",str[i]); } int q; int num, dist; int right, left; sc(q); FOR(i,q){ sc(num); num--; //printf("aslinya: %s",str[num]); if(str[num].at(0)!='?') cout<<str[num]<<endl; else{ dist = 0; right = left = num; right++; left--; bool foundright, foundleft; foundright = foundleft = false; while(true){ dist++; if(left>=0 && str[left].at(0)!='?'){ foundright = true; } if(right<n && str[right].at(0)!='?'){ foundleft = true; } if(foundleft || foundright)break; right++; left--; } if(foundleft && foundright){ //printf("middle of %s and %s\n",str[left],str[right]); cout<<"middle of "<<str[left]<<" and "<<str[right]<<endl; }else{ if(foundleft){ FOR(j,dist){ printf("left of "); } cout<<str[right]<<endl; } else{ FOR(j,dist){ printf("right of "); } cout<<str[left]<<endl; } } } } return 0; } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> using namespace std; int main(void){ int input,length,val; string in; char rem; scanf("%d",&input); for(int i=1;i<=input;i++){ printf("Case %d: ",i); cin>>in; length = in.length(); for(int h=0;h<length;){ rem = in.at(h); val = 0; h++; while(in.at(h)>='0' && in.at(h)<='9'){ val*=10; val+=(in.at(h))-'0'; h++; if(h==length) break; } for(int j=0;j<val;j++) printf("%c",rem); } printf("\n"); } } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ int test; unsigned long long a; cin>>test; for(int i=0;i<test;i++){ cin>>a; cout<<(unsigned long int)sqrt(a)<<endl; } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class MODEX{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger x; int y,n; int test = sc.nextInt(); for(int i=0;i<test;i++){ x = sc.nextBigInteger(); y = sc.nextInt(); n = sc.nextInt(); System.out.println(x.modPow(BigInteger.valueOf(y),BigInteger.valueOf(n))); } sc.nextInt(); } }<file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ //freopen("D:/Code/in.txt","r",stdin); int tc; int dr[] = {-1,-1,-1,0,0,1,1,1}; int dc[] = {-1,0,1,-1,1,-1,0,1}; int bombs[13][13]; char str2[13][13]; sc(tc); int n; char str[13][13]; bool first = true; TC(){ reset(bombs,0); if(first)first = false; else printf("\n"); sc(n); FOR(i,n){ scanf("%s",str[i]); FOR(j,n){ if(str[i][j] == '*'){ FOR(k,8){ int x2,y2; x2 = i+dr[k]; y2 = j+dc[k]; if(x2>=0 && x2<n && y2>=0 && y2<n) bombs[x2][y2]++; } } } } bool bombed = false; FOR(i,n){ scanf("%s",str2[i]); FOR(j,n){ if(str[i][j] == '*' && str2[i][j] == 'x')bombed = true; } } if(bombed){ FOR(i,n){ FOR(j,n){ if(str[i][j] == '*')printf("*"); else if(str2[i][j] == 'x' && str[i][j]!='*')printf("%d",bombs[i][j]); else printf("."); } printf("\n"); } }else{ FOR(i,n){ FOR(j,n){ if(str2[i][j]=='x')printf("%d",bombs[i][j]); else printf("."); } printf("\n"); } } } return 0; } <file_sep>#include<cstdio> #include<cstring> using namespace std; int main(void){ char arr[1010]; while(scanf("%s",arr) && arr[0]!='0'){ printf("%s is ",arr); int len = strlen(arr); int total = 0; for(int i=0;i<len;i++){ total+=arr[i]-'0'; //printf("%d\n",total); } if(total%9==0){ printf("a multiple of 9 and has 9-degree "); int counter = 1; if(total==9) printf("1.\n"); else{ while(total!=9){ int temp = total; int temp2 = 0; while(temp>0){ temp2 += temp%10; temp/=10; } counter++; total = temp2; } printf("%d.\n",counter); } } else printf("not a multiple of 9.\n"); //printf("%d\n",total); } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ int maxrow, maxcol,row,col; int safe[51][51] = {0}; cin>>maxrow>>maxcol; char now; string input; bool lost; while(cin>>row>>col>>now){ getline(cin,input); getline(cin,input); lost = false; for(int i=0;i<input.length();i++){ if(now == 'N'){ if(input.at(i)=='R') now = 'E'; if(input.at(i)=='L') now = 'W'; if(input.at(i)=='F'){ if(col!=maxcol) col++; else if(safe[row][col] == 0){ lost = true; safe[row][col] = 1; break; } } } else if(now == 'S'){ if(input.at(i)=='R') now = 'W'; if(input.at(i)=='L') now = 'E'; if(input.at(i)=='F'){ if(col!=0) col--; else if(safe[row][col] == 0){ lost = true; safe[row][col] = 1; break; } } } else if(now == 'E'){ if(input.at(i)=='R') now = 'S'; if(input.at(i)=='L') now = 'N'; if(input.at(i)=='F'){ if(row!=maxrow) row++; else if(safe[row][col] == 0){ lost = true; safe[row][col] = 1; break; } } } else if(now == 'W'){ if(input.at(i)=='R') now = 'N'; if(input.at(i)=='L') now = 'S'; if(input.at(i)=='F'){ if(row!=0) row--; else if(safe[row][col] == 0){ lost = true; safe[row][col] = 1; break; } } } } cout<<row<<" "<<col<<" "<<now; if(lost) cout<<" LOST"; cout<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define EPS 1e-9 double memo[9][1<<9]; double dist[9][9]; int n; typedef struct{ int x,y; }Point; Point point[9]; bool sort_cmp(Point a, Point b){ if(a.x!=b.x)a.x<b.x; else a.y<b.y; } double tsp(int pos, int bitmask){ if(bitmask == (1<<n)-1){ return 0; } if(memo[pos][bitmask]>-0.5) return memo[pos][bitmask]; double ans = INFLL; FOR(i,n){ if(i!=pos && !(bitmask & (1<<i))){ // printf("trying %d %d\n",pos,i); ans = min(ans,dist[pos][i]+tsp(i,bitmask | (1<<i))); //printf("result of %d %d: %lf\n",pos,i,ans); } } return memo[pos][bitmask] = ans; } void print_path(int pos, int bitmask){ if(bitmask == (1<<n)-1) return; FOR(i,n){ //printf("",i,tsp(i, bitmask|(1<<i)),memo[pos][bitmask]); if(i != pos && (abs(dist[pos][i] + tsp(i, bitmask|(1<<i)) - memo[pos][bitmask])< EPS)){ printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2lf feet.\n",point[pos].x,point[pos].y,point[i].x,point[i].y,16+dist[pos][i]); print_path(i,bitmask | (1<<i)); break; } } } int main(void){ //freopen("in.txt","r",stdin); int casecounter = 1; while(scanf("%d",&n),n){ FOR(i,n){ scanf("%d %d",&point[i].x,&point[i].y); } sort(point,point+n,sort_cmp); FOR(i,n){ dist[i][i] = 0; REP(j,i+1,n){ dist[i][j] = dist[j][i] = hypot(abs(point[i].x-point[j].x), abs(point[i].y-point[j].y)); } } //reset(memo,-1); double ans = INFLL; int idx; FOR(i,n){ reset(memo,-1); tsp(i,1<<i); if(memo[i][1<<i] < ans){ ans = memo[i][1<<i]; idx = i; } } tsp(idx,1<<idx); printf("**********************************************************\n"); printf("Network #%d\n",casecounter++); print_path(idx,1<<idx); printf("Number of feet of cable required is %.2lf.\n",(n-1)*16 + memo[idx][1<<idx]); } return 0; } <file_sep>#include<set> #include<iostream> #include<string.h> #include<algorithm> #include<map> using namespace std; int main(void){ set<string> sorted; set<string> unsorted; map<string, string> sortunsort; string input, temp; while(cin>>input){ if(input == "#") break; temp = input; for(int i=0;i<input.length();i++) if(input.at(i)>='A' && input.at(i)<='Z') input.replace(i,1,1,input.at(i)+32); sort(input.begin(), input.end()); if(sorted.empty()){ sorted.insert(input); unsorted.insert(temp); sortunsort[input] = temp; } else if(sorted.find(input)==sorted.end()){ sorted.insert(input); unsorted.insert(temp); sortunsort[input] = temp; } else{ unsorted.erase(sortunsort[input]); } } for(set<string>::iterator it = unsorted.begin();it!=unsorted.end();it++) cout<<*it<<endl; return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<map> #include<vector> using namespace std; map<int,int> cost; long long ans; void convert(int num, int base){ if(num==0) return; ans+=cost[num%base]; convert(num/base,base); } int main(void){ int test,num,cases; vector<int> cheap; scanf("%d",&test); for(int i=1;i<=test;i++){ printf("Case %d:\n",i); for(int j=0;j<36;j++) scanf("%d",&cost[j]); scanf("%d",&cases); for(int k=0;k<cases;k++){ scanf("%d",&num); printf("Cheapest base(s) for number %d:",num); cheap.clear(); long long min=2147483647; if(num==1||num==0){ for(int j=2;j<=36;j++) printf(" %d",j); printf("\n"); } else{ for(int j=2;j<=36;j++){ ans = 0; convert(num,j); if(ans<min){ min = ans; cheap.clear(); cheap.push_back(j); } else if(ans == min) cheap.push_back(j); } for(vector<int>::iterator it = cheap.begin();it!=cheap.end();it++) printf(" %d",*it); printf("\n"); } } if(i!=test) printf("\n"); } return 0; } <file_sep>#include<iostream> #include<string> #include<stdio.h> #include<map> using namespace std; int main(void){ string test; char pricez; map<char,int> price; int testcase, howmany, line, value; double sumz; cin>>testcase; for(int i=0;i<testcase;i++){ cin>>howmany; sumz = 0; price.clear(); getline(cin,test); for(int j=0;j<howmany;j++){ getline(cin,test); pricez = test.at(0); value = 0; for(int k=2;k<test.length();k++){ value*=10; value+=test.at(k)-'0'; } price[pricez] = value; } cin>>line; getline(cin,test); for(int j=0;j<line;j++){ getline(cin,test); for(int k=0;k<test.length();k++){ if(price.find(test.at(k))!=price.end()) sumz+=price[test.at(k)]; } } printf("%.2lf$",sumz/100); cout<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<map> using namespace std; int main(void){ int N; long long num,total; map<long long, int> mapper; while(scanf("%d",&N)==1){ mapper.clear(); for(int i=0;i<N;i++){ scanf("%lld",&num); mapper[num]++; } total = 0; for(map<long long,int>::iterator it=mapper.begin();it!=mapper.end();it++){ map<long long,int>::iterator it2; it2= it; it2++; total+=it->second*(it->second-1)*mapper[it->first + it->first]/2; for(;it2!=mapper.end();it2++){ total+=it->second*it2->second*mapper[it->first + it2->first]; } } printf("%lld\n",total); } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int testcase, initial, increase; double increasec, total; cin>>testcase; for(int i=1;i<=testcase;i++){ cout<<"Case "<<i<<": "; cin>>initial>>increase; increasec = (5/9.0)*(increase); total = initial+increasec; printf("%.2lf\n",total); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string name, dummy, memorize; bool first = true; int compliance, req, company, max, counter, currentcompliance; double price, min_price; counter = 1; while(true){ cin>>req>>company; if(req == company && company == 0) return 0; if(!first) cout<<endl; first = false; getline(cin,dummy); for(int i=0;i<req;i++){ getline(cin,dummy); } min_price = 2147483640; currentcompliance = -1; for(int i=0;i<company;i++){ getline(cin,name); cin>>price; cin>>compliance; if(compliance>currentcompliance){ currentcompliance = compliance; min_price = price; memorize = name; } if(compliance == currentcompliance && price<min_price){ min_price = price; memorize = name; } getline(cin,dummy); for(int i=0;i<compliance;i++) getline(cin,dummy); } cout<<"RFP #"<<counter<<endl; cout<<memorize<<endl; counter++; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int test, numegg, maxegg, maxweight, currentweight, currentegg; int egg[30]; cin>>test; for(int i=1;i<=test;i++){ cin>>numegg>>maxegg>>maxweight; currentweight = currentegg = 0; for(int j=0;j<numegg;j++){ cin>>egg[j]; } while(currentweight<maxweight && currentegg<maxegg && currentegg<numegg){ if(currentweight+egg[currentegg]<=maxweight){ currentweight+=egg[currentegg]; currentegg++; } else break; } cout<<"Case "<<i<<": "<<currentegg<<endl; } } <file_sep>#include<iostream> using namespace std; int main(void){ long long res[]={0,0,1,2,9,44,265,1854,14833,133496,1334961,14684570,176214841}; long long fact[]={0,0,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600}; int test,in; cin>>test; while(test--){ cin>>in; cout<<res[in]<<"/"<<fact[in]<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> using namespace std; int col, row,gold; int danger[70][70]; char golds[70][70]; int dr[]={0,-1,0,1}; int dc[]={-1,0,1,0}; void floodfill(int r, int c, char c1){ if(golds[r][c]=='#' || golds[r][c]==c1) return; if(golds[r][c]=='G'){ gold++; golds[r][c]=c1; } golds[r][c]=c1; if(danger[r][c]) return; for(int i=0;i<4;i++) floodfill(r+dr[i],c+dc[i],c1); } int main(void){ while(cin>>col>>row){ getchar(); gold = 0; for(int i=0;i<row;i++){ gets(golds[i]); } for(int i=0;i<row;i++) for(int j=0;j<col;j++) danger[i][j]=0; for(int i=0;i<row;i++) for(int j=0;j<col;j++) if(golds[i][j]=='T') for(int d=0;d<4;d++) danger[i+dr[d]][j+dc[d]]=1; for(int i=0;i<row;i++) for(int j=0;j<col;j++) if(golds[i][j]=='P'){ floodfill(i,j,'-'); break; } cout<<gold<<endl; } return 0; } <file_sep>#include<iostream> #include<math.h> #include<stdio.h> using namespace std; int main(void){ int n; unsigned long long int result, sample; while(true){ scanf("%d",&n); if(n<0) break; sample = n; result = (sample*sample + sample)/2+1; cout<<result; printf("\n"); } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ char test; string testing; int length; bool firstzero; while(cin>>test>>testing){ if(testing=="0" && test=='0') return 0; length = testing.length(); firstzero = true; for(int i=0;i<length;i++){ if(testing.at(i)!=test){ if(firstzero && testing.at(i)!='0'){ cout<<testing.at(i); firstzero = false; } else if(!firstzero) cout<<testing.at(i); } } if(firstzero) cout<<"0"; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; long long H(int); int main(void){ int n, test; scanf("%d",&test); for(int i=0;i<test;i++){ scanf("%d",&n); printf("%li\n",H(n)); } return 0; } long long H(int n){ long long res = 0; for(int i = 1; i <= n;i++){ res+=n/i; } return res; } <file_sep>#include<vector> #include<algorithm> #include<cstdio> #include<iostream> #include<queue> #include<map> #include<stdio.h> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; map<int, int> mapper; vector<vii> AdjList; int main(void){ int a,in,b,num,Q,counter,from,to,casecounter=1,layer; while(scanf("%d",&a)==1){ counter = 0; mapper.clear(); AdjList.assign(20,vii()); for(int i=0;i<a;i++){ scanf("%d",&b); if (mapper.find(1) == mapper.end()) { // mapping trick mapper[1] = counter++; } if (mapper.find(b) == mapper.end()) { mapper[b] = counter++; } AdjList[mapper[1]].push_back(ii(mapper[b], 0)); AdjList[mapper[b]].push_back(ii(mapper[1], 0)); } for(int i=2;i<20;i++){ scanf("%d",&in); for(int j=0;j<in;j++){ scanf("%d",&b); if(mapper.find(i)==mapper.end()){ mapper[i]=counter++; } if (mapper.find(b) == mapper.end()) { mapper[b] = counter++; } AdjList[mapper[i]].push_back(ii(mapper[b], 0)); AdjList[mapper[b]].push_back(ii(mapper[i], 0)); } } map<int,int> dist; scanf("%d",&Q); int s,x; printf("Test Set #%d\n",casecounter++); for(int i=0;i<Q;i++){ dist.clear(); scanf("%d %d",&from,&to); s = mapper[from]; x = mapper[to]; dist[s]=0; queue<int> q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (!dist.count(v.first)) { dist[v.first] = dist[u] + 1; //printf("%d%d\n",dist[to],dist[x]); q.push(v.first); } } } printf("%2d to %2d: %d\n",from,to,dist[x]); } printf("\n"); } } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string input; int test; cin>>test; for(int i=0;i<test;i++){ cin>>input; if(input.length() == 5) cout<<"3"; else{ if((input.at(0) == 'o' && input.at(1)=='n') || (input.at(0) == 'o' && input.at(2)=='e') || (input.at(1) == 'n' && input.at(2)=='e')) cout<<"1"; else if((input.at(0) == 't' && input.at(1)=='w') || (input.at(0) == 't' && input.at(2)=='o') || (input.at(1) == 'w' && input.at(2)=='o')) cout<<"2"; } cout<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int testcase; int numoffarmer; int size[20]; int animal[20]; int friendly[20]; int sum; cin>>testcase; for(int i=0;i<testcase;i++){ sum = 0; cin>>numoffarmer; for(int j=0;j<numoffarmer;j++){ cin>>size[j]>>animal[j]>>friendly[j]; sum+=(size[j]*friendly[j]); } cout<<sum<<endl; } return 0; }<file_sep>#include<iostream> #include<stdio.h> #include<queue> using namespace std; int main(void){ int dr[] = {0,-1,0,1}; int dc[] = {-1,0,1,0}; int TC,R,C,x,y; queue<int> q1,q2; char mapper[1001][1001]; int time[1001][1001]; scanf("%d",&TC); while(TC--){ scanf("%d %d",&R,&C); for(int i=0;i<R;i++) for(int j=0;j<C;j++){ cin>>mapper[i][j]; time[i][j] = 10000000; if(mapper[i][j]=='F'){ time[i][j] = 0; q1.push(i); q2.push(j); } else if(mapper[i][j]=='J') x = i,y = j; } while(!q1.empty()){ int x1 = q1.front(); q1.pop(); int y1 = q2.front(); q2.pop(); for(int i=0;i<4;i++){ int x2 = x1+dr[i]; int y2 = y1+dc[i]; if(x2>=0 && x2<R && y2>=0 && y2<C && mapper[x2][y2]!='#' && time[x2][y2]>time[x1][y1]+1){ time[x2][y2] = time[x1][y1]+1; q1.push(x2); q2.push(y2); } } } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int total,current_amt,wax,new_candle,remainder; while(cin>>current_amt>>wax){ total = current_amt; while(current_amt >= wax) { new_candle = current_amt/wax; total = total + new_candle; remainder = current_amt%wax; current_amt = new_candle + remainder; } cout<<total<<endl; } return 0; } <file_sep>#include<map> #include<iostream> #include<string.h> using namespace std; int main(void){ int test, length; string input, input1; map<string,char> dict; dict[".-"] = 'A'; dict["-..."] = 'B'; dict["-.-."] = 'C'; dict["-.."] = 'D'; dict["."] = 'E'; dict["..-."] = 'F'; dict["--."] = 'G'; dict["...."] = 'H'; dict[".."] = 'I'; dict[".---"] = 'J'; dict["-.-"] = 'K'; dict[".-.."] = 'L'; dict["--"] = 'M'; dict["-."] = 'N'; dict["---"] = 'O'; dict[".--."] = 'P'; dict["--.-"] = 'Q'; dict[".-."] = 'R'; dict["..."] = 'S'; dict["-"] = 'T'; dict["..-"] = 'U'; dict["...-"] = 'V'; dict[".--"] = 'W'; dict["-..-"] = 'X'; dict["-.--"] = 'Y'; dict["--.."] = 'Z'; dict["-----"] = '0'; dict[".----"] = '1'; dict["..---"] = '2'; dict["...--"] = '3'; dict["....-"] = '4'; dict["....."] = '5'; dict["-...."] = '6'; dict["--..."] = '7'; dict["---.."] = '8'; dict["----."] = '9'; dict[".-.-.-"] = '.'; dict["--..--"] = ','; dict["..--.."] = '?'; dict[".----."] = '\''; dict["-.-.--"] = '!'; dict["-..-."] = '/'; dict["-.--."] = '('; dict["-.--.-"] = ')'; dict[".-..."] = '&'; dict["---..."] = ':'; dict["-.-.-."] = ';'; dict["-...-"] = '='; dict[".-.-."] = '+'; dict["-....-"] = '-'; dict["..--.-"] = '_'; dict[".-..-."] = '"'; dict[".--.-."] = '@'; cin>>test; getline(cin,input); for(int i=1;i<=test;i++){ getline(cin,input); cout<<"Message #"<<i<<endl; length = input.length(); input1.clear(); for(int j=0;j<length;j++){ if(input1.empty()){ if(input.at(j) ==' ') cout<<" "; else input1 = input.at(j); } else{ if(input.at(j)!=' ') input1 = input1 + input.at(j); else{ cout<<dict[input1]; input1.clear(); } } } if(input1.length()>0) cout<<dict[input1]; cout<<endl; if(i!=test) cout<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define DFS_WHITE -1 vector<vi> AdjList; vi dfs_num, dfs_low; int V,m; string str; vi S, visited; // additional global variables int numSCC; int dfsNumberCounter; void tarjanSCC(int u) { dfs_low[u] = dfs_num[u] = dfsNumberCounter++; // dfs_low[u] <= dfs_num[u] S.push_back(u); // stores u in a vector based on order of visitation visited[u] = 1; for (int j = 0; j < (int)AdjList[u].size(); j++) { int v = AdjList[u][j]; if (dfs_num[v] == DFS_WHITE) tarjanSCC(v); if (visited[v]) // condition for update dfs_low[u] = min(dfs_low[u], dfs_low[v]); } if (dfs_low[u] == dfs_num[u]) { // if this is a root (start) of an SCC numSCC++; while (1) { int v = S.back(); S.pop_back(); visited[v] = 0; //printf(" %d", v); if (u == v) break; } //printf("\n"); } } int main(void){ //freopen("in.txt","r",stdin); map<string,int> mapper; while(scanf("%d %d",&V,&m),(V||m)){ mapper.clear(); getline(cin,str); FOR(i,V){ getline(cin,str); mapper[str] = i; } string fr, to; AdjList.assign(V,vi()); FOR(i,m){ getline(cin,fr); getline(cin,to); AdjList[mapper[fr]].pb(mapper[to]); //AdjList[mapper[to]].pb(mapper[fr]); } dfs_num.assign(V, DFS_WHITE); dfs_low.assign(V, 0); visited.assign(V, 0); dfsNumberCounter = numSCC = 0; for (int i = 0; i < V; i++) if (dfs_num[i] == DFS_WHITE) tarjanSCC(i); printf("%d\n",numSCC); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ int test,dimension,manipulation, a, b; char temptrans; bool swapped[10][10]; string matrices[10], command, temp; cin>>test; for(int i=1;i<=test;i++){ cin>>dimension; for(int l=0;l<dimension;l++) for(int k=0;k<dimension;k++) swapped[l][k] = false; for(int j=0;j<dimension;j++) cin>>matrices[j]; cin>>manipulation; for(int j=0;j<manipulation;j++){ cin>>command; if(command == "row"){ cin>>a>>b; a--; b--; matrices[a].swap(matrices[b]); } else if(command == "col"){ cin>>a>>b; a--; b--; for(int k=0;k<dimension;k++){ temptrans = matrices[k].at(a); matrices[k].replace(a,1,1,matrices[k].at(b)); matrices[k].replace(b,1,1,temptrans); } } else if(command == "inc"){ for(int k=0;k<dimension;k++){ for(int l=0;l<dimension;l++){ if(matrices[k].at(l)=='9') matrices[k].replace(l,1,1,'0'); else matrices[k].at(l)++; } } } else if(command == "dec"){ for(int k=0;k<dimension;k++){ for(int l=0;l<dimension;l++){ if(matrices[k].at(l)=='0') matrices[k].replace(l,1,1,'9'); else matrices[k].at(l)--; } } } else if(command == "transpose"){ for(int k=0;k<dimension;k++){ for(int l=0;l<dimension;l++){ if(!swapped[k][l]){ temptrans = matrices[k].at(l); matrices[k].replace(l,1,1,matrices[l].at(k)); matrices[l].replace(k,1,1,temptrans); swapped[k][l] = swapped[l][k] = true; } } } for(int l=0;l<dimension;l++) for(int k=0;k<dimension;k++) swapped[l][k] = false; } } cout<<"Case #"<<i<<endl; for(int z=0;z<dimension;z++){ cout<<matrices[z]<<endl; } cout<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int testcase, max, student; int speed[100]; cin>>testcase; for(int i=1;i<=testcase;i++){ max = 0; cin>>student; for(int j=0;j<student;j++){ cin>>speed[j]; if(speed[j]>max) max = speed[j]; } cout<<"Case "<<i<<": "<<max<<endl; } return 0; }<file_sep>#include<iostream> #include<string> using namespace std; int main(void){ int test, now; int top,west,east,bot,north,south,temp; string input; while(true){ top = 1; bot = 6; west = 3; east = 4; north = 2; south = 5; cin>>test; if(test == 0) return 0; for(int i=0;i<test;i++){ cin>>input; if(input == "north"){ temp = top; top = south; south = bot; bot = north; north = temp; } else if(input == "west"){ temp = top; top = east; east = bot; bot = west; west = temp; } else if(input == "south"){ temp = top; top = north; north = bot; bot = south; south = temp; } else if(input == "east"){ temp = top; top = west; west = bot; bot = east; east = temp; } } cout<<top<<endl; } return 0; } <file_sep>import java.util.Scanner; import java.util.StringTokenizer; class Tautogram{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); StringTokenizer st; String in, s2; boolean tauto; while(true){ in = sc.nextLine(); if(in.equals("*")) break; char rem; String lower = in.toLowerCase(); st = new StringTokenizer(lower); s2 = st.nextToken(); tauto = true; rem = s2.charAt(0); while(st.hasMoreTokens()){ s2 = st.nextToken(); if(s2.charAt(0)!=rem){ tauto = false; break; } } if(tauto) System.out.println("Y"); else System.out.println("N"); } } }<file_sep>#include<iostream> using namespace std; int main(void){ int test, freq, amp; cin>>test; for(int i=0;i<test;i++){ cin>>amp>>freq; for(int j=0;j<freq;j++){ for(int k=1;k<=amp;k++){ for(int l=1;l<=k;l++){ cout<<k; } cout<<endl; } for(int k=amp-1;k>=1;k--){ for(int l=k;l>0;l--) cout<<k; cout<<endl; } if(i==test-1 && j==freq-1) continue; cout<<endl; } } return 0; } <file_sep>#include<string> #include<iostream> using namespace std; int main(void){ string input; int test, mcounter, fcounter; cin>>test; getline(cin,input); for(int i=0;i<test;i++){ getline(cin,input); mcounter = fcounter = 0; for(int j=0;j<input.length();j+=3){ if(input.at(j)=='M' && input.at(j+1)=='M') mcounter++; else if(input.at(j)=='F' && input.at(j+1) == 'F') fcounter++; } if(mcounter==fcounter && input.length()>=5) cout<<"LOOP"<<endl; else cout<<"NO LOOP"<<endl; } } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int x,y; while(cin>>x>>y){ cout<<x-1 + (y-1)*x; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<math.h> #include<stdio.h> using namespace std; int main(void){ int input; bool found; int test,a; scanf("%d",&input); for(int i=0;i<input;i++){ found = false; scanf("%d",&test); if(test%8!=7){ a = sqrt(test); for(int j=0;j<=a;j++){ for(int k=j;k<=a;k++){ for(int l=k;l<=a;l++){ if(j*j + k*k + l*l == test){ printf("%d %d %d\n",j,k,l); found = true; break; } } if(found) break; } if(found) break; } } if(!found) printf("-1\n"); } } <file_sep>import java.util.Scanner; import java.math.BigInteger; class WorldCupNoise{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int test = sc.nextInt(); BigInteger[] fib = new BigInteger[53]; fib[0] = BigInteger.ONE.add(BigInteger.ONE); fib[1] = fib[0].add(BigInteger.ONE); for(int i=2;i<=52;i++){ fib[i] = fib[i-1].add(fib[i-2]); } for(int i=1;i<=test;i++){ System.out.println("Scenario #"+i+":"); System.out.println(fib[sc.nextInt()-1]); System.out.println(); } } }<file_sep>#include<iostream> using namespace std; int main(void){ long long int year; bool isLeap, isHuluculu, isBulukulu; while(cin>>year){ isLeap = isHuluculu = isBulukulu = false; if(year%400 == 0 || (year%4==0 && year%100!=0)){ isLeap = true; cout<<"This is leap year."<<endl; } if(year%15==0){ isHuluculu = true; cout<<"This is huluculu festival year."<<endl; } if(isLeap && year%55 == 0){ isBulukulu = true; cout<<"This is bulukulu festival year."<<endl; } if(!isLeap && !isHuluculu && !isBulukulu) cout<<"This is an ordinary year."<<endl; cout<<endl; } return 0; } <file_sep>#include<stdio.h> int main(void){ int W, H, N, x1, x2, y1, y2, count, temp; int spot[500][500]; scanf("%d %d %d", &W, &H, &N); while(true){ if(W==0 && H==0 && N==0) break; for(int i=0;i<W;i++) for(int j=0;j<H;j++) spot[i][j] = 0; for(int i=0;i<N;i++){ scanf("%d %d %d %d",&x1, &y1, &x2, &y2); if(x1>x2){ temp = x1; x1 = x2; x2 = temp; } if(y1>y2){ temp = y1; y1 = y2; y2 = temp; } for(int j=x1-1;j<x2;j++) for(int k=y1-1;k<y2;k++) spot[j][k] = 1; } count = 0; for(int j=0;j<W;j++) for(int k=0;k<H;k++) if(spot[j][k] == 0) count++; if(count==0) printf("There is no empty spots.\n"); else if(count==1) printf("There is one empty spot.\n"); else printf("There are %d empty spots.\n",count); scanf("%d %d %d", &W, &H, &N); } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ long long squares[101]; squares[1] = 1; for(int i=2;i<=100;i++){ squares[i] = squares[i-1]+(int)pow(i,2); } int input; while(cin>>input && input){ cout<<squares[input]<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; long long reverse(long long); int main(void){ bool isPrime[1000001]; long long input, rev; for(int i=2;i<=1000000;i++) isPrime[i] = true; for(int i=2;i<=1000000;i++){ if(isPrime[i]){ for(int j=i+i;j<=1000000;j+=i){ isPrime[j] = false; } } } while(cin>>input){ cout<<input; rev = reverse(input); if(isPrime[input]){ if(isPrime[rev] && input!=rev) cout<<" is emirp."<<endl; else cout<<" is prime."<<endl; } else cout<<" is not prime."<<endl; } return 0; } long long reverse(long long input){ long long result = 0; while(input>0){ result = result*10 + input%10; input/=10; } return result; } <file_sep>#include<iostream> #include<vector> #include<string.h> using namespace std; string input[100]; string rule; string alpha[]={"0","1","2","3","4","5","6","7","8","9"}; void comb(int now, int num, int strnow, vector<string> v, int maximum){ if(now==maximum){ for(int i=0;i<maximum;i++) cout<<v.at(i); cout<<endl; return; } else{ if(rule.at(now)=='#'){ v.push_back(input[strnow]); comb(now+1,num,strnow,v,maximum); } else if(rule.at(now)=='0'){ for(int i=0;i<10;i++){ v.push_back(alpha[i]); comb(now+1,i+1,strnow,v,maximum); v.pop_back(); } } } } int main(void){ int test,code; bool contain; vector<string> v; while(cin>>test){ for(int i=0;i<test;i++) cin>>input[i]; cout<<"--"<<endl; cin>>code; for(int j=0;j<code;j++){ cin>>rule; contain = false; for(int k=0;k<rule.length();k++) if(rule.at(k)=='#'){ contain = true; break; } if(contain){ for(int k=0;k<test;k++){ v.clear(); comb(0,0,k,v,rule.length()); } } else comb(0,0,0,v,rule.length()); } } return 0; } <file_sep>#include<iostream> #include<string.h> #include<vector> #include<stdio.h> using namespace std; int row, col; char maze[10][10]; bool visited[10][10]; int dc[] = {-1,0,1}; int dr[] = {0,-1,0}; int loc[7]; string in = "IEHOVA#"; void floodfill(int crow, int ccol, vector<int> r, vector<int> c, int current){ if(crow<0||ccol<0||crow>=row||ccol>=col||visited[crow][ccol]) return; if(current==in.length()-1 && maze[crow][ccol]=='#'){ int rownow,colnow; rownow = r.at(0); colnow = c.at(0); for(int i=1;i<c.size()-1;i++){ if(rownow>r.at(i)) cout<<"forth "; else if(colnow<c.at(i)) cout<<"right "; else if(colnow>c.at(i)) cout<<"left "; colnow = c.at(i); rownow = r.at(i); } if(rownow>r.at(c.size()-1)) cout<<"forth"<<endl; else if(colnow<c.at(c.size()-1)) cout<<"right"<<endl; else if(colnow>c.at(c.size()-1)) cout<<"left"<<endl; return; } if(in.at(current)!=maze[crow][ccol]) return; //cout<<"IN: at"<<in.at(current)<<" I "<<crow<<" J "<<ccol<<endl; visited[crow][ccol]=true; for(int d=0;d<3;d++){ r.push_back(crow+dr[d]); c.push_back(ccol+dc[d]); floodfill(crow+dr[d],ccol+dc[d],r,c,current+1); r.pop_back(); c.pop_back(); } } int main(void){ int test; cin>>test; vector<int> r; vector<int> c; while(test--){ cin>>row>>col; getchar(); r.clear(); c.clear(); for(int i=0;i<row;i++) for(int j=0;j<col;j++){ visited[i][j]=false; } for(int i=0;i<row;i++) gets(maze[i]); for(int i=0;i<row;i++) for(int j=0;j<col;j++) if(maze[i][j]=='@'){ visited[i][j]=true; r.push_back(i); c.push_back(j); //cout<<"I "<<i<<" J "<<j<<endl; for(int d=0;d<3;d++){ r.push_back(i+dr[d]); c.push_back(j+dc[d]); floodfill(i+dr[d],j+dc[d],r,c,0); r.pop_back(); c.pop_back(); } } } return 0; } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> #include<algorithm> using namespace std; int main(void){ char input[51], remember[51]; int length; while(scanf("%s",input)){ if(input[0]=='#') return 0; length = strlen(input); strcpy(remember,input); next_permutation(input,input+length); if(strcmp(remember,input)<0) cout<<input; else cout<<"No Successor"; cout<<endl; } return 0; } <file_sep>#include<map> #include<iostream> #include<stdio.h> using namespace std; int main(void){ int N,M, num; int counter; map<int,int> cd; while(scanf("%d %d",&N,&M)){ if(N == 0 && M == 0) return 0; cd.clear(); counter = 0; for(int i=0;i<N;i++){ scanf("%d",&num); cd[num]++; } for(int i=0;i<M;i++){ scanf("%d",&num); if(cd[num]) counter++; } printf("%d\n",counter); } return 0; } <file_sep>#include <stdio.h> #include <string.h> #define MINE '@' // a mine-filled cell #define FREE '*' // a mine-free cell #define MAX_ROWS 101 // maximum rows of a minefield #define MAX_COLS 100 // maximum columns of a minefield #include<iostream> using namespace std; void scan_minefield(char [][MAX_COLS+1], int *, int *); void count_minefield(char [][MAX_COLS+1], int, int); int main(void) { char minefield[MAX_ROWS][MAX_COLS+1]; int row_size, col_size; // actual size of minefield read int counter,i,j; while(true){ scan_minefield(minefield,&row_size,&col_size); if(row_size == 0 && col_size == 0) return 0; counter=0; for(i=0;i<row_size;i++) for(j=0;j<col_size;j++) { if(minefield[i][j] == MINE) { count_minefield(minefield, i, j); counter++; } } printf("%d\n",counter); } return 0; } // To read in the minefield void scan_minefield(char mines[][MAX_COLS+1], int *row_size_p, int *col_size_p) { int r; scanf("%d %d", row_size_p, col_size_p); getchar(); // to catch the newline for (r=0; r<*row_size_p; r++) gets(mines[r]); } //To read where the minecluster is. void count_minefield(char minefield[][MAX_COLS+1], int row, int col) { int i,j; minefield[row][col]=FREE; for(i=row-1;i<=row+1;i++) for(j=col-1;j<=col+1;j++) if(minefield[i][j]==MINE) count_minefield(minefield,i,j); } <file_sep> #include<cstdio> #include<iostream> #include<cstdlib> #include<cmath> #include<string> #include<cstring> #include<vector> #include<map> #include<stack> #include<queue> #include<deque> #include<algorithm> #include<set> #include<bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define MAX_N 10010 #define LOG_TWO_N 16 class SegmentTree{ private: vi st, A; int n; int left(int p){return p<<1;} int right(int p){return (p<<1)+1;} void build(int p, int L, int R){ if(L==R) st[p] = L; else{ build(left(p), L, (L+R)/2); build(right(p), (L+R)/2+1, R); int p1 = st[left(p)], p2 = st[right(p)]; st[p] = (A[p1] <= A[p2])?p1:p2; } } int rmq(int p, int L, int R, int i, int j){ if(i>R || j<L) return -1; if(L>=i && R<=j) return st[p]; int p1 = rmq(left(p), L, (L+R)/2, i, j); int p2 = rmq(right(p), (L+R)/2+1, R, i,j); if(p1 == -1) return p2; if(p2 == -1) return p1; return (A[p1]<=A[p2]) ? p1:p2; } public: SegmentTree(const vi &_A){ A = _A; n = (int) A.size(); st.assign(4*n,0); build(1,0,n-1); } int rmq(int i, int j){ return rmq(1,0,n-1,i,j); } }; int L[4*MAX_N], E[4*MAX_N], H[MAX_N], idx; bool visited[MAX_N]; vector<vi>children; void dfs(int cur, int depth){ H[cur] = idx; E[idx] = cur; L[idx++] = depth; visited[cur] = true; //printf("now: %d\n",cur); //printf(" for(int i=0;i<(int)children[cur].size();i++){ if(!visited[children[cur][i]]) { dfs(children[cur][i], depth+1); }E[idx] = cur; L[idx++] = depth; } } void buildRMQ(){ idx = 0; memset(H,-1, sizeof H); reset(L,-1); reset(E,-1); memset(visited,false,sizeof visited); dfs(0,0); } int main(void){ //freopen("in.txt","r",stdin); int V; while(scanf("%d",&V),V){ int fr, to; children.assign(V,vi()); FOR(i,V-1){ scanf("%d %d\n",&fr,&to); children[fr].pb(to); children[to].pb(fr); } buildRMQ(); //int counter = 0; int query; scanf("%d",&query); vi _L; FOR(i,idx){ //printf("%d ",E[i]); _L.pb(L[i]); }//printf("\n"); SegmentTree st = SegmentTree(_L); /*FOR(i,idx){ printf("%d ",H[i]); }printf("\n");*/ /*FOR(i,(int)_E.size()){ REP(j,i,(int)_E.size()){ printf("%d\n",st.rmq(H[i],H[j])); } }*/ map<ii,int> mapper; FOR(i,query){ scanf("%d %d",&fr, &to); if(H[fr]>H[to]){ int temp = fr; fr = to; to = temp; } int LCA = E[st.rmq(H[fr],H[to])]; int dist = L[H[fr]] + L[H[to]] - 2*L[H[LCA]]; if(dist %2 == 0){ printf("The fleas meet at %d.\n"); }else{ printf("The fleas jump forever between %d and %d.\n"); } } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ bool found, wrong, first = true; int input, j, temp; int arr[10]; while(cin>>input && input){ if(!first) cout<<endl; first = false; found = false; for(int i=1234;i<98765;i++){ wrong = false; memset(arr,0,sizeof arr); j =i*input; if(j>98765) break; if(i<10000) arr[0] = 1; temp = i; while(temp>0){ arr[temp%10]++; temp/=10; } temp = j; if(temp<10000) arr[0]++; while(temp>0){ arr[temp%10]++; temp/=10; } for(int k=0;k<=9;k++) if(!arr[k]){ wrong = true; break; } if(!wrong){ found = true; if(j<10000) cout<<"0"; cout<<j<<" / "; if(i<10000) cout<<"0"; cout<<i<<" = "<<input<<endl; } } if(!found) cout<<"There are no solutions for "<<input<<"."<<endl; } return 0; } <file_sep>#include<string> #include<iostream> #include<math.h> #include<stdio.h> using namespace std; int main(void){ string number,result, str; int base1, base2, converted, temp; while(cin>>number>>base1>>base2){ converted = 0; for(int i=number.length()-1;i>=0;i--){ if((int)number.at(i)<58) converted+=((int)number.at(i) - 48)*pow((double)base1,number.length()-1-i); else converted+=((int)number.at(i) - 55) * pow((double)base1,number.length()-1-i); } if(converted == 0) result.insert(0,"0"); while(converted>0){ temp=converted%base2; converted/=base2; if(temp<10){ str = (char) temp+48; } else{ str = (char) temp+55; } result.insert(0,str); } if(result.length()>7) printf(" ERROR\n"); else{ for(int i=0;i<7-result.length();i++) printf(" "); cout<<result<<endl; } result.clear(); } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class BasicRemains{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String in; int base; BigInteger x,y; while(true){ base = sc.nextInt(); if(base == 0) break; in = sc.next(); x = new BigInteger(in,base); in = sc.next(); y = new BigInteger(in,base); x = x.mod(y); System.out.println(x.toString(base)); } } }<file_sep>import java.util.*; import java.math.BigInteger; class UncleJack{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger i; int n; while(true){ i = sc.nextBigInteger(); n = sc.nextInt(); if(i.compareTo(BigInteger.ZERO) == 0 && n == 0) break; i = i.pow(n); System.out.println(i); } } }<file_sep>import java.util.Scanner; import java.math.BigInteger; class Product{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger temp; while(sc.hasNextBigInteger()){ temp = sc.nextBigInteger(); temp = temp.multiply(sc.nextBigInteger()); System.out.println(temp); } } }<file_sep>#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int main(void){ int test, ages; while(scanf("%d",&test) && test){ int age[101] = {0}; for(int i=0;i<test;i++){ scanf("%d",&ages); age[ages]++; } for(int i=1;i<100;i++){ for(int j=1;j<=age[i];j++){ if(--test) printf("%d ",i); else printf("%d",i); } } printf("\n"); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ short isPrime[1000001] = {0}; for(int i=2;i<=1000000;i++){ if(isPrime[i] == 0){ for(int j=i;j<=1000000;j+=i){ isPrime[j]++; } } } int input; while(cin>>input && input){ cout<<input<<" : "<<isPrime[input]<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define EPS 1e-9 #define PI acos(-1.0) double DEG_to_RAD(double d) { return d * PI / 180.0; } double RAD_to_DEG(double r) { return r * 180.0 / PI; } struct point { double x, y; // only used if more precision is needed point() { x = y = 0.0; } // default constructor point(double _x, double _y) : x(_x), y(_y) {} // user-defined bool operator == (point other) const { return (fabs(x - other.x) < EPS && (fabs(y - other.y) < EPS)); } }; double area(const vector<point> &P) { double result = 0.0, x1, y1, x2, y2; for (int i = 0; i < (int)P.size()-1; i++) { x1 = P[i].x; x2 = P[i+1].x; y1 = P[i].y; y2 = P[i+1].y; result += (x1 * y2 - x2 * y1); } return fabs(result) / 2.0; } struct vec { double x, y; // name: `vec' is different from STL vector vec(double _x, double _y) : x(_x), y(_y) {} }; vec toVec(point a, point b) { // convert 2 points to vector a->b return vec(b.x - a.x, b.y - a.y); } double cross(vec a, vec b) { return a.x * b.y - a.y * b.x; } double cross(point p, point q, point r) { return (r.x - q.x) * (p.y - q.y) - (r.y - q.y) * (p.x - q.x); } point lineIntersectSeg(point p, point q, point A, point B) { double a = B.y - A.y; double b = A.x - B.x; double c = B.x * A.y - A.x * B.y; double u = fabs(a * p.x + b * p.y + c); double v = fabs(a * q.x + b * q.y + c); return point((p.x * v + q.x * u) / (u+v), (p.y * v + q.y * u) / (u+v)); } vector<point> cutPolygon(point a, point b, const vector<point> &Q) { vector<point> P; for (int i = 0; i < (int)Q.size(); i++) { double left1 = cross(toVec(a, b), toVec(a, Q[i])), left2 = 0; if (i != (int)Q.size()-1) left2 = cross(toVec(a, b), toVec(a, Q[i+1])); if (left1 > -EPS) P.push_back(Q[i]); // Q[i] is on the left of ab if (left1 * left2 < -EPS) // edge (Q[i], Q[i+1]) crosses line ab P.push_back(lineIntersectSeg(Q[i], Q[i+1], a, b)); } if (!P.empty() && !(P.back() == P.front())) P.push_back(P.front()); // make P's first point = P's last point return P; } int main(void){ //freopen("in.txt","r",stdin); int tc; scanf("%d",&tc); int n; vector<point> P; int x,y; TC(){ P.clear(); scanf("%d",&n); FOR(i,n){ scanf("%d %d",&x,&y); P.pb(point(x,y)); } P.pb(P[0]); reverse(P.begin(),P.end()); vector<point> Q; Q = P; //printf("%d",Q.size()); FOR(i,n){ P = cutPolygon(Q[i],Q[i+1],P); //printf("cut #%d: (%.2lf %.2lf) - (%.2lf %.2lf) %.2lf\n",i,Q[i].x,Q[i].y,Q[i+1].x,Q[i+1].y,area(P)); } printf("%.2lf\n",area(P)); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string inputmine[10]; int testcase, dimension; cin>>testcase; for(int i=0;i<testcase;i++){ int bomb[12][12] = {0}; cin>>dimension; for(int j=1;j<=dimension;j++){ cin>>inputmine[j]; for(int k=0;k<inputmine.length();k++) if(inputmine[j].at(k)=='*'){ for(int x=j-1;x<=j+1;x++) for(int y=) } } } return 0; } <file_sep>import java.math.BigInteger; import java.util.Scanner; class BigMod{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger B, P, M; while(sc.hasNextBigInteger()){ B = sc.nextBigInteger(); P = sc.nextBigInteger(); M = sc.nextBigInteger(); System.out.println(B.modPow(P,M)); } } }<file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int extended_euclid(int a, int b, int &x, int &y) { int xx = y = 0; int yy = x = 1; while (b) { int q = a/b; int t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y-q*yy; y = t; } return a; } int main(void){ //freopen("in.txt","r",stdin); int a,b,x,y; while(scanf("%d %d",&a,&b)!=EOF){ int d = extended_euclid(a,b,x,y); printf("%d %d %d\n",x,y,d); } return 0; } <file_sep>#include<map> #include<iostream> using namespace std; int main(void){ map<string, int> chord; string note1, note2, note3; int interval1, interval2; chord["C"] = chord["B#"] = chord["c"] = chord["b#"]= 0; chord["c#"] = chord["db"] = chord["C#"] = chord["Db"] = 1; chord["d"] = chord["D"] = 2; chord["D#"] = chord["Eb"] = chord["d#"] = chord["eb"]= 3; chord["E"] = chord["Fb"] = chord["e"] = chord["fb"] = 4; chord["f"] = chord["e#"]= chord["F"] = chord["E#"] = 5; chord["F#"] = chord["Gb"] = chord["f#"] = chord["gb"]= 6; chord["G"] = chord["G"] = 7; chord["g#"] = chord["ab"] = chord["G#"] = chord["Ab"] = 8; chord["a"] = chord["A"] = 9; chord["A#"] = chord["Bb"] = chord["a#"] = chord["bb"]= 10; chord["b"] = chord["cb"] = chord["B"] = chord["Cb"] = 11; while(cin>>note1>>note2>>note3){ if(chord[note1]>chord[note2]) interval1 = chord[note1] - chord[note2]; else interval1 = chord[note2] - chord[note1]; if(chord[note2]>chord[note3]) interval2 = chord[note2] - chord[note3]; else interval2 = chord[note3] - chord[note2]; if((interval1 == 4 && interval2 == 3)|| (interval1 == 3 && interal2 == 7) || (interval1 == )) } return 0; } <file_sep>#include<stdio.h> int main(void){ int a,b,c,d,e; bool first = true; while(scanf("%d %d %d %d %d",&a,&b,&c,&d,&e) && (a||b||c||d||e)){ printf("%lld\n",a*b*c*d*e*d*e); } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class isLeapYear{ public static void main(String[] args){ BigInteger year; boolean isLeap, isHuluculu, isBulukulu, first = true; Scanner sc = new Scanner(System.in); while(sc.hasNext()){ if(!first) System.out.println(); first = false; isLeap = false; isHuluculu = false; isBulukulu = false; year = sc.nextBigInteger(); if(year.mod(BigInteger.valueOf(400)).compareTo(BigInteger.ZERO) == 0 || (year.mod(BigInteger.valueOf(4)).compareTo(BigInteger.ZERO) == 0 && year.mod(BigInteger.valueOf(100)).compareTo(BigInteger.ZERO) != 0)){ isLeap = true; System.out.println("This is leap year."); } if(year.mod(BigInteger.valueOf(15)).compareTo(BigInteger.ZERO) == 0){ isHuluculu = true; System.out.println("This is huluculu festival year."); } if(isLeap && year.mod(BigInteger.valueOf(55)).compareTo(BigInteger.ZERO) == 0){ isBulukulu = true; System.out.println("This is bulukulu festival year."); } if(!isLeap && !isHuluculu && !isBulukulu) System.out.println("This is an ordinary year."); } } }<file_sep>#include<iostream> #include<map> using namespace std; int main(void){ long long first, counter, casecounter; long long z,i,m,l; map<int, int> aftermod; casecounter = 1; while(cin>>z>>i>>m>>l && (z||m||i||l)){ aftermod.clear(); counter = 1; aftermod[l]=counter++; while(true){ l = z*l+i; l=l%m; if(!aftermod[l]) aftermod[l] = counter++; else break; } cout<<"Case "<<casecounter<<": "<<counter-aftermod[l]<<endl; casecounter++; } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ int n,testcase; double result; cin>>testcase; for(int i=0;i<testcase;i++){ cin>>n; result = 0; for(int j=1;j<=n;j++) result+= log10((double) j); cout<<(int)floor(result+1)<<endl; } return 0; } <file_sep>#include <iostream> using namespace std; int main () { longint i, j, result; while(cin >> i >> j) { result = 0; if(i<j) result=j-i; else result = i-j; cout<<result<<endl; } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ int stop; string card1,card2,card3,card4,card5,card6,card7,card8,card9,card10,card11,card12,card13; while(scanf("%s %s %s %s %s %s %s %s %s %s %s %s %s",ca)) return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<algorithm> #include<vector> #include<queue> using namespace std; typedef vector<int> vi; int main(void){ vector<vi> AdjList; int n,m; int flag[30000]; int sus[30000]; while(cin>>n>>m &&(n || m)){ AdjList.assign(n,vi()); for(int i=0;i<n;i++) flag[i] = 0; for(int i=0;i<m;i++){ int k; cin>>k; for(int j=0;j<k;j++) cin>>sus[j]; for(int j=0;j<k;j++){ int temp = sus[0]; sus[0] = sus[j]; sus[j] = temp; for(int l=1;l<k;l++){ AdjList[sus[0]].push_back(sus[l]); } } } int counter = 0; queue<int> q; q.push(0); while(!q.empty()){ int u = q.front(); q.pop(); if(!flag[u]){ for(int j=0;j<(int)AdjList[u].size();j++){ if(!flag[AdjList[u][j]]){ q.push(AdjList[u][j]); } } flag[u] = 1; counter++; } } printf("%d\n",counter); } return 0; } <file_sep>#include<iostream> #include<algorithm> #include<map> #include<vector> using namespace std; int main(void){ int temp[5]; map<vector<int>,int> fav; int input, max, num,test; while(cin>>input){ max = 0; vector<int> v; if(!input) return 0; else{ fav.clear(); for(int i=0;i<input;i++){ v.clear(); for(int j=0;j<5;j++){ cin>>test; v.push_back(test); } sort(v.begin(),v.end()); fav[v]++; if(fav[v]>max) max = fav[v]; } num = 0; for(map<vector<int>,int>::iterator it = fav.begin();it!=fav.end();it++) if(max==it->second) num+=max; cout<<num<<endl; } } return 0; } <file_sep>#include<iostream> using namespace std; void mergesort(int [], int, int); void merge(int [], int, int, int); long long swapz; int main(void){ int length, train[1000001]; int test, temp; bool is_sorted; while(cin>>length){ swapz = 0; for(int j=0;j<length;j++) cin>>train[j]; mergesort(train, 0, length-1); cout<<swapz<<endl; } return 0; } void mergesort(int a[], int i, int j) { if (i < j) { int mid = (i+j)/2; mergesort(a, i, mid); mergesort(a, mid+1, j); merge(a,i,mid,j); } } void merge(int a[], int i, int mid, int j) { int temp[j-i+1]; int left = i, right = mid+1, it = 0; while (left<=mid && right<=j) { if (a[left] <= a[right]){ temp[it++] = a[left++]; } else{ swapz+=mid-left+1; temp[it++] = a[right++]; } } while (left<=mid){ temp[it++] = a[left++]; } while (right<=j) temp[it++] = a[right++]; for (int k = 0;k < j-i+1; k++) a[i+k] = temp[k]; } <file_sep>#include<iostream> #include<vector> #include<math.h> #include<algorithm> using namespace std; int main() { long long int a,b=0,c,i,j,k,l; vector<long long int>v; for(i=0;i<=31;i++){ for(j=0;j<=31;j++){ for(k=0;k<=31;k++){ for(l=0;l<=31;l++){ a=pow(2,l)*pow(3,k)*pow(5,j)*pow(7,i); if(a>0) v.push_back(a); } } } } sort(v.begin(),v.end()); while(cin>>a){ b++; if(a==0) break; cout<<"The "<<a; if(a%100==11 || a%100==12 || a%100==13) cout<<"th "; else if(((a%100)/10)==1) cout<<"th "; else if((a%10)==1) cout<<"st "; else if((a%10)==2) cout<<"nd "; else if((a%10)==3) cout<<"rd "; else cout<<"th "; cout<<"humble number is "<<v[a-1]<<"."<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <sstream> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define DFS_WHITE -1 vi dfs_low, dfs_num; // ARTICULATION POINT/BRIDGE/STRONGLYCONNECTEDCOMPONENTS vi articulation_vertex; vi dfs_parent; vector<vi> AdjList; int dfsNumberCounter, dfsRoot, rootChildren; void articulationPointAndBridge(int u) { dfs_low[u] = dfs_num[u] = dfsNumberCounter++; // dfs_low[u] <= dfs_num[u] for (int j = 0; j < (int)AdjList[u].size(); j++) { int v = AdjList[u][j]; if (dfs_num[v] == DFS_WHITE) { // a tree edge dfs_parent[v] = u; if (u == dfsRoot) rootChildren++; // special case, count children of root articulationPointAndBridge(v); if (dfs_low[v] >= dfs_num[u]) // articulation point articulation_vertex[u] = 1; // store this information first if (dfs_low[v] > dfs_num[u]) // for bridge //printf(" Edge (%d, %d) is a bridge\n", u, v); dfs_low[u] = min(dfs_low[u], dfs_low[v]); // update dfs_low[u] } else if (v != dfs_parent[u]) // a back edge and not direct cycle dfs_low[u] = min(dfs_low[u], dfs_num[v]); // update dfs_low[u] } } int main(void){ //freopen("in.txt","r",stdin); int n; string str; vi num; while(scanf("%d",&n),n){ getline(cin,str); AdjList.assign(n,vi()); while(getline(cin,str)){ num.clear(); stringstream ss(str); int n; while(ss>>n){ num.pb(n-1); } if(num[0] == -1)break; REP(i,1,num.size()){ AdjList[num[0]].pb(num[i]); AdjList[num[i]].pb(num[0]); } } dfsNumberCounter = 0;dfs_num.assign(n,-1); dfs_low.assign(n, 0); dfs_parent.assign(n, -1); articulation_vertex.assign(n, 0); dfsRoot = 0;rootChildren = 0; articulationPointAndBridge(0); articulation_vertex[0] = (rootChildren > 1)?1:0; int counter = 0; for (int i = 0; i < n; i++) if (articulation_vertex[i] == 1) counter++; printf("%d\n",counter); } return 0; } <file_sep>#include<iostream> #include<map> #include<stdio.h> #include<queue> #include<stdlib.h> using namespace std; int main(void){ int from[4],to[4],temp[4]; int dr[]={1,-1}; int forbidden,num,value,toz; map<int,int>forbid; int test,ori; scanf("%d",&test); while(test--){ for(int i=0;i<4;i++) scanf("%d",&from[i]); for(int i=0;i<4;i++) scanf("%d",&to[i]); scanf("%d",&forbidden); forbid.clear(); for(int i=0;i<forbidden;i++){ value = 0; for(int j=0;j<4;j++){ scanf("%d",&num); value = value*10 + num; } forbid[value]=1; } if(from[0]==to[0] && from[1]==to[1] && from[2] == to[2] && from[3] == to[3]) printf("0\n"); else{ map<int,int>dist; dist.clear(); toz = to[0]*1000 + to[1]*100 + to[2]*10 + to[3]; value = from[0]*1000+from[1]*100+from[2]*10+from[3]; dist[value] = 1; queue<int> n1;n1.push(from[0]); queue<int> n2;n2.push(from[1]); queue<int> n3;n3.push(from[2]); queue<int> n4;n4.push(from[3]); while(!n1.empty()){ from[0] = n1.front();n1.pop(); from[1] = n2.front();n2.pop(); from[2] = n3.front();n3.pop(); from[3] = n4.front();n4.pop(); ori = from[0]*1000 + from[1]*100 + from[2]*10 + from[3]; for(int m=0;m<4;m++) temp[m]=from[m]; for(int i=0;i<4;i++){ for(int j=0;j<2;j++){ from[i]+=dr[j]; if(from[i]>9) from[i]=0; else if(from[i]<0) from[i]=9; value = 0; for(int k=0;k<4;k++){ value*=10; value+=from[k]; } if(!forbid[value] && !dist[value]){ dist[value]=dist[ori]+1; n1.push(from[0]); n2.push(from[1]); n3.push(from[2]); n4.push(from[3]); } from[i]=temp[i]; } } if(dist[toz]) break; } if(dist[toz]) printf("%d\n",dist[toz]-1); else printf("-1\n"); } } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string input; int group, length; while(cin>>group && group){ cin>>input; length = input.length()/group; for(int i=0;i<group;i++){ for(int j=length-1;j>=0;j--) cout<<input.at(i*length+j); } cout<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<vector> #include<map> #include<queue> #define INF 10000000 using namespace std; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector<ii> vii; int main(void){ int tc,N,counter,edge,len,from,to,realfrom,realto; map<int,int> mapper; cin>>tc; vector<vii> AdjList; for(int z=1;z<=tc;z++){ mapper.clear(); counter = 0; cin>>N>>edge>>realfrom>>realto; AdjList.assign(N,vii()); vi dist(N,INF); for(int i=0;i<edge;i++){ cin>>from>>to>>len; if(mapper.find(from)==mapper.end()) mapper[from] = counter++; if(mapper.find(to) == mapper.end()) mapper[to] = counter++; AdjList[mapper[from]].push_back(ii(mapper[to],len)); AdjList[mapper[to]].push_back(ii(mapper[from],len)); } int s; s = mapper[realfrom]; dist[s] = 0; priority_queue< ii, vector<ii>, greater<ii> > pq; pq.push(ii(0, s)); while(!pq.empty()){ ii front = pq.top(); pq.pop(); int d = front.first; int u = front.second; if(d == dist[u]){ for(int j=0;j<(int)AdjList[u].size();j++){ ii v = AdjList[u][j]; if(dist[u] + v.second < dist[v.first]){ dist[v.first] = dist[u] + v.second; pq.push(ii(dist[v.first], v.first)); } } } } printf("Case #%d: ",z); if(dist[mapper[realto]]==INF || edge == 0) printf("unreachable\n"); else printf("%d\n",dist[mapper[realto]]); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int test; int start, finish; int sum; cin>>test; for(int i=1;i<=test;i++){ cin>>start>>finish; sum = 0; if(start%2==0) start++; for(int j=start;j<=finish;j+=2) sum+=j; cout<<"Case "<<i<<": "<<sum<<endl; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define reset(a,b) memset(a,b,sizeof(a)) ll _sieve_size; bitset<100010> bs; // 10^7 should be enough for most cases vi primes; void sieve(ll upperbound) { _sieve_size = upperbound + 1; bs.set(); // set all bits to 1 bs[0] = bs[1] = 0; for (ll i = 2; i <= _sieve_size; i++) if (bs[i]) { for (ll j = i * i; j <= _sieve_size; j += i) bs[j] = 0; primes.push_back((int)i); } } ll numDiv(ll N) { //50 ==> 1, 2, 5, 10, 25, 50, 6 divisors ll PF_idx = 0, PF = primes[PF_idx], ans = 1; // start from ans = 1 while (N != 1 && (PF * PF <= N)) { ll power = 0; // count the power while (N % PF == 0) { N /= PF; power++; } ans *= (power + 1); // according to the formula PF = primes[++PF_idx]; } if (N != 1) ans *= 2; // (last factor has pow = 1, we add 1 to it) return ans; } bool isPrime(ll N) { if (N <= _sieve_size) return bs[N]; for (int i = 0; i < (int)primes.size(); i++) if (N % primes[i] == 0) return false; return true; // it takes longer time if N is a large prime! } int main(void){ //freopen("in.txt","r",stdin); int tc; bool arr[11010]; int arr2[11010]; reset(arr,false); reset(arr2,0); sieve(10000); scanf("%d",&tc); for(int i=2;i<=10000;i++){ if(isPrime(numDiv(ll(i)))){ arr[i] = true; arr2[i] = 1; } arr2[i] += arr2[i-1]; } //while(true){} vector<int> v; TC(){ v.clear(); int L,H; scanf("%d %d",&L,&H); if(L > H){ int temp = H; H = L; L = temp; } if(L == 0){ if(arr2[H] == 0) printf("-1\n"); else{ //vector<int> v; for(int i=L;i<=H;i++){ if(arr[i]){ v.push_back(i); } } for(int i=0;i<v.size()-1;i++){ printf("%d ",v[i]); }printf("%d\n",v[v.size()-1]); } }else{ //printf("%d %d\n",H,L); if((arr2[H] - arr2[L-1])>0){ //vector<int> v; //printf("asdf"); for(int i=L;i<=H;i++){ if(arr[i]){ v.push_back(i); } } for(int i=0;i<v.size()-1;i++){ printf("%d ",v[i]); }printf("%d\n",v[v.size()-1]); }else printf("-1\n"); } } return 0; } <file_sep>#include<map> #include<iostream> using namespace std; int main(void){ int test,pair,pair2,max,counter; cin>>test; map<string,string> party; map<string,int> vote; string name, par,remember; for(int i=0;i<test;i++){ cin>>pair; getline(cin,name); party.clear(); vote.clear(); for(int j=0;j<pair;j++){ getline(cin,name); getline(cin,par); party[name]=par; } cin>>pair2; getline(cin,name); for(int j=0;j<pair2;j++){ getline(cin,name); if(party.find(name)!=party.end()){ vote[name]++; } } max = 0; for(map<string,int>::iterator it=vote.begin();it!=vote.end();it++){ if(it->second>max) max = it->second; } counter = 0; for(map<string,int>::iterator it=vote.begin();it!=vote.end();it++){ if(it->second==max){ counter++; remember = party[it->first]; if(counter>1){ remember = "tie"; break; } } } cout<<remember<<endl; if(i!=test-1) cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string> #include<stdio.h> using namespace std; int main(void){ string name[2]; int length[2],number; double ratio; int value[2]; while(getline(cin,name[0]) && getline(cin,name[1])){ for(int j=0;j<2;j++){ value[j] = 0; length[j] = name[j].length(); for(int i=0;i<length[j];i++){ if((int)name[j].at(i)>=97 && (int)name[j].at(i)<=122) value[j] += (int)name[j].at(i) - 96; else if((int)name[j].at(i)>=65 && (int)name[j].at(i)<=90) value[j] += (int)name[j].at(i) - 64; } while(value[j]>9){ number = 0; while(value[j]>0){ number+= value[j]%10; value[j]/=10; } value[j] = number; } } if(value[0] == value[1] && value[1] == 0) printf("0.00 %%\n"); else{ if(value[0]<value[1]) ratio = 100.0*value[0]/value[1]; else ratio = 100.0*value[1]/value[0]; printf("%.2f %%\n",ratio); } } return 0; } <file_sep>#include<string> #include<iostream> #include<stdio.h> using namespace std; int main(void){ int activity, remember,time1,time2,h1,m1,h2,m2; int counter = 1; int longest,rememberstart, rememberend, rememberstarttemp,longtemp, timeh,timem; string dummy; int h,m, count; bool busy; while(cin>>activity){ int sleep[480]; for(int i=0;i<480;i++) sleep[i] = 0; for(int i=0;i<activity;i++){ scanf("%d:%d %d:%d",&h1,&m1,&h2,&m2); getline(cin,dummy); time1 = h1*60 + m1 - 600; time2 = h2*60 + m2 - 600; for(int i=time1;i<time2;i++) sleep[i] = 1; } count = 0; longest = 0; rememberstart = 0; rememberstarttemp = 0; busy = true; for(int i=0;i<480;i++){ if(busy && sleep[i]==0){ busy = false; rememberstarttemp = i; count = 1; } else if(!busy && sleep[i]==1){ busy = true; if(longest<i - rememberstarttemp){ longest = i - rememberstarttemp; rememberstart = rememberstarttemp; } count = 0; } else count++; } if(!busy){ if(longest< count){ longest = count; rememberstart = rememberstarttemp; } } cout<<"Day #"<<counter<<": the longest nap starts at "; h = longest/60; m = longest%60; timeh = (rememberstart+600)/60; timem = (rememberstart+600)%60; cout<<timeh<<":"; if(timem<10) cout<<"0"; cout<<timem<<" and will last for"; if(h>0) cout<<" "<<h<<" hours and"; cout<<" "<<m<<" minutes."<<endl; counter++; } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class RayThroughGlasses{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger[] fib = new BigInteger[1001]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE.add(BigInteger.ONE); for(int i=2;i<=1000;i++){ fib[i] = fib[i-1].add(fib[i-2]); } while(sc.hasNext()){ System.out.println(fib[sc.nextInt()]); } } }<file_sep>#include<string> #include<iostream> using namespace std; int main(void){ int testcase,numX, numO; string tic; cin>>testcase; for(int i=0;i<testcase;i++){ numX = numO = 0; for(int j=0;j<3;j++){ cin>>tic; for(int k=0;k<tic.length();k++){ if(tic.at(k) == 'X') numX++; else if(tic.at(k) == 'O') numO++; } } if(numX == numO || numX-1 == numO) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; } <file_sep>#include<iostream> #include<math.h> #include<stdio.h> using namespace std; int main(void){ double test; int testcase; scanf("%d",&testcase); while(testcase--){ scanf("%lf",&test); printf("%.0lf\n",floor((-1+pow(1+4*2*test,1/2.0))/2)); } return 0; } <file_sep>#include<stdio.h> int main(void){ int test, h,w,l; scanf("%d",&test); for(int i=1;i<=test;i++){ scanf("%d %d %d",&h,&w,&l); printf("Case %d: ",i); if(h<=20 && w<=20 && l<=20) printf("good\n"); else printf("bad\n"); } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int testcase,num,test; cin>>testcase; for(int i=0;i<testcase;i++){ short a[1000000] = {0}; cin>>num; for(int j=1;j<=num;j++){ cin>>a[j]>>test; a[j]+=test; } for(int j=num;j>0;j--){ a[j-1]+=a[j]/10; a[j] = a[j]%10; } if(a[0]==1) cout<<"1"; for(int j=1;j<=num;j++) cout<<a[j]; cout<<endl; if(i!=testcase-1) cout<<endl; } return 0; } <file_sep>#include<string> #include<iostream> using namespace std; int main(void){ int min, numofsurface, sum; string surface[13]; string dummy; int gap[13]; while(true){ cin>>numofsurface; if(numofsurface == 0) break; min = 26; sum = 0; getline(cin,dummy); for(int i=0;i<numofsurface;i++){ getline(cin,surface[i]); gap[i] = 0; for(int j=0;j<surface[i].length();j++){ if(surface[i].at(j) == ' ') gap[i]++; } if(gap[i]<min) min = gap[i]; } for(int i=0;i<numofsurface;i++) sum+= (gap[i]-min); cout<<sum<<endl; } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; char convert(char); int main(void){ string decodes; while(getline(cin,decodes)){ for(int i=0;i<decodes.length();i++){ cout<<convert(decodes.at(i)); } cout<<endl; } return 0; } char convert(char decode){ int asciivalue; asciivalue = (int) decode - 7; return (char) asciivalue; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ bool found = false; for(int i=1;i<=50000;i++){ found = false; for(int j=0;j<i;j++){ for(int k=j;k<i;k++){ for(int l=k;l<i;l++){ if(j*j*j + k*k*k + l*l*l == i*i*i){ cout<<j<<" "<<k<<" "<<l; found = true; break; } } if(found) break; } if(found) break; } if(!found) cout<<"-1"; cout<<","; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ //freopen("D:/Code/in.txt","r",stdin); int n, m, t; scanf("%d %d %d",&n,&t,&m); int submission[105][14]; reset(submission,-1); char prob[3]; char verdict[5]; ii soln[20]; int time, id; int probnumber; FOR(i,n) soln[i] = ii(-1,-1); FOR(i,m){ scanf("%d %d %s %s",&time,&id,prob,verdict); probnumber = prob[0]-'A'; if(verdict[0] == 'N' || submission[id][probnumber] != -1)continue; //probnumber = prob[0]-'A'; submission[id][probnumber] = time; soln[probnumber] = ii(time,id); } FOR(i,n){ printf("%c ",'A'+i); if(soln[i].first == -1)printf("- -\n"); else printf("%d %d\n",soln[i].first,soln[i].second); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<vector> #include<map> #include<queue> #include<algorithm> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; map<int, int> mapper; vector<vii> AdjList; map<int,int> dist; int main(void){ int test, P, D,counter,a,b; scanf("%d",&test); while(test--){ counter = 0; scanf("%d %d",&P,&D); mapper.clear(); AdjList.assign(P,vii()); for(int i=0;i<D;i++){ scanf("%d %d",&a,&b); if (mapper.find(b) == mapper.end()) mapper[b] = counter++; if(mapper.find(a) == mapper.end()) mapper[a] = counter++; AdjList[mapper[a]].push_back(ii(mapper[b], 0)); AdjList[mapper[b]].push_back(ii(mapper[a], 0)); } dist.clear(); queue<int> q;q.push(mapper[0]); dist[mapper[0]] = 1; while (!q.empty()) { int u = q.front(); q.pop(); for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (!dist.count(v.first)) { dist[v.first] = dist[u] + 1; //printf("%d%d\n",dist[to],dist[x]); q.push(v.first); } } } for(int i=1;i<P;i++){ printf("%d\n",dist[mapper[i]]-1); } if(test) printf("\n"); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) struct edge { int a, b, f, c; int ind; }; const int inf = 1000 * 1000 * 1000; const int MAXN = 1050; int n, m; vector <edge> e; int pt[MAXN]; // very important performance trick vector <int> g[MAXN]; long long flow = 0; queue <int> q; int d[MAXN]; int lim; void add_edge(int a, int b, int c, int ind) { edge ed; //keep edges in vector: e[ind] - direct edge, e[ind ^ 1] - back edge ed.a = a; ed.b = b; ed.f = 0; ed.c = c; ed.ind = ind; g[a].push_back(e.size()); e.push_back(ed); ed.a = b; ed.b = a; ed.f = c; ed.c = c; ed.ind = ind; g[b].push_back(e.size()); e.push_back(ed); } bool bfs() { for (int i = 1; i <= n; i++) d[i] = inf; d[1] = 0; q.push(1); while (!q.empty() && d[n] == inf) { int cur = q.front(); q.pop(); for (size_t i = 0; i < g[cur].size(); i++) { int id = g[cur][i]; int to = e[id].b; //printf("cur = %d id = %d a = %d b = %d f = %d c = %d\n", cur, id, e[id].a, e[id].b, e[id].f, e[id].c); if (d[to] == inf && e[id].c - e[id].f >= lim) { d[to] = d[cur] + 1; q.push(to); } } } while (!q.empty()) q.pop(); return d[n] != inf; } bool dfs(int v, int flow) { if (flow == 0) return false; if (v == n) { //cout << v << endl; return true; } for (; pt[v] < g[v].size(); pt[v]++) { int id = g[v][pt[v]]; int to = e[id].b; //printf("v = %d id = %d a = %d b = %d f = %d c = %d\n", v, id, e[id].a, e[id].b, e[id].f, e[id].c); if (d[to] == d[v] + 1 && e[id].c - e[id].f >= flow) { int pushed = dfs(to, flow); if (pushed) { e[id].f += flow; e[id ^ 1].f -= flow; return true; } } } return false; } void dinic() { for (lim = (1 << 30); lim >= 1;) { if (!bfs()) { lim >>= 1; continue; } for (int i = 1; i <= n; i++) pt[i] = 0; int pushed; while (pushed = dfs(1, lim)) { flow = flow + lim; } //cout << flow << endl; } } int main(void){ int a,b; int water,dari[100],sampe[100]; while(scanf("%d",&a)&&a){ scanf("%d",&b); int mini, maxi; mini = INF; maxi = -1; FOR(i,a){ scanf("%d %d %d",&water,&dari[i],&sampe[i]); maxi = max(sampe[i],maxi); mini = min(mini,dari[i]); add_edge(i*2,i*2+1,water,i); } int cur = a*2; int time0 = cur; REP(i,mini,maxi){ add_edge(cur,cur+1,m,i); cur+=2; } int ctr = 0; REPN(i,mini+1,maxi){ add_edge(time0+ctr,cur+1,INF,i); ctr++; } FOR(i,a){ REP(j,dari[i],sampe[i]){ add_edge(i*2+1,dari[i]-mini+time0,1,i); } } dinic(); cout<<flow<<endl; } } <file_sep>#include<map> #include<iostream> using namespace std; int main(void){ map<char,int> actual; map<char,int> decoded; map<char,char> key; map<char,int>::iterator rem, rem1; int input, max; string input1; cin>>input; getline(cin,input1); for(int i=0;i<input;i++){ actual.clear(); decoded.clear(); key.clear(); getline(cin,input1); getline(cin,input1); for(int j=0;j<input1.length();j++) actual[input1.at(j)]++; getline(cin,input1); for(int j=0;j<input1.length();j++) decoded[input1.at(j)]++; max = 1; while(max!=0){ max = 0; for(map<char,int>::iterator it = actual.begin();it!=actual.end();it++) if(it->second > max){ max = it->second; rem = it; } for(map<char,int>::iterator it = decoded.begin();it!=decoded.end();it++) if(it->second > max){ max = it->second; rem1 = it; } key[rem1->first] = rem->first; rem->second = -1; rem1->second = -1; } for(int j=0;j<input1.length();j++) cout<<key[input1.at(j)]; cout<<endl; if(i!=input-1) cout<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int length, train[1001]; int test, swap,temp; bool is_sorted; while(cin>>length){ swap = 0; for(int j=0;j<length;j++) cin>>train[j]; for (int k = 1; k < length; k++) { is_sorted = true; for (int j = 0; j < length-k; j++) { if (train[j] > train[j+1]) { temp = train[j]; train[j] = train[j+1]; train[j+1] = temp; is_sorted = false; swap++; } } if (is_sorted) break; } cout<<"Minimum exchange operations : "<<swap<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int test,student,score[100001],max, temp, min[100001]; scanf("%d",&test); for(int i=0;i<test;i++){ scanf("%d",&student); max = -10000000; for(int j=0;j<student;j++) scanf("%d",&score[j]); min[student-1]=score[student-1]; for(int j=student-2;j>0;j--) if(score[j]<min[j+1]) min[j]=score[j]; else min[j]=min[j+1]; for(int j=0;j<student-1;j++) if(max<score[j]-min[j+1]) max = score[j]-min[j+1]; printf("%d\n",max); } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int input,station[1422]; bool possible; while(cin>>input && input){ possible = true; for(int i=0;i<input;i++){ cin>>station[i]; } station[input] = 1422; sort(station,station+input); for(int i=0;i<input-1;i++){ if(station[i+1]-station[i]>200){ possible = false; break; } } if(possible && (1422-station[input-1])*2<=200){ cout<<"POSSIBLE"<<endl; } else cout<<"IMPOSSIBLE"<<endl; } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class SummationofPolynomials{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger[] num = new BigInteger[50000]; int input; num[0] = BigInteger.ONE; for(int i=2;i<=50000;i++){ num[i-1] = num[i-2].add(BigInteger.valueOf(i).pow(3)); } while(sc.hasNext()){ input = sc.nextInt(); System.out.println(num[input-1]); } } }<file_sep>#include<iostream> using namespace std; int main(void){ int row[10000], col[10000]; int rowA, colA, R,C,participant, poss, counter = 1; while(cin>>R>>C>>participant && R && C && participant){ for(int i=0;i<R;i++) row[i] = 0; for(int i=0;i<C;i++) col[i] = 0; for(int i=0;i<participant;i++){ cin>>rowA>>colA; row[rowA] = 1; col[colA] = 1; } poss = 0; cin>>rowA>>colA; if(row[rowA] == 0 && col[colA] == 0) poss++; else if(rowA!=0 && row[rowA-1] == 0 && col[colA]==0) poss++; else if(rowA!=R-1 && row[rowA+1] == 0 && col[colA]==0) poss++; else if(colA!=0 && row[rowA] == 0 && col[colA-1]==0) poss++; else if(colA!=C-1 && row[rowA] == 0 && col[colA+1]==0) poss++; cout<<"Case "<<counter<<": "; if(poss){ cout<<"Escaped again! More 2D grid problems!"<<endl; } else cout<<"Party time! Let's find a restaurant!"<<endl; counter++; } return 0; } <file_sep>#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; bool isPrime[33001]; int main(void){ int input, counter,mustfind,remember,count1; bool found; for(int i=2;i<=33000;i++) isPrime[i] = true; for(int i=2;i<=33000;i++){ if(isPrime[i]){ for(int j=i+i;j<=33000;j+=i) isPrime[j]=false; } } while(cin>>input && input){ found = false; count1 = 0; counter = 0; for(int i=2;i<=input;i++){ if(isPrime[i] && isPrime[input - i] && i>=input-i){ counter++; } } printf("%d\n",counter); } return 0; } <file_sep>import java.util.Scanner; class KindergartenCounting{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); boolean found; int counter; while(sc.hasNext()){ String input = sc.nextLine(); counter = 0; found = false; for(int i=0;i<input.length();i++){ if(((int)input.charAt(i) >=65 && (int)input.charAt(i) <=90) || ((int)input.charAt(i) >=97 && (int)input.charAt(i) <=122)){ if(!found){ counter++; found = true; } } else found = false; } System.out.println(counter); } } } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> #include<map> using namespace std; int main(void){ int test,row,col,startr,startc,length,face; map<int,char> mapper; mapper[0]='N'; mapper[1]='E'; mapper[2]='S'; mapper[3]='W'; int dr[]={-1,0,1,0}; int dc[]={0,1,0,-1}; char input[62][62]; bool end; char in[1000]; scanf("%d",&test); while(test--){ scanf("%d %d",&row,&col); getchar(); for(int i=0;i<row;i++) gets(input[i]); scanf("%d %d",&startr,&startc); end = false; startr--; startc--; getchar(); face = 0; while(true){ gets(in); length = strlen(in); for(int i=0;i<length;i++){ switch(in[i]){ case 'Q': end = true; break; case 'R':{ face++; if(face==4) face = 0; break; } case 'L':{ face--; if(face==-1) face = 3; break; } case 'F':{ if(input[startr+dr[face]][startc+dc[face]]!='*'){ startr+=dr[face]; startc+=dc[face]; } } } if(end) break; } if(end) break; } printf("%d %d %c\n",startr+1,startc+1,mapper[face]); if(test) printf("\n"); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ //freopen("D:/Code/in.txt","r",stdin); int tc; int arr[100]; int casecounter = 1; sc(tc); map<int,char> mapper; int now; char command[100010]; mapper[0] = '0'; mapper[1] = '1'; mapper[2] = '2'; mapper[3] = '3'; mapper[4] = '4'; mapper[5] = '5'; mapper[6] = '6'; mapper[7] = '7'; mapper[8] = '8'; mapper[9] = '9'; mapper[10] = 'A'; mapper[11] = 'B'; mapper[12] = 'C'; mapper[13] = 'D'; mapper[14] = 'E'; mapper[15] = 'F'; TC(){ now = 0; reset(arr,0); scanf("%s",command); int length = strlen(command); FOR(i,length){ switch(command[i]){ case '+':{ arr[now]++; arr[now] = arr[now]%256; break; } case '-':{ arr[now]--; if(arr[now] < 0) arr[now] = 255; break; } case '<':{ now--; if(now < 0) now = 99; break; } case '>':{ now++; now = now%100; break; } } } printf("Case %d:",casecounter++); int rem; FOR(i,100){ printf(" "); if(arr[i] == 0)printf("00"); else if(arr[i]<16){ rem = arr[i]%16; printf("0%c",mapper[rem]); } else{ stack<char> st; while(arr[i]>0){ rem = arr[i]%16; arr[i]/=16; st.push(mapper[rem]); } while(!st.empty()){ printf("%c",st.top()); st.pop(); } } } printf("\n"); } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ int testcase, salary, tax; cin>>testcase; for(int i=1;i<=testcase;i++){ tax = 0; cin>>salary; if(salary>=1180000){ tax = 150000; tax+=ceil((double)(salary-1180000)/4.0); } else if(salary>=880000){ tax = 90000; tax+=ceil((double)(salary-880000)/5.0); } else if(salary>=480000){ tax = 30000; tax+=ceil((double)(salary-480000)*3.0/20); } else if(salary>180000){ tax=ceil((double)(salary-180000)/10.0); if(tax<2000) tax = 2000; } cout<<"Case "<<i<<": "<<tax<<endl; } return 0; } <file_sep>#include <stdio.h> #include <string.h> #define MINE '*' // a mine-filled cell #define FREE '.' // a mine-free cell #define MAX_ROWS 120 // maximum rows of a minefield #define MAX_COLS 120 // maximum columns of a minefield #include<iostream> using namespace std; void scan_minefield(char [][MAX_COLS+1], int, int); void count_minefield(char [][MAX_COLS+1], int, int); int counting; int main(void) { char minefield[MAX_ROWS][MAX_COLS+1]; int row_size, col_size; // actual size of minefield read int counter,i,j; bool found; while(cin>>row_size>>col_size && row_size && col_size){ scan_minefield(minefield,row_size,col_size); counter=0; for(i=0;i<row_size;i++) for(j=0;j<col_size;j++) { if(minefield[i][j] == MINE) { counting = 0; count_minefield(minefield,i,j); if(counting == 1) counter++; } } printf("%d\n",counter); } return 0; } // To read in the minefield void scan_minefield(char mines[][MAX_COLS+1], int row, int col) { int r; getchar(); for (r=0; r<row; r++){ gets(mines[r]); } } //To read where the minecluster is. void count_minefield(char minefield[][MAX_COLS+1], int row, int col) { int i,j; counting++; minefield[row][col]=FREE; for(i=row-1;i<=row+1;i++) for(j=col-1;j<=col+1;j++) if(minefield[i][j]==MINE) count_minefield(minefield,i,j); } <file_sep>#include<vector> #include<algorithm> #include<cstdio> #include<iostream> #include<queue> #include<map> #include<stdio.h> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; map<int,int> dist; map<string, int> mapper; map<int, string> reverseMapper; vector<vii> AdjList; map<int, int> p; vector<int> res; void printPath(int u, int s){ if(u==s){ res.push_back(s); return; } printPath(p[u],s); res.push_back(u); } void clearing(){ mapper.clear(); dist.clear(); reverseMapper.clear(); p.clear(); res.clear(); } int main(void){ int route,counter; string from,to; bool first = true; while(cin>>route){ counter = 0; clearing(); if(first) first = false; else cout<<endl; AdjList.assign(route*2,vii()); for(int i=0;i<route;i++){ cin>>from; cin>>to; //cout<<i<<endl; if(mapper.find(from)==mapper.end()){ mapper[from] = counter; reverseMapper[counter] = from; counter++; } //cout<<i<<endl; if(mapper.find(to) == mapper.end()) { mapper[to] = counter; reverseMapper[counter] = to; counter++; } AdjList[mapper[from]].push_back(ii(mapper[to], 0)); AdjList[mapper[to]].push_back(ii(mapper[from], 0)); //cout<<i<<endl; } //cout<<4; cin>>from>>to; if(mapper.find(from)==mapper.end() || mapper.find(to)==mapper.end()) cout<<"No route"<<endl; else{ int s = mapper[from]; queue<int> q; q.push(s); dist[s] = 1; while(!q.empty()){ int u = q.front(); q.pop(); for(int j=0;j<(int)AdjList[u].size();j++){ ii v = AdjList[u][j]; if(!dist.count(v.first)){ dist[v.first] = dist[u] + 1; p[v.first] = u; q.push(v.first); } } } if(dist[mapper[to]]){ printPath(mapper[to],mapper[from]); cout<<reverseMapper[res[0]]<<" "; for(int i=1;i<res.size()-1;i++) cout<<reverseMapper[res[i]]<<endl<<reverseMapper[res[i]]<<" "; cout<<reverseMapper[res[res.size()-1]]<<endl; } else cout<<"No route"<<endl; } } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class HowManyPieces{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger n,result,temp; String in; while(sc.hasNext()){ in = sc.next(); n = new BigInteger(in); temp = n; result = new BigInteger("24"); result = result.subtract(n.multiply(BigInteger.valueOf(18))); n = n.multiply(temp); result = result.add(n.multiply(BigInteger.valueOf(23))); n = n.multiply(temp); result = result.subtract(n.multiply(BigInteger.valueOf(6))); n = n.multiply(temp); result = result.add(n); result = result.divide(BigInteger.valueOf(24)); System.out.println(result); } } }<file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define isOn(S, j) (S & (1 << j)) //check if the bit is on #define setBit(S, j) (S |= (1 << j)) #define clearBit(S, j) (S &= ~(1 << j)) //set bit to 0 int main(void){ freopen("in.txt","r",stdin); int casecounter = 1; int n; int x[81],y[81],z[81],val[81]; while(scanf("%d",&n),n){ FOR(i,n){ scanf("%d %d %d %d",&x[i],&y[i],&z[i],&val[i]); } int maxi = -1; int bitmask = 0; int total; FOR(i,n-2){ total = val[i]; setBit(bitmask,x[i]); setBit(bitmask,y[i]); setBit(bitmask,z[i]); FOR(j,n-1){ if((!isOn(bitmask,x[j])) && (!isOn(bitmask,y[j]) && (!isOn(bitmask,z[j])))){ setBit(bitmask,x[j]); setBit(bitmask,y[j]); setBit(bitmask,z[j]); total+=val[j]; FOR(k,n){ if((!isOn(bitmask,x[k])) && (!isOn(bitmask,y[k]) && (!isOn(bitmask,z[k])))){ maxi = max(total+val[k],maxi); } } total-=val[j]; clearBit(bitmask,x[j]);clearBit(bitmask,y[j]);clearBit(bitmask,z[j]); } } clearBit(bitmask,x[i]);clearBit(bitmask,y[i]);clearBit(bitmask,z[i]); } printf("Case %d: %d\n",casecounter++,maxi); } return 0; } <file_sep>#include<iostream> #include<queue> using namespace std; int main(void){ queue<int> deck; int input; while(cin>>input && input){ for(int i=1;i<=input;i++){ deck.push(i); } cout<<"Discarded cards:"; for(int i=0;i<input-1;i++){ cout<<" "<<deck.front(); deck.pop(); deck.push(deck.front()); deck.pop(); if(i!=input-2) cout<<","; } cout<<endl; cout<<"Remaining card: "<<deck.front()<<endl; deck.pop(); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> using namespace std; long long changes(int, int); int coins[]={1,5,10,25,50}; long long change[6][30100]; int main(void){ memset(change,-1,sizeof change); int input; while(cin>>input){ if(changes(input,0)==1) cout<<"There is only 1 way to produce "<<input<<" cents change."<<endl; else cout<<"There are "<<changes(input,0)<<" ways to produce "<<input<<" cents change."<<endl; } return 0; } long long changes(int money, int value){ if(money==0) return 1; if(money<0 || value>4) return 0; if(change[value][money]!=-1) return change[value][money]; return change[value][money] = changes(money-coins[value],value) + changes(money,value+1); } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int soldier[21]; int N,left,right,counter, counteradd, counterleft, counterright,remember; while(cin>>N>>right>>left && N && left && right){ counter = 0; counterleft = N; counterright = 1; for(int i=1;i<=N;i++) soldier[i] = 1; while(counter<N){ counteradd = 0; while(counteradd<right){ if(counterright>N) counterright = 1; if(soldier[counterright]){ counteradd++; if(counteradd == right) break; counterright++; } else{ counterright++; } } counteradd = 0; while(counteradd<left){ //cout<<"counterleft"<<counterleft<<endl; if(counterleft==0) counterleft = N; if(soldier[counterleft]){ counteradd++; if(counteradd == left) break; counterleft--; } else counterleft--; } soldier[counterleft] = 0; soldier[counterright] = 0; if(counterleft ==counterright){ counter++; printf("%3d",counterright); if(counter<N) cout<<","; } else{ counter+=2; printf("%3d%3d",counterright,counterleft); if(counter<N) cout<<","; } } cout<<endl; } return 0; } <file_sep>#include<stdio.h> \\UVa12188 #include<string.h> #include<math.h> #include<stdlib.h> #include<iostream> using namespace std; int main(void){ char input[10000]; int length,temp; long long total; while(gets(input)){ if(input[0]=='*') return 0; total = 0; length = strlen(input); for(int i=0;i<length;i++){ temp = input[i]- 'a'; if(temp>13) temp = 26-temp; total+=temp; } printf("%lld\n",total); } return 0; } <file_sep>#include<iostream> #include<string.h> #include<map> #include<stdio.h> using namespace std; void count(char input[][1000],int x, int y, char language); int main(void){ int test; int x,y, max; cin>>test; char input[1000][1000]; map<char,int> lang; for(int i=1;i<=test;i++){ lang.clear(); cin>>x>>y; getchar(); // to catch the newline for (int r=0; r<x; r++) gets(input[r]); for(int j=0;j<x;j++) for(int k=0;k<y;k++){ if(input[j][k]!='.'){ lang[input[j][k]]++; count(input,j,k,input[j][k]); } } cout<<"World #"<<i<<endl; while(true){ max = 0; for(map<char,int>::iterator it = lang.begin();it!=lang.end();it++){ if(it->second>max) max = it->second; } if(max == 0) break; for(map<char,int>::iterator it = lang.begin();it!=lang.end();it++){ if(it->second == max){ cout<<it->first<<": "<<it->second<<endl; it->second = 0; } } } } return 0; } void count(char input[][1000], int x, int y, char language){ input[x][y] = '.'; if(input[x-1][y]==language) count(input,x-1,y,language); if(input[x+1][y]==language) count(input,x+1,y,language); if(input[x][y+1]==language) count(input,x,y+1,language); if(input[x][y-1]==language) count(input,x,y-1,language); } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC(tc) while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) vi taken; priority_queue<ii> pq; vector<vii> AdjList; void process(int vtx) { // so, we use -ve sign to reverse the sort order taken[vtx] = 1; for (int j = 0; j < (int)AdjList[vtx].size(); j++) { ii v = AdjList[vtx][j]; if (!taken[v.first]) pq.push(ii(-v.second, -v.first)); } } int main(void){ //freopen("in.txt","r",stdin); int N, mst_cost; bool first = true; //priority_queue<ii>pq; while(scanf("%d",&N)!=EOF){ if(!first)printf("\n"); first = false; int a,b,c,K; AdjList.assign(N,vii()); for(int i=0;i<N-1;i++){ scanf("%d %d %d",&a,&b,&c); AdjList[a-1].push_back(ii(b-1,c)); AdjList[b-1].push_back(ii(a-1,c)); } int u,w; taken.assign(N, 0); // no vertex is taken at the beginning process(0); // take vertex 0 and process all edges incident to vertex 0 mst_cost = 0; while (!pq.empty()) { // repeat until V vertices (E=V-1 edges) are taken ii front = pq.top(); pq.pop(); u = -front.second, w = -front.first; // negate the id and weight again if (!taken[u]) // we have not connected this vertex yet mst_cost += w, process(u); // take u, process all edges incident to u } printf("%d\n",mst_cost); AdjList.assign(N,vii()); scanf("%d",&K); for(int i=0;i<K;i++){ scanf("%d %d %d",&a,&b,&c); AdjList[a-1].push_back(ii(b-1,c)); AdjList[b-1].push_back(ii(a-1,c)); } scanf("%d",&K); for(int i=0;i<K;i++){ scanf("%d %d %d",&a,&b,&c); AdjList[a-1].push_back(ii(b-1,c)); AdjList[b-1].push_back(ii(a-1,c)); } taken.assign(N, 0); // no vertex is taken at the beginning process(0); // take vertex 0 and process all edges incident to vertex 0 mst_cost = 0; while (!pq.empty()) { // repeat until V vertices (E=V-1 edges) are taken ii front = pq.top(); pq.pop(); u = -front.second, w = -front.first; // negate the id and weight again if (!taken[u]) // we have not connected this vertex yet mst_cost += w, process(u); // take u, process all edges incident to u } printf("%d\n",mst_cost); } return 0; } <file_sep>#include<string.h> #include<iostream> using namespace std; int main(void){ string sent[101]; int counter,max; max = counter = 0; while(getline(cin,sent[counter])){ if(sent[counter].length()>max) max = sent[counter].length(); counter++; } for(int i=0;i<max;i++){ for(int j=counter-1;j>=0;j--){ if(sent[j].length()>i){ cout<<sent[j].at(i); } else if(sent[j].length()<=i) cout<<" "; } cout<<endl; } } <file_sep>#include<iostream> #include<math.h> #include<string> using namespace std; int main(void){ string number; int sum; while(true){ cin>>number; if(number.size() == 1 && number.at(0)=='0') break; sum = 0; for(int i=0;i < number.length();i++){ switch (number.at(number.length()-1-i)) { case('0'): break; case('1'): sum+=1*((int)pow(2.0,(i+1))-1); break; case('2'): sum+=2*((int)pow(2.0,(i+1))-1); break; } } cout<<sum<<endl; } return 0; }<file_sep>#include<stack> #include<iostream> using namespace std; int main(void){ int numtrain, desired[1002],now[1002]; int pointernow, pointerdesired; bool found; stack<int> train; while(cin>>numtrain && numtrain){ while(cin>>desired[0] && desired[0]){ found = false; now[0] = 1; for(int i=1;i<numtrain;i++){ cin>>desired[i]; now[i]=i+1; } pointerdesired = pointernow = 0; while(pointerdesired<numtrain){ //cout<<"PTRDESIRED "<<pointerdesired<<" PTRNOW "<<pointernow<<" SIZE STACK "<<train.size()<<endl; if(!train.empty() && desired[pointerdesired]==train.top()){ train.pop(); pointerdesired++; if(pointerdesired == numtrain){ found = true; break; } } else if(pointernow == numtrain) break; else if(pointernow<numtrain){ if(desired[pointerdesired]==now[pointernow]){ pointernow++; pointerdesired++; if(pointerdesired == numtrain){ found = true; break; } } else{ train.push(now[pointernow]); pointernow++; } } } if(found) cout<<"Yes"<<endl; else cout<<"No"<<endl; while(!train.empty()) train.pop(); } cout<<endl; } } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define MAX_N 3 typedef struct{ ll mat[3][3]; }Matrix; Matrix matMul(Matrix a, Matrix b){ Matrix ans; int i,j,k; for(i=0;i<MAX_N;i++) for(j=0;j<MAX_N;j++) for(ans.mat[i][j] = k = 0;k<MAX_N; k++) ans.mat[i][j] = (ans.mat[i][j] + a.mat[i][k]%1000000009 * b.mat[k][j]%1000000009)%1000000009; return ans; } Matrix matPow(Matrix base, ll p){ Matrix ans; int i,j; for(i=0;i<MAX_N;i++) for(j=0;j<MAX_N;j++) ans.mat[i][j] = (i==j); while(p){ if(p&1) ans = matMul(ans,base); base = matMul(base,base); p>>=1; } return ans; } int main(void){ //freopen("in.txt","r",stdin); Matrix trib; // trib.mat = {{1,1,0},{1,0,1},{1,0,0}}; trib.mat[0][0] = trib.mat[0][1] = trib.mat[0][2] = trib.mat[1][0] = trib.mat[2][1] = 1; trib.mat[1][1] = trib.mat[1][2] = trib.mat[2][0] = trib.mat[2][2] = 0; ll n; while(scanf("%lld",&n),n){ printf("%lld\n",matPow(trib,n).mat[1][1]); } return 0; } <file_sep>#include<map> #include<vector> #include<iostream> using namespace std; int main(void){ int input; map<int,int> maps; vector<int> order; bool found; while(cin>>input){ maps[input]++; if(order.empty()) order.push_back(input); else{ found = false; for(int i=0;i<order.size();i++){ if(order.at(i)==input){ found = true; break; } } if(!found) order.push_back(input); } } for(int i=0;i<order.size();i++){ cout<<order.at(i)<<" "<<maps[order.at(i)]<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int h, m,s,ms, total; while(scanf("%2d%2d%2d%2d",&h,&m,&s,&ms) == 4){ total=((h*60 + m)*60+s)*100+ms; total = total*125/108; printf("%07d\n",total); } return 0; } <file_sep>#include<iostream> #include<string> #include<stack> using namespace std; int main(void){ string input; stack<char> strstack; int test; cin>>test; getline(cin,input); for(int i=0;i<test;i++){ getline(cin,input); for(int j=0;j<input.length();j++){ if(input.at(j)=='(' || input.at(j)=='[') strstack.push(input.at(j)); else if(!strstack.empty() && ((input.at(j) == ')' && strstack.top() == '(' )|| (input.at(j) ==']' && strstack.top() == '['))) strstack.pop(); else if(input.at(j)==')' || input.at(j)==']') strstack.push(input.at(j)); } if(strstack.empty()) cout<<"Yes"<<endl; else{ cout<<"No"<<endl; while(!strstack.empty()) strstack.pop(); } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int test; int newcola, total, empty; while(cin>>test && test){ total = 0; empty = test; while(empty>=3){ newcola = empty/3; empty = empty%3 + newcola; total+=newcola; } if(empty == 2){ total++; } cout<<total<<endl; } return 0; } <file_sep>#include<map> #include<queue> #include<stdio.h> #include<string.h> #include<iostream> using namespace std; int main(void){ map<int,int> dist; string from,to; int searched; int dr[]={-2,-2,-1,1,2,2,1,-1};//untuk huruf int dc[]={-1,1,2,2,1,-1,-2,-2};//untuk angka while(cin>>from>>to){ cout<<"To get from "<<from<<" to "<<to<<" takes"; if(from==to){ printf(" 0 knight moves.\n"); } else{ searched = (to.at(0)-'a')*10 + to.at(1)-'0'; dist.clear(); queue<int> nomor; queue<int> huruf; int x = from.at(1)-'0'; int y = from.at(0)-'a'; dist[y*10+x] = 0; nomor.push(x); huruf.push(y); while(!nomor.empty()){ x = nomor.front();nomor.pop(); y = huruf.front();huruf.pop(); for(int i=0;i<8;i++){ int xtemp=x+dc[i]; int ytemp=y+dr[i]; if(xtemp>=1 && xtemp<=8 && ytemp>=0 && ytemp<8){ if(!dist[ytemp*10+xtemp]){ dist[ytemp*10+xtemp] = dist[y*10+x]+1; nomor.push(xtemp); huruf.push(ytemp); } if(dist[searched]) break; } } if(dist[searched]) break; } printf(" %d knight moves.\n",dist[searched]); } } return 0; } <file_sep>#include<iostream> #include<sstream> #include<stdio.h> using namespace std; int main(void){ string str; int h,m,s,speed, timenow; double total; scanf("%d:%d:%d",&h,&m,&s); timenow = h*3600 + m*60 + s; total = 0; cin>>speed; while(scanf("%d:%d:%d",&h,&m,&s)==3){ getline(cin,str); total+= (h*3600+m*60+s-timenow)*speed/3600.0; timenow=h*3600+m*60+s; if(str.length()>2) stringstream(str)>>speed; else{ printf("%02d:%02d:%02d %.2lf km\n",h,m,s,total); } } } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ string input; int test, don; long long saving; cin>>test; saving = 0; for(int i=0;i<test;i++){ cin>>input; if(input == "donate"){ cin>>don; saving+=don; } else if(input == "report"){ cout<<saving<<endl; } } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int a,b,c,d,l; while(scanf("%d %d %d %d %d",&a,&b,&c,&d,&l) && (a||b||c||d||l)){ int counter = 0; long long result; for(int i=0;i<=l;i++){ result = a*i*i + b*i + c; if(!(result%d)) counter++; } printf("%d\n",counter); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ int test, number[16],total; string input; cin>>test; for(int i=0;i<test;i++){ total = 0; for(int j=0;j<4;j++){ cin>>input; number[j*4] = ((int)input.at(0) - 48) * 2; if(number[j*4]>=0 && number[j*4]%9!=0) number[j*4] = number[j*4]%9; else if(number[j*4]==0) number[j*4]=0; else number[j*4] = 9; number[j*4+1] = ((int) input.at(2) - 48) * 2; if(number[j*4+1]>=0 && number[j*4+1]%9!=0) number[j*4+1] = number[j*4+1]%9; else if(number[j*4+1]==0) number[j*4+1]=0; else number[j*4+1] = 9; number[j*4 + 2] = (int) input.at(1) - 48; if(number[j*4+2]>=0 && number[j*4+2]%9!=0) number[j*4+2] = number[j*4+2]%9; else if(number[j*4+2]==0) number[j*4+2]=0; else number[j*4+2] = 9; number[j*4 + 3] = (int) input.at(3) - 48; if(number[j*4+3]>=0 && number[j*4+3]%9!=0) number[j*4+3] = number[j*4+3]%9; else if(number[j*4+3]==0) number[j*4+3]=0; else number[j*4+3] = 9; } for(int j=0;j<16;j++){ total+=number[j]; // cout<<"number["<<j<<"] : "<<number[j]<<endl; } if(total%10 == 0) cout<<"Valid"; else cout<<"Invalid"; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int main(void){ int test, needed; double x,y; cin>>test; for(int i=0;i<test;i++){ cin>>x>>y; needed = ceil((x-2)/3) * ceil((y-2)/3); cout<<needed<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> #include<map> using namespace std; int main(void){ string in; bool valid; map<string,int> insert; int sum, counter = 1; for(char i='a';i<='z';i++){ in = i; insert[in]=counter++; } for(char i='a';i<='y';i++){ for(char j=i+1;j<='z';j++){ in = i; in = in + j; insert[in] = counter++; } } for(char i='a';i<='x';i++){ for(char j=i+1;j<='y';j++){ for(char k=j+1;k<='z';k++){ in = i; in = in + j; in = in + k; insert[in] = counter++; } } } for(char i='a';i<='w';i++){ for(char j=i+1;j<='x';j++){ for(char k=j+1;k<='y';k++){ for(char l=k+1;l<='z';l++){ in = i; in = in + j; in = in + k; in = in + l; insert[in] = counter++; } } } } for(char i='a';i<='v';i++){ for(char j=i+1;j<='w';j++){ for(char k=j+1;k<='x';k++){ for(char l=k+1;l<='y';l++){ for(char m=l+1;m<='z';m++){ in = i; in = in + j; in = in + k; in = in + l; in = in + m; insert[in] = counter++; } } } } } while(cin>>in) cout<<insert[in]<<endl; return 0; } <file_sep>#include<set> #include<map> #include<iostream> #include<stdio.h> using namespace std; int main(void){ set<int> myset; map<int,int> maps; map<int,int>::iterator it; int input,test, in; long long total; while(scanf("%d",&input) && input){ total = 0; maps.clear(); for(int i=0;i<input;i++){ scanf("%d",&test); for(int j=0;j<test;j++){ scanf("%d",&in); maps[in]++; } it =maps.end(); it--; total+=it->first; it->second--; if(it->second==0) maps.erase(it); it = maps.begin(); total-=it->first; it->second--; if(it->second==0) maps.erase(it); } printf("%lld\n",total); } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int test, pointer; bool pos; double cost, collected; while(scanf("%d",&test) && test){ cost = collected = 0; for(int i=0;i<test;i++){ cin>>pointer; collected+=pointer; if(collected<0) cost-=collected; else cost+=collected; } printf("%.0lf\n",cost); } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int jack[10001]; int in; long long max,temp;; while(scanf("%d",&in) && in){ int input; temp = 0; max = -1; for(int i=0;i<in;i++){ cin>>input; temp+=input; if(temp<0) temp = 0; if(temp>max) max = temp; } if(max>0) printf("The maximum winning streak is %lld.\n",max); else printf("Losing streak.\n"); } return 0; } <file_sep>#include<cstdio> #include<vector> using namespace std; typedef vector<int>vi; typedef vector<vi> vii; int main(void){ int tc,n,m,casecounter = 1; int arr[120]; scanf("%d",&tc); vector<vi> AdjList; while(tc--){ scanf("%d %d",&n,&m); for(int i=0;i<n;i++) scanf("%d",&arr[i]); AdjList.assign(n,vi()); int fr,to; for(int i=0;i<m;i++){ scanf("%d %d",&fr,&to); AdjList[fr].push_back(to); } int now = arr[0], total = 0; int temp, maxlearn; while(true){ int maxlearn = 0; if(AdjList[now].size() == 0) break; for(int i=0;i<AdjList[now].size();i++) if(arr[AdjList[now][i]]>maxlearn){ maxlearn = arr[AdjList[now][i]]; temp = AdjList[now][i]; } now = temp; total+=maxlearn; //printf("%d\n",total); } printf("Case %d: %d %d\n",casecounter++,total,now); } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int term1, term2, final, attn, testcase; double ave, total; int test[3]; cin>>testcase; for(int i=1;i<=testcase;i++){ cout<<"Case "<<i<<": "; cin>>term1>>term2>>final>>attn; for(int j=0;j<3;j++) cin>>test[j]; sort(test, test+3); ave = (test[2] + test[1])/2; total = term1+term2+final+attn+ave; if(total>=90) cout<<"A"; else if(total>=80) cout<<"B"; else if(total>=70) cout<<"C"; else if(total>=60) cout<<"D"; else cout<<"F"; cout<<endl; } return 0; } <file_sep>#include<map> #include<stdio.h> #include<iostream> using namespace std; int main(void){ map<int,int> in; int N,K,input; map<int,int>::iterator it; long long sum; while(scanf("%d %d",&N,&K) && N && K){ in.clear(); if(N==K){ sum = 0; for(int i=0;i<N;i++){ scanf("%d",&input); sum+=input; } printf("%lld\n",sum); } else{ for(int i=0;i<N;i++){ scanf("%d",&input); in[input]++; } sum = 0; it = in.end(); it--; for(int i=0;i<K;i++){ sum+=it->first; it->second--; if(!it->second) it--; } printf("%lld\n",sum); } } } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ #ifdef ccsnoopy freopen("D:/Code/in.txt","r",stdin); #endif //to compile: g++ -o foo filename.cpp -lm -Dccsnoopy for debug. return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int val[15][105], weight[15][105], parent[15][105]; void compare(int x1, int y1, int x2, int y2){ if(weight[x1][y1]>weight[x2][y2] + val[x1][y1]){ parent[x1][y1] = x2; weight[x1][y1] = weight[x2][y2] + val[x1][y1]; } } int main(void){ freopen("in.txt","r",stdin); int n,m; vector<vi> path; while(scanf("%d %d",&m,&n)!=EOF){ FOR(i,m){ FOR(j,n){ scanf("%d",&val[i][j]); weight[i][j] = INF; } } FOR(i,m){ weight[i][0] = val[i][0]; parent[i][0] = i; } REP(j,1,n){ FOR(i,m){ //compare(i,j,(i-1+m)%m,j-1); //compare(i,j,i,j-1); //compare(i,j,(i+1)%m,j-1); if(i == 0){ compare(i,j,0,j-1); //printf("comparing: %d\n",((i-1)%m+m)%m); compare(i,j,(i+1)%m,j-1); compare(i,j,(i+m-1)%m,j-1); }else if(i == m-1){ compare(i,j,(i+1)%m,j-1); compare(i,j,(i+m-1)%m,j-1); compare(i,j,i,j-1); }else{ compare(i,j,i-1,j-1); compare(i,j,i,j-1); compare(i,j,i+1,j-1); } } } int minweight = INF; path.clear(); int idx = -1; FOR(i,m){ //printf("%d %d\n",weight[i][n-1]); if(minweight > weight[i][n-1]){ minweight = weight[i][n-1]; //printf("minweight now: %d\n",minweight); idx = i; } } int counter = 0; FOR(i,m){ if(minweight == weight[i][n-1]){ path.pb(vector<int>()); for(int j=n-1;j>=0;j--){ path[counter].pb(idx+1); idx = parent[idx][j]; } counter++; } } FOR(i,counter)reverse(path[i].begin(),path[i].end()); int best; //FOR(i,path.size()){ //} FOR(i,path.size()){ FOR(j,path[0].size()){ printf("%d ",path[i][j]); }printf("\n");} printf("%d\n%d\n",path[0][path[0].size()-1],minweight); } return 0; } <file_sep>#include<iostream> using namespace std; void insertion(int[]); int main(void){ int a[10] = {2,3,1,4,5,6,7,9,8,10}; insertion(a); for(int i=0;i<10;i++){ cout<<a[i]; } return 0; } void insertion(int a[]){ int next,j; for(int i=1;i<10;i++){ for(j=i-1;j>=0 && a[j]>a[i];j--) a[j+1] = a[j]; a[j+1] = a[i]; } } <file_sep>#include<iostream> using namespace std; int main(void){ int test, n; int age[11]; cin>>test; for(int i=1;i<=test;i++){ cin>>n; for(int j=0;j<n;j++) cin>>age[j]; cout<<"Case "<<i<<": "<<age[n/2]<<endl; } return 0; } <file_sep>#include<iostream> #include<map> #include<string.h> using namespace std; int main(void){ map<string,int> conq; int in; string dum; cin>>in; for(int i=0;i<in;i++){ cin>>dum; conq[dum]++; getline(cin,dum); } for(map<string,int>::iterator it = conq.begin();it!=conq.end();it++) cout<<it->first<<" "<<it->second<<endl; return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) ll _sieve_size; bitset<10000010> bs; // 10^7 should be enough for most cases vi primes; void sieve(ll upperbound) { for(int i=9;i>=2;i--)primes.push_back((int)i); } vi primeFactors(ll N) { // remember: vi is vector of integers, ll is long long vi factors; // vi `primes' (generated by sieve) is optional ll PF_idx = 0, PF = primes[PF_idx]; // using PF = 2, 3, 4, ..., is also ok for(int i=9;i>=2;i--){ while(N%i == 0){N/=i;factors.push_back(i);} } if (N != 1) factors.push_back(N); // special case if N is actually a prime return factors; // if pf exceeds 32-bit integer, you have to change vi } int main(void){ // freopen("in.txt","r",stdin); int tc,n; vi vint; sieve(25); scanf("%d",&tc); TC(){ scanf("%d",&n); if(n == 0 || n == 1)printf("%d\n",n); else{ vint.clear(); vint = primeFactors(n); sort(vint.begin(),vint.end()); if(vint[vint.size()-1]>9){ printf("-1\n"); } else{ FOR(i,vint.size()){ printf("%d",vint[i]); } printf("\n"); } } } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; //typedef pair<int,int> ii; typedef pair<double,int>ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) class UnionFind { // OOP style private: vi p, rank, setSize; // remember: vi is vector<int> int numSets; public: UnionFind(int N) { setSize.assign(N, 1); numSets = N; rank.assign(N, 0); p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { if (!isSameSet(i, j)) { numSets--; int x = findSet(i), y = findSet(j); // rank is used to keep the tree short if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } } int numDisjointSets() { return numSets; } int sizeOfSet(int i) { return setSize[findSet(i)]; } }; vi taken; priority_queue<ii>pq; vector<vii> AdjList; void process(int vtx) { // so, we use -ve sign to reverse the sort order taken[vtx] = 1; for (int j = 0; j < (int)AdjList[vtx].size(); j++) { ii v = AdjList[vtx][j]; if (!taken[v.second]) pq.push(ii(-v.first, -v.second)); } } int main(void){ //freopen("in.txt","r",stdin); int tc,casecounter = 1; scanf("%d",&tc); TC(){ int V,threshold; int x[1010],y[1010]; scanf("%d%d",&V,&threshold); UnionFind UF(V); AdjList.assign(V,vii()); for(int i=0;i<V;i++){ scanf("%d %d",&x[i],&y[i]); } for(int i=0;i<V;i++) for(int j=i+1;j<V;j++){ double dist = hypot(x[i]-x[j],y[i]-y[j]); //printf("%lf %d %d\n",dist,i,j); AdjList[i].push_back(ii(dist,j)); AdjList[j].push_back(ii(dist,i)); if(dist <= threshold){ if(!UF.isSameSet(i,j)){ UF.unionSet(i,j); } } } /* for(int i=0;i<AdjList.size();i++) for(int j=0;j<AdjList[i].size();j++) printf("%lf %d %d\n",AdjList[i][j].first,AdjList[i][j].second,i); */ int u; double w; taken.assign(V, 0); // no vertex is taken at the beginning process(0); // take vertex 0 and process all edges incident to vertex 0 double mst_cost = 0, mst_small = 0; while (!pq.empty()) { // repeat until V vertices (E=V-1 edges) are taken ii front = pq.top(); pq.pop(); u = -front.second, w = -front.first; // negate the id and weight again if (!taken[u]){ // we have not connected this vertex yet //printf("take: %lf %d\n",w,u); if(w > threshold) mst_cost += w; // take u, process all edges incident to u else mst_small +=w; //printf("now processing: %d\n",u); process(u); } } // each edge is in pq only once! printf("Case #%d: %d %.0lf %.0lf\n",casecounter++,UF.numDisjointSets(),round(mst_small),round(mst_cost)); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int change[10000], changeopt[502]; int num[] = {5,10,20,50,100,200}; int opt(int money, int coin[]){ if(money == 0) return change[0] = 0; if(money < 0) return INF; if(change[money]!=-1) return change[money]; int optans = INF; FOR(i,6){ if(coin[i]>0){ coin[i]--; optans = min(optans,1+opt(money-num[i],coin)); coin[i]++; } } return (change[money] = optans); } int opt2(int money){ if(money == 0) return changeopt[0] = 0; if(money < 0) return INF; if(changeopt[money]!=0) return changeopt[money]; int optans = INF; FOR(i,6) optans = min(optans, 1+opt2(money-num[i])); return changeopt[money] = optans; } int main(void){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int coin[6]; double money; int monint; reset(changeopt,0); opt2(500); while(scanf("%d %d %d %d %d %d",&coin[0],&coin[1],&coin[2],&coin[3],&coin[4],&coin[5]),(coin[0]||coin[1]||coin[2]||coin[3]||coin[4]||coin[5])){ int total = 0; FOR(i,6){ total+=coin[i]*num[i]; } scanf("%lf",&money); monint = money*100+1e-6; //printf("%d",monint); reset(change,-1); opt(total,coin); int optimal = INF; total = min(total,1000); for(int i=monint;i<=total,(i-monint)<=500;i+=5){ if(change[i]!=-1) optimal = min(optimal,change[i]+changeopt[i-monint]); //if(optimal == 1)printf("%d %d %d\n",i,change[i],changeopt[i-monint]); //printf("%d: %d\n",i,optimal); } printf("%3d\n",optimal); //FOR(i,96)printf("%d: %d\n",i,change[i]); } return 0; } <file_sep>#include<map> #include<iostream> #include<stdio.h> #include<sstream> using namespace std; int main(void){ string dum1,dum2, line; map<string,string> dict; while(true){ getline(cin, line); istringstream is(line); string s1, s2; if (!(is >> s1 >> s2)) break; dict[s2] = s1; } while(getline(cin,dum1)){ if(dict.find(dum1)==dict.end()) cout<<"eh"<<endl; else cout<<dict.find(dum1)->second<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<queue> #include<vector> #include<map> using namespace std; typedef pair<int,int> ii; int dr[]={0,-1,0,1}; int dc[]={-1,0,1,0}; int main(void){ int row,col,startx,starty,endx,endy; map<ii,int> step; while(scanf("%d %d",&row,&col) && row && col){ int rowmine,numrow,nummine,mine; scanf("%d",&rowmine); bool grid[1001][1001]; for(int i=0;i<rowmine;i++){ scanf("%d %d",&numrow,&nummine); for(int j=0;j<nummine;j++){ scanf("%d",&mine); grid[numrow][mine] = true; } } scanf("%d %d",&startx,&starty); scanf("%d %d",&endx,&endy); step.clear(); queue<int> qr,qc; step[ii(startx,starty)] = 1; qr.push(startx); qc.push(starty); while(!qr.empty()){ int currow,curcol; currow = qr.front();curcol = qc.front(); qr.pop(); qc.pop(); for(int i=0;i<4;i++){ int curx = currow+dr[i], cury = curcol+dc[i]; if(curx<row && cury<col && curx>=0 && cury>=0 && !step[ii(curx,cury)] && !grid[curx][cury]){ step[ii(curx,cury)] = step[ii(currow,curcol)]+1; qr.push(curx); qc.push(cury); } } if(!step[ii(endx,endy)]) break; } printf("%d\n",step[ii(endx,endy)]-1); } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int test; int salary[3]; cin>>test; for(int i=1;i<=test;i++){ cout<<"Case "<<i<<": "; for(int j=0;j<3;j++) cin>>salary[j]; sort(salary,salary+3); cout<<salary[1]<<endl; } return 0; } <file_sep>#include<string.h> #include<stdio.h> #include<stdlib.h> #include<algorithm> #include<iostream> using namespace std; int main(void){ int test; char input[12]; scanf("%d\n",&test); for(int i=0;i<test;i++){ scanf("%s",input); sort(input,input+strlen(input)); do{ printf("%s\n",input); }while(next_permutation(input,input+strlen(input))); cout<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int testcase,numofwall, high, low; int wall[50]; cin>>testcase; for(int i=1;i<=testcase;i++){ cout<<"Case "<<i<<":"; cin>>numofwall; cin>>wall[0]; high = 0; low = 0; for(int j=1;j<numofwall;j++){ cin>>wall[j]; if(wall[j-1]<wall[j]) high++; else if(wall[j-1]>wall[j]) low++; } cout<<" "<<high<<" "<<low<<endl; } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string input[2]; int month[2],date[2],year[2], age; int test; cin>>test; for(int i=1;i<=test;i++){ cout<<"Case #"<<i<<": "; for(int j=0;j<2;j++){ cin>>input[j]; date[j] = ((int)input[j].at(0) - 48)*10 + (int)input[j].at(1) - 48; month[j] = ((int)input[j].at(3) - 48)*10 + (int)input[j].at(4) - 48; year[j] = ((int)input[j].at(6) - 48)*1000 + ((int)input[j].at(7) - 48)*100 + ((int)input[j].at(8) - 48)*10 + (int)input[j].at(9) - 48; } if(year[0]<year[1] || year[0]==year[1] && month[0]<month[1] || year[0]==year[1] && month[0]==month[1] && date[0]<date[1]) cout<<"Invalid birth date"<<endl; else{ age = year[0]-year[1]; if(month[0]<month[1]) age--; else if(month[0]==month[1] && date[0]<date[1]) age--; if(age>130) cout<<"Check birth date"<<endl; else cout<<age<<endl; } } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> using namespace std; long long changes(int, int); int coins[21]; long long change[22][30100]; int main(void){ for(int i=1;i<=21;i++) coins[i-1] = i*i*i; memset(change,-1,sizeof change); int input; while(cin>>input){ cout<<changes(input,0)<<endl; } return 0; } long long changes(int money, int value){ if(money==0) return 1; if(money<0 || value>=21) return 0; if(change[value][money]!=-1) return change[value][money]; return change[value][money] = changes(money-coins[value],value) + changes(money,value+1); } <file_sep>#include<iostream> #include<string.h> using namespace std; typedef struct{ string name; int point; int game_played; int win; int tie; int loss; int goaldif; int goalscored; int goalagainst; }team; int main(void){ int test; int numteam, nummatch; string event; team teams[1000]; cin>>test; getline(cin,event); for(int i=0;i<test;i++){ getline(cin,event); cout<<event<<endl; cin>>numteam; for(int j=0;j<numteam;j++){ getline(cin,teams[j].name); } cin>>nummatch; for(int j=0;j<nummatch;j++){ } } return 0; } <file_sep>#include<map> #include<iostream> #include<string.h> using namespace std; int main(void){ int n,k; string sing,plur,in; map<string,string>irr; cin>>n>>k; for(int i=0;i<n;i++){ cin>>sing>>plur; irr[sing]=plur; } for(int i=0;i<k;i++){ cin>>in; if(irr.find(in)!=irr.end()) cout<<irr[in]<<endl; else{ if(in.at(in.length()-1)=='y' && in.at(in.length()-2)!='a' && in.at(in.length()-2)!='e' && in.at(in.length()-2)!='i' && in.at(in.length()-2)!='o' && in.at(in.length()-2)!='u'){ for(int i=0;i<in.length()-1;i++) cout<<in.at(i); cout<<"ies"<<endl; } else if(in.at(in.length()-1)=='o' || in.at(in.length()-1)=='x' || in.at(in.length()-1)=='s' || ((in.at(in.length()-2)=='c' || in.at(in.length()-2)=='s') && in.at(in.length()-1)=='h')) cout<<in<<"es"<<endl; else cout<<in<<"s"<<endl; } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int score[101][101]; int match, player, scoring, max, top; bool first; while(cin>>match>>player && match && player){ for(int i=0;i<match;i++){ for(int j=1;j<=player;j++){ cin>>score[i][j]; } } cin>>scoring; for(int i=0;i<scoring;i++){ max = 0; int scoresystem[101] = {0}; int total[101] = {0}; first = true; cin>>top; for(int j=1;j<=top;j++) cin>>scoresystem[j]; for(int j=1;j<=player;j++){ for(int k=0;k<match;k++) total[j]+=scoresystem[score[k][j]]; if(total[j]>max) max = total[j]; } for(int j=1;j<=player;j++) if(total[j]==max){ if(first){ cout<<j; first = false; } else cout<<" "<<j; } cout<<endl; } } return 0; } <file_sep>#include<stdio.h> #include<math.h> int main(void){ double a,b; while(scanf("%lf %lf",&a,&b)==2){ printf("%.0lf\n",pow(b,1/a)); } return 0; } <file_sep>#include<string> #include<iostream> using namespace std; int main(void){ int round, falsecounter; string realstr, trial; bool isRight; while(true){ cin>>round; if(round == -1) break; cout<<"Round "<<round<<endl; cin>>realstr>>trial; for(int i=0;i<trial.length()-1;i++){ for(int j=i+1;j<trial.length();j++) if(trial.at(i)==trial.at(j)){ trial.erase(j,1); j--; } } falsecounter = 0; for(int i=0;i<=trial.length();i++){ if(falsecounter==7){ cout<<"You lose."<<endl; break; } if(realstr.length() == 0){ cout<<"You win."<<endl; break; } if(i==trial.length()){ cout<<"You chickened out."<<endl; break; } isRight = false; for(int j=0;j<realstr.length();j++){ if(realstr.at(j) == trial.at(i)){ realstr.erase(j,1); j--; isRight = true; } } if(!isRight) falsecounter++; } } return 0; } <file_sep>#include<iostream> #include<vector> #include<algorithm> using namespace std; int prime[]={2,3,5,7,11,13,17,19,23,29,31}; void prime_ring(int i, vector<int> x,int iter){ if(x.size() == i){ if(binary_search(prime,prime+11,x.at(i-1) + x.at(0))){ for(int j=0;j<i-1;j++) cout<<x.at(j)<<" "; cout<<x.at(i-1)<<endl; x.clear(); } } else{ for(int j=2;j<=i;j++){ //cout<<"j: "<<j<<" size x:"<<x.size()<<" iteration: "<<iter<<endl; if(binary_search(prime,prime+11,x.at(x.size()-1)+j)){ bool have = false; for(int k=0;k<x.size();k++){ if(x.at(k)==j) have = true; } if(!have){ x.push_back(j); prime_ring(i,x,iter+1); x.pop_back(); } } } } return; } int main(void){ vector<int> x; bool first = true; int input, counter = 1; while(cin>>input){ if(first) first = false; else{ cout<<endl; } cout<<"Case "<<counter++<<":"<<endl; x.push_back(1); prime_ring(input,x,0); x.clear(); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #define INF 1000000 using namespace std; int main(void){ int graph[102][102]; int test; cin>>test; for(int z=1;z<=test;z++){ int edge,vertice; cin>>edge>>vertice; for(int i=0;i<edge;i++) for(int j=0;j<edge;j++){ if(i!=j) graph[i][j] = INF; else graph[i][j] = 0; } int x,y; for(int i=0;i<vertice;i++){ cin>>x>>y; graph[x][y] = graph[y][x] = 1; } int start,end; cin>>start>>end; printf("Case %d: ",z); if(edge == 1) cout<<0<<endl; else if(edge == 2 && start != end) cout<<1<<endl; else if(edge == 2) cout<<2<<endl; else{ for(int k=0;k<edge;k++) for(int i=0;i<edge;i++) for(int j=0;j<edge;j++) graph[i][j] = min(graph[i][j],graph[i][k] + graph[k][j]); int maxi = graph[start][end]; for(int i=0;i<edge;i++) if(i!=start && i!=end){ maxi = max(maxi,graph[start][i] + graph[i][end]); } cout<<maxi<<endl; } } return 0; } <file_sep>#include<iostream> #include<stdlib.h> using namespace std; int main(void){ int x1,x2,y1,y2,test,test2,dimension; cin>>test; for(int i=0;i<test;i++){ cin>>test2>>dimension; for(int j=0;j<test2;j++){ cin>>x1>>y1>>x2>>y2; if((x1 + y1)%2 == (x2 + y2)%2){ if(x1 == x2 && y1 == y2) cout<<"0"<<endl; else if(abs(x1-x2) == abs(y1-y2)) cout<<"1"<<endl; else cout<<"2"<<endl; } else cout<<"no move"<<endl; } } return 0; } <file_sep>#include <limits> #include<iostream> using namespace std; int main(void){ long long num; long long sum; while(cin>>num){ if(num == 1) sum = 1; else{ num = (num+1)/2; num*=num; sum = 6*(num-1)-3; } cout<<sum<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int notes[10001]; int input, peak; bool increase; while(true){ cin>>input; peak = 0; if(input == 0) return 0; for(int i=1;i<=input;i++) cin>>notes[i]; notes[input+1] = notes[1]; notes[0] = notes[input]; if(notes[0]>notes[1]) increase = false; else increase = true; for(int i=1;i<=input;i++){ if(notes[i]>notes[i+1]){ if(increase){ peak++; } increase = false; } else{ if(!increase) peak++; increase = true; } } cout<<peak<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int test,numcase = 1,counter,n; while(cin>>test){ if(test<0) break; else{ cout<<"Case "<<numcase<<": "; } if(test == 1){ cout<<"0"; } else{ n = 1; counter = 0; while(test>n){ n*=2; counter++; } cout<<counter; } numcase++; cout<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int test,bolbal, timeacross, maxcarry, numcar, timenow, carcarried; int car[1440]; cin>>test; for(int i=0;i<test;i++){ cin>>maxcarry>>timeacross>>numcar; for(int j=0;j<numcar;j++) cin>>car[j]; timenow = carcarried = bolbal = 0; for(int j=0;j<numcar;j++){ if(car[j]>timenow) timenow=car[j]; carcarried++; if(carcarried==maxcarry){ carcarried = 0; timenow+=timeacross*2; } } if(numcar%maxcarry == 0){ timenow-=timeacross; bolbal = numcar/maxcarry; } else bolbal = numcar/maxcarry+1; cout<<timenow<<" "<<bolbal<<endl; } return 0; } <file_sep>#include<map> #include<string.h> #include<iostream> #include<algorithm> using namespace std; map<string,int> sorts; bool compsort(string a, string b){ return sorts[a]<sorts[b]; } int main(void){ int test, length, num, counter; cin>>test; string arr[101]; while(test--){ cin>>length>>num; for(int i=0;i<num;i++){ cin>>arr[i]; counter = 0; if(!sorts[arr[i]]){ for(int j=0;j<length-1;j++){ for(int k=j+1;k<length;k++) if(arr[i].at(j)>arr[i].at(k)) counter++; } sorts[arr[i]] = counter; } } stable_sort(arr,arr+num, compsort); for(int i=0;i<num;i++) cout<<arr[i]<<endl; if(test) cout<<endl; } return 0; } <file_sep>#include<cstdio> using namespace std; bool valid; int arr[5],d; int counter = 0; bool does(int total,int x){ if(x==4){ counter++; printf("%d\n",total); if(total == 23){valid = true;} return false; } //printf("%d %d\n",total,x); //scanf("%d",&d); does(total+arr[x+1],x+1); does(total-arr[x+1],x+1); does(total*arr[x+1],x+1); //return false; } int main(void){ while(1){ for(int i=0;i<5;i++) scanf("%d",&arr[i]); if(arr[0] == arr[1] && arr[1]==arr[2] && arr[2]==arr[3] && arr[3] == arr[4] && arr[0] == 0) break; valid = false; does(arr[0],0); if(valid) printf("Possible\n"); else printf("Impossible\n"); printf("%d\n",counter); } return 0; } <file_sep>import java.util.*; import java.math.BigInteger; class IntegerInquiry{ public static void main(String[] args){ BigInteger sum = BigInteger.ZERO; BigInteger sum2; Scanner sc = new Scanner(System.in); while(true){ sum2 = sc.nextBigInteger(); if(sum2.intValue() == 0) break; sum = sum.add(sum2); } System.out.println(sum); return; } } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int have, cardA, cardB; int max, min, countA, countB; while(cin>>cardA>>cardB && cardA && cardB){ int cards[100001] = {0}; min = 100001; max = 0; countA = countB = 0; for(int i=0;i<cardA;i++){ cin>>have; cards[have] = 3; if(have>max) max = have; if(have<min) min = have; } for(int i=0;i<cardB;i++){ cin>>have; if(have>max) max = have; if(have<min) min = have; if(cards[have]==0 || cards[have]==3) cards[have]+=5; } for(int i=min;i<=max;i++){ if(cards[i]==3) countA++; else if(cards[i]==5) countB++; } if(countA<countB) cout<<countA<<endl; else cout<<countB<<endl; } } <file_sep>#include<iostream> using namespace std; int main(void){ int k, good, bad; int arr[26]; } <file_sep>#include<map> #include<iostream> #include<string.h> #include<algorithm> using namespace std; int main(void){ map<char,int> map1; map<char,int> map2; string a,b; int length; while(getline(cin,a) && getline(cin,b)){ map1.clear(); map2.clear(); length = a.length(); for(int i=0;i<length;i++) map1[a.at(i)]++; length = b.length(); for(int i=0;i<length;i++) map2[b.at(i)]++; for(char i='a';i<='z';i++){ if(map1[i] && map2[i]){ length = min(map1[i],map2[i]); for(int j=0;j<length;j++){ cout<<i; } } } cout<<endl; } return 0; } <file_sep>#include<iostream> #include<math.h> #include<stdio.h> using namespace std; int main(void){ double test; int room; while(scanf("%d %lf",&room,&test)==2){ test+=room*(room+1)/2.0+1; printf("%.0lf\n",floor((-1+pow(1+4*2*test,1/2.0))/2)); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<stdlib.h> #include<math.h> #define INF 10000000 using namespace std; int main(void){ int test, in, casecounter = 1; double graph[101][101]; double x[101],y[101]; cin>>in; while(in--){ cin>>test; for(int i=0;i<test;i++){ cin>>x[i]>>y[i]; } for(int i=0;i<test;i++) for(int j=0;j<test;j++){ graph[i][j] = INF; if(i==j) graph[i][j] = 0; } for(int i=0;i<test-1;i++) for(int j=i+1;j<test;j++){ graph[i][j] = pow(abs(x[i]-x[j]),2) + pow(abs(y[i]-y[j]),2); if(graph[i][j]>100) graph[i][j] = INF; else graph[i][j] = sqrt(graph[i][j]); graph[j][i] = graph[i][j]; } cout<<"Case #"<<casecounter++<<":"<<endl; for(int k=0;k<test;k++) for(int i=0;i<test;i++) for(int j=0;j<test;j++) graph[i][j] = min(graph[i][j],graph[i][k]+graph[k][j]); double res = 0; for(int i=0;i<test;i++) for(int j=0;j<test;j++) if(i!=j) res = max(res,graph[i][j]); if(res==INF) cout<<"Send Kurdy"<<endl<<endl; else{ printf("%.4lf\n\n",res); } } return 0; } <file_sep>#include<map> #include<iostream> #include<string.h> using namespace std; int main(void){ string input; map<char,char> dict; dict['~'] = '~'; dict['!'] = '!'; dict['@'] = '@'; dict['#'] = '#'; dict['$'] = 'Q'; dict['%'] = 'J'; dict['^'] = 'L'; dict['&'] = 'M'; dict['*'] = 'F'; dict['('] = 'P'; dict[')'] = '?'; dict['_'] = '{'; dict['+'] = '}'; dict['Q'] = '$'; dict['W'] = '%'; dict['E'] = '^'; dict['R'] = '>'; dict['T'] = 'O'; dict['Y'] = 'R'; dict['U'] = 'S'; dict['I'] = 'U'; dict['O'] = 'Y'; dict['P'] = 'B'; dict['{'] = ':'; dict['}'] = '+'; dict['|'] = '|'; dict['A'] = '&'; dict['S'] = '*'; dict['D'] = '('; dict['F'] = 'A'; dict['G'] = 'E'; dict['H'] = 'H'; dict['J'] = 'T'; dict['K'] = 'D'; dict['L'] = 'C'; dict[':'] = 'K'; dict['"'] = '_'; dict['Z'] = ')'; dict['X'] = 'Z'; dict['C'] = 'X'; dict['V'] = '<'; dict['B'] = 'I'; dict['N'] = 'N'; dict['M'] = 'W'; dict['<'] = 'V'; dict['>'] = 'G'; dict['?'] = '"'; dict['`'] = '`'; dict['1'] = '1'; dict['2'] = '2'; dict['3'] = '3'; dict['4'] = 'q'; dict['5'] = 'j'; dict['6'] = 'l'; dict['7'] = 'm'; dict['8'] = 'f'; dict['9'] = 'p'; dict['0'] = '/'; dict['-'] = '['; dict['='] = ']'; dict['q'] = '4'; dict['w'] = '5'; dict['e'] = '6'; dict['r'] = '.'; dict['t'] = 'o'; dict['y'] = 'r'; dict['u'] = 's'; dict['i'] = 'u'; dict['o'] = 'y'; dict['p'] = 'b'; dict['['] = ';'; dict[']'] = '='; dict['\\'] = '\\'; dict['a'] = '7'; dict['s'] = '8'; dict['d'] = '9'; dict['f'] = 'a'; dict['g'] = 'e'; dict['h'] = 'h'; dict['j'] = 't'; dict['k'] = 'd'; dict['l'] = 'c'; dict[';'] = 'k'; dict['\''] = '-'; dict['z'] = '0'; dict['x'] = 'z'; dict['c'] = 'x'; dict['v'] = ','; dict['b'] = 'i'; dict['n'] = 'n'; dict['m'] = 'w'; dict[','] = 'v'; dict['.'] = 'g'; dict['/'] = '\''; dict[' '] = ' '; while(getline(cin,input)){ for(int i=0;i<input.length();i++) cout<<dict[input.at(i)]; cout<<endl; } return 0; } <file_sep>#include<vector> #include<iostream> using namespace std; long long maximum; void wronghat(int now, int supposed, int arr[]){ if(now>supposed){ maximum++; return; } int temp; for(int i=1;i<=supposed;i++) if(now!=i && arr[i]!=0){ arr[i]=0; wronghat(now+1,supposed,arr); arr[i]=i; } return; } int main(void){ int arr[13]; for(int i=2;i<=12;i++){ for(int j=1;j<=i;j++) arr[j]=j; maximum = 0; wronghat(1,i,arr); cout<<maximum<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int n; while(cin>>n && n){ int mtx[100][100]; int row[100] = {0}; int col[100] = {0}; int countrow, countcol, remembercol, rememberrow; bool corrupt; for(int i=0;i<n;i++){ for(int j=0;j<n;j++) cin>>mtx[i][j]; } corrupt = false; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ row[i]+=mtx[i][j]; col[j]+=mtx[i][j]; } row[i] = row[i]%2; } countrow = countcol = 0; for(int i=0;i<n;i++) col[i] = col[i]%2; for(int i=0;i<n;i++){ if(col[i]==1){ countcol++; remembercol = i; } if(row[i]==1){ countrow++; rememberrow = i; } if(countcol>1 || countrow>1){ corrupt = true; break; } } if(countcol == 0 && countrow == 0) cout<<"OK"<<endl; if(corrupt || (countcol == 1 && countrow == 0) || (countcol == 0 && countrow == 1)) cout<<"Corrupt"<<endl; else if(countcol == 1 && countrow == 1) cout<<"Change bit ("<<rememberrow+1<<","<<remembercol+1<<")"<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int testcase; int height[10]; bool consistent; cin>>testcase; cout<<"Lumberjacks:"<<endl; for(int i=0;i<testcase;i++){ cin>>height[0]>>height[1]; consistent = true; for(int j=2;j<=9;j++) cin>>height[j]; if(height[0]>height[1]){ for(int j=1;j<9;j++) if(height[j]<height[j+1]){ consistent = false; break; } } else{ for(int j=1;j<9;j++) if(height[j]>height[j+1]){ consistent = false; break; } } if(consistent) cout<<"Ordered"<<endl; else cout<<"Unordered"<<endl; } return 0; } <file_sep>#include<map> #include<iostream> #include<string> using namespace std; int main(void){ map<string,int> dict; string input, newstr; char in; int len; while(getline(cin,input)){ len = input.length(); for(int i=0;i<len;i++){ if(input.at(i)>='A' && input.at(i)<='Z'){ in = tolower(input.at(i)); newstr = newstr + in; } else if(input.at(i)>='a' && input.at(i)<='z') newstr = newstr + input.at(i); else if(newstr.length()>0){ dict[newstr]++; newstr.clear(); } if(i == len-1 && newstr.length()>0){ dict[newstr]++; newstr.clear(); } } } for(map<string,int>::iterator it = dict.begin(); it!=dict.end();it++) cout<<it->first<<endl; } <file_sep>#include<iostream> using namespace std; int main(void){ int start, dial1, dial2, dial3, total; while(true){ cin>>start>>dial1>>dial2>>dial3; if(start==dial1 && dial1==dial2 && dial2 == dial3 && dial3 == 0) break; total = 1080; if(start<dial1) total+= 360-(dial1-start)*9; else total+= 360-((dial1*9) + (40-start)*9); if(dial1>dial2) total+= 360-(dial1-dial2)*9; else total+= 360-((40-dial2)*9 + dial1*9); if(dial2<dial3) total+= 360-((dial3-dial2)*9); else total+= 360-((dial3*9) + (40-dial2)*9); cout<<total<<endl; } return 0; } <file_sep>#include<iostream> #include<algorithm> #include<vector> #include<math.h> using namespace std; int main(void){ vector<long long> myint; long long temp; long long input; for(long long i=0;i<=31;i++) for(long long j=0;j<20;j++){ temp = pow(2,i)*pow(3,j); if(temp>0) myint.push_back(temp); } sort(myint.begin(),myint.end()); vector<long long>::iterator it; it = myint.begin(); while(cin>>input && input){ if(binary_search(myint.begin(),myint.end(),input)) cout<<input<<endl; else{ it = upper_bound(myint.begin(),myint.end(),input); cout<<*it<<endl; } } return 0; } <file_sep>#include<iostream> #include<algorithm> #include<math.h> using namespace std; int main(void){ long long land[41]; long long test,j,cost,tempnum; cin>>test; for(int i=0;i<test;i++){ for(j=0;j<40;j++){ cin>>land[j]; if(!land[j]) break; } j--; sort(land,land+j+1); cost = 0; tempnum = j; for(int k=0;k<=j;k++){ cost+= pow(land[tempnum],k+1)*2; tempnum--; } if(cost>5000000) cout<<"Too expensive"; else cout<<cost; cout<<endl; } } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> #include<algorithm> using namespace std; char mines[500][500]; int dr[] = {0,1,0,-1}; int dc[] = {-1,0,1,0}; int maxrow, maxcol; typedef struct{ char name; int number; }holes; void scan_minefield(int row, int col){ int r; getchar(); for (r=0; r<row; r++){ gets(mines[r]); } } bool sortcomp(holes a, holes b){ if(a.number!=b.number) return a.number>b.number; else return a.name<b.name; } int floodfill(int row, int col, char c1, char c2){ if(row<0||row>=maxrow||col<0||col>=maxcol) return 0; if(mines[row][col]!=c1) return 0; mines[row][col] = c2; int ans = 1; for(int d=0;d<4;d++) ans+=floodfill(row+dr[d],col+dc[d],c1,c2); return ans; } int main(void){ int counter, countprob = 1; holes hole[250000]; while(cin>>maxrow>>maxcol && maxrow && maxcol){ scan_minefield(maxrow,maxcol); counter = 0; for(int i=0;i<maxrow;i++) for(int j=0;j<maxcol;j++) if(mines[i][j]!='.'){ hole[counter].name = mines[i][j]; hole[counter].number = floodfill(i,j,mines[i][j],'.'); counter++; } cout<<"Problem "<<countprob++<<":"<<endl; if(counter>1) sort(hole,hole+counter,sortcomp); if(counter==0) cout<<endl; else for(int i=0;i<counter;i++) cout<<hole[i].name<<" "<<hole[i].number<<endl; } } <file_sep>#include<iostream> using namespace std; int main(void){ int sum[1001]; int test, counter, dummy; while(cin>>test && test){ counter = 0; while(test--){ cin>>dummy; if(dummy){ sum[counter] = dummy; counter++; } } if(counter>0){ for(int i=0;i<counter-1;i++){ cout<<sum[i]<<" "; } cout<<sum[counter-1]<<endl; } else cout<<"0"<<endl; } return 0; } <file_sep>import java.util.*; import java.math.BigInteger; class uva787{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); BigInteger[] bi = new BigInteger[102]; int[] zeros = new int[102]; while(sc.hasNext()){ int counter = 1; for(int i=0;i<102;i++)zeros[i] = 0; bi[0] = BigInteger.ONE; while(true){ int x = sc.nextInt(); if(x == -999999)break; if(x==0){ bi[counter] = BigInteger.ZERO; zeros[counter] = 1; }else{ if(zeros[counter-1] == 1){ bi[counter] = BigInteger.valueOf(x); }else{ bi[counter] = bi[counter-1].multiply(BigInteger.valueOf(x)); } } counter++; } BigInteger maximum, current; maximum = new BigInteger("-999999999999"); current = bi[0]; for(int i=1;i<counter;i++){ if(zeros[i] == 1){ if(maximum.compareTo(BigInteger.ZERO) < 0) maximum = BigInteger.ZERO; } else{ for(int j=i;j<counter;j++){ if(zeros[j] == 1) break; if(zeros[i-1] == 1){ current = bi[j]; }else{ current = bi[j].divide(bi[i-1]); } //System.out.println("Current: "+current+" i:"+i+" j:"+j); if(maximum.compareTo(current) < 0) maximum = current; } } } System.out.println(maximum); } } }<file_sep>#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int main(void){ int numinput,searched; int num[10001],hi,lo; while(scanf("%d",&numinput)==1){ for(int i=0;i<numinput;i++) scanf("%d",&num[i]); scanf("%d",&searched); sort(num,num+numinput); for(int i=0;num[i]<=searched/2;i++){ if(num[i]==searched/2 && num[i+1]==searched/2){ hi = num[i]; lo = num[i]; break; } if(binary_search(num,num+numinput,searched-num[i])){ hi = searched-num[i]; lo = num[i]; } } printf("Peter should buy books whose prices are %d and %d.\n\n",lo,hi); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int h1,m1,h2,m2, timefrom, timeto; while(cin>>h1>>m1>>h2>>m2){ if(h1 == 0 && h2 == 0 && m1 == 0 && m2 == 0) return 0; timefrom = h1*60 + m1; timeto = h2*60 + m2; if(timefrom<=timeto) cout<<timeto-timefrom; else cout<<1440 - timefrom + timeto; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> using namespace std; int main(void){ int row, col, command, rownow, colnow, countsticker; char com[51000]; char field[101][101]; char now; while(scanf("%d %d %d",&row,&col,&command) && row && col && command){ getchar(); for(int i=0;i<row;i++) gets(field[i]); gets(com); countsticker = 0; for(int i=0;i<row;i++) for(int j=0;j<col;j++) if(field[i][j]=='N'){ now = 'N'; rownow = i; colnow = j; break; } else if(field[i][j]=='S'){ now = 'S'; rownow = i; colnow = j; break; } else if(field[i][j]=='L'){ now = 'L'; rownow = i; colnow = j; break; } else if(field[i][j]=='O'){ now = 'O'; rownow = i; colnow = j; break; } for(int i=0;i<command;i++) switch(com[i]){ case 'D':{ if(now=='N') now = 'L'; else if(now=='L') now = 'S'; else if(now=='O') now = 'N'; else if(now=='S') now = 'O'; break; } case 'E':{ if(now=='N') now = 'O'; else if(now=='L') now = 'N'; else if(now=='O') now = 'S'; else if(now=='S') now = 'L'; break; } case 'F':{ if(now=='N' && rownow!=0){ rownow--; if(field[rownow][colnow]=='#') rownow++; if(field[rownow][colnow]=='*'){ countsticker++; field[rownow][colnow]='.'; } } else if(now=='L' && colnow!=col-1){ colnow++; if(field[rownow][colnow]=='#') colnow--; if(field[rownow][colnow]=='*'){ countsticker++; field[rownow][colnow]='.'; } } else if(now=='S' && rownow!=row-1){ rownow++; if(field[rownow][colnow]=='#') rownow--; if(field[rownow][colnow]=='*'){ countsticker++; field[rownow][colnow]='.'; } } else if(now=='O' && colnow!=0){ colnow--; if(field[rownow][colnow]=='#') colnow++; if(field[rownow][colnow]=='*'){ countsticker++; field[rownow][colnow]='.'; } } break; } } cout<<countsticker<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string> using namespace std; int main(void){ string words; int occur[128]; int max; while(getline(cin,words)){ max = 0; for(int i=0;i<128;i++) occur[i] = 0; for(int i=0;i<words.length();i++){ if((int) words.at(i)>64 && (int) words.at(i)<128) occur[(int)words.at(i)]++; if(occur[(int)words.at(i)]>max) max = occur[(int) words.at(i)]; } for(int i=65;i<122;i++){ if(occur[i]==max) cout<<(char) i; } cout<<" "<<max<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<algorithm> #include<vector> using namespace std; typedef vector<int> vi; typedef vector<vi> vii; vii AdjList; vi topoSort; int dfs[100000]; void dfsnum(int vtx){ dfs[vtx] = 1; for(int i=0;i<(int)AdjList[vtx].size();i++){ int v = AdjList[vtx][i]; if(dfs[v] == 0) dfsnum(v); } topoSort.push_back(vtx); } int main(void){ int numvertex = 0,numneighbor,x,total; while(cin>>numvertex){ topoSort.clear(); AdjList(numvertex,vii()); for(int i=0;i<numvertex;i++){ cin>>numneighbor; for(int j=0;j<numneighbor;j++){ cin>>x; AdjList[i].push_back(x); } } for(int i=0;i<numvertex;i++) dfs[i] = 0; for(int i=0;i<numvertex;i++) if(dfs[i]==0) dfsnum(i); reverse(topoSort.begin(),topoSort.end()); int ways[numvertex]={}; ways[0] = 1; for(int i=0;i<topoSort.size();i++){ int x = topoSort[i]; for(int j=0;j<(int)AdjList[x].size();j++) ways[AdjList[x][j]]+=ways[x]; } total = 0; for(int j=0;j<topoSort.size();j++) if((int)AdjList[j].size() == 0){ total+=ways[AdjList[j]]; } cout<<total<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> #include<stdio.h> using namespace std; char grid[100][100]; int painted[100][100]; int dr[]={0,-1,0,1}; int dc[]={-1,0,1,0}; int counter; void floodfill(int row, int col, char c1){ if(row<0||col<0||row>=counter-1||col>=80 || painted[row][col]) return; if(grid[row][col]=='X'){ painted[row][col]=1; return; } if(row-1>=0 && grid[row-1][col]=='X'){ grid[row][col]='#'; painted[row][col] = 1; } if(col-1>=0 && grid[row][col-1]=='X'){ grid[row][col]='#'; painted[row][col] = 1; } if(row+1<counter-1 && grid[row+1][col]=='X'){ grid[row][col]='#'; painted[row][col] = 1; } if(col+1<100 && grid[row][col+1]=='X'){ grid[row][col]='#'; painted[row][col] = 1; } painted[row][col]=1; for(int d=0;d<4;d++) floodfill(row+dr[d],col+dc[d],c1); } int main(void){ int test; cin>>test; getchar(); for(int i=0;i<test;i++){ counter = 0; while(true){ gets(grid[counter]); counter++; if(grid[counter-1][0]=='_') break; } for(int i=0;i<counter-1;i++) for(int j=strlen(grid[i]);j<=80;j++) grid[i][j]=' '; for(int i=0;i<counter;i++) for(int j=0;j<100;j++) painted[i][j]=0; for(int i=0;i<counter-1;i++) for(int j=0;j<strlen(grid[i]);j++) if(grid[i][j]=='*'){ grid[i][j]=' '; floodfill(i,j,'#'); } int last; for(int i=0;i<counter-1;i++){ last = 0; for(int j=0;j<80;j++) if(grid[i][j]=='#' || grid[i][j]=='X') last = j; if(last||grid[i][0]=='#'||grid[i][0]=='X') grid[i][last+1]='\0'; else grid[i][0]='\0'; } for(int i=0;i<counter;i++) printf("%s\n",grid[i]); } return 0; } <file_sep>#include<iostream> #include<string.h> #include<algorithm> using namespace std; bool isSubset(string a, string b){ if(a.length()<b.length() && b.length()%a.length()==0) for(int j=0;j<a.length();j++) for(int i=j;i<b.length();i+=a.length()){ if(b.at(i)!=a.at(j)) return false; return true; } else if(a.length()>b.length() && a.length()%b.length()==0){ for(int j=0;j<b.length();j++) for(int i=j;i<a.length();i+=b.length()){ if(a.at(i)!=b.at(j)) return false; return true; } } else return false; } bool sort_comp(string a, string b){ int counta, countb; if(a==b||(a.length()!=b.length() && isSubset(a,b))) return a.at(0)>b.at(0); counta = countb = 0; while(a.at(counta)==b.at(countb)){ counta++; countb++; if(counta==a.length()) counta=0; if(countb==b.length()) countb=0; } return a.at(counta)>b.at(countb); } int main(void){ int input; string in[100000]; while(cin>>input && input){ for(int i=0;i<input;i++) cin>>in[i]; stable_sort(in,in+input,sort_comp); for(int i=0;i<input;i++) cout<<in[i]; cout<<endl; } return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int numhead, numsol,solcount,headcount, total; int head[20000], soldier[20000]; while(cin>>numhead>>numsol && numhead && numsol){ for(int i=0;i<numhead;i++) cin>>head[i]; for(int i=0;i<numsol;i++) cin>>soldier[i]; if(numhead>numsol) cout<<"Loowater is doomed!"<<endl; else{ sort(head,head+numhead); sort(soldier,soldier+numsol); total = headcount = solcount = 0; while(headcount<numhead && solcount<numsol){ while(head[headcount]>soldier[solcount]){ solcount++; if(solcount == numsol) break; } if(solcount==numsol) break; total+=soldier[solcount]; solcount++; headcount++; } if(headcount<numhead) cout<<"Loowater is doomed!"<<endl; else if(headcount == numhead) cout<<total<<endl; } } return 0; } <file_sep>#include<vector> #include<algorithm> #include<cstdio> #include<iostream> #include<queue> #include<map> #include<stdio.h> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; map<int, int> mapper, reverseMapper,lister; vi p; vector<vii> AdjList; int main(void){ int notreached,casecounter = 1; int numpair,g1,g2,a,b,counter; int mapped,TTL; int s,layer; map<int,int> dist; while(cin>>numpair && numpair){ counter = 0; AdjList.clear(); lister.clear(); AdjList.assign(60,vii()); mapper.clear(); reverseMapper.clear(); for(int i=0;i<numpair;i++){ scanf("%d %d",&a,&b); if (mapper.find(a) == mapper.end()) { // mapping trick mapper[a] = counter++; reverseMapper[mapper[a]] = a; } if (mapper.find(b) == mapper.end()) { mapper[b] = counter++; reverseMapper[mapper[b]] = b; } AdjList[mapper[a]].push_back(ii(mapper[b], 0)); AdjList[mapper[b]].push_back(ii(mapper[a], 0)); } while(scanf("%d %d",&mapped,&TTL)&& (mapped||TTL)){ dist.clear(); notreached = 0; p.assign(60,-1); s = mapper[mapped]; dist[s]=0; queue<int> q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); layer = dist[u]; for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (!dist.count(v.first)) { dist[v.first] = dist[u] + 1; if(dist[v.first]<=TTL) notreached++; p[v.first] = u; q.push(v.first); } } } printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",casecounter++,lister.size()-1-notreached,mapped,TTL); } } return 0; } <file_sep>#include<iostream> using namespace std; int gcd(int,int); int main(void){ int test; int x, res, counter; while(cin>>test){ x = test*2; counter = 0; for(int i=test+1;i<=x;i++){ res = i-test; if(gcd(res,test*i)==res) counter++; } cout<<counter<<endl; for(int i=test+1;i<=x;i++){ res = i-test; if(gcd(res,test*i)==res){ cout<<"1/"<<test<<" = 1/"<<test*i/res<<" + 1/"<<i<<endl; } } } return 0; } int gcd(int a , int b){return (b==0?a:gcd(b,a%b));} <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ int test[16]; int N,K, testcase; cin>>testcase; for(int i=0;i<testcase;i++){ cin>>N>>K; for(int j=0;j<N-K;j++) test[j] = 0; for(int j=N-K;j<N;j++) test[j] = 1; do { for(int j=0;j<N;j++) cout<<test[j]; cout<<endl; } while ( next_permutation (test,test+N) ); } return 0; } <file_sep>#include<map> #include<stdio.h> #include<string.h> #include<iostream> using namespace std; long long fib[100]; int main(void){ map<int,char> fibzz; long long temp = 2147483647; int counter = 2, counter1; fib[0]=1; fib[1]=2; string str; int res[100],input,test; for(int i=2;i<=45;i++) fib[i]=fib[i-1]+fib[i-2]; cin>>input; for(int i=0;i<input;i++){ fibzz.clear(); cin>>test; for(int j=0;j<test;j++){ cin>>res[j]; } getline(cin,str); getline(cin,str); counter = counter1 = 0; while(counter<test){ if(str.at(counter1)>='A' && str.at(counter1)<='Z'){ fibzz[res[counter]]=str.at(counter1); counter++; counter1++; } else counter1++; } for(int i=0;i<test;i++){ if(fibzz.find(fib[i])==fibzz.end()){ cout<<" "; test++; } else cout<<fibzz[fib[i]]; } cout<<endl; } return 0; } <file_sep>#include <stdio.h> #include <string.h> #define MAX_ROWS 101 // maximum rows of a minefield #define MAX_COLS 100 // maximum columns of a minefield #include<iostream> using namespace std; void scan_minefield(int, int); int count_minefield(int, int, int, int, char, char); int dr[] = {1,1,0,-1,-1,-1,0,1}; int dc[] = {0,1,1,1,0,-1,-1,-1}; char savechar; char minefield[MAX_ROWS][MAX_COLS+1]; int main(void) { int maxtemp, maxcont,dummy; int row_size, col_size; // actual size of minefield read int i,j, firstminex, firstminey; while(scanf("%d %d", &row_size, &col_size) == 2){ scan_minefield(row_size,col_size); cin>>firstminex>>firstminey; savechar = minefield[firstminex][firstminey]; dummy=count_minefield(firstminex,firstminey, row_size, col_size, savechar, savechar+1); maxcont = dummy; for(i=0;i<row_size;i++) for(j=0;j<col_size;j++) { if(minefield[i][j] == savechar) { maxtemp = count_minefield(i, j, row_size,col_size, savechar, savechar+1); if(maxtemp>maxcont) maxcont = maxtemp; } } printf("%d\n",maxcont); } return 0; } // To read in the minefield void scan_minefield(int row, int col) { int r; getchar(); for (r=0; r<row; r++){ gets(minefield[r]); } } //To read where the minecluster is. int count_minefield(int row, int col, int row_size, int col_size, char c1, char c2) { if(row<0 || row>=row_size || col<0 || col>=col_size) return 0; if(minefield[row][col]!=c1) return 0; int ans = 1; minefield[row][col] = c2; if(col==0) ans+=count_minefield(row,col_size-1,row_size,col_size,c1,c2); if(col==col_size-1) ans+=count_minefield(row,0,row_size,col_size,c1,c2); for(int i=0;i<8;i++) ans+=count_minefield(row+dr[i],col+dc[i], row_size, col_size, c1, c2); return ans; } <file_sep>#include<iostream> #include<sstream> #include<stdio.h> #include<vector> using namespace std; int counter; string news[13]; void comb(int now, int count, int maxz, vector<string> name){ if(count==maxz){ for(int i=0;i<maxz-1;i++) cout<<name.at(i)<<", "; cout<<name.at(maxz-1)<<endl; name.clear(); return; } else{ for(int i=now;i<counter-1;i++){ name.push_back(news[i]); comb(i+1,count+1,maxz,name); name.pop_back(); } } return; } int main(void){ string in; vector<string> name; int test, low, high, cond; cin>>test; getchar(); getchar(); for(int j=0;j<test;j++){ name.clear(); getline(cin,in); if(in.length()>2){ stringstream(in)>>low>>high; cond = 1; } else if(in.at(0)=='*'){ cond = 2; } else{ stringstream(in)>>low; cond = 3; } counter = 0; while(getline(cin,news[counter++])){ if(news[counter-1].empty()) break; } if(cond==1){ for(int i=low;i<=high;i++){ name.clear(); cout<<"Size "<<i<<endl; comb(0,0,i,name); cout<<endl; } } else if(cond==2){ for(int i=1;i<counter;i++){ name.clear(); cout<<"Size "<<i<<endl; comb(0,0,i,name); cout<<endl; } } else if(cond==3){ name.clear(); cout<<"Size "<<low<<endl; comb(0,0,low,name); cout<<endl; } if(j!=test-1) cout<<endl; } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class Krakovia{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int counter = 1; int numbill, friends; while(true){ BigInteger total = BigInteger.ZERO; numbill = sc.nextInt(); friends = sc.nextInt(); BigInteger fr = BigInteger.valueOf(friends); if(numbill == 0 && friends == 0) break; for(int i=0;i<numbill;i++){ total = total.add(sc.nextBigInteger()); } System.out.println("Bill #"+counter+" costs "+total+": each friend should pay "+total.divide(fr)); System.out.println(); counter++; } return; } }<file_sep>#include<iostream> #include<string.h> #include<stdio.h> using namespace std; char tree[1000][1000]; int fills[1000][1000]; int counter,countrow; int c; int maxeachrow[1000]; int dr[]={-1,-1,-1,0,0,1,1,1}; int dc[]={-1,0,1,-1,1,-1,0,1}; void floodfill(int row, int col, char c1, char c2, int c){ if(row<0||row>=countrow||col<0||col>=counter) return; if(tree[row][col]!=c1) return; fills[row][col] = c; tree[row][col] = c2; for(int d=0;d<8;d++) floodfill(row+dr[d],col+dc[d],c1,c2,c); } int main(void){ string input; while(getline(cin,input)){ counter = 0; for(int i=0;i<input.length();i++) if(input.at(i)!=' ') tree[0][counter++] = input.at(i); countrow = 1; c = 1; while(getline(cin,input)){ if(input.at(0)=='%') break; counter = 0; for(int i=0;i<input.length();i++) if(input.at(i)!=' ') tree[countrow][counter++] = input.at(i); countrow++; } for(int i=0;i<countrow;i++) for(int j=0;j<counter;j++){ if(tree[i][j]!=' '){ floodfill(i,j,tree[i][j],' ',c); c++; } } memset(maxeachrow,0,sizeof maxeachrow); for(int i=0;i<counter;i++) for(int j=0;j<countrow;j++) if(maxeachrow[i]<fills[j][i]) maxeachrow[i]=fills[j][i]; for(int i=0;i<countrow;i++){ for(int j=0;j<counter-1;j++){ if(maxeachrow[j]<10) printf("%d ",fills[i][j]); else if(maxeachrow[j]<100) printf("%2d ",fills[i][j]); else if(maxeachrow[j]<1000) printf("%3d ",fills[i][j]); else if(maxeachrow[j]<10000) printf("%4d ",fills[i][j]); else if(maxeachrow[j]<100000) printf("%5d ",fills[i][j]); else if(maxeachrow[j]<1000000) printf("%6d ",fills[i][j]); } if(maxeachrow[counter-1]<10) printf("%d",fills[i][counter-1]); else if(maxeachrow[counter-1]<100) printf("%2d",fills[i][counter-1]); else if(maxeachrow[counter-1]<1000) printf("%3d",fills[i][counter-1]); else if(maxeachrow[counter-1]<10000) printf("%4d",fills[i][counter-1]); else if(maxeachrow[counter-1]<100000) printf("%5d",fills[i][counter-1]); else if(maxeachrow[counter-1]<1000000) printf("%6d",fills[i][counter-1]); cout<<endl; } cout<<"%"<<endl; } } <file_sep>#include<iostream> #include<algorithm> #include<stdio.h> #include<math.h> #include<stdlib.h> using namespace std; int main(void){ long long test[1001]; int input, query; long long data, ans, permanent = 0; long long closest; int counter = 1; bool found, small; while(scanf("%d",&input) && input){ for(int i=0;i<input;i++) scanf("%lld",&test[i]); sort(test,test+input); scanf("%d",&query); printf("Case %d:\n",counter++); for(int i=0;i<query;i++){ found = false; cin>>data; closest = 2147483647; if(data>=(test[input-1] + test[input-2])) permanent = test[input-1] + test[input-2]; else{ for(int j=0;j<input-1;j++){ if(test[j]+test[j]>data){ if((test[j]+test[j+1] - data) < closest){ permanent = test[j] + test[j+1]; break; } } for(int k=j+1;k<input;k++){ ans = test[j] + test[k]; if(ans==data){ permanent = ans; found = true; break; } else if(abs(ans-data)<closest){ closest = abs(ans-data); permanent = ans; } if(ans>data) break; } if(found) break; } } cout<<"Closest sum to "<<data<<" is "<<permanent<<"."<<endl; } } return 0; } <file_sep>#include<iostream> #include<stdio.h> using namespace std; int main(void){ int test, player, start, pass, land; scanf("%d",&test); for(int i=1;i<=test;i++){ scanf("%d %d %d",&player,&start,&pass); land = start+pass; land = land%player; if(!land) land = player; printf("Case %d: %d\n",i,land); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int length, train[51]; int test, swap,temp; bool is_sorted; cin>>test; for(int i=0;i<test;i++){ swap = 0; cin>>length; for(int j=0;j<length;j++) cin>>train[j]; for (int k = 1; k < length; k++) { is_sorted = true; for (int j = 0; j < length-k; j++) { if (train[j] > train[j+1]) { temp = train[j]; train[j] = train[j+1]; train[j+1] = temp; is_sorted = false; swap++; } } if (is_sorted) break; } cout<<"Optimal train swapping takes "<<swap<<" swaps."<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<string.h> #define INF 1000000 using namespace std; int main(void){ int member, route,casecounter = 1; int graph[24][24]; string name[24]; while(cin>>member>>route && member){ for(int i=1;i<=member;i++) cin>>name[i]; for(int i=1;i<=member;i++) for(int j=1;j<=member;j++){ if(i!=j) graph[i][j] = INF; else graph[i][j] = 0; } int x,y,dis; for(int i=0;i<route;i++){ cin>>x>>y>>dis; graph[x][y] = graph[y][x] = dis; } for(int k=1;k<=member;k++) for(int i=1;i<=member;i++) for(int j=1;j<=member;j++) graph[i][j] = min(graph[i][j],graph[i][k]+graph[k][j]); int min[25],temp,res; for(int i=1;i<=member;i++){ min[i] = 0; for(int j=1;j<=member;j++){ min[i] += graph[i][j]; //cout<<graph[i][j]<<" "; } //cout<<endl; } temp = INF; for(int i=1;i<=member;i++){ if(temp>min[i]){ temp = min[i]; res = i; } } cout<<"Case #"<<casecounter++<<" : "<<name[res]<<endl; } return 0; } <file_sep>#include<iostream> #include<vector> #include<stdio.h> #include<algorithm> using namespace std; int main(void){ vector<int> fibo; fibo.push_back(0); fibo.push_back(1); int test, num; for(int i=2;i<40;i++) fibo.push_back(fibo[i-1] + fibo[i-2]); scanf("%d",&test); while(test--){ scanf("%d",&num); bool first = false; printf("%d = ",num); if(!num) printf("0 (fib)\n"); else{ for(int i=39;i>1;i--){ if(num>=fibo[i]){ first = true; printf("1"); num-=fibo[i]; } else if(first) printf("0"); } printf(" (fib)\n"); } } return 0; } <file_sep> #include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int main(void){ //freopen("in.txt","r",stdin); int tc; scanf("%d",&tc); ll box[27][27]; string str; getline(cin,str); getline(cin,str); TC(){ reset(box,0); int counter = 0; int len = 0; while(getline(cin,str)){ if(str==""){ //printf("ga ada apa2"); break; } len = str.length(); FOR(i,len){ if(str.at(i)=='1')box[counter][i] = 1; else box[counter][i] = -INF; if(i>0) box[counter][i]+=box[counter][i-1]; if(counter>0) box[counter][i]+=box[counter-1][i]; if(i>0 && counter>0)box[counter][i] -= box[counter-1][i-1]; } counter++; } /*FOR(i,counter){ FOR(j,len) printf("%lld ",box[i][j]); printf("\n"); }*/ ll optimum = 0, subRect; FOR(i,counter){ FOR(j,len){ REP(k,i,counter){ REP(l,j,len){ subRect = box[k][l]; if(i>0) subRect -= box[i-1][l]; if(j>0) subRect -= box[k][j-1]; if(i>0 && j>0) subRect += box[i-1][j-1]; optimum = max(optimum, subRect); } } } } printf("%lld\n",optimum); if(tc)printf("\n"); } return 0; } <file_sep>#include <iostream> using namespace std; int main () { longint i, j, result; while(cin >> i >> j){ result = 0; if(i<j) result = j-i; else result = i-j; cout<<result<<endl; } return 0; } <file_sep>#include<iostream> #include<stdlib.h> #include<algorithm> using namespace std; int main(){ int testcase, numrel, median, totaldist; int dist[500]; cin>>testcase; for(int i=0;i<testcase;i++){ cin>>numrel; totaldist = 0; for(int j=0;j<numrel;j++){ cin>>dist[j]; } sort(dist,dist+numrel); if(numrel%2==1) median = dist[numrel/2]; else median = (dist[numrel/2-1]+dist[numrel/2])/2; for(int j=0;j<numrel;j++){ totaldist+=abs(dist[j]-median); } cout<<totaldist<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<vector> #include<map> using namespace std; typedef vector<int> vi; typedef vector<vi> vii; vii AdjList; map<int,int> mapper,reverseMapper; int visited[101]; int startnode; void dfs(int x){ visited[x]++; for(int i=0;i<AdjList[x].size();i++){ if(!visited[AdjList[x][i]]){ dfs(AdjList[x][i]); } } } int main(void){ int N,start,counter,numnode,num; vi unvisited; while(cin>>N && N){ mapper.clear(); reverseMapper.clear(); AdjList.clear(); AdjList.assign(N+1,vi()); counter = 0; while(cin>>start){ if(start){ if(mapper.find(start)==mapper.end()){ mapper[start] = counter; reverseMapper[counter] = start; counter++; } while(cin>>num && num){ if(mapper.find(num)==mapper.end()){ mapper[num] = counter; reverseMapper[counter] = num; counter++; } AdjList[start].push_back(num); } } else{ cin>>numnode; for(int i=0;i<numnode;i++){ unvisited.clear(); for(int j=0;j<=N;j++){ visited[j] = 0; } cin>>startnode; visited[startnode] = -1; dfs(startnode); for(int j=1;j<=N;j++){ if(!visited[j]){ unvisited.push_back(j); } } cout<<unvisited.size(); for(int j=0;j<unvisited.size();j++) cout<<" "<<unvisited[j]; cout<<endl; } break; } } } return 0; } <file_sep>#include<map> #include<string.h> #include<iostream> #include<stdio.h> using namespace std; int main(void){ map<string,int> freq; int in,max,length,a; string str,rem,str2; while(scanf("%d",&in)==1){ getline(cin,str); max = 0; freq.clear(); length = str.length() - in + 1; for(int i=0;i<=length;i++){ str2 = str.substr(i,in); freq[str2]++; if(freq[str2]>=max){ max = freq[str2]; rem = str2; } } cout<<rem<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int turn[151]; int turnedoff, counter,tries, countadd; bool fail; int n; tries = 1; for(int n=3;n<150;n++){ fail = false; for(int i=2;i<=n;i++) turn[i]=1; turn[1] = 0; counter = 1; turnedoff = 1; while(turnedoff<n){ countadd = 1; while(countadd<tries){ if(turn[counter]){ countadd++; counter++; } else{ counter++; } if(counter>n) counter = 1; } if(turn[counter]){ turn[counter]=0; turnedoff++; } else{ while(turn[counter]==0){ counter++; if(counter>n) counter=1; } turn[counter]=0; turnedoff++; } if(counter==2 && turnedoff<n){ tries++; n--; fail=true; break; } } if(!fail){ cout<<n<<" "<<tries<<endl; tries = 1; } } } <file_sep>#include<iostream> #include<algorithm> using namespace std; int main(void){ long long triangle[3]; int test; cin>>test; for(int i=1;i<=test;i++){ for(int j=0;j<3;j++) cin>>triangle[j]; cout<<"Case "<<i<<": "; sort(triangle,triangle+3); if(triangle[2]>=triangle[0]+triangle[1]) cout<<"Invalid"<<endl; else if(triangle[0]<=0 || triangle[1]<=0 || triangle[2]<=0) cout<<"Invalid"<<endl; else if(triangle[0]==triangle[1]&&triangle[1]==triangle[2]) cout<<"Equilateral"<<endl; else if(triangle[0]==triangle[1] || triangle[0]==triangle[2] || triangle[1] == triangle[2]) cout<<"Isosceles"<<endl; else cout<<"Scalene"<<endl; } return 0; } <file_sep>#include<iostream> #include<string.h> using namespace std; int main(void){ bool self[1000001]; memset(self,true,sizeof self); int num,temp; for(int i=1;i<=1000000;i++){ num = i; temp = num; while(num>0){ temp+=num%10; num/=10; } if(temp<1000001) self[temp] = false; } for(int i=1;i<=1000000;i++) if(self[i]) cout<<i<<endl; return 0; } <file_sep> /* 8 Queens Chess Problem */ #include <iostream> #include <string.h> #include <math.h> #include <stdlib.h> #include <stdio.h> using namespace std; int row[9], TC, a, b, lineCounter; // it is ok to use global variables in competitive programming int count; int rowcol[92][9]; int quest[9]; bool place(int col, int tryrow) { for (int prev = 1; prev < col; prev++) // check previously placed queens if (row[prev] == tryrow || (abs(row[prev] - tryrow) == abs(prev - col))) return false; // an infeasible solution if share same row or same diagonal return true; } void backtrack(int col) { for (int tryrow = 1; tryrow <= 8; tryrow++) // try all possible row if (place(col, tryrow)) { // if can place a queen at this col and row... row[col] = tryrow; // put this queen in this col and row if (col == 8) { // a candidate solution & (a, b) has 1 queen for(int i=1;i<=8;i++) rowcol[count][i]=row[i]; count++; } else backtrack(col + 1); // recursively try next column } } int main() { int max,temp,casecounter=1; count = 0; memset(row, 0, sizeof row); lineCounter = 0; backtrack(1); // generate all possible 8! candidate solutions while (cin>>quest[1]) { max = 8; for(int i=2;i<=8;i++) cin>>quest[i]; for(int i=0;i<92;i++){ temp = 0; for(int j=1;j<=8;j++) if(quest[j]!=rowcol[i][j]){ temp++; } if(temp<max) max = temp; } printf("Case %d: %d\n",casecounter++,max); } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) int main(void){ freopen("D:/Code/in.txt","r",stdin); int k,q,q2; while(scanf("%d %d %d",&k,&q,&q2)!=EOF){ if(k == q)printf("Illegal state\n"); else{ bool ilmove = false; bool stuck = false; bool notallowed = false; if(k == q2)ilmove = true; int oldx, oldy, newx, newy, kingx, kingy; kingx = k/8; kingy = k%8; oldx = q/8; oldy = q%8; newx = q2/8; newy = q2%8; if(oldx != newx && oldy != newy)ilmove = true; if(q == q2)ilmove = true; if(!ilmove){ if(oldx == newx){ int a = min(oldy,newy); int b = max(oldy,newy); REPN(i,a,b){ if(oldx == kingx && i==kingy)ilmove = true; } } else{ int a= min(oldx,newx); int b = max(oldx,newx); REPN(i,a,b){ if(oldy == kingy && i == kingx)ilmove = true; } } } } } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC(tc) while(tc--) #define reset(a,b) memset(a,b,sizeof(a)) vi taken; priority_queue<ii>pq; vector<vii> AdjList; void process(int vtx) { // so, we use -ve sign to reverse the sort order taken[vtx] = 1; for (int j = 0; j < (int)AdjList[vtx].size(); j++) { ii v = AdjList[vtx][j]; if (!taken[v.first]) pq.push(ii(-v.second, -v.first)); } } int main(void){ //freopen("in.txt","r",stdin); int tc; string name,name2; int V,route,cost; map<string,int>mapper; scanf("%d",&tc); //int mst_cost; TC(tc){ scanf("%d %d",&V,&route); AdjList.assign(V,vii()); int counter = 0; mapper.clear(); for(int i=0;i<route;i++){ cin>>name>>name2>>cost; if(mapper.find(name)==mapper.end()){ mapper[name] = counter++; } if(mapper.find(name2)==mapper.end()) mapper[name2] = counter++; AdjList[mapper[name]].push_back(ii(mapper[name2],cost)); AdjList[mapper[name2]].push_back(ii(mapper[name],cost)); } int u,w; taken.assign(V, 0); // no vertex is taken at the beginning process(mapper[name]); // take vertex 0 and process all edges incident to vertex 0 int mst_cost = 0; while (!pq.empty()) { // repeat until V vertices (E=V-1 edges) are taken ii front = pq.top(); pq.pop(); u = -front.second, w = -front.first; // negate the id and weight again if (!taken[u]) // we have not connected this vertex yet mst_cost += w, process(u); // take u, process all edges incident to u } printf("%d\n",mst_cost); if(tc)printf("\n"); } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int main(void){ int arr[3]; while(scanf("%d %d %d",&arr[0],&arr[1],&arr[2]) && arr[0] && arr[1] && arr[2]){ sort(arr,arr+3); if(arr[0] == arr[1] && arr[1] == arr[2]){ if(arr[1]==13) printf("*\n"); else{ arr[0]++; printf("%d %d %d\n",arr[0],arr[0],arr[0]); } } else if(arr[0] == arr[1] || arr[1]==arr[2]){ if(arr[1]==13 && arr[2]==13 && arr[0]==12) printf("1 1 1\n"); else if(arr[1] == 13 && arr[2]==13) printf("%d 13 13\n",arr[0]+1); else if(arr[0] == arr[1]){ if(arr[2]==13) printf("1 %d %d\n",arr[0]+1,arr[1]+1); else printf("%d %d %d\n",arr[0],arr[1],arr[2]+1); } else if(arr[1]==arr[2]){ if(arr[0]+1!=arr[1]) printf("%d %d %d\n",arr[0]+1,arr[1],arr[2]); else printf("%d %d %d\n",arr[1],arr[2],arr[0]+2); } } else{ printf("1 1 2\n"); } } return 0; } <file_sep>#define MAX_N 3 typedef struct{ ll mat[3][3]; }Matrix; Matrix matMul(Matrix a, Matrix b){ Matrix ans; int i,j,k; for(i=0;i<MAX_N;i++) for(j=0;j<MAX_N;j++) for(ans.mat[i][j] = k = 0;k<MAX_N; k++) ans.mat[i][j] = (ans.mat[i][j] + a.mat[i][k]%1000000009 * b.mat[k][j]%1000000009)%1000000009; //if you want real answer, delete the modulo return ans; } Matrix matPow(Matrix base, ll p){ Matrix ans; int i,j; for(i=0;i<MAX_N;i++) for(j=0;j<MAX_N;j++) ans.mat[i][j] = (i==j); while(p){ if(p&1) ans = matMul(ans,base); base = matMul(base,base); p>>=1; } return ans; //trifib(n) is in base[1][1], change to fib(n) --> stored in [1][0] } <file_sep>#include <iostream> #include <string.h> #include<stdio.h> void count_eagle(string [], int, int); int main(void) { string field[27]; int size; int counter; cin>>size; for(int i=1;i<=size;i++){ cin>>field[i]; } for(int i=1;i<size;i++) for(int j=0;j<size;j++) { if(field[i].charAt(j) == '1') { count_eagle(field, i, j); counter++; } } printf("%d",counter); return 0; } void count_eagle(string[] field, int row, int col){ minefield[row][col]=0; for(int i=row-1;i<=row+1;i++) for(int j=col-1;j<=col+1;j++) if(field[i].charAt(j)=='1') count_minefield(minefield,i,j); } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int gcd(int a, int b) { int tmp; while(b){a%=b; tmp=a; a=b; b=tmp;} return a; } int extended_euclid(int a, int b, int &x, int &y) { int xx = y = 0; int yy = x = 1; while (b) { int q = a/b; int t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y-q*yy; y = t; } return a; } int mod(int a, int b) { return ((a%b)+b)%b; } // computes b such that ab = 1 (mod n), returns -1 on failure int mod_inverse(int a, int n) { int x, y; int d = extended_euclid(a, n, x, y); if (d > 1) return -1; return mod(x,n); } // computes x and y such that ax + by = c; on failure, x = y =-1 void linear_diophantine(int a, int b, int c, int &z, int &zz) { int d = gcd(a,b); if (c%d) { z = zz = -1; } else { z = c/d * mod_inverse(a/d, b/d); zz = (c-a*z)/b; } } int main(void){ //freopen("in.txt","r",stdin); int a,b,n,x,y,z,zz; /*while(scanf("%d",&n),n){ int dummy; scanf("%d %d",&dummy,&a); scanf("%d %d",&dummy,&b); linear_diophantine(a,b,n,x,y); if(z == zz && z == -1)printf("failed\n"); else printf("%d %d %d %d %d\n",a,b,x,y,z,zz); }*/ scanf("%d",&n); linear_diophantine(9,1,n,z,zz); printf("%d %d %d %d %d %d %d\n",a,b,n,x,y,z,zz); return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ bool hartal[3651]; int test, N,politic[100],party,counter; cin>>test; for(int i=0;i<test;i++){ counter = 0; cin>>N; for(int j=1;j<=N;j++){ hartal[j] = true; } cin>>party; for(int j=0;j<party;j++){ cin>>politic[j]; for(int k=politic[j];k<=N;k+=politic[j]) hartal[k] = false; } for(int j=6;j<=N;j+=7){ hartal[j] = hartal[j+1] = true; } for(int j=1;j<=N;j++) if(!hartal[j]) counter++; cout<<counter<<endl; } } <file_sep>#include<algorithm> #include<iostream> #include<stdio.h> using namespace std; int main(void){ int size; int input[15]; bool first = true; while(cin>>size && size){ if(first) first = false; else printf("\n"); for(int i=0;i<size;i++) cin>>input[i]; sort(input,input+size); for(int i=0;i<size-5;i++) for(int j=i+1;j<size-4;j++) for(int k=j+1;k<size-3;k++) for(int l=k+1;l<size-2;l++) for(int m=l+1;m<size-1;m++) for(int n=m+1;n<size;n++) printf("%d %d %d %d %d %d\n",input[i],input[j],input[k],input[l],input[m],input[n]); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int device, operation, capacity, max, temp, op, dummy, idx; int devicepower[21], on[21]; bool isBlown; idx = 1; while(true){ cin>>device>>operation>>capacity; if(device==operation && operation == capacity && capacity == 0) break; temp = max = 0; isBlown = false; for(int i=0;i<device;i++){ cin>>devicepower[i]; on[i] = 0; } for(int i=0;i<operation;i++){ cin>>op; if(on[op-1]==0){ on[op-1] = 1; temp+= devicepower[op-1]; if(max<temp) max = temp; if(max>capacity){ isBlown = true; } } else if(on[op-1]==1){ on[op-1] = 0; temp-=devicepower[op-1]; } } cout<<"Sequence "<<idx<<endl; if(isBlown){ cout<<"Fuse was blown."<<endl; } else{ cout<<"Fuse was not blown."<<endl; cout<<"Maximal power consumption was "<<max<<" amperes."<<endl; } cout<<endl; idx++; } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) class UnionFind { // OOP style private: vi p, rank, setSize; // remember: vi is vector<int> int numSets; public: UnionFind(int N) { setSize.assign(N, 1); numSets = N; rank.assign(N, 0); p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { if (!isSameSet(i, j)) { numSets--; int x = findSet(i), y = findSet(j); // rank is used to keep the tree short if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } } int numDisjointSets() { return numSets; } int sizeOfSet(int i) { return setSize[findSet(i)]; } }; int main(void){ //freopen("D:/Code/in.txt","r",stdin); int tc, n, yes, no; char line[1000], q; int c1, c2; scanf("%d\n", &tc); while (tc--) { yes = no = 0; scanf("%d\n\n", &n); UnionFind set(n); while (true) { gets(line); if (strcmp(line, "") == 0 || feof(stdin)) break; sscanf(line, "%c %d %d", &q, &c1, &c2); c1--; c2--; if (q == 'c') { set.unionSet(c1, c2); } else if (q == 'q') { if (set.isSameSet(c1, c2)) yes++; else no++; } } printf("%d,%d\n", yes, no); if (tc) printf("\n"); } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int testcase; int number; cin>>testcase; for(int i=0;i<testcase;i++){ cin>>number; number*=63; number+=7492; number*=5; number-=498; number/=10; number = number%10; if(number<0) number*=-1; cout<<number<<endl; } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class SimpleBaseConversion{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String in; BigInteger x; while(true){ in = sc.next(); if(in.charAt(0) == '-') break; if(in.length()>1 && in.charAt(1)=='x'){ x = new BigInteger(in.substring(2),16); System.out.println(x); } else{ x = new BigInteger(in); System.out.println("0x"+x.toString(16).toUpperCase()); } } } }<file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string judge[100],tobejudged[100]; int line1, line2, counter; bool accepted; counter = 0; while(true){ counter++; cin>>line1; if(line1 == 0) return 0; for(int i=0;i<line1;i++) getline(cin,judge[i]); cin>>line2; for(int i=0;i<line2;i++) getline(cin,tobejudged[i]); accepted = true; if(line1==line2){ for(int i=0;i<line1;i++){ if(judge[i]!=tobejudged[i]){ accepted = false; break; } } if(accepted) cout<<"Run #"<<counter<<": Accepted"<<endl; else{ for(int i=0;i<line1;i++){ for(int j=0;j<judge[i].length();j++){ if((int)judge[i].at()) } for(int j=0;j<tobejudged[i].length();j++){ } } } } } return 0; } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define EPS 1e-9 #define PI acos(-1.0) #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) #define sc(x) scanf("%d",&x) map<char,int> mapper; typedef struct{ char name[2]; }card; typedef vector<card> vcard; int main(void){ freopen("D:/Code/in.txt","r",stdin); char arah[5]; char kartu[50]; mapper['N'] = 0; mapper['E'] = 1; mapper['S'] = 2; mapper['W'] = 3; //vector<card> vcard; vector<vcard>vvc; int now; while(scanf("%s",arah) && arah[0]!='#'){ now = mapper[arah[0]]; vvc.assign(4,vcard()); FOR(i,2){ scanf("%s",kartu); FOR(j,13){ card x; x.name[0] = kartu[2*j]; x.name[1] = kartu[2*j+1]; vvc[now].pb(x); now++; now = now % 4; } } FOR(i,4){ FOR(j,13){ printf("%c%c ",vvc[i][j].name[0],vvc[i][j].name[1]); }printf("\n"); } } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int catcher[100000]; int input; int counter, cases; bool done,first = true; cases = 1; while(true){ counter = 0; cin>>input; if(input == -1) break; catcher[0] = input; counter++; if(!first) cout<<endl; else first = false; while(true){ cin>>input; if(input==-1) break; done = false; for(int i=0;i<counter;i++){ if(catcher[i]<input){ catcher[i] = input; done = true; break; } } if(!done) catcher[counter++] = input; } cout<<"Test #"<<cases<<":"<<endl; cases++; cout<<" maximum possible interceptions: "<<counter<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int test, e,f,c, total, current, newsoda, remainder; cin>>test; for(int i=0;i<test;i++){ cin>>e>>f>>c; total = 0; current = e+f; while(current>=c){ newsoda = current/c; total+=newsoda; remainder = current%c; current = newsoda+remainder; } cout<<total<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(void){ int test, tcase; int newcola, total, empty, numchef; cin>>tcase; for(int i=0;i<tcase;i++){ cin>>test>>numchef; total = test/numchef; empty = test/numchef + test%numchef; while(empty>=numchef){ newcola = empty/numchef; empty = empty%numchef + newcola; total+=newcola; } if(empty == 1){ cout<<total<<endl; } else cout<<"cannot do this"<<endl; } return 0; } <file_sep>import java.util.Scanner; import java.math.BigInteger; class FactorialFrequencies{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int test; String res; int[] digits; BigInteger[] fact = new BigInteger [367]; fact[0] = BigInteger.ONE; fact[1] = BigInteger.ONE; for(int i=2;i<=366;i++){ fact[i] = fact[i-1].multiply(BigInteger.valueOf(i)); } while(true){ test = sc.nextInt(); if(test == 0) break; res = fact[test].toString(); digits = new int[10]; for(int i=0;i<res.length();i++) digits[(int)res.charAt(i)-'0']++; System.out.println(test+"! --"); System.out.println(" (0) "+digits[0]+" (1) "+digits[1]+" (2) "+digits[2]+" (3) "+digits[3]+" (4) "+digits[4]); System.out.println(" (5) "+digits[5]+" (6) "+digits[6]+" (7) "+digits[7]+" (8) "+digits[8]+" (9) "+digits[9]); } } }<file_sep>#include<iostream> #include<map> #include<stdio.h> using namespace std; int main(void){ map<string, double> forest; int test; double counter; cin>>test; string dummy; getline(cin, dummy); getline(cin,dummy); for(int i=0;i<test;i++){ forest.clear(); counter = 0; while(getline(cin,dummy)){ if(dummy.length()==0) break; forest[dummy]++; counter++; } counter/=100; for(map<string, double>::iterator it = forest.begin(); it!=forest.end();it++) printf("%s %.4lf\n", ((string)it->first).c_str(), (it->second)/counter); if(i!=test-1) cout<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<sstream> #include<queue> #include<map> using namespace std; typedef struct{ double x; double y; }Point; int main(void){ int v,m,counter,maxi; Point pt[1001]; string input; while(cin>>v>>m && v && m){ counter = 0; maxi = v*m*v*m; while(getline(cin,input)){ if(input.empty()) break; else{ stringstream(input)>>pt[counter].x>>pt[counter].y; counter++; } } } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<vector> #include<map> using namespace std; int AdjMat[101][101]; int visited; int dr[] = {0,-1,0,1}; int dc[] = {-1,0,1,0}; int dimension; void bfs(int row, int col,int intended){ if(!row||!col||row>dimension||col>dimension) return; if(AdjMat[row][col]==-1 || AdjMat[row][col]!=intended) return; visited++; AdjMat[row][col] = -1; for(int i=0;i<4;i++) bfs(row+dr[i],col+dc[i],intended); } int main(void){ int x,y; while(cin>>dimension && dimension){ bool notgood = false; for(int i=0;i<=dimension;i++) for(int j=0;j<=dimension;j++) AdjMat[i][j] = 0; for(int i=1;i<dimension;i++){ for(int j=0;j<dimension;j++){ cin>>x>>y; AdjMat[x][y] = i; } } for(int i=0;i<dimension;i++){ for(int j=1;j<=dimension;j++){ for(int k=1;k<=dimension;k++){ if(AdjMat[j][k]!=-1){ visited = 0; bfs(j,k,AdjMat[j][k]); if(visited % dimension!=0){ notgood = true; break; } } } if(notgood) break; } if(notgood) break; } if(notgood) cout<<"wrong"<<endl; else cout<<"good"<<endl; } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; int main(void){ string str; bool isPalindrome; int len; while(getline(cin,str)){ if(str == "DONE") return 0; isPalindrome = true; for(int i=0;i<str.length();i++){ if((int)str.at(i)<65 || ((int)str.at(i)>90 && (int)str.at(i)<97) || (int)str.at(i)>122){ str.erase(i,1); i--; } else if((int)str.at(i)>=97) str.at(i)-=32; } for(int i=0;i<str.length()/2;i++){ if(str.at(i)!=str.at(str.length()-1-i)){ isPalindrome = false; break; } } if(isPalindrome) cout<<"You won't be eaten!"<<endl; else cout<<"Uh oh.."<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<math.h> using namespace std; int main(void){ double nephew, CD; while(cin>>nephew>>CD){ if(nephew == 0 && CD == 0) return 0; printf("%.0lf\n",pow(nephew,CD)); } return 0; } <file_sep>#include<iostream> #include<string> using namespace std; double conv(string); int main(void){ int test,testtime; double gmt; string time, fr, to, mornaft; cin>>test; for(int i=0;i<test;i++){ cin>>time; } return 0; } double conv(string time){ if(time == "UTC" || time == "GMT" || time =="WET") return 0; if(time == "BST" || time == "IST" || time == "WEST" || time =="CET") return 1; if(time == "CEST" || time == "EET") return 2; if(time == "EEST" || time == "MSK") return 3; if(time == "MSD") return 4; if(time == "AST" || time == "EDT") return -4; if(time == "ADT") return -3; if(time == "NST") return -3.5; if(time == "NDT") return -2.5; if(time == "EST" || time == "CDT") return -5; if(time == "CST" || time == "MDT") return -6; if(time == "MST" || time == "PDT") return -7; if(time == "PST" || time == "AKDT") return -8; if(time == "HST") return -10; if(time == "AKST") return -9; if(time == "AEST") return 10; if(time == "AEDT") return 11; if(time == "ACST") return 9.5; if(time == "ACDT") return 10.5; } <file_sep>#include<iostream> #include<stdio.h> #include<map> #include<string.h> using namespace std; int main(void){ int test,numphone,length,value,counter; map<int,int> dir; map<char,int> ph; ph['A'] = ph['B'] = ph['C'] = 2; ph['D'] = ph['E'] = ph['F'] = 3; ph['G'] = ph['H'] = ph['I'] = 4; ph['J'] = ph['K'] = ph['L'] = 5; ph['M'] = ph['N'] = ph['O'] = 6; ph['P'] = ph['R'] = ph['S'] = 7; ph['T'] = ph['U'] = ph['V'] = 8; ph['W'] = ph['X'] = ph['Y'] = 9; char phone[500]; scanf("%d",&test); while(test--){ scanf("%d",&numphone); getchar(); dir.clear(); while(numphone--){ gets(phone); length = strlen(phone); value = counter = 0; for(int i=0;i<length;i++){ if(phone[i]>='0' && phone[i]<='9'){ value*=10; value+=phone[i]-'0'; counter++; if(counter==7) break; } else if(phone[i]>='A' && phone[i]<='Z'){ value*=10; value+=ph[phone[i]]; counter++; if(counter==7) break; } } dir[value]++; } bool printed = false; for(map<int,int>::iterator it = dir.begin();it!=dir.end();it++) if(it->second>1){ printf("%03d-%04d %d\n",it->first/10000,it->first%10000,it->second); printed=true; } if(!printed) printf("No duplicates.\n"); if(test) printf("\n"); } return 0; } <file_sep>#include<string> #include<iostream> using namespace std; int convert(char); int main(void){ bool isPrime; string test; int total; while(cin>>test){ isPrime = true; total = 0; for(int i=0;i<test.length();i++) total+=convert(test.at(i)); for(int i=2;i<total;i++){ if(total%i == 0){ isPrime = false; break; } } if(isPrime) cout<<"It is a prime word."<<endl; else cout<<"It is not a prime word."<<endl; } return 0; } int convert(char converted){ if((int) converted >96){ return (int) converted - 96; } else{ return (int) converted - 38; } } <file_sep>#include <stdio.h> #include <iostream> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <set> #include <bitset> using namespace std; typedef long long ll; typedef long long LL; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #ifdef DEBUG #define cek(x) cout<<x #else #define cek(x) if(false){} #endif // DEBUG #define fi first #define se second #define INF 1000000000 #define INFLL 1000000000000000000LL #define pb push_back #define TC() while(tc--) #define FOR(i,n) for(int i=0;i<n;i++) #define FORN(i,n) for(int i=0;i<=n;;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define REPN(i,a,b) for(int i=a;i<=b;i++) #define reset(a,b) memset(a,b,sizeof(a)) int main(void){ //freopen("in.txt","r",stdin); int n,m; int in[101]; vector<vi> AdjList; while(scanf("%d %d",&n,&m),(n||m)){ AdjList.assign(n,vi()); reset(in,0); int fr,to; FOR(i,m){ scanf("%d %d",&fr,&to); fr--,to--; in[to]++; AdjList[fr].pb(to); } queue<int> q; FOR(i,n){ if(!in[i])q.push(i); } vi toposort; while(!q.empty()){ int v = q.front();q.pop(); toposort.pb(v); int sizes = AdjList[v].size(); FOR(i,sizes){ int node = AdjList[v][i]; in[node]--; if(!in[node])q.push(node); } } printf("%d",toposort[0]+1); REP(i,1,toposort.size()){ printf(" %d",toposort[i]+1); } printf("\n"); } return 0; } <file_sep>#include<stdio.h> int main(void){ int input, counter; long long number; while(scanf("%d",&input)==1){ counter = 1; number = 1; while(true){ if(number%input==0){ printf("%d\n",counter); break; } number = number*10 + 1; number = number%input; counter++; } } return 0; } <file_sep>#include<map> #include<string.h> #include<iostream> using namespace std; int main(void){ map<char,char> mirror; mirror['A']='A'; mirror['E']='3'; mirror['H']='H'; mirror['I'] = 'I'; mirror['j'] = 'L'; mirror['L'] = 'J'; mirror['M'] = 'M'; mirror['O'] = 'O'; mirror['S'] = '2'; mirror['T'] = 'T'; mirror['U'] = 'U'; mirror['V'] = 'V'; mirror['W'] = 'W'; mirror['X'] = 'X'; mirror['Y'] = 'Y'; mirror['Z'] = '5'; mirror['1'] = '1'; mirror['2'] = 'S'; mirror['3'] = 'E'; mirror['5'] = 'Z'; mirror['8'] = '8'; string input1, input2; bool isMirror, isPal, first = true; int length; while(cin>>input1){ if(first) first = false; else cout<<endl; length = input1.length(); input2 = input1.at(length-1); for(int i=length-2;i>=0;i--){ input2 = input2 + input1.at(i); } isPal = false; if(input2 == input1) isPal = true; input2 = mirror[input1.at(length-1)]; for(int i=length-2;i>=0;i--) input2 = input2 + mirror[input1.at(i)]; isMirror = false; if(input2 == input1) isMirror = true; if(isMirror && isPal) cout<<input1<<" -- is a mirrored palindrome."<<endl; else if(isMirror) cout<<input1<<" -- is a mirrored string."<<endl; else if(isPal) cout<<input1<<" -- is a regular palindrome."<<endl; else cout<<input1<<" -- is not a palindrome."<<endl; } return 0; } <file_sep>#include<iostream> #include<stdio.h> #include<map> #include<algorithm> #include<vector> using namespace std; typedef vector<int> vi; typedef vector<vi> vii; vii AdjList; int visited[201]; int visited2[201]; void dfs(int x, int color){ visited[x] = color; for(int i=0;i<AdjList[x].size();i++){ int y = AdjList[x][i]; if(visited[y]==-1) dfs(y,(color+1)%2); } } bool dfscheck(int x){ bool valid = true; int use = visited[x]; visited2[x] = 1; for(int i=0;i<AdjList[x].size();i++){ int y = AdjList[x][i]; if(visited[y]==visited[x]) {valid = false; break;} if(!visited2[y]) dfscheck(y); } return valid; } int main(void){ int num; while(cin>>num && num){ AdjList.assign(num,vi()); int edge; cin>>edge; for(int i=0;i<num;i++) visited[i] = -1; for(int i=0;i<edge;i++){ int from,to; cin>>from>>to; AdjList[from].push_back(to); AdjList[to].push_back(from); } dfs(0,1); for(int i=0;i<num;i++) visited2[i]=0; if(dfscheck(0)){ cout<<"BICOLORABLE."<<endl; } else cout<<"NOT BICOLORABLE."<<endl; } return 0; } <file_sep>import java.util.*; class Dates{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int test, jump, month; Integer year, day; StringTokenizer st; String input, mth; test = sc.nextInt(); for(int i=1;i<=test;i++){ System.out.print("Case "+i+": "); input = sc.next(); st = new StringTokenizer(input,"-"); input = st.nextToken(); year = (input.charAt(0)-'0')*1000 + (input.charAt(1)-'0')*100 + (input.charAt(2)-'0')*10 + (input.charAt(3)-'0'); mth = st.nextToken(); input = st.nextToken(); day = (input.charAt(0) - '0')*10 + input.charAt(1)-'0'; if(mth.equals("January")) month = 0; else if(mth.equals("February")) month = 1; else if(mth.equals("March")) month = 2; else if(mth.equals("April")) month = 3; else if(mth.equals("May")) month = 4; else if(mth.equals("June")) month = 5; else if(mth.equals("July")) month = 6; else if(mth.equals("August")) month = 7; else if(mth.equals("September")) month = 8; else if(mth.equals("October")) month = 9; else if(mth.equals("November")) month = 10; else month = 11; Calendar cal = Calendar.getInstance(); cal.set(year,month,day); jump = sc.nextInt(); cal.add(Calendar.DATE,jump); year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); day = cal.get(Calendar.DATE); System.out.print(year+"-"); if(month == 0) mth = "January"; else if(month == 1) mth = "February"; else if(month == 2) mth = "March"; else if(month == 3) mth ="April"; else if(month == 4) mth = "May"; else if(month == 5) mth = "June"; else if(month == 6) mth = "July"; else if(month == 7) mth = "August"; else if(month == 8) mth = "September"; else if(month == 9) mth = "October"; else if(month == 10) mth = "November"; else mth = "December"; System.out.print(mth+"-"); if(day<10) System.out.print("0"); System.out.println(day); } } }<file_sep>#include<vector> #include<algorithm> #include<cstdio> #include<iostream> #include<queue> #include<map> #include<stdio.h> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; map<int,int> dist; map<char, int> mapper; map<int, char> reverseMapper; vector<vii> AdjList; map<int, int> p; vector<int> res; void clearing(){ mapper.clear(); dist.clear(); reverseMapper.clear(); p.clear(); res.clear(); } void printPath(int u, int s){ if(u==s){ cout<<reverseMapper[u]; return; } printPath(p[u],s); cout<<reverseMapper[u]; } int main(void){ int test; cin>>test; while(test--){ clearing(); int counter = 0; int numroad,question; cin>>numroad>>question; AdjList.assign(numroad*2,vii()); string from,to; char fromc,toc; for(int i=0;i<numroad;i++){ cin>>from>>to; fromc = from.at(0); toc = to.at(0); if(mapper.find(fromc)==mapper.end()){ mapper[fromc] = counter; reverseMapper[counter++] = fromc; } if(mapper.find(toc) == mapper.end()) { mapper[toc] = counter; reverseMapper[counter++] = toc; } AdjList[mapper[fromc]].push_back(ii(mapper[toc], 0)); AdjList[mapper[toc]].push_back(ii(mapper[fromc], 0)); } for(int i=0;i<question;i++){ cin>>from>>to; fromc = from.at(0); toc = to.at(0); dist.clear(); p.clear(); int s = mapper[fromc]; queue<int> q; q.push(s); dist[s] = 1; while(!q.empty()){ int u = q.front(); q.pop(); for(int j=0;j<(int)AdjList[u].size();j++){ ii v = AdjList[u][j]; if(!dist.count(v.first)){ dist[v.first] = dist[u] + 1; p[v.first] = u; q.push(v.first); } } } printPath(mapper[toc],mapper[fromc]); cout<<endl; } if(test) cout<<endl; } } <file_sep>#include<iostream> #include<queue> #include<stdio.h> #include<map> #include<sstream> #include<vector> #include<string> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; bool differbyone(string a, string b){ int c=0; for(int i=0;i<a.length();i++){ if(a.at(i)!=b.at(i)) c++; if(c>1) return false; } return c==1?true:false; } int main(void){ vector<vii> AdjList; int test,len,counter; map<string, int> word; map<int,string> reverseWord; map<int,int> length; string input,from,to,input2; scanf("%d",&test); while(test--){ AdjList.assign(201,vii()); counter = 0; word.clear(); reverseWord.clear(); while(true){ cin>>input; if(input=="*") break; word[input]=counter; reverseWord[counter] = input; length[counter] = input.length(); for(int j=0;j<counter;j++){ if(length[j] == length[counter] && differbyone(reverseWord[j], reverseWord[counter])){ AdjList[j].push_back(ii(counter,0)); AdjList[counter].push_back(ii(j,0)); } } counter++; } getline(cin,input); while(getline(cin,input2)){ if(input2.empty()) break; stringstream ss; ss<<input2; ss>>from>>to; cout<<from<<" "<<to<<" "; if(from==to) cout<<0<<endl; else{ queue<int> q; map<int,int> dist; dist[word[from]]=1; q.push(word[from]); while(!q.empty()){ int s = q.front(); q.pop(); for(int i=0;i<(int)AdjList[s].size();i++){ ii v = AdjList[s][i]; if(!dist[v.first]){ dist[v.first] = dist[s]+1; q.push(v.first); } } if(dist[word[to]]) break; } cout<<--dist[word[to]]<<endl; } } if(test) cout<<endl; } return 0; } <file_sep>#include<iostream> #include<string> #include<stdio.h> using namespace std; int main(void){ string lines[5],command; int row,col,counter=0; bool valid,finish; char temp; while(true){ counter++; for(int i=0;i<5;i++){ getline(cin,lines[i]); if(lines[i].length()==1 && lines[i].at(0)=='Z') return 0; for(int j=0;j<5;j++){ if(lines[i].at(j)==' '){ col = j; row = i; } } } finish = false; valid = true; while(true){ getline(cin,command); for(int i=0;i<command.length();i++){ if(command.at(i)=='0'){ finish = true; break; } switch(command.at(i)){ case 'A':{ if(valid && row>0){ lines[row].replace(col,1,1,lines[row-1].at(col)); lines[row-1].replace(col,1,1,' '); row--; } else{ valid = false; } break; } case 'B':{ if(valid && row<4){ lines[row].replace(col,1,1,lines[row+1].at(col)); lines[row+1].replace(col,1,1,' '); row++; } else{ valid = false; } break; } case 'R':{ if(valid && col<4){ lines[row].replace(col,1,1,lines[row].at(col+1)); lines[row].replace(col+1,1,1,' '); col++; } else{ valid = false; } break; } case 'L':{ if(valid && col>0){ lines[row].replace(col,1,1,lines[row].at(col-1)); lines[row].replace(col-1,1,1,' '); col--; } else valid = false; break; } default: valid = false; } } if(finish) break; } cout<<"Puzzle #"<<counter<<":"<<endl; if(valid){ for(int i=0;i<5;i++){ for(int j=0;j<4;j++){ cout<<lines[i].at(j)<<" "; } cout<<lines[i].at(4)<<endl; } } else cout<<"This puzzle has no final configuration."<<endl; cout<<endl; } return 0; }
e2a7a60e13303bde79e926d45fb75aa430c3a596
[ "Java", "C++" ]
410
C++
jonathandarryl/UVa-Code
0cbe8b6e091fc699abba25cbd72ebf1aa9e1709d
9ab900ee87e67469ffaa753ae57e070ed60d0b8c
refs/heads/master
<repo_name>mhdcamara/api_psr<file_sep>/Podfile # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'API_PSR' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # Pods for API_PSR # pod 'API_PSR', :path => '../' # pod 'TextFieldEffects' pod 'Alamofire', '~> 4.8.2' pod 'SwiftyJSON' # pod 'MaterialComponents/TextControls+OutlinedTextAreas' # pod 'MaterialComponents/TextControls+OutlinedTextFields' # pod 'SKCountryPicker' pod 'EzPopup' # pod 'EasyTipView', '~> 2.0.4' target 'API_PSR_ExamplesTests' do # Pods for testing end target 'API_PSR_ExamplesUITests' do # Pods for testing end target 'API_PSRTests' do # Pods for testing end end target 'API_PSR_Examples' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # Pods for API_PSR_Examples end <file_sep>/API_PSR_Examples/ViewController.swift // // ViewController.swift // API_PSR_Examples // // Created by <NAME> on 9/16/20. // Copyright © 2020 PayDunya. All rights reserved. // import UIKit //import EzPopup //import Alamofire //import SwiftyJSON class ViewController: UIViewController { // let VC = ViewController.instantiate() // // @IBAction func showFullCustomPopupButtonTapped(_ sender: Any) { // guard let pickerVC = VC else { return } // //// pickerVC.delegate = self // // // let popupVC = PopupViewController(contentController: pickerVC, position: .top(50), popupWidth: self.view.frame.width - 20, popupHeight: self.view.frame.height - 70) // popupVC.backgroundAlpha = 0.3 // popupVC.backgroundColor = .black // popupVC.canTapOutsideToDismiss = true // popupVC.cornerRadius = 10 // popupVC.shadowEnabled = true // present(popupVC, animated: true, completion: nil) // // CheckoutInvoice() // } // override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .brown } // // //MARK: Privates Function // // private func CheckoutInvoice() // { // /* // * Préparation de la requete // */ // // // // Initialisation des paramétres de la requete // let Store = PaydunyaStore( // name: "paydunyaIOS-Plugin", // tagline: "L'élégance c'est nous!", // postal_address: "11500", // phone: 778064927, // logo_url: "", // website_url: "" // ) // // Store.total_amount = 200 // Store.description = "Chaussures Croco" // // Store.items = [ // "name": "<NAME>", // "quantity": 3, // "unit_price": "10000", // "total_price": "30000", // "description": "Chaussures faites en peau de crocrodile authentique qui chasse la pauvreté" // ] // // Store.taxes = [ // "name": "TVA (18%)", // "amount": 12 // ] // // //Initialisation des Clé d'API // let Setup = PaydunyaSetup( // MasterKey: AppConstant.master_key, // PrivateKey: AppConstant.private_key, // Token: <PASSWORD>.token, // cancel_url: AppConstant.cancel_url, // return_url: AppConstant.return_url, // callback_url: AppConstant.callback_url // ) // // let invoice = PaydunyaInvoice() // // let Headers: HTTPHeaders = Setup.setup() // // let Parametres: Parameters = invoice.Invoice(store: Store, setup: Setup) // // // La requete avec Alamofire // // Alamofire.request("https://app.paydunya.com/api/v1/checkout-invoice/create", method: .post ,parameters: Parametres, encoding: JSONEncoding.default, headers: Headers).responseJSON // { // response in // print("ResultJSON: \(response.result)") // On affiche la réponse en JSON // // // // On regarde la réponse renvoyée par la requete // switch response.result // { // case let .success(value): // En cas de Succes de la requete // // let json = JSON(value) // // print("Voici la réponse: \(json)") // // let urlpaiement = json["response_text"].stringValue // // AppConstant.payment_url = urlpaiement // // //On redirige l'utilisateur vers la page de paiement // // let token = json["token"].stringValue // // print("Le token: \(token)") // print("L'url: \(urlpaiement)") // // AppConstant.invoice_token = token // // case let .failure(error): print(error) // } // // } // } }
3037162de9f96b3e16e8df1f2f649e3dbca9a988
[ "Swift", "Ruby" ]
2
Ruby
mhdcamara/api_psr
c7a1c9b1efaf2fb25d92c901410ebf9d05a8c2ee
8b304835ac845676744c6f7a4447670fb8e6c500
refs/heads/master
<file_sep>package main import ( "fmt" log1 "github.com/cihub/seelog" "time" ) import "log" func main() { defer log1.Flush() log1.Info("Hello from Seelog!") log.Println("geger") fmt.Println(time.Now().Format("2006-01-02 15:04:05")) t := time.Now() fmt.Printf("当前的时间是: %d-%d-%d %d:%d:%d\n", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) //str := t.Format("2006-01-02 15:04:05") //str := t.Format("2006-01-02") //str := t.Format("15:04:05") str := t.Format("2006") fmt.Println(str) fmt.Println("over") time.Sleep(time.Second * 2) go func() { fmt.Println("sleep") time.Sleep(time.Second) fmt.Println("sleep2") }() } <file_sep>package main import ( "fmt" "runtime" ) func say(s string) { for i := 0; i < 5; i++ { runtime.Gosched() fmt.Printf("%s,第%d次\n", s, i) } } func main() { //runtime.GOMAXPROCS(4) /*go say("3hello") go say("1world")//开一个新的Goroutines执行 say("2hello")//当前Goroutines执行*/ /*ci := make(chan int) cs := make(chan string) cf := make(chan interface{})*/ a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[len(a)/2:], c) go sum(a[:len(a)/2], c) x, y := <-c, <-c fmt.Println(x, y, x+y) c = make(chan int, 2) //指定channel的缓冲大小 c <- 1 //c <- 4 fmt.Println(<-c) c <- 3 fmt.Println(<-c) } //无缓冲channel func sum(a []int, c chan int) { sum := 0 for _, v := range a { sum += v } c <- sum } <file_sep>package main import ( "fmt" //"io/ioutil" "net" "os" "time" ) func main() { tcpAddr, err := net.ResolveTCPAddr("tcp4", ":8181") checkErr(err) listener, err := net.ListenTCP("tcp", tcpAddr) checkErr(err) for { fmt.Println("服务器监听:") conn, err := listener.Accept() if err != nil { continue } var b [512]byte n, err := conn.Read(b[:]) //result, err := ioutil.ReadAll(conn) fmt.Println("收到消息:", string(b[0:n])) daytime := time.Now().String() conn.Write([]byte(daytime)) fmt.Println("发送消息:", daytime) conn.Close() } } func checkErr(e error) { if e != nil { fmt.Fprintf(os.Stderr, "Fatal error: s%", e.Error()) os.Exit(1) } } <file_sep>package main import ( "fmt" "time" ) func main() { prod := make(chan int) go producer(prod) consumer(prod) fmt.Println("comsumer") } func producer(prod chan int) { for i := 0; i < 10; i++ { time.Sleep(time.Nanosecond) fmt.Println("生产:", i) prod <- i } } func consumer(cons chan int) { for i := 0; i < 10; i++ { value := <-cons fmt.Println("消费:", value) } } <file_sep>package main import ( "fmt" "net/http" "reflect" ) type controllerInfo struct { url string controllerType reflect.Type } type ControllerRegistor struct { routers []*controllerInfo } type ControllerInterface interface { Do() } type UserController struct { } type DefaultController struct { } func (u *UserController) Do() { fmt.Println("I`m UserController") } func (d *DefaultController) Do() { fmt.Println("I`m DefaultController") } func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) { //now create the Route t := reflect.TypeOf(c).Elem() route := &controllerInfo{} route.url = pattern route.controllerType = t p.routers = append(p.routers, route) } // AutoRoute func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) { var started bool requestPath := r.URL.Path fmt.Println(requestPath) //find a matching Route for _, route := range p.routers { if requestPath == route.url { vc := reflect.New(route.controllerType) method := vc.MethodByName("Do") method.Call(nil) started = true fmt.Fprintf(w, "Hello "+route.controllerType.Name()) break } } //if no matches to url, throw a not found exception if started == false { http.NotFound(w, r) } } //实现简单的路由功能 func main() { mux := &ControllerRegistor{} mux.Add("/", &DefaultController{}) mux.Add("/user", &UserController{}) http.ListenAndServe(":9527", mux) } <file_sep>package main import ( "errors" "fmt" //"github.com/pkg/errors" ) func main() { fmt.Println("Hello, world or 你好,世界 or καλημ ́ρα κóσμ or こんにちは世界") var vname1, vname2, vname3 = "name1", "name2", "name3" fmt.Println(vname1, vname2, vname3) const pi float32 = 3.1415926 fmt.Println(pi) var enable, disabled bool = true, false fmt.Println(enable, disabled) /** !Go还支持复数。它的默认类型是complex128(64位实数+64位虚数)。如果需要小一些的,也 有complex64(32位实数+32位虚数)。 */ var c complex64 = 5 + 5i fmt.Println(c) var s string = "ahello" //字符串是不可变的 var ch = []byte(s) // 将字符串 s 转换为 []byte 类型 ch[0] = 'h' s = string(ch) // 再转换回 string 类型 fmt.Println(s) s = "hello" s = "c" + s[1:] // 字符串虽不能更改,但可进行切片操作 fmt.Println(s) //如果要声明一个多行的字符串怎么办?可以通过`来声明: m := `hello world` fmt.Println(m) //括起的字符串为Raw字符串,即字符串在代码中的形式就是打印时的形式,它没有字符转义,换行也将原样输出。 err := errors.New("emit macho dwarf") fmt.Println(err) f := float32(3.14) fmt.Println(f) var i byte = 'd' fmt.Println(i) var ( s1 = 5 s2 float32 ) fmt.Println(s1, s2) const ( x = iota y = iota z = iota ) fmt.Println(x, y, z) } func getName() (firstName, middleName, lastName, nickName string) { firstName = "May" middleName = "M" lastName = "Chen" nickName = "Babe" return } <file_sep>package main import ( "fmt" "io" "log" "net" "net/http" "net/http/httputil" "sync" ) // Proxy reverse proxy inherit from httputil.ReverseProxy and add https support type Proxy struct { httputil.ReverseProxy } func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Println(r.URL) if r.Method == http.MethodConnect { p.ServeHTTPS(w, r) } else { if !r.URL.IsAbs() { handleError(w, "proxy error: not respond to non-proxy requests", http.StatusBadRequest) } else { p.ReverseProxy.ServeHTTP(w, r) } } } // ServeHTTPS handle https proxy func (p *Proxy) ServeHTTPS(w http.ResponseWriter, r *http.Request) { hijack, ok := w.(http.Hijacker) if !ok { handleError(w, "proxy error: not support hijack", http.StatusBadGateway) return } oConn, oBufrw, err := hijack.Hijack() if err != nil { handleError(w, fmt.Sprintf("proxy error: %v", err.Error()), http.StatusBadGateway) return } tConn, err := net.Dial("tcp", r.Host) if err != nil { handleError(w, fmt.Sprintf("proxy error: %v", err.Error()), http.StatusBadGateway) return } oBufrw.WriteString("HTTP/1.0 200 OK\r\n\r\n") oBufrw.Flush() oTCPConn, ok1 := oConn.(*net.TCPConn) tTCPConn, ok2 := tConn.(*net.TCPConn) if ok1 && ok2 { go pipeTCPConn(oTCPConn, tTCPConn) go pipeTCPConn(tTCPConn, oTCPConn) } else { wg := &sync.WaitGroup{} wg.Add(2) go pipeConn(oConn, tConn, wg) go pipeConn(tConn, oConn, wg) wg.Wait() oConn.Close() tConn.Close() } } func handleError(w http.ResponseWriter, err string, code int) { fmt.Println(err) http.Error(w, err, code) } func pipeTCPConn(src, dst *net.TCPConn) { if _, err := io.Copy(dst, src); err != nil { fmt.Println(err) } src.CloseRead() dst.CloseWrite() } func pipeConn(src, dst net.Conn, wg *sync.WaitGroup) { if _, err := io.Copy(dst, src); err != nil { fmt.Println(err) } wg.Done() } func proxy() *Proxy { return &Proxy{ ReverseProxy: httputil.ReverseProxy{Director: func(req *http.Request) {}}, } } func main() { log.Fatal(http.ListenAndServe(":8080", proxy())) } <file_sep>package main import ( "github.com/thinkoner/thinkgo" "github.com/thinkoner/thinkgo/app" "github.com/thinkoner/thinkgo/context" "github.com/thinkoner/thinkgo/router" "thinkgo/controller" "thinkgo/handler" "thinkgo/middleware" ) func main() { thinkGo := thinkgo.BootStrap() thinkGo.RegisterRoute(routeFunc) thinkGo.RegisterHandler(func(app *app.Application) app.Handler { //全局处理器 return &handler.HandLog{} }) thinkGo.Run("127.0.0.1:8081") } func routeFunc(route *router.Route) { route.Get("/", controller.Hello) route.Get("/ping", controller.Ping) // Dependency injection route.Get("/user/{name}", controller.UserName) //中间件 route.Get("/foo", func(request *context.Request) *context.Response { return thinkgo.Text("Hello ThinkGo !") }).Middleware(middleware.CheckParam) //重定向 route.Get("/redirect", func(request *context.Request) *context.Response { return context.Redirect("http://google.com") }) route.Get("/cookie", func(request *context.Request) *context.Response { response := thinkgo.Text("cookies") response.Cookie("name", "ys") return response }) route.Get("/tpl", func(request *context.Request) *context.Response { data := map[string]interface{}{"Title": "ThinkGo", "Message": "Hello ThinkGo !"} return thinkgo.Render("tpl.html", data) }) route.Get("/getsession", controller.GetSession) route.Get("/setsession", controller.SetSession) route.Get("/info", controller.Info) route.Get("/setcache/{k}/{v}", controller.SetCache) route.Get("/getcache/{k}", controller.GetCache) } <file_sep>package main import ( "fmt" "os" ) func main() { os.Mkdir("ys", 0777) os.MkdirAll("ys/y1/y2", 0777) err := os.Remove("ys") if err != nil { fmt.Println(err) //panic(err) } os.RemoveAll("ys") } <file_sep>package main import "fmt" func main() { ch := make(chan int, 1) for i := 1; i <= 10; i++ { select { case ch <- 3: case ch <- 1: } i := <-ch fmt.Println("Value received:", i) } } <file_sep>package main import "fmt" func main() { b := func(a, b int, z float64) bool { return a*b < int(z) }(3, 2, 7.1) fmt.Println(b) //Go语言中的闭包同样也会引用到函数外的变量。闭包的实现确保只要闭包还被使用,那么 //被闭包引用的变量会一直存在 go学习笔记P60 var j int = 5 a := func() func() { var i int = 10 return func() { fmt.Printf("i, j: %d, %d\n", i, j) } }() a() j *= 2 a() } <file_sep>package main import "os" func main() { file, _ := os.Create("a.txt") defer file.Close() //file, _ = os.Open("a.txt") //arr :=make([]byte,1) file.WriteString("yishuang\n") file.Write([]byte("just a test1!")) os.Remove("a.txt") } <file_sep>package store import ( "github.com/gomodule/redigo/redis" "github.com/thinkoner/thinkgo/cache" ) var memRepository *cache.Repository var redisRepository *cache.Repository func init() { memRepository, _ = cache.Cache(cache.NewMemoryStore("store")) address := "127.0.0.1:6379" //password := "123" pool := &redis.Pool{ MaxIdle: 3, MaxActive: 5, Dial: func() (conn redis.Conn, e error) { con, err := redis.Dial("tcp", address) if err != nil { return nil, err } /*if _, err := con.Do("AUTH",password); err != nil {//没设密码,不需认证 con.Close() return nil,err }*/ return con, err }, } redisRepository, _ = cache.Cache(cache.NewRedisStore(pool, "rstore")) } func MemRepository() *cache.Repository { return memRepository } func RedisReposotory() *cache.Repository { return redisRepository } <file_sep>package main import ( "sync" "time" ) func main() { twoprint() time.Sleep(time.Second * 2) } var a string var once sync.Once func setup() { a = "hello, world" println(a) } //once的Do()方法可以保证在全局范围内只调用指定的函数一次(这里指 //setup()函数),而且所有其他goroutine在调用到此语句时,将会先被阻塞,直至全局唯一的 //once.Do()调用结束后才继续。 func doprint() { once.Do(setup) //setup() println(a) } func twoprint() { go doprint() go doprint() } <file_sep>package main import ( "crypto/md5" "crypto/sha1" "fmt" ) func main() { test := "Hi,pandaman!" Md5Inst := md5.New() Md5Inst.Write([]byte(test)) Result := Md5Inst.Sum([]byte("")) fmt.Printf("%x\n\n", Result) ShaInst := sha1.New() ShaInst.Write([]byte(test)) Result = ShaInst.Sum([]byte("")) fmt.Printf("%x\n\n", Result) s := fmt.Sprintf("%d", 4) fmt.Printf(s) s = fmt.Sprint("hello", "yi", "shu") fmt.Printf(s) } <file_sep>package main import "fmt" func main() { c := make(chan int, 100) i := 1 b := &i go t1(*b, c) t2(*b, c) } func t1(i int, c chan int) { for ; i <= 103; i++ { if i&1 == 1 { fmt.Println("t1生产", i) c <- i } else { fmt.Println("t1消费", <-c) } } } func t2(i int, c chan int) { for ; i <= 100; i++ { if i&1 == 0 { fmt.Println("t2生产", i) c <- i if i == 100 { i-- break } } else { fmt.Println("t2消费", <-c) } } } <file_sep>package main import ( "fmt" ) type lessadd interface { less(b Integer) bool add(b Integer) } type Integer int func (i Integer) less(b Integer) bool { return i < b } func (a Integer) add(b Integer) { //不会改变 a += b } func (a *Integer) add1(b Integer) { //会改变a *a += b } func main() { var a Integer = 1 if a.less(5) { fmt.Println(a) } a.add(3) fmt.Println(a) a.add1(3) fmt.Println(a) var b lessadd = &a b.add(4) f, ok := b.(Integer) if ok { fmt.Println(f) } } <file_sep>package main import "fmt" func main() { /*var P person P.name = "Astaxie" P.age = 25 fmt.Println(P)*/ //按照顺序提供初始化值 /*P := person{"tom",30} fmt.Println(P)*/ //通过field:value的方式初始化,这样可以任意顺序 /*P := person{age:28, name:"yishuang"} fmt.Println(P)*/ stu := student{human{"ys", 23, 63}, human2{4}, ""} stu.human.age = 22 fmt.Println(stu) } type person struct { name string age int } type human struct { name string age int weight int } type human2 struct { age int } type student struct { human human2 speciality string } func (s student) String() string { //调用fmt.print会输出此处 return "rr✆" } <file_sep>package middleware import ( "github.com/thinkoner/thinkgo" "github.com/thinkoner/thinkgo/context" "github.com/thinkoner/thinkgo/router" ) func CheckParam(request *context.Request, next router.Closure) interface{} { if _, err := request.Input("name"); err != nil { return thinkgo.Text("Invalid parameters") } return next(request) } <file_sep>1、先初始化全局常量、变量,然后执行init,多个init按上下顺序执行,再执行main defer语句的含义是不管程序是否出现异常,均在函数退出时自动执行相关代码。 Go语言要求public的变量必须以大写字母开头,private变量则以小写字母开头, 这种做法不仅免除了public、private关键字,更重要的是统一了命名风格。 Go语言反对函数和操作符重载(overload),而C++、Java和C#都允许出现同名函数或 操作符,只要它们的参数列表不同。 Go语言支持类、类成员方法、类的组合,但反对继承,反对虚函数(virtual function) 和虚函数重载。确切地说,Go也提供了继承,只不过是采用了组合的文法来提供: type Foo struct { Base ... } func (foo *Foo) Bar() { ... } 在Go语言中,只要两个接口拥有相同的方法列表,那么它们就是等同的,可以相互赋值 iota比较特殊,可以被认为是一个可被编译器修改的常量,在每一个const关键字出现时被 重置为0,然后在下一个const出现之前,每出现一次iota,其所代表的数字会自动增1。 如果两个const的赋值语句的表达式是一样的,那么可以省略后一个赋值表达式。因此,上 面的前两个const语句可简写为: const ( // iota被重设为0 c0 = iota // c0 == 0 c1 // c1 == 1 c2 // c2 == 2 ) const ( a = 1 <<iota // a == 1 (iota在每个const开头被重设为0) b // b == 2 c // c == 4 ) 两个不同类型的整型数不能直接比较,比如int8类型的数和int类型的数不能直接比较,但 各种类型的整型变量都可以直接与字面常量(literal)进行比较,<file_sep>package gotest import "testing" // go test -file webbench_test.go -test.bench=".*" func BenchmarkDivision(b *testing.B) { for i := 0; i < b.N; i++ { Division(4, 5) } } <file_sep>package handler import ( "github.com/thinkoner/thinkgo/app" "github.com/thinkoner/thinkgo/context" "github.com/thinkoner/thinkgo/log" "time" ) type HandLog struct { } func (h *HandLog) Process(r *context.Request, next app.Closure) interface{} { log.Info("[%s] %q %v", r.Method(), r.Path(), time.Now()) return next(r) } <file_sep>package main import ( "fmt" "time" ) func main() { var arr [10]int arr[0] = 42 arr[1] = 13 fmt.Println(arr) //数组可以使用另一种:=来声明 a := [3]int{1, 2, 3} // 声明了一个长度为3的int数组 b := [10]int{1, 2, 3} // 声明了一个长度为10的int数组,其中前三个元素初始化为1、2、3,其它默认为0 c := [...]int{4, 5, 6} // 可以省略长度而采用`...`的方式,Go会自动根据元素个数来计算长度 fmt.Println(a, b, c) doubleArray := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}} fmt.Println(doubleArray) slice := []int{1, 2, 3} fmt.Println(slice) //map //var numbers map[string] int numbers := make(map[string]int) numbers["one"] = 1 numbers["two"] = 2 numbers["three"] = 3 fmt.Println(numbers) for k, v := range numbers { //由于 Go 支持 “多值返回”, 而对于“声明而未被调用”的变量, 编译器会报错, 在这种情况下, 可以使用_来丢弃 //不需要的返回值 fmt.Println(k, v) } for _, v := range numbers { fmt.Println(v) } rating := map[string]float32{"C": 5, "Go": 4.5, "Python": 4.5} cs, ok := rating["C"] if ok { fmt.Println("csharp in map", cs) } else { fmt.Println("no csharp") } delete(rating, "C") //myFunc() /** Go里面switch默认相当于每个case最后带有break,匹 配成功后不会自动向下执行其他case,而是跳出整个switch, 但是可以使用fallthrough强制执行后面的case代 码。 */ integer := 6 switch integer { case 4: fmt.Println("integer <= 4") case 5: fmt.Println("integer <= 5") case 6: fmt.Println("integer <= 6") fallthrough case 7: fmt.Println("integer <= 7") fallthrough default: fmt.Println("default case") } fmt.Println(max(5, 8)) fmt.Println(max(8, 5)) args(2, 4, 6) for i := 0; i < 5; i++ { defer fmt.Println(i) } } //goto语句,用goto跳转到必须在当前函数内定义的标签 func myFunc() { i := 0 Here: fmt.Println(i) time.Sleep(1000000000) i++ if i < 5 { goto Here } } func max(a, b int) (max int, min int) { if a > b { max, min = a, b } else { max, min = b, a } return } func args(arg ...int) { for i, j := range arg { fmt.Println("args", i, j) } } <file_sep>package main import ( "fmt" "github.com/thinkoner/thinkgo" "github.com/thinkoner/thinkgo/context" "github.com/thinkoner/thinkgo/router" ) func main() { app := thinkgo.BootStrap() /*app.RegisterRoute(func(route *router.Route) { route.Get("/", func(req *context.Request) *context.Response { return thinkgo.Text("Hello ThinkGo !") }) route.Get("/ping", func(req *context.Request) *context.Response { return thinkgo.Json(map[string]string{ "message": "pong", }) }) // Dependency injection route.Get("/user/{name}", func(req *context.Request, name string) *context.Response { return thinkgo.Text(fmt.Sprintf("Hello %s !", name)) }) })*/ app.RegisterRoute(routeFun) // listen and serve on 0.0.0.0:9011 app.Run("127.0.0.1:8081") } /* 将写在参数的函数独立出来*/ func routeFun(route *router.Route) { route.Get("/", func(req *context.Request) *context.Response { return thinkgo.Text("Hello ThinkGo !") }) route.Get("/ping", func(req *context.Request) *context.Response { return thinkgo.Json(map[string]string{ "message": "pong", }) }) // Dependency injection route.Get("/user/{name}", func(req *context.Request, name string) *context.Response { return thinkgo.Text(fmt.Sprintf("Hello %s !", name)) }) } <file_sep>package main import ( "fmt" "runtime" ) type Vector []float64 func (v Vector) DoSome(i, n int, u Vector, c chan int) { for ; i < n; i++ { //v[i] += u.Op(v[i]) } c <- 1 } const NCPU = 16 // 假设总共有16核 func (v Vector) DoAll(u Vector) { c := make(chan int, NCPU) // 用于接收每个CPU的任务完成信号 for i := 0; i < NCPU; i++ { go v.DoSome(i*len(v)/NCPU, (i+1)*len(v)/NCPU, u, c) } // 等待所有CPU的任务完成 for i := 0; i < NCPU; i++ { <-c // 获取到一个数据,表示一个CPU计算完成了 } // 到这里表示所有计算已经结束 } func main() { fmt.Println(runtime.NumCPU()) a := runtime.GOMAXPROCS(8) fmt.Println(a) } <file_sep>package main import ( "database/sql" "encoding/json" "fmt" _ "github.com/Go-SQL-Driver/Mysql" "net/http" "os" "runtime" "webDemo/db" ) func find(uid string) (id int, username, departname, created string) { db, err := sql.Open("mysql", "root:admin@/test") checkErr(err) //查询数据 rows, err := db.Query("select * from userinfo where uid=" + uid) checkErr(err) for rows.Next() { err = rows.Scan(&id, &username, &departname, &created) checkErr(err) fmt.Println(id, username, departname, created) } return id, username, departname, created } func checkErr(e error) { if e != nil { panic(e) } } func getuser(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() uid := params.Get(":uid") id, username, departname, created := find(uid) _, _ = fmt.Fprint(w, id, username, departname, created) } func modifyuser(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() uid := params.Get(":uid") _, _ = fmt.Fprintf(w, "you are modify user %s", uid) } func deleteuser(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() uid := params.Get(":uid") _, _ = fmt.Fprintf(w, "you are delete user %s", uid) } func adduser(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() uid := params.Get(":uid") _, _ = fmt.Fprintf(w, "you are add user %s", uid) } type Book struct { Title string Authors []string Publisher string IsPublished bool Price float64 } type User struct { Title string Authors []string Publisher string IsPublished bool Price float64 } func main() { db.Save() bo := new(Book) bo.Title = "rt" fmt.Println("bo-", bo) boo := Book{} fmt.Println("boo-", boo) boo1 := &Book{} boo1.Title = "boo1" fmt.Println("boo1-", boo1) gobook := Book{"Go语言编程", []string{"XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan", "XuDaoli"}, "ituring.com.cn", true, 9.99, } user := User{"Go语言编程", []string{"XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan", "XuDaoli"}, "ituring.com.cn", true, 9.99} b, err := json.Marshal(gobook) if err == nil { fmt.Println(string(b)) } else { fmt.Fprintln(os.Stderr, err) } b, err = json.Marshal(user) if err == nil { fmt.Println(string(b)) } else { fmt.Fprintln(os.Stderr, err) } m := map[int]int{3: 4, 4: 5} for k, v := range m { fmt.Println(k, v) } fmt.Println(runtime.GOOS) /*mux := routes.New() mux.Get("/user/:uid", getuser) mux.Post("/user/:uid", modifyuser) mux.Del("/user/:uid", deleteuser) mux.Put("/user/:uid", adduser) http.Handle("/", mux) addr := ":8080" fmt.Printf("服务器开启在%s端口\n",addr) http.ListenAndServe(addr, nil)*/ } func init() { fmt.Println("init...", f) f = 78 } func init() { fmt.Println("init...2", f, b) } var f = 4 const b = 56 //先初始化全局常量、变量,然后执行init,多个init按上下顺序执行,再执行main <file_sep>package main import "fmt" func main() { f := func(x, y int) int { //匿名函数,可以随意对该匿名函数变量进行传递和调用 return x + y } fmt.Println(f(4, 5)) var ifly iFly = new(Bird) ifly.Fly() } type Bird struct { } func (b Bird) Fly() { fmt.Println("鸟飞行") } type iFly interface { Fly() } <file_sep>package main import ( "fmt" ) func main() { myFun(3, 45, 6, 345) } func myFun(args ...int) { fmt.Println(args) myFun1(args[1:]...) myFun2(1, 5, 8.3, 22) } func myFun1(args ...int) { fmt.Println(args) } func myFun2(args ...interface{}) { for i, v := range args { fmt.Println(i, v) } fmt.Println(args) } <file_sep>package main import "fmt" func main() { slice := make([]int, 5) //创建一个初始元素个数为5的数组切片,元素初始值为0 fmt.Println(slice) //创建一个初始元素个数为5的数组切片,元素初始值为0,并预留10个元素的存储空间len=5,cap=10 slice1 := make([]int, 5, 10) fmt.Println(slice1) //直接创建并初始化包含5个元素的数组切片,事实上还会有一个匿名数组被创建出来,只是不需要我们来操心而已 slice3 := []int{1, 2, 3, 4, 5} fmt.Println(slice3) m := make(map[string]string, 10) m["s"] = "s" a, ok := m["s"] if ok { fmt.Println(a) } delete(m, "s") } <file_sep>package main import "fmt" func main() { fmt.Println("good") r1 := Rectangle{3, 5} fmt.Println(r1.area()) var a interface{} = "hello" fmt.Println(a) } type Rectangle struct { width, height float64 } func (r Rectangle) area() float64 { return r.height * r.width } <file_sep>package model type User struct { id int username string department string created string } <file_sep>package main import ( "fmt" ) func main() { var v5 struct { f int } //v5.f = 5 v6 := "fdf" v7 := &v6 fmt.Println(v5) fmt.Println(v7) fmt.Println(*v7) fmt.Println(&v7) const home = 56 var f1 float32 var f2 float32 = 6 if f1 == f2 { fmt.Println(f1) } fmt.Println(^-3) value1 := 3.4 + 5i fmt.Println(value1) str := "Hello,世界" n := len(str) for i := 0; i < n; i++ { ch := str[i] // 依据下标取字符串中的字符,类型为byte fmt.Println(i, ch) } for i, ch := range str { fmt.Println(i, ch) //ch的类型为rune } } <file_sep>package main import ( "fmt" ) //当main()函数返回时,程序退出, //且程序并不等待其他goroutine(非主goroutine)结束。 func main() { // go Add(2, 4) fmt.Println(9) Add(2, 3) //time.Sleep(time.Second) ch := make(chan int) ch <- 9 <-ch } func Add(x, y int) { z := x + y fmt.Println(z) } <file_sep>package main import ( "fmt" ) func sumSubarrayMins1(A []int) int { var sum int double := make([][]int, len(A)) for i := 0; i < len(A); i++ { double[i] = make([]int, len(A)+1) } fmt.Println(double) for i := 0; i < len(A); i++ { double[i][i] = A[i] for j := i; j < len(A); j++ { if A[j] < double[i][j] { double[i][j+1] = A[j] sum += A[j] } else { double[i][j+1] = double[i][j] sum += double[i][j] } //sum += findMin(A[i:j+1]) } } fmt.Println(double) return sum % (1e9 + 7) } func sumSubarrayMins(A []int) int { //动态规划 var sum int for i := 0; i < len(A); i++ { min := A[i] for j := i; j < len(A); j++ { if A[j] < min { min = A[j] //子数组的最小值 } sum += min } } return sum % (1e9 + 7) } func main() { A := []int{3, 1, 2, 4} fmt.Println(sumSubarrayMins(A)) /*fmt.Println(2508796223%int(1e9+7)) var arr = []int{33,2} fmt.Println(arr)*/ d := make([]int, 1) fmt.Println(d) } <file_sep>package main import ( "errors" "fmt" ) func main() { var e error fmt.Println(e) e = errors.New("errtrg") fmt.Println(e) fmt.Println(e.Error()) e = &MyError{"myError"} fmt.Println(e) //无论foo()中是否触发了错误处理流程,该匿名defer函数都将在函数退出时得到执行 defer func() { if r := recover(); r != nil { fmt.Println("recover()执行", r) } }() panic(MyError{"模拟发生错误"}) } type MyError struct { message string } func (e *MyError) Error() string { return e.message } <file_sep>package main import ( "fmt" "log" ) func main() { a := []int{1, 2, 3} //切片或数组 [3]int{1,2,3} b := a b[1]++ //如果是切片,会改变a;如果是数组不会改变a fmt.Println(a, b) r := Rect{1, 2, 3, 4} r1 := new(Rect) //new 返回的指针 r2 := &Rect{1, 2, 3, 4} r3 := NewRect(1, 2, 3, 4) fmt.Println(r.Area()) fmt.Println(r2.Area()) fmt.Println(r, r1, r2, r3) /*job := new(Job) job.Start()*/ defer func() { if r := recover(); r != nil { } }() } type Rect struct { x, y float64 width, height float64 } func NewRect(x float64, y float64, width float64, height float64) *Rect { return &Rect{x: x, y: y, width: width, height: height} } func (r *Rect) Area() float64 { return r.width * r.height } type Job struct { Command string *log.Logger } func (job *Job) Start() { job.Println("starting now...") } <file_sep>package controller import ( "fmt" "github.com/thinkoner/thinkgo" "github.com/thinkoner/thinkgo/context" "github.com/thinkoner/thinkgo/log" "thinkgo/store" "time" ) func Hello(request *context.Request) *context.Response { data := map[string]interface{}{ "Title": "ThinkGo", "Message": "Hello ThinkGo !", "name": "yishuang", } return thinkgo.Render("index.html", data) } func Ping(request *context.Request) *context.Response { return thinkgo.Json(map[string]string{ "message": "pong", }) } func UserName(request *context.Request, name string) *context.Response { return thinkgo.Text(fmt.Sprintf("Hello %s !", name)) } //todo session的存取有错误 func SetSession(request *context.Request) *context.Response { request.Session().Set("user", "alice") fmt.Println("setsession") return thinkgo.Text("session set") } func GetSession(request *context.Request) *context.Response { user := request.Session().Get("user") fmt.Println(user) return thinkgo.Text("session get") } func Info(request *context.Request) *context.Response { log.Debug("log") log.Info("info") log.Error("error") log.Alert("alert") return thinkgo.Text("info") } //var c = store.MemRepository() var c = store.RedisReposotory() func SetCache(request *context.Request, k string, v string) *context.Response { c.Put(k, v, time.Hour*24) return thinkgo.Text("setCache " + k + " " + v) } func GetCache(request *context.Request, k string) *context.Response { var v string c.Get(k, &v) return thinkgo.Text("getCache " + k + " " + v) } <file_sep>package main import ( "fmt" "io/ioutil" "net" "os" ) func main() { tcpAddr, err := net.ResolveTCPAddr("tcp4", ":8181") checkErr(err) conn, err := net.DialTCP("tcp", nil, tcpAddr) checkErr(err) _, err = conn.Write([]byte("hello")) fmt.Println("发送消息") checkErr(err) result, err := ioutil.ReadAll(conn) checkErr(err) fmt.Print("收到回复:") fmt.Println(string(result)) conn.Close() } func checkErr(e error) { if e != nil { fmt.Fprintf(os.Stderr, "Fatal error: s%", e.Error()) os.Exit(1) } }
99ddaec31487381ba68169279749116ec87c6e65
[ "Markdown", "Go" ]
38
Go
TurboTurn/godemo
966892334c8b73c5ab83a132c0905892a9142f4c
fc075161deb11c33d6a4bc2add30e5cb81940bcf
refs/heads/master
<repo_name>rahulkumarsah/little-basket<file_sep>/All PHP files/index.php <?php require 'common.php'; if(isset($_SESSION['email'])) { header('location:home.php'); } ?> <!DOCTYPE html> <html> <head> <title>Little Basket</title> <link rel="stylesheet" type="text/css" href=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script> <script src=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js "></script> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <nav class="navbar navbar-fixed-top"> <div class="container my_navbar"> <div class="navbar-header" > <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="index.php" class="navbar-brand black_color"><strong><em>Little Basket</em></strong></a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right" > <li><a href="signup.php" target="_blank" class="black_color"><span class="glyphicon glyphicon-user"></span>Sign Up</a> </li> <li><a href=".modal" data-toggle="modal" class="black_color"><span class="glyphicon glyphicon-log-in">Login</span> </a> </li> </ul> </div> </div> </nav> <div class="container"> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h3>Login</h3> <button type="button" data-dismiss="modal" style="float: right" > <span class="glyphicon glyphicon-remove" ></span> </button> </div> <div class="modal-body"> <div class="row"> <div class="col-sm-12"> Don't have an account? <a href="signup.php" style="text-decoration:none">Register</a> <form method="post" action="login.php"> <input type="text" placeholder="Email" name="email" class="form-control form-group " pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" style="width: 100%" > <input type="text" placeholder="<PASSWORD>" name="password" class="form-control form-group"> <input type="submit" value="Login" class="btn btn-primary" style="width:100px"> </form> </div> </div> </div> <div class="modal-footer"> <a href="forgot_password.php" target="_blank" style="text-decoration:none ; float: left">Forget Password?</a> </div> </div> </div> </div> </div> <!-- ===================================B O D Y=====================================================--> <div class="container-fluid" style="margin-top: 60px"> <div class="row"> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> item 1 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://www.aashirvaad.com/assets/Aashirvaad/images/NMP_FOP.png"> </a> <div class="caption"> <p>Aashirvad atta 5 kg india's no.1 atta , Rs 250/- </p> </div> <a href="signup.php"><center><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div> </div> </div> <div class="col-sm-4 col-sm-offset-"> <div class="panel panel-default"> <div class="panel-heading"> Item 2 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://5.imimg.com/data5/FI/JI/MY-45727586/toor-dal-500x500.jpg" style="width:350px;height:320px"> </a> <div class="caption"> <p>Toor dal 2 kg Best price , RS 150 </p> </div> <a href="signup.php"><centre><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div>s </div> </div> <div class="col-sm-4 col-sm-offset"> <div class="panel panel-default"> <div class="panel-heading"> Item 3 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://media.gettyimages.com/photos/riceland-extra-long-grain-bag-picture-id521991888?k=6&m=521991888&s=612x612&w=0&h=bt70QJf9k2nzRnwQ6DTOGuJxui8xEk-1MIF0qDLHtpY=" style="width:350px;height:320px"> </a> <div class="caption"> <p>Rice 2 kg Best price , RS 150 </p> </div> <a href="signup.php"><centre><button type="button" class="btn btn-primary btn-block" >Order Now!</button></centre></a> </div> </div> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 4 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://m.media-amazon.com/images/I/81JmTiQA68L._SX425_.jpg" style="width:350px;height:320px"> </a> <div class="caption"> <p>Besan 2 kg fresh besan pack , Rs 120/- </p> </div> <a href="signup.php"><center><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 5 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXkyr0VE5mGO-HPMQ7Ap8etqDxM3CiDsqBx47stJ2iOrG4Jt2c1sm6Fe27ukcJQVVZbTI&usqp=CAU" style="width:350px;height:320px" > </a> <div class="caption"> <p>TEA pack Tea pack of three, Rs 999/- </p> </div> <a href="signup.php"><center><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 6 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRUmiFRnI5R0-LqL1BU4Byz6eqHVlZ2jA-6JA&usqp=CAU" style="width:350px;height:320px"> </a> <div class="caption"> <p> Madhur Sugar 1 Kg Closed Packet, Verified Rs 500- </p> </div> <a href="signup.php"><center><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div> </div> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 7 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://www.bigbasket.com/media/uploads/p/xxl/274148-2_6-fortune-sun-lite-sunflower-refined-oil.jpg" style="width:350px;height:320px" > </a> <div class="caption"> <p>sun lite fortune refine 5L refine oil pack, Rs 549/- </p> </div> <a href="signup.php"><center><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 8 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSAafR1a2t3zPYFrEwceSUmER82X4bZMcR3jg&usqp=CAU" style="width:350px;height:320px"> </a> <div class="caption"> <p><NAME> kachhi ghani 1 L , Rs 200/- </p> </div> <a href="signup.php"><center><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 9 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXgNdeHjsjFvgzMyxVMmcuZCtQPiBWEazl-Q&usqp=CAU" style="width:350px;height:320px"> </a> <div class="caption"> <p>soap soap pack , RS 120 </p> </div> <a href="signup.php"><center><button type="button" class="btn btn-primary btn-block" >Order Now!</button></center></a> </div> </div> </div> </div> </body> </html> <file_sep>/All PHP files/cart_add.php <?php require 'common.php'; if(!isset($_SESSION['email'])) { header('location:index.php'); } $user_id=$_SESSION['id']; $item_id=$_GET['id']; $insert_query="INSERT INTO user_items(user_id,item_id,status) VALUES ('$user_id','$item_id','Added to cart') "; $insert_query_result=mysqli_query($con,$insert_query) or die(mysqli_error($con)); header('location:home.php'); ?><file_sep>/All PHP files/signup.php <?php require 'common.php'; if(isset($_SESSION['email'])) { header('location:home.php'); } ?> <!DOCTYPE> <html> <head> <title>Signup</title> <link rel="stylesheet" type="text/css" href=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script> <script src=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js "></script> </head> <body style="background-color:rgba(255,245,34,0.31)"> <?php require 'header.php'; ?> <div class="row"> <div class="container"> <div class="col-sm-6 col-sm-offset-3"> <h3>SIGN UP</h3> <form method="post" action="signup_script.php"> <input type="text" name="name" placeholder="Name" class="form-control form-group input-lg" > <input type="text" name="email" placeholder="Email" class="form-control form-group input-lg" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" > <input type="text" name="password" placeholder="<PASSWORD>" class="form-control form-group input-lg"> <input type="number" name="contact" placeholder="Contact" class="form-control form-group input-lg" title="10 numerbers" pattern=".{10}"> <input type="text" name="city" placeholder="City" class="form-control form-group input-lg"> <input type="text" name="address" placeholder="Address" class="form-control form-group input-lg"> <button class="btn btn-default btn-primary btn-lg">Submit</button> </form> </div> </div> </div> </body> <?php require 'footer.php'; ?> </html> <file_sep>/All PHP files/signup_script.php <div style="margin-top: 80px"></div> <?php require 'common.php'; if(isset($_SESSION['email'])) { header('location:home.php'); } $regex_email = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/"; $regex_contact = "/^[789][0-9]{9}$/"; $name=mysqli_real_escape_string($con,$_POST['name']); $email=mysqli_real_escape_string($con,$_POST['email']); $password=mysqli_real_escape_string($con,$_POST['password']); $password=md5(<PASSWORD>); $contact=mysqli_real_escape_string($con,$_POST['contact']); $city=mysqli_real_escape_string($con,$_POST['city']); $address=mysqli_real_escape_string($con,$_POST['address']); $select_query="select id from users where email='$email'"; $select_query_result=mysqli_query($con,$select_query) or die(mysqli_error($con)); $count_of_users=mysqli_num_rows($select_query_result); if($count_of_users > 0) { echo "Email id already exists"; } else if($name==null or $email==null or $password==null or $contact==null or $city==null or $address==null) { echo "Please fill all the details"; } else if(!preg_match($regex_email,$email)) { echo "Email does not match the pattern "; } else if(!preg_match($regex_contact,$contact)) { echo "Contact does not match the pattern"; } else { $insert_query="insert into users (name,email,password,contact,city,address) values ('$name','$email','$password','$contact','$city','$address')"; $insert_query_submit=mysqli_query($con,$insert_query) or die (mysqli_error($con)); $_SESSION['id']=mysqli_insert_id($con); $_SESSION['email']=$email; $_SESSION['name']=$name; header('location:home.php'); } ?><file_sep>/All PHP files/login.php <?php require 'common.php'; if(isset($_SESSION['email'])) { header('location:home.php'); } $regex_email = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/"; $email=mysqli_real_escape_string($con,$_POST['email']); $password=mysqli_real_escape_string($con,$_POST['password']); $password=md5($password); $select_query="SELECT id,email,name FROM users WHERE email='$email'"; $select_query_2="SELECT password,name FROM users WHERE password='$<PASSWORD>'"; $select_query_3="SELECT * FROM users WHERE password='$<PASSWORD>' AND email='$email'"; $select_query_result=mysqli_query($con,$select_query) or die(mysqli_error($con)); $select_query_result_2=mysqli_query($con,$select_query_2) or die(mysqli_error($con)); $select_query_result_3=mysqli_query($con,$select_query_3) or die(mysqli_error($con)); $count_of_users=mysqli_num_rows($select_query_result); $count_of_users_2=mysqli_num_rows($select_query_result_2); $row=mysqli_fetch_array($select_query_result_3); if(!preg_match($regex_email,$email)) { echo "Enter a valid email address"; } else if($count_of_users==0) { echo "No such email is exists"; } else if( $count_of_users==1 and $count_of_users_2==0) { echo "Wrong password entered"."<br>"; echo $password; } else { $row=mysqli_fetch_array($select_query_result); $_SESSION['id']=$row['id']; $_SESSION['email']=$row['email']; $_SESSION['name']=$row['name']; header('location:home.php'); } ?><file_sep>/All PHP files/forgot_password.php <?php require 'header.php'; require 'common.php'; if(isset($_SESSION['email'])) { header('location:home.php'); } ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script> <script src=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js "></script> </head> <body style="background-color: rgba(255,0,150,0.15)"> <div class="container"> <center> <h1>Please enter your email</h1> <div style="margin-top: 80px"> <form method="post" action="forgot_password.php"> <input type="text" placeholder="email" name="email" class="form-group form-control input-lg" style="width: 300px"> </form> </div> </center> </div> </body> <?php $email=mysqli_real_escape_string($con,$_POST['email']); $select_query="select * from users where email='$email'"; $select_query_result=mysqli_query($con,$select_query) or die(mysqli_error($con)); $count_of_users=mysqli_num_rows($select_query_result); if($count_of_users==0) { echo "No such email id exists"; } else{ $row=mysqli_fetch_array($select_query_result); $row['password']="<PASSWORD>"; echo "YOUR PASSWORD HAS BEEN MAILED TO YOUR EMAIL ADDRESS"; } ?> </html> <file_sep>/All PHP files/cart.php <?php require 'common.php'; if(!isset($_SESSION['email'])){ header('location:index.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script> <script src=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js "></script> <title>Cart </title> <style> a:link { color: white; text-decoration: none } a:visited { color: black; text-decoration: none } a:hover { color: blue; text-decoration: none } a:active { color: red; text-decoration: none } </style> </head> <body> <div style="margin-bottom: 80px;margin-top: 100px"></div> <?php require 'header_home.php'; $user_id=$_SESSION['id']; $select_query="SELECT * FROM user_items INNER JOIN items ON user_items.item_id=items.pid WHERE user_items.user_id='$user_id' AND user_items.status='Added to cart'"; $select_query_result=mysqli_query($con,$select_query) or die(mysqli_error($con)); $count_of_rows=mysqli_num_rows($select_query_result); if($count_of_rows==0) { echo "Add items to the cart first!"; } else{ ?> <div class="container"> <center> <table class="table table-bordered table-striped table-hover table-responsive"> <tbody> <tr> <th>Item number</th> <th>Mobile Name</th> <th>Mobile Price</th> <th>Changed your mind?</th> </tr> <?php $sum = 0; while ($row = mysqli_fetch_array($select_query_result)) { $id = $row['pid']; $sum += $row['price']; echo "<tr><td>" . $row['pid'] . "</td><td>" . $row['name'] . "</td><td>" . $row['price'] . "</td><td> <button class='btn btn-danger'><a href='cart_remove.php?id={$row['pid']}' class='remove_item_link' >Remove</button></a></td></tr>"; } echo "<tr><td style='font-weight: bolder'>Total</td><td style='font-weight: bolder'>Rs/-" . $sum . "</td><td><a href='success.php?id={$id}' class='btn btn-primary'>Confirm Order</a></td></tr>"; } ?> </tbody> </table> </center> </div> </body> </html> <file_sep>/All PHP files/check_if_added.php <?php function check_if_added($item_id) { include "common.php"; $user_id=$_SESSION['id']; $select_query="SELECT * FROM user_items WHERE item_id='$item_id' AND user_id='$user_id' AND status='Added to cart'"; $select_query_result = mysqli_query($con, $select_query) or die(mysqli_error($con)); $count_of_rows = mysqli_num_rows($select_query_result); if($count_of_rows>=1) { return 1; } else return 0; } ?> <file_sep>/All PHP files/home.php <?php require 'common.php'; if (!isset($_SESSION['email'])){ header('location:index.php'); } ?> <!DOCTYPE html> <html> <head> <title>little basket-Home</title> <link rel="stylesheet" type="text/css" href=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script> <script src=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js "></script> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body style="background-color: rgba(85,85,85,0.76)"> <div style="margin-top: 100px ; margin-left: 20px" class="container-fluid"> <h4 class="welcome"><b>Welcome: <?php echo $_SESSION['name']; ?></b></h4> </div> <nav class="nav nav-default navbar-fixed-top"> <div class="container" style="background-color: rgba(249,249,249,0.6)"> <div class="navbar-header" > <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <?php if(isset($_SESSION['email'])){?> <a href="home.php" class="navbar-brand black_color">little basket</a> <?php }else { ?> <a href="index.php" class="navbar-brand black_color">little basket</a> <?php } ?> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right" > <li><a href="cart.php" target="_blank" class="black_color"><span class="glyphicon glyphicon-shoppingcart"></span>Cart</a> </li> <!-- <li><a href="settings.php" class="black_color"><span class="glyphicon glyphicon-user">Settings</span> </a> </li> --> <li><a href="logout.php" target="_blank" class="black_color"><span class="glyphicon glyphicon-login"></span>Logout </a> </li> </ul> </div> </div> </nav> <div class="container"> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h3>Login</h3> <button type="button" data-dismiss="modal" style="float: right" > <span class="glyphicon glyphicon-remove" ></span> </button> </div> <div class="modal-body"> <div class="row"> <div class="col-sm-12"> Don't have an account? <a href="signup.php" style="text-decoration:none">Register</a> <form method="post" action="login.php"> <input type="text" placeholder="Email" name="email" class="form-control form-group " pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" style="width: 100%" > <input type="text" placeholder="<PASSWORD>" name="<PASSWORD>" class="form-control form-group"> <input type="submit" value="Login" class="btn btn-primary" style="width:100px"> </form> </div> </div> </div> <div class="modal-footer"> <a href="forgot_password.php" target="_blank" style="text-decoration:none ; float: left">Forget Password?</a> </div> </div> </div> </div> </div> <!-- ===================================B O D Y=====================================================--> <?php require 'check_if_added.php'; ?> <div class="container-fluid" style="margin-top: 20px"> <div class="row"> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 1 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://www.aashirvaad.com/assets/Aashirvaad/images/NMP_FOP.png"style="width:350px;height:320px"> </a> <div class="caption"> <p>Aashirvaad aata 5 kg no.1 aata of india , Rs 250/- </p> </div> <?php if(check_if_added(1)) { echo '<a class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else{ echo '<a href="cart_add.php?id=1"><center><button type="button" class="btn btn-primary btn-block" >Add to cart</button></center></a>'; } ?> </div> </div> </div> <div class="col-sm-4 col-sm-offset-"> <div class="panel panel-default"> <div class="panel-heading"> Item 2 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://5.imimg.com/data5/FI/JI/MY-45727586/toor-dal-500x500.jpg"style="width:350px;height:320px"> </a> <div class="caption"> <p>Toor dal 2 kg Best price ,RS 150 </p> </div> <?php if(check_if_added(2)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else{ echo '<a href="cart_add.php?id=2"><center><button type="button" class="btn btn-primary btn-block" >Add to cart</button></center></a>'; } ?> </div> </div> </div> <div class="col-sm-4 col-sm-offset"> <div class="panel panel-default"> <div class="panel-heading"> Item 3 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://media.gettyimages.com/photos/riceland-extra-long-grain-bag-picture-id521991888?k=6&m=521991888&s=612x612&w=0&h=bt70QJf9k2nzRnwQ6DTOGuJxui8xEk-1MIF0qDLHtpY=" style="width:350px;height:320px"> </a> <div class="caption"> <p> Rice 2 kg Best price , RS 150 </p> </div> <?php if(check_if_added(3)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else{ echo '<a href="cart_add.php?id=3"><center><button type="button" class="btn btn-primary btn-block" >Add to cart</button></center></a>'; } ?> </div> </div> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item4 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://m.media-amazon.com/images/I/81JmTiQA68L._SX425_.jpg" style="width:350px;height:320px"> </a> <div class="caption"> <p>Besan 2 kg fresh besan pack , Rs 120/- </p> </div> <?php if(check_if_added(4)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else{ echo '<a href="cart_add.php?id=4"><center><button type="button" class="btn btn-primary btn-block" >Add to cart</button></center></a>'; } ?> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 5 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXkyr0VE5mGO-HPMQ7Ap8etqDxM3CiDsqBx47stJ2iOrG4Jt2c1sm6Fe27ukcJQVVZbTI&usqp=CAU" style="width:350px;height:320px" > </a> <div class="caption"> <p>TEA pack Tea pack of three, Rs 999/- </p> </div> <?php if(check_if_added(5)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else{ echo '<a href="cart_add.php?id=5"><center><button type="button" class="btn btn-primary btn-block" >Add to cart</button></center></a>'; } ?> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 6 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRUmiFRnI5R0-LqL1BU4Byz6eqHVlZ2jA-6JA&usqp=CAU" style="width:350px;height:320px"> </a> <div class="caption"> <p> Madhur Sugar 1 Kg Closed Packet, Verified Rs 500- </p> </div> <?php if(check_if_added(6)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else { echo '<a href="cart_add.php?id=6"><button type="button" class="btn btn-primary btn-block">Add to cart</button></a>'; } ?> </div> </div> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 7 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://www.bigbasket.com/media/uploads/p/xxl/274148-2_6-fortune-sun-lite-sunflower-refined-oil.jpg" style="width:350px;height:320px"> </a> <div class="caption"> <p>sun lite fortune refine 5L refine oil pack, Rs 549/- </p> </div> <?php if(check_if_added(7)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else { echo '<a href="cart_add.php?id=7"><button type="button" class="btn btn-primary btn-block">Add to cart</button></a>'; } ?> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 8 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSAafR1a2t3zPYFrEwceSUmER82X4bZMcR3jg&usqp=CAU" style="width:350px;height:320px"> </a> <div class="caption"> <p>Kachi ghanni kachhi ghani 1 L , Rs 200/- </p> </div> <?php if(check_if_added(8)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else { echo '<a href="cart_add.php?id=8"><button type="button" class="btn btn-primary btn-block">Add to cart</button></a>'; } ?> </div> </div> </div> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> Item 9 </div> <div class="panel-body"> <a class="thumbnail"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXgNdeHjsjFvgzMyxVMmcuZCtQPiBWEazl-Q&usqp=CAU" style="width:350px;height:320px"> </a> <div class="caption"> <p>soap soap pack , RS 120 </p> </div> <?php if(check_if_added(9)) { echo '<a href="#" class="btn btn-danger btn-block" disabled>Added to cart</a>'; } else { echo '<a href="cart_add.php?id=9"><button type="button" class="btn btn-primary btn-block">Add to cart</button> </a>'; } ?> </div> </div> </div> </body> </html> <file_sep>/All PHP files/success.php <?php require 'common.php'; if(!isset($_SESSION['email'])) { header('location:index.php'); } else { ?> <!DOCTYPE> <html> <head> <title>Success</title> <link rel="stylesheet" type="text/css" href=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script> <script src=" https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js "></script> <style> a:link { color: black; text-decoration: none } a:visited { color: black; text-decoration: none } a:hover { color: white; text-decoration: none } a:active { color: white; text-decoration: none } </style> </head> <body> <?php require 'header_home.php'; $item_id = $_GET['id']; $user_id = $_SESSION['id']; $update_query = "UPDATE user_items SET status='Confirmed' WHERE user_id='$user_id' AND item_id='$item_id' AND status='Added to cart'"; $update_query_result = mysqli_query($con, $update_query) or die(mysqli_error($con)); ?> <div class="container" style="margin-top: 70px"> <div class="jumbotron"> <h1 style="color: blue; text-align: center">Success</h1> <h3 style="text-align: center">Congratulations Your order is confirmed and will be delivered shortly</h3> <h4 style="text-align: center">Thank you for shopping with little basket</h4> </div> <button class="btn btn-primary" style="margin-left: 450px"><a href="home.php" target="_self"> Click here</a> </button> to purchase any other items </div> </body> <?php } ?>
c0ef7bee0d062bad126414cbbc083c6fdf142c84
[ "PHP" ]
10
PHP
rahulkumarsah/little-basket
7ebd0b3a3a00c11074126d29a4036e9ae87498b8
020c7e024f0856098df675f9c3aa4760b019ae40
refs/heads/master
<file_sep>package com.yan.workreport.model; import java.util.Date; public class WorkReportText { private String id; private String day; private String title; /** * 个人工作日志还是团队工作日志 * 个人 person * 团队 team */ private String type; private String writerName; private String projectCode; private String projectName; private String workText; private String validStatus; private Date insertTime; private Date updateTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDay() { return day; } public void setDay(String day) { this.day = day; } public String getWriterName() { return writerName; } public void setWriterName(String writerName) { this.writerName = writerName; } public String getProjectCode() { return projectCode; } public void setProjectCode(String projectCode) { this.projectCode = projectCode; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getWorkText() { return workText; } public void setWorkText(String workText) { this.workText = workText; } public Date getInsertTime() { return insertTime; } public void setInsertTime(Date insertTime) { this.insertTime = insertTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValidStatus() { return validStatus; } public void setValidStatus(String validStatus) { this.validStatus = validStatus; } public String getType() { return type; } public void setType(String type) { this.type = type; } } <file_sep># workreport 管理工作日志 <file_sep>package com.yan.workreport.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.yan.workreport.dao.WorkReportTextMongoDaoUtil; import com.yan.workreport.model.WorkReportText; import com.yan.workreport.vo.ResultVo; import com.yan.workreport.vo.WorkReportTextVo; @CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS, RequestMethod.HEAD, RequestMethod.PUT, RequestMethod.PATCH}, origins="*") @RestController public class WorkReportController { @RequestMapping(value="/findWorkReports", method=RequestMethod.POST) public ResultVo findWorkReports(@RequestParam Map<String, Object> map) { ResultVo queryResultVo = new ResultVo(); //根据条件查询总条数 long total = 0; //查询结果 WorkReportTextMongoDaoUtil workReportTextMongoDaoUtil = new WorkReportTextMongoDaoUtil(); List<WorkReportText> workReportTexts = workReportTextMongoDaoUtil.findWorkReportTextDocumentsByCondition(map); //返回给前台的rows不能是null,否则前台js会报rows is null异常 List<WorkReportTextVo> workReportTextVos = new ArrayList<WorkReportTextVo>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(workReportTexts != null && workReportTexts.size() > 0) { //workReportTextVos = new ArrayList<WorkReportTextVo>(); for(WorkReportText workReportText:workReportTexts){ WorkReportTextVo workReportTextVo = new WorkReportTextVo(); workReportTextVo.setId(workReportText.getId()); workReportTextVo.setDay(workReportText.getDay()); workReportTextVo.setTitle(workReportText.getTitle()); workReportTextVo.setType(workReportText.getType()); workReportTextVo.setProjectName(workReportText.getProjectName()); workReportTextVo.setProjectCode(workReportText.getProjectCode()); workReportTextVo.setWriterName(workReportText.getWriterName()); workReportTextVo.setWorkText(workReportText.getWorkText()); workReportTextVo.setUpdateTime(sdf.format(workReportText.getUpdateTime())); workReportTextVos.add(workReportTextVo); } } total = workReportTextMongoDaoUtil.countWorkReportTextVoDocumentsByCondition(map); queryResultVo.setTotal(total); //返回给前台的rows不能是null,否则前台js会报rows is null异常 queryResultVo.setRows(workReportTextVos); return queryResultVo; } @RequestMapping("/findUniqueWorkReport") public ResultVo findUniqueWorkReport(@RequestParam(value="id") String id) { boolean success = true; String errorMsg = null; ResultVo resultVo = new ResultVo(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); WorkReportTextVo workReportTextVo = null; if(id != null && !"".equals(id.trim())) { WorkReportTextMongoDaoUtil workReportTextMongoDaoUtil = new WorkReportTextMongoDaoUtil(); WorkReportText workReportText = workReportTextMongoDaoUtil.findWorkReportById(id); if(workReportText != null) { workReportTextVo = new WorkReportTextVo(); workReportTextVo.setId(workReportText.getId()); workReportTextVo.setDay(workReportText.getDay()); workReportTextVo.setTitle(workReportText.getTitle()); workReportTextVo.setType(workReportText.getType()); workReportTextVo.setProjectName(workReportText.getProjectName()); workReportTextVo.setProjectCode(workReportText.getProjectCode()); workReportTextVo.setWriterName(workReportText.getWriterName()); workReportTextVo.setWorkText(workReportText.getWorkText()); workReportTextVo.setUpdateTime(sdf.format(workReportText.getUpdateTime())); } } resultVo.setObject(workReportTextVo); resultVo.setErrorMsg(errorMsg); resultVo.setSuccess(success); return resultVo; } @RequestMapping("/saveWorkReport") public ResultVo saveWorkReport(@RequestParam Map<String, Object> map) { boolean success = true; String errorMsg = null; ResultVo resultVo = new ResultVo(); if(map != null){ WorkReportText reportText = new WorkReportText(); reportText.setId((String)map.get("id")); reportText.setDay((String)map.get("day")); reportText.setTitle((String)map.get("title")); reportText.setType((String)map.get("type")); reportText.setProjectName((String)map.get("projectName")); reportText.setProjectCode((String)map.get("projectCode")); reportText.setWriterName((String)map.get("writerName")); reportText.setWorkText((String)map.get("workText")); reportText.setValidStatus("1"); String editType = (String)map.get("editType"); WorkReportTextMongoDaoUtil workReportTextMongoDaoUtil = new WorkReportTextMongoDaoUtil(); if(editType != null && "new".equals(editType.trim())) { reportText.setInsertTime(new Date()); reportText.setUpdateTime(new Date()); String id = workReportTextMongoDaoUtil.insertWorkReportText(reportText); reportText.setId(id); resultVo.setObject(reportText); }else if (editType != null && "edit".equals(editType.trim())) { reportText.setUpdateTime(new Date()); workReportTextMongoDaoUtil.updateWorkReportText(reportText); resultVo.setObject(reportText); } }else{ success = false; errorMsg = "缺少参数或请求数据不全!"; } resultVo.setErrorMsg(errorMsg); resultVo.setSuccess(success); return resultVo; } @RequestMapping("/deleteWorkReport") public ResultVo deleteWorkReport(@RequestParam(value="id") String id) { boolean success = true; String errorMsg = null; ResultVo resultVo = new ResultVo(); if(id != null && !"".equals(id.trim())){ WorkReportTextMongoDaoUtil workReportTextMongoDaoUtil = new WorkReportTextMongoDaoUtil(); //目前采用修改有效无效标志位的方式来标志删除 workReportTextMongoDaoUtil.updateWorkReportTextValidStatus(id, "0"); }else{ success = false; errorMsg = "缺少参数或请求数据不全!"; } resultVo.setErrorMsg(errorMsg); resultVo.setSuccess(success); return resultVo; } }<file_sep>package com.yan.workreport.dao; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.yan.workreport.model.WorkReportText; import com.yan.workreport.util.SchameDocumentUtil; public class WorkReportTextMongoDaoUtil { public static void main(String[] args) throws Exception { WorkReportTextMongoDaoUtil workReportTextMongoDaoUtil = new WorkReportTextMongoDaoUtil(); WorkReportText workReportText = new WorkReportText(); workReportText.setDay("20171018"); workReportText.setProjectCode("test"); workReportText.setProjectName("测试"); workReportText.setWriterName("张三"); workReportText.setTitle("20171018工作日志"); workReportText.setWorkText("工作日志的具体内容如下:\\n1、.....\\n2、...\\n3、..."); workReportText.setInsertTime(new Date()); workReportText.setUpdateTime(new Date()); workReportTextMongoDaoUtil.insertWorkReportText(workReportText); } public String insertWorkReportText(WorkReportText workReportText){ //To connect to a single MongoDB instance: //You can explicitly specify the hostname and the port: MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); //Access a Database MongoDatabase database = mongoClient.getDatabase("manage"); //Access a Collection MongoCollection<Document> collection = database.getCollection("WorkReportText"); //Create a Document Document doc = SchameDocumentUtil.schameToDocument(workReportText, WorkReportText.class); //Insert a Document collection.insertOne(doc); //System.out.println("id:" + doc.get("_id")); String id = null; if(doc.get("_id") != null){ id = doc.get("_id").toString(); } return id; } public List<WorkReportText> findWorkReportTextDocumentsByCondition(Map<String, Object> condition){ List<WorkReportText> workReportTexts = null; if(condition != null && condition.size() > 0) { //To connect to a single MongoDB instance: //You can explicitly specify the hostname and the port: MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); //Access a Database MongoDatabase database = mongoClient.getDatabase("manage"); //Access a Collection MongoCollection<Document> collection = database.getCollection("WorkReportText"); List<Bson> bsons = new ArrayList<Bson>(0); //分页的页码 int page = 1; //分页每页条数 int rows = 10; for(Iterator<Entry<String, Object>> iterator = condition.entrySet().iterator();iterator.hasNext();) { Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); //因为查询条件改为了and,所以当条件为空字符串的时候不向查询条件中拼写 if(value != null && !"".equals(value.toString().trim())){ if("id".equals(key)) { bsons.add(Filters.eq("_id", new ObjectId(value.toString()))); }else if ("startDay".equals(key)) { bsons.add(Filters.gte("day", value.toString())); }else if ("endDay".equals(key)) { bsons.add(Filters.lte("day", value.toString())); }else if ("writerName".equals(key) || "projectCode".equals(key) || "type".equals(key)) { bsons.add(Filters.eq(key, value.toString())); }else if ("page".equals(key)) { page = Integer.parseInt(value.toString()); }else if ("rows".equals(key)) { rows = Integer.parseInt(value.toString()); }else { //其他的进行右模糊查询 //参考下regex的使用 //i  如果设置了这个修饰符,模式中的字母会进行大小写不敏感匹配。 //m 默认情况下,PCRE 认为目标字符串是由单行字符组成的(然而实际上它可能会包含多行).如果目标字符串 中没有 "\n"字符,或者模式中没有出现“行首”/“行末”字符,设置这个修饰符不产生任何影响。 //s 如果设置了这个修饰符,模式中的点号元字符匹配所有字符,包含换行符。如果没有这个修饰符,点号不匹配换行符。 //x 如果设置了这个修饰符,模式中的没有经过转义的或不在字符类中的空白数据字符总会被忽略,并且位于一个未转义的字符类外部的#字符和下一个换行符之间的字符也被忽略。 这个修饰符使被编译模式中可以包含注释。 注意:这仅用于数据字符。 空白字符 还是不能在模式的特殊字符序列中出现,比如序列 。 //注:JavaScript只提供了i和m选项,x和s选项必须使用$regex操作符 //在命令行的时候pattern左右使用//包起来,是因为通过//来表示包起来的是pattern,但是如果java中再将//拼接到字符串中,那么//就会当做pattern的一部分去匹配,就会出现问题 //debug的时候,发现pattern中居然包括//这是不对的 bsons.add(Filters.regex(key, "" + value.toString() + ".*", "i")); } } } int limit = rows; int skip = 0; if(page >= 0){ skip = (page - 1) * rows; } List<Document> docs = collection.find(Filters.and(bsons)).limit(limit).skip(skip).sort(new Document("day", -1)).into(new ArrayList<Document>()); if(docs != null){ workReportTexts = new ArrayList<WorkReportText>(); for(Document doc : docs){ WorkReportText workReportText = new WorkReportText(); //将document转换为interview //System.out.println(doc.get("_id")); workReportText = (WorkReportText)SchameDocumentUtil.documentToSchame(doc, WorkReportText.class); workReportTexts.add(workReportText); } } } return workReportTexts; } public Long countWorkReportTextVoDocumentsByCondition(Map<String, Object> condition){ long count = 0L; if(condition != null && condition.size() > 0) { //To connect to a single MongoDB instance: //You can explicitly specify the hostname and the port: MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); //Access a Database MongoDatabase database = mongoClient.getDatabase("manage"); //Access a Collection MongoCollection<Document> collection = database.getCollection("WorkReportText"); List<Bson> bsons = new ArrayList<Bson>(0); for(Iterator<Entry<String, Object>> iterator = condition.entrySet().iterator();iterator.hasNext();) { Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); //因为查询条件改为了and,所以当条件为空字符串的时候不向查询条件中拼写 if(value != null && !"".equals(value.toString().trim())){ if("id".equals(key)) { bsons.add(Filters.eq("_id", new ObjectId(value.toString()))); }else if ("startDay".equals(key)) { bsons.add(Filters.gte("day", value.toString())); }else if ("endDay".equals(key)) { bsons.add(Filters.lte("day", value.toString())); }else if ("writerName".equals(key) || "projectCode".equals(key) || "type".equals(key)) { bsons.add(Filters.eq(key, value.toString())); }else if ("page".equals(key) || "rows".equals(key)) { //这两个参数是分页参数,在分页查询数据时会用到,但是在查询总条数的时候并不会用到,但是也不能拼接到查询语句中 }else { //其他的进行右模糊查询 //参考下regex的使用 //i  如果设置了这个修饰符,模式中的字母会进行大小写不敏感匹配。 //m 默认情况下,PCRE 认为目标字符串是由单行字符组成的(然而实际上它可能会包含多行).如果目标字符串 中没有 "\n"字符,或者模式中没有出现“行首”/“行末”字符,设置这个修饰符不产生任何影响。 //s 如果设置了这个修饰符,模式中的点号元字符匹配所有字符,包含换行符。如果没有这个修饰符,点号不匹配换行符。 //x 如果设置了这个修饰符,模式中的没有经过转义的或不在字符类中的空白数据字符总会被忽略,并且位于一个未转义的字符类外部的#字符和下一个换行符之间的字符也被忽略。 这个修饰符使被编译模式中可以包含注释。 注意:这仅用于数据字符。 空白字符 还是不能在模式的特殊字符序列中出现,比如序列 。 //注:JavaScript只提供了i和m选项,x和s选项必须使用$regex操作符 //在命令行的时候pattern左右使用//包起来,是因为通过//来表示包起来的是pattern,但是如果java中再将//拼接到字符串中,那么//就会当做pattern的一部分去匹配,就会出现问题 //debug的时候,发现pattern中居然包括//这是不对的 bsons.add(Filters.regex(key, "" + value.toString() + ".*", "i")); } } } count = collection.count(Filters.and(bsons)); } return count; } public WorkReportText findWorkReportById(String id) { WorkReportText workReportText = null; if(id!= null && !"".equals(id.trim())) { //To connect to a single MongoDB instance: //You can explicitly specify the hostname and the port: MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); //Access a Database MongoDatabase database = mongoClient.getDatabase("manage"); //Access a Collection MongoCollection<Document> collection = database.getCollection("WorkReportText"); List<Document> docs = collection.find(Filters.eq("_id", new ObjectId(id))).into(new ArrayList<Document>()); if(docs != null && docs.size() > 0) { workReportText = (WorkReportText)SchameDocumentUtil.documentToSchame(docs.get(0), WorkReportText.class); } } return workReportText; } public void insertWorkReportTextList(List<WorkReportText> WorkReportTexts){ } public void updateWorkReportText(WorkReportText workReportText){ //To connect to a single MongoDB instance: //You can explicitly specify the hostname and the port: MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); //Access a Database MongoDatabase database = mongoClient.getDatabase("manage"); //Access a Collection MongoCollection<Document> collection = database.getCollection("WorkReportText"); //Create a Document Document doc = SchameDocumentUtil.schameToDocument(workReportText, WorkReportText.class); //Update a Document collection.updateOne(Filters.eq("_id", doc.get("_id")), new Document("$set", doc)); } public void updateWorkReportTextValidStatus(String id, String validStatus){ //To connect to a single MongoDB instance: //You can explicitly specify the hostname and the port: MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); //Access a Database MongoDatabase database = mongoClient.getDatabase("manage"); //Access a Collection MongoCollection<Document> collection = database.getCollection("WorkReportText"); //Create a Document Document doc = new Document("validStatus", validStatus); //Update a Document collection.updateOne(Filters.eq("_id", new ObjectId(id)), new Document("$set", doc)); } }
8c8ee0c2c76711aa102ce3a0ed183f1936a6e0ae
[ "Markdown", "Java" ]
4
Java
yankj12/workreport
701a0584fde9e3b693e89eeda69e6f9d1a169388
5c9cae353d8dc3a653c3296ca09caac201e838ab
refs/heads/master
<repo_name>YatingPan/conway-game-of-life<file_sep>/settings.gradle rootProject.name = 'conway-game-of-life' include 'ui' <file_sep>/src/main/java/com/miklesw/conway/grid/model/CellState.java package com.miklesw.conway.grid.model; import org.springframework.util.Assert; import java.awt.Color; import java.util.Objects; public class CellState { private final boolean live; private final Color color ; private CellState(boolean live, Color color) { this.live = live; this.color = color; } public static CellState live(Color color) { Assert.notNull(color, "Live cells must be assigned a color"); return new CellState(true, color); } public static CellState dead() { return new CellState(false, null); } public boolean isLive(){ return live; } public Color getColor() { return color; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CellState cellState = (CellState) o; return live == cellState.live && Objects.equals(color, cellState.color); } @Override public int hashCode() { return Objects.hash(live, color); } @Override public String toString() { return "CellState{" + "live=" + live + ", session=" + color + '}'; } } <file_sep>/src/main/java/com/miklesw/conway/utils/ColorUtils.java package com.miklesw.conway.utils; import java.awt.*; import java.util.List; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public final class ColorUtils { private ColorUtils() { } public static Color average(List<Color> colors) { Double redAverage = colors.stream().mapToInt(Color::getRed).average().orElse(0); Double greenAverage = colors.stream().mapToInt(Color::getGreen).average().orElse(0); Double blueAverage = colors.stream().mapToInt(Color::getBlue).average().orElse(0); return new Color(redAverage.intValue(), greenAverage.intValue(), blueAverage.intValue()); } public static String toHexColor(Color color) { if (color == null) { return null; } return String.format("#%02X%02X%02X", color.getRed(), color.getGreen(), color.getBlue()); } public static Color randomColor() { Random rand = new Random(); int r, g, b; r = rand.nextInt(255); g = rand.nextInt(255); b = rand.nextInt(255); return new Color(r, g, b); } } <file_sep>/src/main/java/com/miklesw/conway/web/session/AssignedColorRepository.java package com.miklesw.conway.web.session; import java.awt.*; import java.util.Set; public interface AssignedColorRepository { void add(Color color); void remove(Color color); Set<Color> getAll(); } <file_sep>/src/main/java/com/miklesw/conway/grid/GridService.java package com.miklesw.conway.grid; import com.miklesw.conway.grid.events.GridEventPublisher; import com.miklesw.conway.grid.model.CellPosition; import com.miklesw.conway.grid.model.CellState; import com.miklesw.conway.grid.model.GridSize; import com.miklesw.conway.utils.ColorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import java.awt.*; import java.util.*; import java.util.List; import static com.miklesw.conway.grid.util.GridUtils.determineNeighbouringCells; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; public class GridService { private static final Logger LOGGER = LoggerFactory.getLogger(GridService.class); private final Grid grid; private final GridEventPublisher gridEventPublisher; public GridService(Grid grid, GridEventPublisher gridEventPublisher) { this.grid = grid; this.gridEventPublisher = gridEventPublisher; } public GridSize getGridSize() { return new GridSize(grid.getGridSizeX(), grid.getGridSizeY()); } public Map<CellPosition, CellState> findLiveCells() { // TODO: Test return grid.getCells().entrySet().stream() .filter((e) -> e.getValue().isLive()) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); } //TODO: change to async (needs reworking of tests) public void spawnCell(CellPosition position, Color color) { LOGGER.info("SPAWNING cell at {} with {}.", position, color); grid.lock(); try { CellState currentState = grid.getCellState(position); if (currentState.isLive()) { String message = String.format("Cell at %s is already live with colour %s!", position, currentState.getColor()); LOGGER.warn(message); throw new IllegalStateException(message); } CellState liveState = CellState.live(color); grid.updateCellState(position, liveState); gridEventPublisher.publishCellChangedEvent(position, liveState); } finally { grid.unlock(); } } private void killCell(CellPosition position) { LOGGER.info("KILLING cell at {}.", position); grid.lock(); try { grid.updateCellState(position, CellState.dead()); gridEventPublisher.publishCellChangedEvent(position, CellState.dead()); } finally { grid.unlock(); } } public void computeNextState() { LOGGER.debug("Computing next grid state."); Set<CellPosition> cellsToKill = new HashSet<>(); Map<CellPosition, Color> cellsToSpawn = new HashMap<>(); grid.lock(); try { LOGGER.debug("Determining next grid state."); for (Map.Entry<CellPosition, CellState> gridEntry : grid.getCells().entrySet()) { CellPosition cellPosition = gridEntry.getKey(); CellState cellState = gridEntry.getValue(); List<CellState> liveNeighbours = findLiveNeighbourCellStates(cellPosition); int liveNeighbourCount = liveNeighbours.size(); if (cellState.isLive() && (liveNeighbourCount < 2 || liveNeighbourCount > 3)) { cellsToKill.add(cellPosition); } else if (!cellState.isLive() && liveNeighbourCount == 3) { cellsToSpawn.put(cellPosition, findAverageCellColor(liveNeighbours)); } } LOGGER.debug("Applying next grid state."); cellsToKill.forEach(this::killCell); // not handling runtime exception because: // - forEach swallows runtime exceptions // - locks will prevent race conditions when computing state cellsToSpawn.forEach(this::spawnCell); LOGGER.debug("Finished applying next grid state."); } finally { grid.unlock(); } } private Color findAverageCellColor(List<CellState> cellStates) { List<Color> cellColors = cellStates.stream() .map(CellState::getColor) .collect(toList()); return ColorUtils.average(cellColors); } private List<CellState> findLiveNeighbourCellStates(CellPosition cellPosition) { return determineNeighbouringCells(cellPosition, grid.getGridSizeX(), grid.getGridSizeY()).stream() .map(grid::getCellState) .filter(CellState::isLive) .collect(toList()); } } <file_sep>/src/test/java/com/miklesw/conway/grid/util/ColorUtilsTest.java package com.miklesw.conway.grid.util; import com.miklesw.conway.utils.ColorUtils; import org.junit.Test; import java.awt.*; import java.util.List; import static java.awt.Color.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class ColorUtilsTest { @Test public void givenAListOfUniqueColours_whenAverageMethodIsCalled_thenCorrectAverageColorShouldBeReturned(){ // given List<Color> colors = asList(BLUE, YELLOW, GREEN, new Color(200,50,50)); // when Color result = ColorUtils.average(colors); // then assertThat(result).isEqualTo(new Color(113,140,76)); } @Test public void givenAListOfNonUniqueColours_whenAverageMethodIsCalled_thenCorrectAverageColorShouldBeReturned(){ // given List<Color> colors = asList(BLUE, YELLOW, YELLOW, GREEN, GREEN, new Color(200,50,50)); // when Color result = ColorUtils.average(colors); // then assertThat(result).isEqualTo(new Color(118,178,50)); } }<file_sep>/README.MD # Conway's Game Of Life A multi-player implementation of Conway’s Game of Life. The game is modeled as a grid with 4 simple rules: - Any live cell with fewer than two live neighbours dies, as if caused by under-population. - Any live cell with two or three live neighbours lives on to the next generation. - Any live cell with more than three live neighbours dies, as if by overcrowding. - Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. Users will be assigned a random color that will persist for the length of their session. If a color is assigned to a user session it may not be assigned to another user. This is an implementation of a recruitment technical challenge for [Fullstack-Backend Developers](https://hackmd.io/s/SyXikdg_g#Full-Stack--Backend-Developer--Eng-Manager). ## Build & Deployment For ease of deployment and convenience, the UI has been packaged as a sub-module within the back-end app project. The [gradle-node-plugin](https://github.com/srs/gradle-node-plugin) is used to download **node & npm** and execute `npm run build`. The `copyUIResources` gradle task copies generated production UI code into the app's `src/main/resources/public` folder. This is far from ideal and would not be used in real life scenario. The UI should be an independent component deployed on a web server or reverse proxy such as **Nginx**, having mappings defined to direct requests to the backend app. ### Local Builds Build: `./gradlew clean build` Run: `./gradlew bootRun` ### Deploying on Heroku from Github This application is configured to build (from Github) and deploy on Heroku without any additional configuration. Git Url: https://github.com/miklesw/conway-game-of-life NOTE: Gradle buildpack must be added to app on heroku. ## Configuration | Property | Default | Desc | |---|---|---| | grid.size.x | n/a | width of the grid in cells | | grid.size.y | n/a | height of the grid in cells | | grid.impl | memory | implementation of the grid to use | | session.color.repo.impl | memory | implementation of the session color repository to use | | grid.next.state.interval.ms | n/a | interval in milliseconds to recompute grid state | | grid.next.state.enabled | n/a | enable recomputation of grid state (needs to be disabled for some tests) | ## Testing Unit and web integration tests have been implemented as needed. Full service tests and additional coverage are desirable. ### Manual testing The following features have been tested manually: - Patterns: - Block - Glider - Beehive - Blinker - Color assignment for multiple browsers/user. - Application of average color when spawning cells ## Backend Design ### Packaging Since this is a relatively small project all the packages have been implemented in a single module. The project is made up of 4 main packages which can be cleanly extracted to independent modules/projects: - com.miklesw.conway.grid (maintaining the grid's state) - com.miklesw.conway.events (implementation and configuration of grid events) - com.miklesw.conway.schedule (scheduling of grid state computation) - com.miklesw.conway.web (web layer implementation) ### Maintaining the grid's state The `GridService` makes use of a `Grid` bean to maintain the state of the grid. In this solution the `Grid` interface has been implemented as an `InMemoryGrid` consisting of: - `ConcurrentHashMap` to store `CellState` by `CellPosition` - `ReentrantLock` to maintain grid locks (see Concurrency section below) NOTE: I was conflicted about whether the cell state and position belong together as part of a cell class, but in the end a map was the most sensible solution for accessing cell states, and I wasn't keen on having the position as both the map's key and an attribute. #### Scaling To scale the application across multiple instances, the `Grid` interface can be implemented to use a distributed solution for storing states and locks, such as **Hazelcast**. #### Concurrency Although the `ConcurrentHashMap` is threadsafe, it does not ensure atomic operations (e.g read + write). Typically this is addressed using methods such as `computeIfAbsent()` or the `synchronized` keyword. When computing the next grid state, the next state for the entire grid needs to be determined before any cell state changes are applied. This means that there is potential for a race condition while determining the next state; any user requests to spawn a cell may result in an inconsistent grid state or conflicts. (e.g. next state computation tries to spawn a cell with color X, but it has already been spawned by a user with color y). The `synchonized` keyword does not provide sufficient flexibility to handle this scenario. `ReentrantLock` was used since it allows for a shared lock between the `spawnCell()`, `computeNextState()` and `killCell()` methods. A problem with this approach is that `computeNextState()` may keep the lock for too long, depending on the size of the grid. This may result in wait timeouts if the front-end will expect a response when it makes a request to spawn a cell. Async requests for spawning cells may need to be considered. ### Computing the next grid state The grid state computation is triggers by a scheduled method that has a configurable fixed delay interval. ### Maintaining a user's assigned color There are many approaches available to maintain values for a user session with spring; `UserDetails` in the spring security context, session-scoped beans and session attributes. For the purposes of this project, the most suitable was to store a session attribute in the http session object. An in-memory repository backed by a `Set` derived from `ConcurrentHashMap`, was implemented to maintain a list of assigned colors. This is used when generating a random color to ensure the color is not already assigned. Leveraging Spring's **http session events**, the assigned color is added and removed to the repository when a session is created or destroyed (expired). This will ensure that the colors are recycled for future use. #### Scaling For color assignment to scale across multiple instances, 2 changes are required (unless sticky sessions are used): - Implement a distributed repository for assigned colors. - Implement distributed sessions (Spring's `SessionRepository`) ### Cell change events Cell change events are triggered when a user spawns a cell and for individual cell changes when the next grid state is applied. This allows individual cell updates to be sent to the frontend via websockets. As a result, the frontend only needs to receive the entire grid on initial connection or when reconnecting. This implementation uses **Spring Events** for simplicity. The `@Async` annotation ensures that the handling of the event does not block the publishing thread. #### Scaling To scale the application across multiple instances, the application can be updated to use **Spring Integration** and a **Message Broker** instead of Spring Events, so that the `CellStateChangedEvent` is handled by an event consumer in all instances. NOTE: When using Spring Integration, the `GridEventPublisher` may need to be changed to accept `CellStateChangedEvent` (instead of 2 parameters), so that implementation-less gateways can be used. ### Publishing events to the client A number of technologies have been considered to address this requirement, namely; **Websockets**, **Server-sent events (SSE)** and **polling**. A high-level comparison can be found [here](https://image.slidesharecdn.com/2015-06-22parisjswebsocketvsssev2-150624185438-lva1-app6891/95/websocket-vs-sse-parisjs-240615-11-638.jpg?cb=1435172291) SSE was chosen based on 3 considerations: - Unidirectional streams were sufficient given requests to spawn a cell were handled by a REST endpoint. - Ease of implementation versus web sockets (polling was a non-starter) - Multiple claims that SSE provides better support for load balancing and better latency. Client-side support for Microsoft browsers can be addressed using one of many polyfils available. NOTE: **Spring Webflux's** WebClient was used to build a test SSE client, but it didn't seem to be a natural fit for the event use-case on the server. Additional reading may be required to see how it can be applied. ### Endpoints | Endpoint | Method | Desc | |---|---|---| | /api/grid/size | GET | Returns the size of the grid which is used by the front-end to generate the model and view | | /api/grid/cells/live | GET | Return a list of currently live cells, so that ui can re-initialise state on connect/reconnect | | /api/grid/cells/{x}/{y}/spawn | POST | Spawns a cell at a specified position | | /api/grid/cells/events | GET | Subscribes to CellStateChangedEvents | ## Frontend Design ### Web Framework Angular, React and Vue were considered for this project. VueJs was selected because of the following reasons: - Similarity with Angular (briefly worked with Angular in a previous role) - Lightweight - Recommended for small teams - Quick learning curve Axios was used for backend calls, since vue-resource is no longer recommended by Vue. ### Events Initially the event implementation was attempted using vue-sse, but it seems like this module is for an older version of Vue. EventSource was used to handle SSE events. event-source-polyfill was installed to provide support for Microsoft browsers. #### Re-connections When the EventSource connection is lost, some events maybe be lost and the state of the grid in the UI may become out of sync. To prevent this from happening, the grid state is re-initialised every time the EventSource connection is opened (or re-opened) ### Browser Compatibility The UI was tested with Chrome 68 & Firefox 43. ES6 syntax was used, so there might be issues in older browsers (there are ways around this) ### Responsive Design The grid and cells should always maintain the same size. The page is set to overflow with scrolling if the grid is larger than the viewport. ### Possible Improvements - Extract API calls to a service. More reading required to find out how to inject services like in Angular. - Validation of vue component properties. - Deterioration of responsiveness after having the page open for extended periods. ## Unimplemented Features The pattern toolbar hasn't been implemented due to time constraints.<file_sep>/src/main/java/com/miklesw/conway/web/model/CellStateChangeInfo.java package com.miklesw.conway.web.model; import java.util.Objects; public class CellStateChangeInfo { private Position position; private boolean live; private String color; private CellStateChangeInfo() { } public CellStateChangeInfo(Position position, boolean live, String color) { this.position = position; this.live = live; this.color = color; } public Position getPosition() { return position; } public boolean isLive() { return live; } public String getColor() { return color; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CellStateChangeInfo that = (CellStateChangeInfo) o; return live == that.live && Objects.equals(position, that.position) && Objects.equals(color, that.color); } @Override public int hashCode() { return Objects.hash(position, live, color); } } <file_sep>/src/main/java/com/miklesw/conway/web/WebConfig.java package com.miklesw.conway.web; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.security.web.session.HttpSessionEventPublisher; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableWebMvc @EnableAsync @Import({ WebSecurityConfig.class }) public class WebConfig extends WebMvcAutoConfiguration { @Bean public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } } <file_sep>/src/main/java/com/miklesw/conway/schedule/ScheduleConfig.java package com.miklesw.conway.schedule; import com.miklesw.conway.grid.GridService; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling public class ScheduleConfig { @Bean @ConditionalOnProperty(name = "grid.next.state.enabled", havingValue = "true", matchIfMissing = true) StateComputationScheduler stateComputationScheduler(GridService gridService) { return new StateComputationScheduler(gridService); } } <file_sep>/src/test/java/com/miklesw/conway/web/GameOfLiveServiceTest.java package com.miklesw.conway.web; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; /** * Test the actual game */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource( properties = { "grid.next.state.enabled=true" } ) public class GameOfLiveServiceTest { @LocalServerPort private int port; private CellChangeEventTestClient cellChangeEventTestClient; @Test public void givenAPATTERN_whenGameTicks_thenPATTERNWILLCHANGEASEXPECTED() { // given // when // then Assert.assertTrue(true); } } <file_sep>/src/main/resources/application.properties grid.size.x=80 grid.size.y=40 grid.impl=memory session.color.repo.impl=memory grid.next.state.interval.ms=2000 grid.next.state.enabled=true <file_sep>/src/main/java/com/miklesw/conway/events/CellStateChangedEvent.java package com.miklesw.conway.events; import com.miklesw.conway.grid.model.CellState; import com.miklesw.conway.grid.model.CellPosition; public class CellStateChangedEvent { private final CellPosition cellPosition; private final CellState cellState; public CellStateChangedEvent(CellPosition cellPosition, CellState cellState) { this.cellPosition = cellPosition; this.cellState = cellState; } public CellPosition getCellPosition() { return cellPosition; } public CellState getCellState() { return cellState; } } <file_sep>/build.gradle group 'com.miklesw.conway' version '1.0-SNAPSHOT' buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } mavenCentral() } dependencies { classpath "org.springframework.boot:spring-boot-gradle-plugin:2.0.4.RELEASE" classpath "com.moowork.gradle:gradle-node-plugin:1.2.0" } } apply plugin: 'java' apply plugin: 'org.springframework.boot' sourceCompatibility = 1.8 repositories { mavenCentral() } task stage(dependsOn: ['build', 'clean']) build.mustRunAfter clean compileJava.dependsOn('copyUIResources') task copyUIResources (dependsOn:[":ui:buildUI"]){ doFirst { logger.info("Deleting static resources..") delete 'src/main/resources/public' } doLast { logger.info("Copying static resources..") copy{ from 'ui/dist' into 'src/main/resources/public' } } } dependencies { compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.4.RELEASE' compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.0.4.RELEASE' compile group: 'com.google.guava', name: 'guava', version: '19.0' compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' testCompile group: 'junit', name: 'junit', version: '4.12' testCompile group: 'org.assertj', name: 'assertj-core', version: '3.10.0' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.4.RELEASE' testCompile group: 'org.mockito', name: 'mockito-core', version: '2.21.0' testCompile group: 'com.shazam', name: 'shazamcrest', version: '0.11' testCompile group: 'com.google.code.gson', name: 'gson', version: '2.8.5' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '2.0.4.RELEASE' testCompile group: 'org.awaitility', name: 'awaitility', version: '3.1.2' } <file_sep>/src/main/java/com/miklesw/conway/grid/events/GridEventPublisher.java package com.miklesw.conway.grid.events; import com.miklesw.conway.grid.model.CellState; import com.miklesw.conway.grid.model.CellPosition; public interface GridEventPublisher { void publishCellChangedEvent(CellPosition position, CellState cellState); } <file_sep>/src/main/java/com/miklesw/conway/grid/GridConfig.java package com.miklesw.conway.grid; import com.miklesw.conway.grid.events.GridEventPublisher; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GridConfig { @Bean @ConditionalOnProperty(name = "grid.impl", havingValue = "memory", matchIfMissing = true) Grid inMemoryGrid(@Value("${grid.size.x}") String gridSizeX, @Value("${grid.size.y}") String gridSizeY) { int x = Integer.parseInt(gridSizeX); int y = Integer.parseInt(gridSizeY); return new InMemoryGrid(x, y); } @Bean GridService gridService(Grid grid, GridEventPublisher gridEventPublisher) { return new GridService(grid, gridEventPublisher); } } <file_sep>/ui/build.gradle apply plugin: 'com.moowork.node' node { version = '8.11.3' npmVersion = '5.6.0' distBaseUrl = 'https://nodejs.org/dist' download = true workDir = file("${project.buildDir}/nodejs") npmWorkDir = file("${project.buildDir}/npm") nodeModulesDir = file("${project.projectDir}") } task buildUI(type: NpmTask) { args = ['run', 'build'] } buildUI.dependsOn(npmInstall) <file_sep>/src/test/java/com/miklesw/conway/grid/InMemoryGridTest.java package com.miklesw.conway.grid; import com.miklesw.conway.grid.model.CellPosition; import com.miklesw.conway.grid.model.CellState; import org.junit.Test; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class InMemoryGridTest { @Test public void whenInitialised_thenWillGenerateGridOfDeadCellsOfSizeXY() { // given int gridSizeX = 6; int gridSizeY = 4; // when InMemoryGrid grid = new InMemoryGrid(gridSizeX, gridSizeY); // then Map<CellPosition, CellState> cells = grid.getCells(); for (int x = 1; x <= gridSizeX; x++) { for (int y = 1; y <= gridSizeY; y++) { CellPosition position = new CellPosition(x, y); CellState cellState = cells.get(position); assertThat(cellState).isNotNull(); assertThat(cellState.isLive()).isFalse(); assertThat(cellState.getColor()).isNull(); } } } // TODO: testing other methods }<file_sep>/src/main/java/com/miklesw/conway/web/session/UnassignedColorFinder.java package com.miklesw.conway.web.session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.awt.*; import static com.miklesw.conway.utils.ColorUtils.randomColor; @Component public class UnassignedColorFinder { private final AssignedColorRepository assignedColorRepository; @Autowired public UnassignedColorFinder(AssignedColorRepository assignedColorRepository) { this.assignedColorRepository = assignedColorRepository; } public Color find() { Color unassignedColor = null; while (unassignedColor == null) { Color randomColor = randomColor(); if (! assignedColorRepository.getAll().contains(randomColor)) { unassignedColor = randomColor; } } return unassignedColor; } }
d7f8185f4f32656e597b22e6887d0fc01bf9df6d
[ "Markdown", "Java", "INI", "Gradle" ]
19
Gradle
YatingPan/conway-game-of-life
76bd98e1ad49fa442427a94657256c53b15f4cd3
a32b969da394cc73af294ee84e748cb9ea0d32ac
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using CommunicationServers.Sockets; using Services; using ProtocolFamily.Modbus; using System.Net.Sockets; using System.Windows.Threading; using MesToPlc.Models; using Services.DataBase; using System.Diagnostics; using MesToPlc; using System.Threading.Tasks; namespace MesToPlc.Pages { /// <summary> /// OperatePage.xaml 的交互逻辑 /// </summary> public partial class OperatePage : Page { //SqlHelper sql = new SqlHelper(); AccessHelper sql = new AccessHelper(); Socket socketClient; SocketServer socketServer; IniHelper ini = new IniHelper(System.AppDomain.CurrentDomain.BaseDirectory + @"\Set.ini"); CharacterConversion characterConversion; DispatcherTimer LinkToMesTimer = new DispatcherTimer(); DispatcherTimer LinkToMesStateTimer = new DispatcherTimer(); DispatcherTimer LinkToPlcTimer = new DispatcherTimer(); DispatcherTimer VerifyTimer = new DispatcherTimer(); int PlcDelayCount; int MesDelayCount; public OperatePage() { InitializeComponent(); this.Loaded += OperatePage_Loaded; this.Unloaded += OperatePage_Unloaded; this.LinkToMesTimer.Interval = new TimeSpan(0,0,10); this.LinkToMesTimer.IsEnabled = true; this.LinkToMesTimer.Tick += LinkToMesTimer_Tick; this.LinkToPlcTimer.Interval = new TimeSpan(0,0,1); this.LinkToPlcTimer.Tick += LinkToPlcTimer_Tick; this.VerifyTimer.Interval = new TimeSpan(0, 0, 1); this.VerifyTimer.Tick += VerifyTimer_Tick; this.VerifyTimer.IsEnabled = true; this.LinkToMesStateTimer.Interval = new TimeSpan(0, 0, 1); this.LinkToMesStateTimer.Tick += LinkToMesStateTimer_Tick; this.PlcState.Source = ConnectResult.Normal; this.MesState.Source = ConnectResult.Normal; this.PlcDelayCount = 1; this.MesDelayCount = 1; } private void LinkToMesStateTimer_Tick(object sender, EventArgs e) { if (this.MesDelayCount-- == 0) { this.MesDelayCount = 1; this.MesState.Source = ConnectResult.Normal; this.LinkToMesStateTimer.IsEnabled = false; this.LinkToMesStateTimer.Stop(); } } private void VerifyTimer_Tick(object sender, EventArgs e) { HandInputVerify(); if (this.lstInfoLog.Items.Count >= 60) { int ClearLstCount = lstInfoLog.Items.Count - 60; this.lstInfoLog.Items.RemoveAt(ClearLstCount); } } private void LinkToPlcTimer_Tick(object sender, EventArgs e) { if (this.PlcDelayCount-- == 0) { this.PlcDelayCount = 1; this.PlcState.Source = ConnectResult.Normal; this.LinkToPlcTimer.IsEnabled = false; this.LinkToPlcTimer.Stop(); } } /// <summary> /// 访问Mes定时器 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LinkToMesTimer_Tick(object sender, EventArgs e) { if (this.txtSerialNum.Text == "") return; MesLoad mesload = new MesLoad(); MesLoadResult mesLoadResult = new MesLoadResult(); string url = ini.ReadIni("Config", "MesInterface") + this.txtSerialNum.Text.Trim(); Task<RequestResult> task = new Task<RequestResult>(() => { return mesload.GetData(out mesLoadResult, url); }); task.Start(); Task tsk = task.ContinueWith(t => { RequestResult result = (RequestResult)t.Result; Dispatcher.BeginInvoke(new Action(() => { switch (result) { case RequestResult.Success: SetMesState(ConnectResult.Success); this.AddLog("请求MES成功"); break; case RequestResult.Fail: SetMesState(ConnectResult.Fail); this.AddLog("请求MES系统没有响应"); return; default: break; } switch (mesLoadResult.Type) { case "S": this.txtWuLiaoBianHao.Text = mesLoadResult.MaterialCode; this.AddLog("MES返回物料编号:" + mesLoadResult.MaterialCode); this.GetChengXuHao(this.txtWuLiaoBianHao.Text); break; case "E": SetMesState(ConnectResult.Fail); this.AddLog("未找到该序列号对应型号"); break; default: break; } HandInputVerify(); })); }); } private void GetWuLiaoHao() { Dispatcher.BeginInvoke(new Action(() => { if (this.txtSerialNum.Text == "") return; MesLoad mesload = new MesLoad(); MesLoadResult mesLoadResult = new MesLoadResult(); switch (mesload.GetData(out mesLoadResult, ini.ReadIni("Config", "MesInterface") + this.txtSerialNum.Text.Trim())) { case RequestResult.Success: SetMesState(ConnectResult.Success); this.AddLog("请求MES成功"); break; case RequestResult.Fail: SetMesState(ConnectResult.Fail); this.AddLog("请求MES系统没有响应"); return; default: break; } switch (mesLoadResult.Type) { case "S": this.txtWuLiaoBianHao.Text = mesLoadResult.MaterialCode; this.AddLog("MES返回物料编号:" + mesLoadResult.MaterialCode); this.GetChengXuHao(this.txtWuLiaoBianHao.Text); break; case "E": SetMesState(ConnectResult.Fail); this.AddLog("未找到该序列号对应型号"); break; default: break; } HandInputVerify(); })); } private void SetMesState(BitmapImage connectResult) { this.LinkToMesStateTimer.Start(); Dispatcher.BeginInvoke(new Action(() => { this.MesState.Source = connectResult; })); } private void OperatePage_Unloaded(object sender, RoutedEventArgs e) { socketClient.Close(); } private void OperatePage_Loaded(object sender, RoutedEventArgs e) { this.btnSure.IsEnabled = false; string port = ini.ReadIni("Config", "Port"); socketServer = new SocketServer(); this.txtWuLiaoBianHaoR.Text = ini.ReadIni("Response","WuLiaoBianHao"); this.txtSerialNumR.Text = ini.ReadIni("Response", "SerialNum"); this.txtModelNumR.Text = ini.ReadIni("Response", "ModelNum"); this.txtIndexR.Text = ini.ReadIni("Response", "Index"); bool listenResult = socketServer.Listen(port); if(listenResult == false) { MessageBox.Show(string.Format("监听{0}口失败", port)); } SimpleLogHelper.Instance.WriteLog(LogType.Info,"监听端口:" + listenResult); socketServer.NewConnnectionEvent += SocketServer_NewConnnectionEvent; socketServer.NewMessage1Event += SocketServer_NewMessage1Event; } private void SocketServer_NewMessage1Event(Socket socket, string Message) { try { SimpleLogHelper.Instance.WriteLog(LogType.Info, Message); if (Message.Length != 24) return; AddLog("PLC数据请求" + Message); ModbusTcpServer modbusTcpServer = new ModbusTcpServer(); modbusTcpServer.AffairID = Message.Substring(0, 4); modbusTcpServer.ProtocolID = Message.Substring(4, 4); int requestDataLength = MathHelper.HexToDec(Message.Substring(Message.Length - 4, 4)); //请求数据长度 modbusTcpServer.BackDataLength = MathHelper.DecToHex((requestDataLength * 2).ToString()).PadLeft(2, '0'); modbusTcpServer.SlaveId = Message.Substring(12, 2); modbusTcpServer.Length = MathHelper.DecToHex((3 + requestDataLength * 2).ToString()).PadLeft(4, '0'); string backdata = modbusTcpServer.AffairID + modbusTcpServer.ProtocolID + modbusTcpServer.Length + modbusTcpServer.SlaveId + ModbusFunction.ReadHoldingRegisters + modbusTcpServer.BackDataLength; string chengxuhao = ini.ReadIni("Request", "Index"); if (string.IsNullOrEmpty(chengxuhao)) { chengxuhao = "0"; } chengxuhao = MathHelper.DecToHex(chengxuhao).PadLeft(4, '0'); string xinghao = MathHelperEx.StrToASCII1(ini.ReadIni("Request", "ModelNum")); string xinghaolength = MathHelper.DecToHex((ini.ReadIni("Request", "ModelNum").Length * 2).ToString()).PadLeft(4, '0'); backdata += (chengxuhao + xinghaolength + xinghao).PadRight(104, 'F'); string wuliaobianhao = MathHelperEx.StrToASCII1(ini.ReadIni("Request", "WuLiaoBianHao")); string wuliaobianhaolength = MathHelper.DecToHex((ini.ReadIni("Request", "WuLiaoBianHao").Length * 2).ToString()).PadLeft(4, '0'); backdata += (wuliaobianhaolength + wuliaobianhao).PadRight(100, 'F'); if (this.socketServer.IsConnected(this.socketClient)) { characterConversion = new CharacterConversion(); this.socketServer.Send(this.socketClient, characterConversion.HexConvertToByte(backdata)); AddLog("返回PLC数据:" + backdata); CopyMesToPlc(); } this.LinkToPlcTimer.Start(); Dispatcher.BeginInvoke(new Action(() => { this.PlcState.Source = ConnectResult.Success; })); } catch { AddLog("PLC请求数据失败"); this.LinkToPlcTimer.Start(); Dispatcher.BeginInvoke(new Action(() => { this.PlcState.Source = ConnectResult.Fail; })); } } private void CopyMesToPlc() { Dispatcher.BeginInvoke(new Action(() => { this.txtIndex.Clear(); this.txtWuLiaoBianHao.Clear(); this.txtModelNum.Clear(); this.txtSerialNum.Clear(); this.txtWuLiaoBianHaoR.Text = ini.ReadIni("Request", "WuLiaoBianHao"); this.txtSerialNumR.Text = ini.ReadIni("Request", "SerialNum"); this.txtModelNumR.Text = ini.ReadIni("Request", "ModelNum"); this.txtIndexR.Text = ini.ReadIni("Request", "Index"); ini.WriteIni("Request", "WuLiaoBianHao", ""); ini.WriteIni("Request", "SerialNum", ""); ini.WriteIni("Request", "ModelNum", ""); ini.WriteIni("Request", "Index", ""); ini.WriteIni("Response", "WuLiaoBianHao", this.txtWuLiaoBianHaoR.Text); ini.WriteIni("Response", "SerialNum", this.txtSerialNumR.Text); ini.WriteIni("Response", "ModelNum", this.txtModelNumR.Text); ini.WriteIni("Response", "Index", this.txtIndexR.Text); })); } private void SocketServer_NewConnnectionEvent(Socket socket) { socketClient = socket; } private void HandInputVerify() { string commandText = "SELECT * FROM [User] Where Authority = '0'"; List<UserModel> users = sql.GetDataTable<UserModel>(commandText); if (users == null) return; foreach (var item in users) { if (ini.ReadIni("Config", "UserName") == item.UserName) { this.HandInput.IsEnabled = true; return; } } this.HandInput.IsEnabled = false; //this.txtIndex.IsEnabled = false; //this.txtModelNum.IsEnabled = false; } private void AddChengXuHao_DataBackEvent(ChengXuHaoModel chengXuHaoModel) { Dispatcher.BeginInvoke(new Action(() => { this.txtIndex.Text = chengXuHaoModel.ChengXuHao; this.txtWuLiaoBianHao.Text = chengXuHaoModel.WuLiaoBianHao; this.txtModelNum.Text = chengXuHaoModel.XingHao; GetChengXuHao(chengXuHaoModel.XingHao); })); } private void btnSure_Click(object sender, RoutedEventArgs e) { if (this.txtModelNum.Text == "") return; this.GetChengXuHao(this.txtModelNum.Text); } private void GetChengXuHao(string xinghao) { List<ChengXuHaoModel> chengXuHaoModels = sql.GetDataTable<ChengXuHaoModel>("select * from ChengXuHao"); foreach (var item in chengXuHaoModels) { if (this.txtWuLiaoBianHao.Text == item.WuLiaoBianHao) { this.txtIndex.Text = item.ChengXuHao; this.txtModelNum.Text = item.XingHao; ini.WriteIni("Request","WuLiaoBianHao",this.txtWuLiaoBianHao.Text); ini.WriteIni("Request", "SerialNum", this.txtSerialNum.Text); ini.WriteIni("Request", "ModelNum", item.XingHao); ini.WriteIni("Request", "Index", item.ChengXuHao); AddLog("型号与成序号映射成功并保存"); AddLog("物料编号:" + this.txtWuLiaoBianHao.Text); AddLog("型号:" + this.txtModelNum.Text); AddLog("程序号:" + item.ChengXuHao); return; } } AddLog("未找到对应程序号"); } private void HandInput_Click(object sender, RoutedEventArgs e) { if (this.HandInput.IsChecked == true) { AddLog("已切换到手动输入"); this.btnSure.IsEnabled = true; this.LinkToMesTimer.IsEnabled = false; AddChengXuHao addChengXuHao = new AddChengXuHao(); addChengXuHao.DataBackEvent += AddChengXuHao_DataBackEvent; ini.WriteIni("Config", "AddWindowShow", WindowShowState.ShowState.Select.ToString()); addChengXuHao.Show(); } else { AddLog("已切换到自动请求"); //this.btnSure.IsEnabled = false; this.LinkToMesTimer.IsEnabled = true; } } private void AddLog(string log) { Dispatcher.BeginInvoke(new Action(() => { log = DateTime.Now + ": " + log; this.lstInfoLog.Items.Add(log); Decorator decorator = (Decorator)VisualTreeHelper.GetChild(lstInfoLog, 0); ScrollViewer scrollViewer = (ScrollViewer)decorator.Child; scrollViewer.ScrollToEnd(); SimpleLogHelper.Instance.WriteLog(LogType.Info, log); })); } private void btnClear_Click(object sender, RoutedEventArgs e) { this.lstInfoLog.Items.Clear(); } } } <file_sep>[Config] Port = 2756 SqlUrl = Data Source =192.168.127.12,7006; Initial Catalog = ChuangYan; User Id = sa; Password = <PASSWORD> UserName =admin PassWord = MesInterface = http://127.0.0.1:7005/ECSWebService/REST/GetMaterialCode/ MesDebug = {"MaterialCode":"CDX6081212R3204","Message":"查询成功","SerialNumber":"1YHP000002A4402","Type":"S"} AddWindowShow =Select [Request] *序列号 SerialNum = *物料编号 WuLiaoBianHao =222 *型号 ModelNum=222 *程序号 Index =2 [Response] SerialNum = WuLiaoBianHao =222 ModelNum=222 Index =2 <file_sep>using Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Script.Serialization; using Newtonsoft.Json; using System.Diagnostics; namespace MesToPlc.Models { public enum RequestResult { Success, Fail } public class MesLoad { public JavaScriptSerializer js = new JavaScriptSerializer(); public MesLoadResult bdata = new MesLoadResult(); IniHelper ini = new IniHelper(System.AppDomain.CurrentDomain.BaseDirectory + @"\Set.ini"); public RequestResult GetData(out MesLoadResult mesLoadResult,string url) { mesLoadResult = null; try { string jsonData = Http.HttpGet(url); //string jsonData = ini.ReadIni("Config", "MesDebug"); var data1 = JsonConvert.DeserializeObject<MesLoadResult>(jsonData); mesLoadResult = data1; if (mesLoadResult == null) { return RequestResult.Fail; } return RequestResult.Success; } catch { return RequestResult.Fail; } } } public class MesLoadResult { //{"MaterialCode":"CDX6081212R3204","Message":"查询成功","SerialNumber":"1YHP000002A4402","Type":"S"} public string MaterialCode { get; set; } public string Message { get; set; } public string SerialNumber { get; set; } public string Type { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using WpfServers; using MesToPlc.Models; using System.Collections.ObjectModel; using System.Data; using Services.DataBase; using System.Diagnostics; using Services; namespace MesToPlc { public delegate void DataBack(ChengXuHaoModel chengXuHaoModel); /// <summary> /// AddChengXuHao.xaml 的交互逻辑 /// </summary> public partial class AddChengXuHao : Window { IniHelper ini = new IniHelper(System.AppDomain.CurrentDomain.BaseDirectory + @"\Set.ini"); public event DataBack DataBackEvent; public PagingModel<ChengXuHaoModel> PagingModel; public ObservableCollection<ChengXuHaoModel> ChengXuHaoModels = new ObservableCollection<ChengXuHaoModel>(); public ObservableCollection<ChengXuHaoModel> ChengXuHaoModelsBranch = new ObservableCollection<ChengXuHaoModel>(); //SqlHelper sql = new SqlHelper(); AccessHelper sql = new AccessHelper(); ChengXuHaoModel SelectModel = new ChengXuHaoModel(); public AddChengXuHao() { InitializeComponent(); this.Loaded += AddChengXuHao_Loaded; } private void AddChengXuHao_Loaded(object sender, RoutedEventArgs e) { IniChengXuHaoModels(); PagingModel = new PagingModel<ChengXuHaoModel>(ChengXuHaoModels, 30); PagingModel.GetPageData(JumpOperation.GoHome); //绑定 this.txtCurrentPage.SetBinding(TextBlock.TextProperty, new Binding("CurrentIndex") { Source = PagingModel, Mode = BindingMode.TwoWay }); this.txtTotalPage.SetBinding(TextBlock.TextProperty, new Binding("PageCount") { Source = PagingModel, Mode = BindingMode.TwoWay }); this.txtTargetPage.SetBinding(TextBox.TextProperty, new Binding("JumpIndex") { Source = PagingModel, Mode = BindingMode.TwoWay }); this.Record.SetBinding(DataGrid.ItemsSourceProperty, new Binding("ShowDataSource") { Source = PagingModel, Mode = BindingMode.TwoWay }); if (ini.ReadIni("Config", "AddWindowShow") == WindowShowState.ShowState.Select.ToString()) { this.Title = "选择型号与程序号"; this.btnSure.Visibility = Visibility.Visible; this.btnAdd.Visibility = Visibility.Collapsed; this.btnDelete.Visibility = Visibility.Collapsed; this.btnChange.Visibility = Visibility.Collapsed; this.btnSearch.Visibility = Visibility.Collapsed; this.btnRefresh.Visibility = Visibility.Collapsed; } } private void IniChengXuHaoModels() { List<ChengXuHaoModel> chengXuHaoModels = sql.GetDataTable<ChengXuHaoModel>("select * from ChengXuHao"); if (chengXuHaoModels == null) return; ChengXuHaoModels.Clear(); chengXuHaoModels.ForEach(p => ChengXuHaoModels.Add(p)); } private void btnAdd_Click(object sender, RoutedEventArgs e) { List<ChengXuHaoModel> chengXuHaoModels = sql.GetDataTable<ChengXuHaoModel>("select * from ChengXuHao"); foreach (var item in ChengXuHaoModels) { if (item.XingHao == this.txtXingHao.Text) { MessageBox.Show("型号已存在"); return; } if(item.ChengXuHao == this.txtChengXuHao.Text) { MessageBox.Show("程序号已存在"); return; } } string commandtext = string.Format("insert into ChengXuHao (ChengXuHao,XingHao,AddTime,WuLiaoBianHao) values ('{0}','{1}','{2}','{3}')", this.txtChengXuHao.Text, this.txtXingHao.Text, DateTime.Now.ToString(),this.txtWuLiaoBianHao.Text); if (sql.Execute(commandtext)) { MessageBox.Show("添加成功"); } else { MessageBox.Show("添加失败"); } RefreshRecords(); } private void btnChange_Click(object sender, RoutedEventArgs e) { if (this.txtXingHao.Text != "" || this.txtChengXuHao.Text != "" || this.txtWuLiaoBianHao.Text != "") { string commandtext = string.Format("update ChengXuHao set ChengXuHao='{0}',XingHao='{1}',AddTime='{2}' where XingHao='{3}'", this.txtChengXuHao.Text, this.txtXingHao.Text, DateTime.Now.ToString(),SelectModel.XingHao); if (sql.Execute(commandtext)) { MessageBox.Show("修改成功"); } else { MessageBox.Show("修改失败"); } RefreshRecords(); } } private void PageOperationClick(object sender, RoutedEventArgs e) { Button btn = (Button)e.Source; switch (btn.Name) { case "btnHomePage": PagingModel.GetPageData(JumpOperation.GoHome); break; case "btnPreviousPage": PagingModel.GetPageData(JumpOperation.GoPrevious); break; case "btnNextPage": PagingModel.GetPageData(JumpOperation.GoNext); break; case "btnEndPage": PagingModel.GetPageData(JumpOperation.GoEnd); break; case "btnJmpPage": PagingModel.JumpPageData(Convert.ToInt32(txtTargetPage.Text)); break; } } private void ShowData(string displayName) { List<ChengXuHaoModel> lst = ChengXuHaoModels.Where(m => m.XingHao == displayName).ToList(); if(lst == null) { MessageBox.Show("未找到该型号"); return; } ListToObservable(lst, ChengXuHaoModelsBranch); PagingModel.DataSource = ChengXuHaoModelsBranch; //记录 PagingModel.Refresh(); } private void btnSearch_Click(object sender, RoutedEventArgs e) { if(this.txtXingHao.Text == "") { MessageBox.Show("型号不能为空"); return; } ShowData(this.txtXingHao.Text); } private void ListToObservable(List<ChengXuHaoModel> lst, ObservableCollection<ChengXuHaoModel> obc) { obc.Clear(); lst.ForEach(p => obc.Add(p)); } private void btnRefresh_Click(object sender, RoutedEventArgs e) { IniChengXuHaoModels(); PagingModel.DataSource = ChengXuHaoModels; PagingModel.GetPageData(JumpOperation.GoHome); PagingModel.Refresh(); } private void RefreshRecords() { IniChengXuHaoModels(); PagingModel.DataSource = ChengXuHaoModels; PagingModel.GetPageData(JumpOperation.GoHome); PagingModel.Refresh(); } private void Record_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.Record.SelectedItem != null) { var a = this.Record.SelectedItem; SelectModel = a as ChengXuHaoModel; this.txtXingHao.Text = SelectModel.XingHao; this.txtChengXuHao.Text = SelectModel.ChengXuHao; this.txtWuLiaoBianHao.Text = SelectModel.WuLiaoBianHao; } } private void btnDelete_Click(object sender, RoutedEventArgs e) { if (this.Record.SelectedItem != null) { var a = this.Record.SelectedItem; SelectModel = a as ChengXuHaoModel; string commandtext = string.Format("delete from ChengXuHao where XingHao='{0}'",SelectModel.XingHao); if (MessageBox.Show("是否删除?", "提示", MessageBoxButton.OKCancel)== MessageBoxResult.OK) { sql.Execute(commandtext); } IniChengXuHaoModels(); PagingModel.DataSource = ChengXuHaoModels; PagingModel.GetPageData(JumpOperation.GoHome); PagingModel.Refresh(); this.txtXingHao.Clear(); this.txtChengXuHao.Clear(); RefreshRecords(); } } private void btnSure_Click(object sender, RoutedEventArgs e) { if (this.Record.SelectedItem != null) { var a = this.Record.SelectedItem; SelectModel = a as ChengXuHaoModel; DataBackEvent(SelectModel); this.Close(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MesToPlc.Models { public static class WindowShowState { public enum ShowState { Select, Add } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using WpfServers.Notification; namespace MesToPlc.Models { public class ChengXuHaoModel : NotificationObject { private string xingHao; private string chengXuHao; private string addTime; private string wuLiaoBianHao; public string XingHao { get { return xingHao; } set { xingHao = value; RaisePropertyChanged("XingHao"); } } public string ChengXuHao { get { return chengXuHao; } set { chengXuHao = value; RaisePropertyChanged("ChengXuHao"); } } public string AddTime { get { return addTime; } set { addTime = value; RaisePropertyChanged("AddTime"); } } public string WuLiaoBianHao { get { return wuLiaoBianHao; } set { wuLiaoBianHao = value; } } } }
31c1bcbea0033d859d810f9da39946eae90b820b
[ "C#", "INI" ]
6
C#
meilidao12/MesToPlc
61299585d52764ca85cebb363e61a23381283390
c8269440864dae65e42b060b5252e173f4883ef6
refs/heads/master
<file_sep>public class MyProgram { public static void main(String[] args) { // Variable to hold my name and age String myName = "Josemy"; int age = 26; System.out.println("Hello my name is " + myName + " and I am " + age + " years old"); } }
ec9ce93e4713d85c87fcd04f7922c9a5c7144665
[ "Java" ]
1
Java
josmyJJ/MathTwo
b277c7b9f643eb58eacd82174d9d2d5dbd040019
bd2a9d1cd1a952ed8deba398203970f35e704442
refs/heads/master
<file_sep><?php function h($value) { return htmlspecialchars($value,ENT_QUOTES); } // function arr2csv($fields) { // $fp = fopen('php://temp', 'r+b'); // foreach($fields as $field) { // fputcsv($fp, $field); // } // rewind($fp); // $tmp = str_replace(PHP_EOL, "\r\n", stream_get_contents($fp)); // return mb_convert_encoding($tmp, 'SJIS-win', 'UTF-8'); // } ?> <file_sep>-- phpMyAdmin SQL Dump -- version 4.2.11 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 2018 年 1 朁E27 日 05:23 -- サーバのバージョン: 5.6.21 -- PHP Version: 5.6.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Database: `gs_db` -- -- -------------------------------------------------------- -- -- テーブルの構造 `gs_an_table` -- CREATE TABLE IF NOT EXISTS `gs_an_table` ( `id` int(12) NOT NULL, `employ_id` int(6) NOT NULL DEFAULT '100000', `employ_name` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `employ_yomi` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL, `employ_birthday` date NOT NULL, `employ_hiredate` date NOT NULL, `employ_Hwage` int(5) NOT NULL, `employ_memo` text COLLATE utf8_unicode_ci, `employ_updatetime` datetime NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- テーブルのデータのダンプ `gs_an_table` -- INSERT INTO `gs_an_table` (`id`, `employ_id`, `employ_name`, `employ_yomi`, `employ_birthday`, `employ_hiredate`, `employ_Hwage`, `employ_memo`, `employ_updatetime`) VALUES (1, 100001, '<NAME>', 'さとう しょうた', '1976-02-06', '2014-01-01', 1400, '直接入力', '2018-01-25 00:00:00'), (2, 100002, '山田 電機', 'ヤマダ デンキ', '1980-01-01', '2014-02-01', 1200, 'まだまだ安いんだ', '2018-01-25 22:37:24'); -- -- Indexes for dumped tables -- -- -- Indexes for table `gs_an_table` -- ALTER TABLE `gs_an_table` ADD PRIMARY KEY (`id`,`employ_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `gs_an_table` -- ALTER TABLE `gs_an_table` MODIFY `id` int(12) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3; /*!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 */; <file_sep><!DOCTYPE html> <html lang="ja"> <?php include"head.html"; include"functions.php"; // 入力チェック if( !isset($_POST["employ_id"]) || $_POST["employ_id"]=="" || !isset($_POST["employ_name"]) || $_POST["employ_name"]=="" || !isset($_POST["employ_yomi"]) || $_POST["employ_yomi"]=="" || !isset($_POST["employ_birthday"]) || $_POST["employ_birthday"]=="" || !isset($_POST["employ_hiredate"]) || $_POST["employ_hiredate"]=="" || !isset($_POST["employ_Hwage"]) || $_POST["employ_Hwage"]=="" || !isset($_POST["employ_memo"]) || $_POST["employ_memo"]=="" ){ exit("ParamError"); } $employ_id = $_POST["employ_id"]; $employ_name = $_POST["employ_name"]; $employ_yomi = $_POST["employ_yomi"]; $employ_birthday = $_POST["employ_birthday"]; $employ_hiredate = $_POST["employ_hiredate"]; $employ_Hwage = $_POST["employ_Hwage"]; $employ_memo = $_POST["employ_memo"]; try { $pdo = new PDO('mysql:dbname=gs_db;charset=utf8;host=localhost','root',''); } catch(PDOException $e){ exit('データベースに接続できませんでした'.$e->getMessage()); } $sql = "INSERT INTO gs_an_table(id, employ_id, employ_name, employ_yomi, employ_birthday, employ_hiredate, employ_Hwage, employ_memo, employ_updatetime ) VALUES(NULL, :a1, :a2, :a3, :a4, :a5, :a6, :a7, sysdate())"; $stmt = $pdo->prepare($sql); $stmt->bindValue(":a1", $employ_id, PDO::PARAM_INT); $stmt->bindValue(":a2", $employ_name, PDO::PARAM_STR); $stmt->bindValue(":a3", $employ_yomi, PDO::PARAM_STR); $stmt->bindValue(":a4", $employ_birthday, PDO::PARAM_INT); $stmt->bindValue(":a5", $employ_hiredate, PDO::PARAM_INT); $stmt->bindValue(":a6", $employ_Hwage, PDO::PARAM_INT); $stmt->bindValue(":a7", $employ_memo, PDO::PARAM_STR); $status = $stmt->execute(); if($status==false){ $error = $stmt->errorInfo(); exit("ErrorQuery".$error[2]); }else{ header("Location: employ_input.php"); exit(); } // $str = $employ_id.",".$employ_name.",".$employ_yomi.",".$employ_birthday.",".$employ_entryday.",".$employ_Hwage; // $str_SJIS = mb_convert_encoding($str, 'SJIS-win','UTF-8'); // $file = fopen("employ/employ.csv","a"); // flock($file, LOCK_EX); // fwrite($file,$str_SJIS."\n"); // flock($file, LOCK_UN); // fclose($file); ?> <body> <header> <h1>新規登録</h1> <h2>登録しました</h2> </header> <table> <tr> <td>社員番号</td> <td><?=h($employ_id)?></td> </tr> <tr> <td>氏名</td> <td><?=h($employ_name)?></td> </tr> <tr> <td>ふりがな</td> <td><?=h($employ_yomi)?></td> </tr> <tr> <td>生年月日</td> <td><?=h($employ_birthday)?></td> </tr> <tr> <td>入社日</td> <td><?=h($employ_entryday)?></td> </tr> <tr> <td>時給</td> <td><?=h($employ_Hwage)?></td> </tr> </table> <a href="employ_input.php"><button>続けて登録</button></a> <button>閉じる</button> </body> </html>
dd22a9010757415aa947da99c3a1a5a834654af3
[ "SQL", "PHP" ]
3
PHP
gagaga81/07_43_hangaisho
e19e7dad5e81fa1bed3b2a94c31ae880709ca257
ebc2425fe31f7b2c69336109b6dc7f9dfe5a05a5
refs/heads/master
<file_sep>package ResponseStatusCode; import ServerRequest.Request; import ServerResponse.*; import java.io.IOException; public class Response401Status extends Response { public Response401Status(Request request) throws IOException, InterruptedException { super(request); } @Override public void processRequest(Request request) { responseValues.put("STATUS_CODE", "401"); responseValues.put("REASON_PHRASE", "Unauthorized"); responseHeaders.put("WWW-Authenticate", "Basic"); } } <file_sep>package ResponseStatusCode; import ServerConfig.Configuration; import ServerRequest.Request; import ServerResponse.ResourceOperation; import ServerResponse.Response; import java.io.IOException; public class Response404Status extends Response { public Response404Status(Request request) throws IOException, InterruptedException { super(request); } @Override public void processRequest(Request request) throws IOException { responseValues.put("STATUS_CODE", "404"); responseValues.put("REASON_PHRASE", "Not Found"); responseHeaders.put("CONTENT_TYPE", Configuration.getMime("html")); String dir = System.getProperty("user.dir"); responseBody = ResourceOperation.readContents(dir + "/PrebuiltWebPages/404Error.html"); responseHeaders.put("Content-Length", Integer.toString(responseBody.size())); } } <file_sep>package ServerResponse; import java.io.*; import java.util.*; import java.text.*; public class ResourceOperation { public static ArrayList<Byte> readContents(String path) throws IOException { ArrayList<Byte> body = new ArrayList<>(); FileInputStream fin = new FileInputStream(path); int i = 0; while ((i = fin.read()) != -1) { body.add((byte) i); } fin.close(); return body; } public static void createFile(String path, byte[] contents) throws IOException { File f = new File(path); if(f.createNewFile()) { FileWriter myWriter = new FileWriter(path); for(byte element : contents) { myWriter.write(element); } myWriter.close(); } else { deleteFile(path); createFile(path, contents); } } public static void deleteFile(String path) { File f = new File(path); f.delete(); } public static String formatDate(Date dateToModify) { String formattedDate = new SimpleDateFormat("EE, dd MMM yyyy kk:mm:ss z").format(dateToModify); return formattedDate; } public static String lastModified(String path) { File f = new File(path); Date lastModifiedDate = new Date(f.lastModified()); return formatDate(lastModifiedDate); } } <file_sep>package ServerConfig; import ServerUtils.ServerHelper; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.*; import java.util.*; public class Configuration { private static final ServerConfiguration serverConfig = new ServerConfiguration(); private static final ServerMimeMap mimeMap = new ServerMimeMap(new File(System.getProperty("user.dir") + "/conf/mime.types")); static { try { String dir = System.getProperty("user.dir"); serverConfig.createSettingsFromFile(Paths.get(dir + "/conf/httpd.conf")); } catch(IOException e) { ServerHelper.isServerError = true; e.printStackTrace(); } } public static String getMime(String ext) { return mimeMap.getMime(ext); } public static String getServerRoot() { return serverConfig.getServerRoot(); } public static String getDocumentRoot() { return serverConfig.getDocumentRoot(); } public static String getDirectoryIndex() { return serverConfig.getDirectoryIndex(); } public static String getAccessFile() { return serverConfig.getAccessFile(); } public static String getPort() { return serverConfig.getPort(); } public static String getLogFilePath() { return serverConfig.getLogFilePath(); } public static String getPathForAlias(String alias) { return serverConfig.getPathForAlias(alias); } public static String getPathForScriptAlias(String scriptAlias) { return serverConfig.getPathForScriptAlias(scriptAlias); } public static HashMap<String, String> getSettings() { return serverConfig.getSettings(); } public static HashMap<String, String> getScriptAlias() { return serverConfig.getScriptAlias(); } public static HashMap<String, String> getAlias() { return serverConfig.getAlias(); } private static class ServerConfiguration { private final HashMap<String, String> settings; private final HashMap<String, String> alias; private final HashMap<String, String> scriptAlias; ServerConfiguration() { settings = new HashMap<>(); settings.put("DirectoryIndex", "index.html"); settings.put("Listen", "8080"); settings.put("AccessFile", ".htaccess"); alias = new HashMap<>(); scriptAlias = new HashMap<>(); } String getAccessFile() { return settings.get("AccessFile"); } String getDirectoryIndex() { return settings.get("DirectoryIndex"); } String getServerRoot() { return settings.get("ServerRoot"); } String getDocumentRoot() { return settings.get("DocumentRoot"); } String getPort() { return settings.get("Listen"); } String getLogFilePath() { return settings.get("LogFile"); } HashMap<String, String> getSettings() { return settings; } HashMap<String, String> getScriptAlias() { return scriptAlias; } HashMap<String, String> getAlias() { return alias; } String getPathForAlias(String alias) { return getAlias().get(alias); } String getPathForScriptAlias(String scriptAlias) { return getScriptAlias().get(scriptAlias); } void createSettingsFromFile(Path configPath) throws IOException { List<String> fileLines = Files.readAllLines(configPath, Charset.defaultCharset()); for(String line : fileLines) { ConfigEntry setting = new ConfigParser(line).getSetting(); setting.storeEntry(); } } } private static class ServerMimeMap { private HashMap<String, String> mapExt; ServerMimeMap(File mimeFile) { try { createMapping(mimeFile); } catch(IOException e) { ServerHelper.isServerError = true; e.printStackTrace(); } } String getMime(String ext){ return mapExt.get(ext); } private void createMapping(File mimeFile) throws IOException { HashMap<String,String> extMap = new HashMap<>(); Scanner fileReader = new Scanner(mimeFile); while(fileReader.hasNext()) { String str = fileReader.nextLine(); if (str.startsWith("#") || str.startsWith(" ")) { continue; } String mimeType; String[] splitArr = str.split("\\s+"); mimeType = splitArr[0]; for(int i = 1; i < splitArr.length;i++){ extMap.put(splitArr[i],mimeType); } } this.mapExt = extMap; } } } <file_sep>package ServerResponse; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.ArrayList; import ServerRequest.Request; public abstract class Response { public HashMap<String, String> responseValues; public HashMap<String, String> responseHeaders; public ArrayList<Byte> responseBody; protected Response() { } public String getHttpVersion() { return responseValues.get("HTTP_PROTOCOL"); } public String getStatusCode() { return responseValues.get("STATUS_CODE"); } public String getReasonPhrase() { return responseValues.get("REASON_PHRASE"); } public HashMap<String, String> getResponseHeaders() { return responseHeaders; } public ArrayList getResponseBody() { return responseBody; } public Response(Request request) throws IOException, InterruptedException { responseValues = new HashMap<>(); responseHeaders = new HashMap<>(); responseValues.put("HTTP_PROTOCOL", request.getHttpVersion()); responseHeaders.put("Server", "KnoxMoServer"); responseHeaders.put("Date", ResourceOperation.formatDate(new Date())); processRequest(request); } public abstract void processRequest(Request request) throws IOException, InterruptedException; } <file_sep>package ServerUtils; import ServerConfig.Configuration; import ServerRequest.Request; import ServerResponse.ResourceOperation; import ServerResponse.Response; import java.io.*; import java.io.File; import java.net.Inet4Address; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; public class Logger { private static String user = "-"; public static void outputLog(Request request, Response response) throws IOException { String ip = Inet4Address.getLocalHost().toString(); String userId = user; String formattedDate = new SimpleDateFormat("dd/MMM/yyyy:kk:mm:ss Z").format(new Date()); String size = "-"; if(response.getResponseHeaders().containsKey("CONTENT-LENGTH")) { size = response.getResponseHeaders().get("CONTENT-LENGTH"); } String fullLog = ip + " - " + userId + " [" + formattedDate + "] \"" + request.getHttpMethod() + " " + request.getURI() + " " + request.getHttpVersion() + "\" " + response.getStatusCode() + " " + size + "\n"; System.out.print(fullLog); outputToLogFile(fullLog); } private static void outputToLogFile(String logOutput) throws IOException{ File f = new File(Configuration.getLogFilePath()); if(!f.exists()) { ResourceOperation.createFile(Configuration.getLogFilePath(), logOutput.getBytes()); } else { BufferedWriter out = new BufferedWriter( new FileWriter(Configuration.getLogFilePath(), true)); out.write(logOutput); out.close(); } } public static void setUser(String userId) { user = userId; } } <file_sep>package ResponseStatusCode; import ServerResponse.*; import ServerRequest.*; import CGI.*; import java.io.IOException; public class ResponseCGI200Status extends Response { public ResponseCGI200Status(Request request) throws IOException, InterruptedException { super(request); } @Override public void processRequest(Request request) throws IOException, InterruptedException { CGI programExecutor = new CGI(request); responseHeaders = programExecutor.getHeaders(); responseValues.put("STATUS_CODE", "200"); responseValues.put("REASON_PHRASE", "OK"); responseBody = programExecutor.getBody(); } } <file_sep>package ResponseStatusCode; import ServerRequest.Request; import ServerRequest.UriHandler; import ServerResponse.ResourceOperation; import ServerResponse.Response; import java.io.IOException; public class Response304Status extends Response { public Response304Status(Request request) throws IOException, InterruptedException { super(request); } @Override public void processRequest(Request request) { responseValues.put("STATUS_CODE", "304"); responseValues.put("REASON_PHRASE", "Not Modified"); responseHeaders.put("LAST_MODIFIED", ResourceOperation.lastModified(UriHandler.resolveURI(request.getURI()))); } } <file_sep>package ServerConfig; import ServerUtils.Helpers; class ConfigParser { private final ConfigEntry setting; ConfigParser(String line) { String[] splitLine = line.split("\""); String value = ""; if(splitLine.length > 1) { value = Helpers.removeOuterQuotes(splitLine[1]); } String[] keywords = splitLine[0].split("\\s+"); setting = createConfigEntry(keywords, value); } private ConfigEntry createConfigEntry(String[] keywords, String value) { ConfigEntry entry; if(keywords[0].equals("ScriptAlias")) { entry = new ScriptAliasEntry(keywords[1], value); } else if(keywords[0].equals("Alias")) { entry = new AliasEntry(keywords[1], value); } else if(keywords[0].startsWith("#")) { entry = new ServerConfigEntry("", ""); } else if(value.equals("")) { entry = new ServerConfigEntry(keywords[0], keywords[1]); } else { entry = new ServerConfigEntry(keywords[0], value); } return entry; } public ConfigEntry getSetting() { return setting; } } <file_sep>package ServerUtils; import ServerConfig.HtaccessHandler; import ServerConfig.HtpasswdHandler; import ServerRequest.Request; import ServerRequest.UriHandler; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.NoSuchAlgorithmException; public class AuthorizationUtils { public static boolean isRequestAuthenticated(Request request) throws IOException, NoSuchAlgorithmException { String content = readHtAccessFileContent(); HtaccessHandler htaccessHandler = new HtaccessHandler(content); if (!isFileAtPathProtected(UriHandler.resolveURI(request.getURI()))) { return true; } else { if (htaccessHandler.require.equals("valid-user")) { if (!request.getHeaders().containsKey("AUTHORIZATION")) { return false; } else { return isAuthorizationHeaderMatching(request); } } else { return true; } } } private static boolean isAuthorizationHeaderMatching(Request request) throws IOException, NoSuchAlgorithmException { String[] encryptedStringArray = request.getHeaders().get("AUTHORIZATION").split("\\s+"); String encryptedString = encryptedStringArray[encryptedStringArray.length-1]; if (HtpasswdHandler.isAuthorized(encryptedString)) { if (HtpasswdHandler.isAuthenticated(encryptedString)) { return true; } else { return false; } } else { return false; } } private static String readHtAccessFileContent() throws IOException { String dir = System.getProperty("user.dir"); File htaccessFile = new File(dir + "/htFiles/.htaccess"); FileInputStream htaccess = new FileInputStream(htaccessFile); byte[] data = new byte[(int) htaccessFile.length()]; htaccess.read(data); htaccess.close(); String content = ""; for(byte dataElement : data) { content = content + (char) dataElement; } return content; } private static boolean isFileAtPathProtected(String path){ String htaccessPath = path.subSequence(0, path.lastIndexOf("/")).toString(); File f = new File(htaccessPath + "/.htaccess"); return f.exists(); } } <file_sep>package ResponseStatusCode; import ServerRequest.BadRequest; import ServerResponse.Response; import ServerRequest.Request; import ServerRequest.UriHandler; import ServerUtils.AuthorizationUtils; import ServerUtils.ServerHelper; import java.io.*; import java.security.NoSuchAlgorithmException; public class ResponseStatusFactory { public static Response createResponse(Request request) throws IOException,InterruptedException, NoSuchAlgorithmException { if(ServerHelper.isServerError) { ServerHelper.isServerError = false; return new Response500Status(request); } else if(BadRequest.isBadRequest) { BadRequest.isBadRequest = false; return new Response400Status(request); } else if (!fileExists(UriHandler.resolveURI(request.getURI())) && !request.getHttpMethod().equals("PUT")) { return new Response404Status(request); } else if(AuthorizationUtils.isRequestAuthenticated(request)) { if (request.getHttpMethod().equals("PUT")) { return new Response201Status(request); } else if (request.getHttpMethod().equals("HEAD")) { return new Response304Status(request); } else if (request.getHttpMethod().equals("DELETE")) { return new Response204Status(request); } else if (UriHandler.isResourceScript(request.getURI())) { return new ResponseCGI200Status(request); } else { return new Response200Status(request); } } else if (request.getHeaders().containsKey("AUTHORIZATION")) { return new Response403Status(request); } else { return new Response401Status(request); } } private static boolean fileExists(String filePath) { File f = new File(filePath); return f.exists(); } } <file_sep>package ServerConfig; class AliasEntry extends ConfigEntry { AliasEntry(String key, String value) { this.keyword = key; this.value = value; this.configCategory = Configuration.getAlias(); } }
4175814d323ccfbd03db4cdf2548cf9d051ae529
[ "Java" ]
12
Java
MoFarah-42/WebServerProject
f4613e392db0effff6992e5469da81704c86a2d0
50c37ddf66e0e8501a554ddbc24d4efeb67de89a
refs/heads/main
<repo_name>DanielCruzAr/PF_Actividades_Integradoras<file_sep>/Act 5.3/act5.3_paralelo.cpp /* #################################### # Actividad Integradora 5.3 # # Resaltador de sintaxis paralelo # # Version 1 # # # # <NAME> A01701370 # # <NAME> A01706155 # #################################### */ //compilacion en linux: g++ -pthread act5.3_paralelo.cpp //compilacion en otros sistemas: g++ -lpthread act5.3_paralelo.cpp #include <iostream> #include <string> #include <sstream> #include <stack> #include <fstream> #include <vector> #include <chrono> #include <thread> using namespace std; #define THREADS 8 class DFA { private: //string token; vector<string> v; int count; //Variable para saber cuantos elementos hay en los vectores int index; //variable auxiliar en caso de que se requieran saltar índices en el ciclo for de lexerAritmetico public: DFA(vector<string> &vec) {v=vec; count = 0; index=0;} //void lexerAritmetico(string &, int, int); void processEntry(string &, int, int); bool rw(string, string, int); bool str(string, int); string var(string, int); bool isFloat(string, int); string nfloat(string, int); string entero(string, int); }; /* void DFA::lexerAritmetico(string &token, int start, int end){ string s; for (int nline = start; nline < end; nline++){ s = v[nline]; proccesEntry(s, token); token += "<br>"; } } */ //funcion para las palabras reservadas bool DFA::rw(string s, string rws, int i){ stringstream aux; int acum = -1; for(int j = i; j < rws.size()+i; j++){ aux << s[j]; acum++; } if(aux.str() == rws){ index += acum; return true; } else return false; } //funcion para los caracteres que forman un string bool DFA::str(string s, int i){ if(s[i] == '"'){ index++; for(int j = i+1; j < s.size(); j++){ index ++; if(s[j] == '"'){ return true; } } } else if(s[i] == '\''){ index++; for(int j = i+1; j < s.size(); j++){ index ++; if(s[j] == '\''){ return true; } } } else if(s[i] == '<'){ index++; for(int j = i+1; j < s.size(); j++){ index ++; if(s[j] == '>'){ return true; } } } return false; } //funcion que une todos los caracteres que forman una variable string DFA::var(string s, int i) { stringstream aux; for(int j = i; j < s.size(); j++){ if(isalpha(s[j]) || s[j] == '_' || isdigit(s[j])){ aux << s[j]; index++; } else { break; } } return aux.str(); } //funcion que verifica si un numero tiene punto flotante bool DFA::isFloat(string s, int i){ for(int j = i; j < s.size(); j++){ if(s[j] == '.' || s[j] == 'E') return true; } return false; } //funcion que une todos los caracteres que forman un numero flotante string DFA::nfloat(string s, int i) { stringstream aux; for(int j = i; j < s.size(); j++){ if(isdigit(s[j]) || s[j] == '.' || s[j] == 'E' || (s[j] == '-' && s[j-1] != (isdigit(s[j-1]) || ' '))){ aux << s[j]; index ++; } else { break; } } return aux.str(); } //funcion que une todos los caracteres que forman un numero entero string DFA::entero(string s, int i) { stringstream aux; for(int j = i; j < s.size(); j++){ if(isdigit(s[j]) || (s[j] == '-' && s[j-1] != (isdigit(s[j-1]) || ' '))) { aux << s[j]; index++; } else{ break; } } return aux.str(); } //función que recibe un string y clasifica cada caracter void DFA::processEntry(string &token, int start, int end){ char c; string s; for (int nline = start; nline < end; nline++){ s = v[nline]; for (int i = 0; i < s.size(); i++){ c = s[i]; stringstream aux; index = 0; //Comentarios if(c == '/' && s[i+1] == '/') { for(int j = i; j < s.size(); j++) aux << s[j]; token += "<span class='comment'>" + aux.str() + "</span>"; count++; break; } //Palabras reservadas else if(isalpha(c) && rw(s, "int", i) == true){ token += "<span class='reserved-word'> int </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "char", i) == true){ token += "<span class='reserved-word'> char </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "float", i) == true){ token += "<span class='reserved-word'> float </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "string", i) == true){ token += "<span class='reserved-word'> string </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "bool", i) == true){ token += "<span class='reserved-word'> bool </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "auto", i) == true){ token += "<span class='reserved-word'> auto </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "long", i) == true){ token += "<span class='reserved-word'> long </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "void", i) == true){ token += "<span class='reserved-word'> void </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "if", i) == true){ token += "<span class='reserved-word'> if </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "else", i) == true){ token += "<span class='reserved-word'> else </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "while", i) == true){ token += "<span class='reserved-word'> while </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "for", i) == true){ token += "<span class='reserved-word'> for </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "var", i) == true){ token += "<span class='reserved-word'> var </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "let", i) == true){ token += "<span class='reserved-word'> let </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "const", i) == true){ token += "<span class='reserved-word'> const </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "include", i) == true){ token += "<span class='reserved-word'> include </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "std", i) == true){ token += "<span class='reserved-word'> std </span>"; count++; i += index; } else if(isalpha(c) && rw(s, "return", i) == true){ token += "<span class='reserved-word'> return </span>"; count++; i += index; } //Variables else if(isalpha(c)) { aux << c; aux << var(s, i+1); token += "<span class='var'>" + aux.str() + "</span>"; count++; i += index; } //Enteros y flotantes else if(isdigit(c) || (c == '-' && isdigit(s[i+1]) && s[i-1] == ('('))) { aux << c; switch(isFloat(s, i+1)){ case true: aux << nfloat(s, i+1); token += "<span class='float'>" + aux.str() + "</span>"; count++; i += index; break; case false: aux << nfloat(s, i+1); token += "<span class='int'>" + aux.str() + "</span>"; count++; i += index; break; } } //Strings else if(str(s, i) == true) { aux << c; for(int j = i+1; j < s.size(); j++){ aux << s[j]; if(s[j] == '"' || s[j] == '\'' || s[j] == '>') break; } token += "<span class='string'>" + aux.str() + "</span>"; count ++; i += index; } //#include else if(c == '#') { for(int j = i; j < s.size(); j++){ aux << s[j]; index++; if(s[j] == ' ') break; } token += "<span class='include'>" + aux.str() + "</span>"; count ++; i += index; } //Operadores else if(c == '=') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == ',') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '+') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '-') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '*') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '/') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '^') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '(') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == ')') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '{') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '}') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '[') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == ']') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == ';') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == ':') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '<') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '>') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '|') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '%') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '&') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '?') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '!') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } else if(c == '~') { aux << c; token += "<span class='operador'>" + aux.str() + "</span>"; count++; } //Tabs else if(c == '\t') { token += "&nbsp;&nbsp;&nbsp;&nbsp;"; } //Espacios else if(c == ' ') { token += "&nbsp;"; } } token += "<br>"; } } //funcion para escribir el archivo .html void write(string token) { string head = "<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'><meta name='viewport' content='width=device-width, initial-scale=1.0'><title>Actividad Integradora 5.3 Resaltador de sintaxis paralelo</title><link rel='stylesheet' href='css/style.css'></head><body>"; ofstream escribe("prueba.html"); if(escribe.is_open()){ escribe << head; escribe << token; escribe << "</body></html>"; escribe.close(); } else{ cout << "Unable to open file"; } } //funcion que recibe el nombre de un archivo y lo lee si lo encuentra vector<string> readf(string archivo){ string line; vector<string> v; ifstream lee(archivo); if (lee.is_open()){ while (getline(lee, line, '\n')){ v.push_back(line); } lee.close(); } else{ cout << "Unable to open file"; } return v; } int main(int argc, char* argv[]) { string file; cout << "Introduzca el nombre del archivo que desea cargar: "; getline(cin, file); cout << "\n"; //tiempo inicial auto startt = chrono::steady_clock::now(); string tokens[THREADS]; vector<string> vfile = readf(file); int block = vfile.size()/THREADS; vector<int> starts, ends; int start, end; DFA dfa(vfile); for (int i = 0; i < THREADS; i++){ start = i*block; end = (i == THREADS - 1)? vfile.size() : (i + 1) * block; starts.push_back(start); ends.push_back(end); } thread t1([&] { dfa.processEntry(tokens[0], starts[0], ends[0]) ; }); thread t2([&] { dfa.processEntry(tokens[1], starts[1], ends[1]) ; }); thread t3([&] { dfa.processEntry(tokens[2], starts[2], ends[2]) ; }); thread t4([&] { dfa.processEntry(tokens[3], starts[3], ends[3]) ; }); thread t5([&] { dfa.processEntry(tokens[4], starts[4], ends[4]) ; }); thread t6([&] { dfa.processEntry(tokens[5], starts[5], ends[5]) ; }); thread t7([&] { dfa.processEntry(tokens[6], starts[6], ends[6]) ; }); thread t8([&] { dfa.processEntry(tokens[7], starts[7], ends[7]) ; }); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); t6.join(); t7.join(); t8.join(); stringstream ftoken; for (string word: tokens) ftoken << word; //cout << ftoken.str() << endl; write(ftoken.str()); //tiempo final auto endt = chrono::steady_clock::now(); //tiempo total double tiempo = double (chrono::duration_cast <chrono::nanoseconds> (endt - startt).count()); cout << "Tiempo de ejecucion: " << tiempo/1e9 << "s" << endl; }<file_sep>/Act 5.3/README.md Tiempo de ejecución act5.3_noParalelo.cpp: 0.0249196s Tiempo de ejecución act5.3_paralelo.cpp: 0.0177455s Diferencia de tiempo: 0.0071741s Conclusión: El paralelo tuvo un menor tiempo de ejecución <file_sep>/README.md # Actividad Integradora 3.4 Resaltador de sintaxis <file_sep>/Act 3.4/prueba.cpp //Actividad 3.4 Resaltador de sintaxis //<NAME> A01701370 //Código de prueba realizado por <NAME> //Recuperado de https://github.com/Manchas2k4/tc2037/blob/main/project1/test.c #include <iostream> int main(int argc, char* argv[]) { string s = "Variable string"; int i = 0; for (i = 0; i < 10; i++) { printf("%i", i); } printf("\n"); return 0; std::cout << s << endl; }
1311ff87781801dcf7f4f5f2114c16c8c775eee6
[ "Markdown", "C++" ]
4
C++
DanielCruzAr/PF_Actividades_Integradoras
7715e4735f13ca70abd7e7eb213797c9f572a058
400679cf1af28c05c783461f0873002b0c5077ae
refs/heads/master
<file_sep># speech_api_compare Html5 Web Speech API × Microsoft Bing Speech API <file_sep>var bingClientTTS = new BingTTS.Client("46adbdd87c3e442d92bb33e7f5b5d317"); var speak_text = document.getElementById("speak_text"); var tts_select_one=document.getElementById("tool_one"); var speech = new webkitSpeechRecognition(); speech.lang = "ja"; document.getElementById("play_btn").addEventListener("click", function () { var answer_text_speak = speak_text.value; var index = tts_select_one.selectedIndex; var optionvalue = tts_select_one.options[index].value; if (optionvalue == "Microsoft-BingSpeech") { microsoft_speak(answer_text_speak); } else{ /* var su = new SpeechSynthesisUtterance(); su.lang = "ja"; su.text = answer_text_speak; speechSynthesis.speak(su); */ html_speak(answer_text_speak); } }); function microsoft_speak(answer_text_speak){ bingClientTTS.multipleXHR = document.getElementById("multipleXHRChk").checked; bingClientTTS.synthesize(answer_text_speak, BingTTS.SupportedLocales.jpJP_Female); } function html_speak(answer_text_speak) { var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()&;|{}【】‘;:”“'。,、?]{5,}"); for(i=0;i<100;i++) answer_text_speak = answer_text_speak.replace(pattern, '') var splitPatten = new RegExp("[、。??]") var res = answer_text_speak.split(splitPatten) for(var j = 0; j < res.length; j++){ if (navigator.userAgent.indexOf("Chrome") > -1){ responsiveVoice.speak( res[j], 'Japanese Female', { rate: 1.0 } ); } } }
adb9eb2714faa18f75bd0f517880128938696782
[ "Markdown", "JavaScript" ]
2
Markdown
youngspring1/speech_api_compare
b1af41928811f969875ef7400d24dd551464c691
496c77091b6ab7561ec8fb8c2621b4b4dad33212
refs/heads/master
<file_sep>var mongoose = require('mongoose'); var crypto = require('crypto'); var User = require('../models/Users'); module.exports = { signUp : function(req,res){ var data = req.body; console.log(data); User.findOne({email:data.email},function(err, users) { if (users) { res.json({ status:"unsuccess", message:"Email already exit." }); } else { var user = new User({ email : data.email, name : data.name, password : <PASSWORD>, role : data.role, token : [] }); user.save(function(err) { if (err) throw err; }); res.json({ status:"success", message:"user add successfully.", data: user }); } }); }, login : function(req,res) { User.findOne({email:req.body.email, password:req.body.password},function(err,user){ if(!user){ res.json({ status: 'unsuccess', message: 'User not found' }); }else{ var token = crypto.randomBytes(20).toString('hex') var now = Math.floor(new Date(new Date().getTime())) var expireDate = parseInt(now+(1*24*60*60*1000)) if(!user.token || !user.token.length){ var access_token = { 'access_token':token, expire:expireDate } user.token.push(access_token) //user.markModified('token'); user.save(function(err){ if (err) console.log(err); res.json({ status:"success", message:"user access_token generate.", data: {access_token:token} }); }); } else{ user.token.forEach(function(t,i){ if(t.expire < now){ user.token.splice(i,1); } }) var access_token = {'access_token':token,expire:expireDate} user.token.push(access_token) //user.markModified('token'); user.save(function(err){ if (err) { console.log(err); } res.json({ status:"success", message:"user access_token generate.", data: {access_token:token} }); }); } } }) } }<file_sep>var express = require('express'); var http = require('http'); var app = express(); const server = http.createServer(app); var mongoose = require('mongoose'); mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost:27017:/eventManager'); app.set('views','views'); app.set('view engine', 'ejs'); app.enable('trust proxy'); var api = require('./routes/api'); app.use('/',api); app.listen(3000, function () { console.log("App Started on PORT 3000"); });<file_sep>var mongoose = require('mongoose'); var Event = require('../models/Events'); module.exports ={ createEvent : function (req, res) { var data = req.body; console.log(data); var event = new Event({ title : data.title, location : data.location, organiser : req.user.name, description : data.description, ticket_price : data.ticket_price, comments : {}, date : new Date() }); event.save(function(err) { if (err) throw err; }); res.json({ status:"success", message:"event add successfully.", data: event }); }, getEventList : function(req, res){ var find={}; if(req.query.eventId){ find={ _id : req.query.eventId }; } Event.find(find,function(err, events){ if(err){ throw err; }else{ res.json({ status:"success", data: events }); } }); }, updateEvent : function(req, res){ var find={}; if(req.body.eventId){ find={ _id : req.body.eventId }; Event.findOne(find,function(err, event){ if(err){ throw err; }else if(event){ event.title = req.body.title; event.location = req.body.location; event.description = req.body.description; event.ticket_price = req.body.ticket_price; event.save(function(err){ if(err){ throw err; }else{ res.json({ status:"success", data: event }); } }); }else{ return res.json({ status:"fail", message:"invalid event id" }); } }); }else{ return res.json({ status:"fail", message:"event id required" }); } }, deleteEvent : function(req, res){ if(req.body.eventId){ find={ _id : req.body.eventId }; Event.deleteOne(find,function(err, event){ if(err){ throw err; }else if(event){ res.json({ status : "success", mesage : "successfully deleted" }); }else{ return res.json({ status:"fail", message:"invalid event id" }); } }); }else{ return res.json({ status:"fail", message:"event id required" }); } }, }<file_sep>var express = require('express'); var bodyParser = require('body-parser'); var router = express.Router(); var passport = require('passport'); BearerStrategy = require('passport-http-bearer').Strategy; var userController = require('../controllers/UserController'); var eventController = require('../controllers/EventController'); var User = require('../models/Users'); router.use(bodyParser.json()); router.use(bodyParser.urlencoded({ extended: true })); router.post('/login', userController.login); router.post('/signup',userController.signUp); router.get('/event',eventController.getEventList); router.post('/event', isLoggedIn, requireRole('organisers'), eventController.createEvent); router.put('/event',isLoggedIn,requireRole('organisers'), eventController.updateEvent); router.delete('/event',isLoggedIn,requireRole('organisers'),eventController.deleteEvent); passport.use(new BearerStrategy( function (token, done) { User.findOne({ 'token': { $elemMatch: { "access_token": token } } }, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } var matched_token = 0; user.token.forEach(function (u, i) { if (u.access_token == token) { matched_token = u; }; }) if (matched_token.expire < Math.floor(Date.now())) { return done(null, false, { message: 'Token expired' }); } return done(null, user, { scope: 'read' }); }); } )); function isLoggedIn(req, res, next) { return passport.authenticate('bearer', { session: false }, function (err, user, info) { if (err) { return next(err); } if (!user) { if (info) { return res.status(401).json({ status: "unsuccess", message: info }); } else { return res.status(401).json({ status: "unsuccess", message: 'Not authorized' }); } } req.user = user; return next(); })(req, res, next); } function requireRole(role) { return function (req, res, next) { if (req.user && req.user.role === role) { return next(); } else { return res.json({ "error" : "invalid_access", "message" : "You are not authorized" }); } } } module.exports = router;
237b098aa5ce901b6439d0e37650d6c7b4b917ad
[ "JavaScript" ]
4
JavaScript
dipanshu1994/Event-Management
79cf2b99878ae0ed7c077f639330c98c2e720695
35ec6d24ade3407178b8870ec974b17b359b0210
refs/heads/master
<file_sep>import React from 'react'; import Authenticate from './components/Login/Authenticate'; import Login from './components/Login/Login'; const App = () => { return ( <div className="App"> <Login /> </div> ); } export default Authenticate(App); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; const Tab = props => { console.log(props.tab) const Active = props.tab === props.selectedTab; return ( <div className={`tab ${Active ? 'active-tab' : ''}`} onClick={props.changeSelected} > {props.tab.toUpperCase()} </div> ); }; // Included PropTypes on your props. Tab.propTypes = { tab: PropTypes.string, }; export default Tab;<file_sep>1. What are PropTypes used for? PropTypes are what we use to export a number of validators to check the data that your recieving is valid and the type that you want. For example, in a piece of code, you have an input that you want a user to enter their birthday. Proptypes come in handy bc we can make sure that the user sees an error if they put the wrong type of data in. So the program does crash and burn bc someone put in the string month in stead of the 2 digit month. 2. What is a lifecycle event in React? The React Component life cycle is broken down into three phases birth, growth, and death. In the birth phase the component is being built from the ground up. Our data is being constructed and our render function is invoked displaying the information in the view. The grow state is when the component is updated in some way. For example we can use the setState method in this phase to change the components data. This will force a call to render. The death phase is when the component is removed from the screen. 3. What is a Higher Order Component? Higher order components are functions that receive a component as a parameter and returns new information. Like when working on our project we used a higher order component to conditionally render a component based on where or not a user was logged in. We performed this check by seeing what was loaded in local storage. Using that information we can decided to load either one component or another. We can also used shared functionality among components to help avoid repetition. 4. What are three different ways to style components in React? We can style components in react by using plain css imported from a css file. We can use the bootstrap library to add in custom styles. We can also install a package referred to as styled components. This will give us the ability to style our components in Javascript.
6dba200c3ed927c78140ade7777740b8e74b0f9a
[ "JavaScript", "Markdown" ]
3
JavaScript
meganfontenot/Sprint-Challenge-Lambda-Times-React
cd2ff3f7e181d99098b601022383a14d0f9a0fa6
d4b39ae4883a0323ce93ed322a64bef8490a28f2
refs/heads/master
<repo_name>Mbareck/Analyzing-the-Tweets-of-Alexandria-Ocasio-Cortez-VS-Ann-Coulter<file_sep>/README.md # Text Analytics Here, I compare the engagement of AOC vs Coulter on Twitter <file_sep>/The Code.R #Coulter Tweet Analysis #2 #March 4 2019 # Thanks to <NAME> for these ideas # Shout out to <NAME> for graphics material #Load 'er up, Bob! library(lubridate) library(ggplot2) library(dplyr) library(readr) library(tidytext) library(stringr) library(kableExtra) library(knitr) #Load the tweets Coulter <- rio::import("Coulter.csv") AOC <- rio::import("AOC.csv") #---------------------------------------------------------------------# #Part 2: Let's Analyze News and Twitter Narratives # #---------------------------------------------------------------------# #Formating the Tweets in kable #Save as html file using export function in Plots viewer #---------------------------------------------------------------------# # Exercise #2: Measure how much engagement (likes) Coulter gets over time #---------------------------------------------------------------------# # Measure how much engagement (likes) Coulter gets over time # Construct a table based on favorite count, chart it # Favorite count Fav <- Coulter %>% select(screen_name, favorite_count, created_at) %>% filter(favorite_count > 0) %>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon) %>% arrange(desc(favorite_count)) #plot ggplot(Fav)+ aes(x = yearmon, y = favorite_count, fill = yearmon)+ geom_col(show.legend = F) + theme_bw()+ labs(title = "Ann Coulter Tweeter engagement", subtitle = "Ann Coulter Twitter Feed", caption = "Source: Twitter 2019", x="Year/Month", y="Tweets Favorites") #---------------------------------------------------------------------# # Exercise #3: Measure how much engagement (likes) AOC gets over time #---------------------------------------------------------------------# # Measure how much engagement (likes) AOC gets over time # Construct a table based on favorite count, chart it # Favorite count AOC_fav <- AOC %>% select(screen_name, created_at, favorite_count) %>% filter(favorite_count > 0) %>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon, favorite_count) %>% arrange(desc(favorite_count)) #plot ggplot(AOC_fav)+ aes(x = yearmon, y = favorite_count, fill = yearmon )+ geom_col(show.legend = F) + theme_bw()+ scale_y_continuous(labels = scales::comma)+ expand_limits(y = c(1000000,8000000)) + labs(title = "AOC engagement", subtitle = "Cortez Twitter Feed", caption = "Source: Twitter Feed Sept 2018-Jan 2019", x="Year/Month", y="Tweets/Favorites") #---------------------------------------------------------------------# # Exercise #4: Compare Tables - monthly tweets #---------------------------------------------------------------------# #Build monthly Tweets Table #AOC AOC_y_Month <- AOC %>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon) %>% count(yearmon) #Coulter Coulter_y_Month <- Coulter %>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon) %>% count(yearmon) #Add identifying label to the AOC and Coulter dataframes #data$newcolumn<-"your text" Coulter_y_Month$Name <- "Coulter" AOC_y_Month$Name <- "AOC" #Combine dataframes using rbind AOC_Coulter_Mo <- rbind(AOC_y_Month, Coulter_y_Month) #plot ggplot(AOC_Coulter_Mo)+ aes(x = yearmon, y = n, fill = Name)+ geom_col() + theme_bw()+ labs(title = "AOC-Coulter monthly Tweets", subtitle = "AOC-Coulter Twitter Feeds", caption = "Source: Twitter 2019", x="Year/Month", y="Tweets Per month") #---------------------------------------------------------------------# # Exercise #5: Build Table with AOC, Coulter Engagement (likes) # Plot over time #---------------------------------------------------------------------# C_likes <- Coulter %>% select(favorite_count, created_at) %>% filter(favorite_count >0) %>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon) %>% arrange(favorite_count) # construct a table by month C_likes_m <- C_likes %>% summarise(fav_sum = sum(favorite_count)) ggplot(C_likes_m)+ aes(x = yearmon, y = fav_sum, fill= yearmon)+ geom_col(show.legend = F)+ expand_limits(y = c(0,1750000))+ labs(title = "Times Coulter's Tweets whave been liked by Ohers") # AOC AOC_likes <- AOC %>% select(favorite_count, created_at) %>% filter(favorite_count >0) %>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon) %>% arrange(favorite_count) # construct a table by month AOC_likes_m <- AOC_likes %>% summarise(fav_sum = sum(favorite_count)) ggplot(AOC_likes_m)+ aes(x = yearmon, y = fav_sum, fill= yearmon)+ geom_col(show.legend = F)+ scale_y_continuous(labels = scales::comma)+ theme_bw()+ expand_limits(y = c(1000000,7000000))+ labs(title = "Times AOC's Tweets whave been liked by Ohers") C_likes_m$Name <- "Coulter" AOC_likes_m$Name <- "AOC" AOC_Cul_Likes_Mo <- rbind(C_likes_m, AOC_likes_m) ggplot(AOC_Cul_Likes_Mo)+ aes(x = yearmon, y = fav_sum, fill= Name)+ geom_col(show.legend = T)+ scale_y_continuous(labels = scales::comma)+ theme_bw()+ labs(title = "Times AOC & Coulter's Tweets have been liked by Ohers") #---------------------------------------------------------------------# # Exercise #6: Build Table with AOC, Coulter Immigration Narrative # Plot over time #---------------------------------------------------------------------# Coulter_imm <- Coulter %>% filter(grepl ("Immigration", text, ignore.case = T)) %>% select(created_at, text) %>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon) %>% count(yearmon) AOC_imm <- AOC %>% filter(grepl ("Immigration|ice", text, ignore.case = T)) %>% select(created_at, text)%>% mutate(created_at = ymd_hms(created_at)) %>% mutate(yearmon= format(created_at, "%Y-%m")) %>% group_by(yearmon) %>% count(yearmon) ggplot(AOC_imm, aes(x = yearmon, y = n, label = n, fill=yearmon)) + geom_bar(stat = "identity", show.legend = F) + geom_text(colour="black", vjust=-0.3, size=3.5) + labs(title = "Number of Immigration Tweets per Month", subtitle = "Ann Coulter Twitter Feed", caption = "Source: Twitter aGraphic by <NAME>", x="Month", y="Number of Tweets") AOC_imm$Name <- "AOC" Coulter_imm$Name <- "Coulter" #Combine dataframes using rbind AOC_Coulter_Imm_Mo <- rbind(AOC_imm, Coulter_imm) #plot ggplot(AOC_Coulter_Imm_Mo)+ aes(x = yearmon, y = n, fill = Name)+ geom_col() + theme_bw()+ labs(title = "AOC-Coulter Tweets", subtitle = "AOC-Coulter Twitter Feeds", caption = "Source: Twitter 2019", x="Year/Month", y="Tweets Per month")
310338d8b749fc99f33080de6439efd097002d5f
[ "Markdown", "R" ]
2
Markdown
Mbareck/Analyzing-the-Tweets-of-Alexandria-Ocasio-Cortez-VS-Ann-Coulter
cf43907d16fe0c51f5f89af0cdafac28cbad1f9c
5594ab9792ca33f7cde025bba66ceee4d12d4d37
refs/heads/master
<file_sep># Images tasks with gulp Work to the <b>start</b> folder, the solutions are in the <b>end</b> folder ## 1. Declare packages Declare packages in your gulpfile.js ``` var imagemin = require('gulp-imagemin'); var imageminPngquant = require('imagemin-pngquant'); var imageminJpegRecompress = require('imagemin-jpeg-recompress'); var cache = require('gulp-cache'); ``` ## 2. Install packages Install the 3 imagemin packages ``` npm install --save-dev gulp-imagemin@3.0.1 imagemin-pngquant@5.0.0 imagemin-jpeg-recompress@5.0.0 gulp-cache ``` ## 3. Declare static variables Write code to gulpfile.js ``` // static image variables var srcImg = 'images/**/*.{png,jpeg,jpg,svg,gif}'; var distImg = '../web/images'; ``` ## 4. Create an images task, and run it Write code to gulpfile.js ``` gulp.task('images', function(){ return gulp.src(srcImg) .pipe(imagemin()) .pipe(gulp.dest(distImg)) }); ``` Run task ``` gulp images ``` ``` gulp-imagemin: Minified 0 images ``` ## 5. Rename the image path in index.html ``` from :src/images/ to: web/images/ ``` ## 6. Extend our images task ``` imagemin.gifsicle(), imagemin.jpegtran(), imagemin.optipng(), imagemin.svgo(), imageminPngquant(), imageminJpegRecompress() ``` ## 7. Run again your images task the result will be: ``` gulp-imagemin: Minified 21 images (saved 569.81 kB - 39.3%) ``` ## 8. Extend images task ```$xslt .pipe(cache(imagemin( [ imagemin.gifsicle(), imagemin.jpegtran(), imagemin.optipng(), imagemin.svgo(), imageminPngquant(), imageminJpegRecompress() ] ))) ``` ## 9. Run again your images task the result will be: ``` gulp-imagemin: Minified 0 images ```<file_sep><?php /*$to = "<EMAIL>"; $from = $_REQUEST['name']; $headers = "Content-type: text/html;From: $from"; $fields = array(); $fields["name"] = $_REQUEST['name']; $fields["email"] = $_REQUEST['email']; $fields["message"] = $_REQUEST['message']; $body = "Here is what was sent:\n\n"; $body .= 'Name : '.$fields['name']. '<br>'; $body .= 'Email : '.$fields['email']. '<br>'; $body .= 'Message : '.$fields['message']. '<br>'; $send = mail($to, $body, $headers); */<file_sep>var gulp = require('gulp'); var sass = require('gulp-sass'); var plumber = require('gulp-plumber'); var autoprefixer = require('gulp-autoprefixer'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); var browserSync = require('browser-sync').create(); var imagemin = require('gulp-imagemin'); var imageminPngquant = require('imagemin-pngquant'); var imageminJpegRecompress = require('imagemin-jpeg-recompress'); var cache = require('gulp-cache'); // static css variables var srcScss = 'scss/style.scss'; var distCss = '../web/css'; var minCss = 'style.min.css'; // vendor static css variables var distVendorCss = '../web/css/vendor'; var vendorCss = 'css/vendor/*.css'; var vendorPackCssMin = 'vendor.packs.min.css'; // static javascript variables var srcMainJs = 'js/main.js'; var distMainJs = '../web/js'; var minMainJs = 'main.min.js'; // vendor static javascript variables var distVendorJs = '../web/js/vendor'; var vendorJs = 'js/vendor/plugins/*.js'; var vendorPackJsMin = 'vendor.packs.min.js'; // static image variables var srcImg = 'images/**/*.{png,jpeg,jpg,svg,gif}'; var distImg = '../web/images'; // Styles gulp.task('sass', function(){ console.log('starting sass task'); return gulp.src(srcScss) .pipe(plumber(function (err){ console.log('Sass task error'); console.log(err); this.emit('end'); })) .pipe(sourcemaps.init()) .pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe(sass({ outputStyle: 'compressed' })) // Converts Sass to Css with gulp sass .pipe(concat(minCss)) .pipe(sourcemaps.write('./maps')) .pipe(gulp.dest(distCss)) .pipe(browserSync.stream()); }); gulp.task('vendor-css', function(){ return gulp.src(vendorCss) .pipe(plumber(function (err){ console.log('Sass task error'); console.log(err); this.emit('end'); })) .pipe(concat(vendorPackCssMin)) .pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe(sass({ outputStyle: 'compressed' })) // Converts Sass to Css with gulp sass .pipe(gulp.dest(distVendorCss)); }); // /Styles // Scripts gulp.task('main-js', function(){ return gulp.src(srcMainJs) .pipe(sourcemaps.init()) .pipe(uglify()) .pipe(concat(minMainJs)) .pipe(sourcemaps.write('./maps')) .pipe(gulp.dest(distMainJs)) .pipe(browserSync.stream()); }); gulp.task('vendor-js', function(){ return gulp.src(vendorJs) .pipe(uglify()) .pipe(concat(vendorPackJsMin)) .pipe(gulp.dest(distVendorJs)); }); // /Scripts /* images */ gulp.task('images', function(){ return gulp.src(srcImg) .pipe(cache(imagemin( [ imagemin.gifsicle(), imagemin.jpegtran(), imagemin.optipng(), imagemin.svgo(), imageminPngquant(), imageminJpegRecompress() ] ))) .pipe(gulp.dest(distImg)) }); // browserSync gulp.task('browserSync', function() { browserSync.init({ server: { baseDir: '../' } }); gulp.watch("scss/*.scss", ['sass']); gulp.watch("js/*.js", ['main-js']); }); gulp.task('default', ['browserSync'], function (){ gulp.watch('../index.html', browserSync.reload); });
bf66f2cccb5f0dc566e557ed9e69c350501068fe
[ "Markdown", "JavaScript", "PHP" ]
3
Markdown
vorenus85/gulp-workshop-2017-q4-session-5
61237493a1fc5dd24d25282b324153ce2a1d31c8
679369c718082cf55a3388a4ddb64c3a155dd96f
refs/heads/main
<repo_name>Xcode123456/Component01<file_sep>/Podfile # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'ComponentDemo' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! pod 'Helper',:path => 'Lib/Helper' # Pods for ComponentDemo target 'ComponentDemoTests' do inherit! :search_paths # Pods for testing end target 'ComponentDemoUITests' do # Pods for testing end end
ec380900859cdf64a52447479fbae3c874f54ed3
[ "Ruby" ]
1
Ruby
Xcode123456/Component01
a4208f6138fcded55bfd96a10b790c229fc9746d
bca6b7ae30ff12d3f33e6f5e136ca1c4d7ae6dbd
refs/heads/master
<repo_name>jacob-seiler/Wallpaper-Changer<file_sep>/README.md # Wallpaper-Changer Changes desktop wallpaper depending on the time of day TODO - GUI - Cuztomize file paths - Customize times that wallpaper changes - Test Win 32 - Mac OS Support - Linux Support <file_sep>/wallpaperChanger.pyw from datetime import datetime import ctypes import winreg import os.path import platform def is_64bit_windows(): """Check if 64 bit Windows OS""" return platform.architecture()[0] == '64bit' def changeBG(path, fit): """Change background depending on bit size""" if not os.path.isfile(path): print("Error setting wallpaper. Could not find file '" + path + "'") return REG_PATH = "Control Panel\\\\Desktop" key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE) winreg.SetValueEx(key, "WallpaperStyle", 0, winreg.REG_SZ, str(fit)) winreg.SetValueEx(key, "TileWallpaper", 0, winreg.REG_SZ, "0") winreg.CloseKey(key) SPI_SETDESKWALLPAPER = 20 if is_64bit_windows(): ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, path, 3) else: ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, path, 3) def main(): time = datetime.now().hour path = "C:\\Users\\Jacob\\Pictures\\Wallpapers\\" + str(time) + "00.jpg" changeBG(path, 2) if __name__ == "__main__": main()
c5a7fe54ee7e30c4de4e7146f4967b560027a49e
[ "Markdown", "Python" ]
2
Markdown
jacob-seiler/Wallpaper-Changer
9cccf012a278133a53a1a6128b7f6b7250e3819e
66837a4a711c09b80aff41abba7062b89542eb97
refs/heads/master
<file_sep>var gulp = require("gulp"); var concat = require("gulp-concat"); var uglify = require("gulp-uglify"); var rename = require("gulp-rename"); var connect = require("gulp-connect"); var sass = require("gulp-sass"); //sass编译 gulp.task("sassfile",function(){ gulp.src(["scss/*.scss"]) .pipe(sass()) .pipe(gulp.dest("D:\\phpStudy\\WWW\\XiangQu\\css")); }); //定义一个复制文件的任务(命令) gulp.task("copyfile",function(){ //gulp.src("index.html").pipe(gulp.dest("dist")); gulp.src("*.html").pipe(gulp.dest("D:\\phpStudy\\WWW\\XiangQu")); }); // 复制js gulp.task("jsfile",function(){ //gulp.src("index.html").pipe(gulp.dest("dist")); gulp.src("js/*.js").pipe(gulp.dest("D:\\phpStudy\\WWW\\XiangQu\\js")); }); // //复制html // gulp.task("html",function(){ // gulp.src("*.html") // .pipe(gulp.dest("dist\\D:\\phpStudy\\WWW\\XiangQu")); // }); //复制图片文件 gulp.task("imagesflie",function(){ gulp.src("img/*.{jpg,png,gif,ico,svg}") .pipe(gulp.dest("D:\\phpStudy\\WWW\\XiangQu\\img")); }); //合并文件 // gulp.task("concatjs",function(){ // gulp.src(["js/index.js","js/goodslist.js"]) // .pipe(concat("common.js")) // .pipe(gulp.dest("dist\\D:\\phpStudy\\WWW\\XiangQu\\js")); // }); //合并和压缩文件 // gulp.task("concatanduglifyjs",function(){ // gulp.src(["js/index.js","js/goodslist.js"]) // .pipe(concat("common.js")) // .pipe(uglify()) // .pipe(gulp.dest("dist\\D:\\phpStudy\\WWW\\XiangQu\\js")); // }); //合并和压缩重命名文件 // gulp.task("concatanduglifyandrenamejs",function(){ // gulp.src(["js/index.js","js/goodslist.js"]) // .pipe(concat("common.js")) // .pipe(gulp.dest("dist\\js")) // .pipe(uglify()) // .pipe(rename("common.min.js")) // .pipe(gulp.dest("dist\\D:\\phpStudy\\WWW\\XiangQu\\js")); // }); //合并和压缩重命名文件 // gulp.task("babel",function(){ // gulp.src("js/goodsdetail.js") // .pipe(babel()) // .pipe(gulp.dest("dist\\D:\\phpStudy\\WWW\\XiangQu\\js")); // }); //启动监听器 gulp.task("watchall",function(){ gulp.watch("scss/*.scss",["sassfile"]); gulp.watch("*.html",["copyfile"]); gulp.watch("img/*.{jpg,png,gif,ico,svg}",["imagesflie"]); gulp.watch("js/*.js",["jsfile"]); // gulp.watch(["js/index.js","js/goodslist.js"],["concatanduglifyandrenamejs"]); }); // //简易的web服务器 // gulp.task("server",function(){ // connect.server({ // "root":"dist" // }); // });<file_sep> $(function(){ $('.square').mouseover(function(){ $('.square span').addClass("bank"); $('.square a').addClass("colors"); $(this).siblings().children().removeClass("bank"); $(this).siblings().children().removeClass("colors"); }); });
8c494319a72fd7b466f4c1b9424b6e5968a36e65
[ "JavaScript" ]
2
JavaScript
Anjingde234/XiangQu
2b61cfaa1549fd32f49f034b96b454ceae590e15
7a1a5a8335b414474078df96beddd9c3d5f5ed37
refs/heads/master
<file_sep>#!/usr/bin/env python import sys import argparse from aws_cfn_control import CfnControl def prRed(prt): print("\033[91m{}\033[00m".format(prt)) def prGreen(prt): print("\033[92m{}\033[00m".format(prt)) def prYellow(prt): print("\033[93m{}\033[00m".format(prt)) def prLightPurple(prt): print("\033[94m{}\033[00m".format(prt)) def prPurple(prt): print("\033[95m{}\033[00m".format(prt)) def prCyan(prt): print("\033[96m{}\033[00m".format(prt)) def prLightGray(prt): print("\033[97m{}\033[00m".format(prt)) def prBlack(prt): print("\033[98m{}\033[00m".format(prt)) progname = 'getinstinfo' def arg_parse(): parser = argparse.ArgumentParser(prog=progname, description='Get instance info') opt_group = parser.add_argument_group() opt_group.add_argument('-s', dest='instance_state', required=False, help='Instance State (pending | running | shutting-down | terminated | stopping | stopped)' ) req_group = parser.add_argument_group('required arguments') req_group.add_argument('-r', dest='region', required=True) return parser.parse_args() def main(): rc = 0 args = arg_parse() region = args.region instance_state = args.instance_state client = CfnControl(region=region) for inst, info in client.get_instance_info(instance_state=instance_state).items(): print(inst) for k, v in info.items(): if k == 'State': if v == 'running': prGreen(" {0}: {1}".format(k, v)) elif v == 'stopped' or v == 'terminated': prRed(" {0}: {1}".format(k, v)) else: print(" {0}: {1}".format(k, v)) else: print(" {0}: {1}".format(k, v)) print('-----------') return rc if __name__ == "__main__": try: sys.exit(main()) except KeyboardInterrupt: print '\nReceived Keyboard interrupt.' print 'Exiting...' except ValueError as e: print('ERROR: {0}'.format(e))
f449cd672e456e6493829b62fe8b71cd8b8787d8
[ "Python" ]
1
Python
liozzazhang/aws-cfn-control
2594ccb03f6feb52693f0311a7d6cf8098fc18bf
0fee4dc651ab470f0a2ac221bf32f43495f4a767
refs/heads/master
<repo_name>Jenhop8786/activerecord-validations-lab-v-000<file_sep>/app/models/post.rb class Post < ActiveRecord::Base validates_presence_of :title validates :content, length: { minimum: 250 } validates :summary, length: { maximum: 250 } validates :category, inclusion: {in: %w(Fiction Nonfiction)} validate :clickbait CLICKBAIT = [/Won\'t Believe/i, /Secret/i, /Top[0-9]*/i, /Guess/i] def clickbait if CLICKBAIT.none? {|t| t.match title} errors.add(:title, "Smells a little clickbait-y!") end end end
3411c6a22953bb27b2bcdcd7283252addbd6e21d
[ "Ruby" ]
1
Ruby
Jenhop8786/activerecord-validations-lab-v-000
eb11fd115d7ee21d47e724346109e25e1938ed5f
9d5c19cf75de5502fc1a85b9c8845fc2c9c62824
refs/heads/master
<repo_name>yoseph-buitrago/US-State-Dictionary<file_sep>/pop_dictionary copy.py states = { "California": [ 39000000, "Sacramento", "Los Angeles", "The Golden State" ], "New York": [ 8000000, "Albany", "New York City", "The Empire State" ], "Florida": [ 21000000, "Tallahassee", "Maiami", "The Sunshine State" ], "Alaska": [ 739795, "Juneau", "Anchorage", "The Last Frontier" ], "Hawaii": [ 1000000, "Honolulu", "Honolulu", "The Aloha State" ], "Tennessee": [ 7000000, "Nashville", "Nashville", "The Volunteer State" ], "Kentucky": [ 4000000, "Frankfort", "Louisville", "Bluegrass State" ], "Louisiana": [ 5000000, "B<NAME>", "New Orleans", "Child of the Mississippi, Creole State, Bayou State, Sugar State, Sportsman's Paradise, and Pelican State" ], "Delaware": [ 961939, "Dover", "Wilmington", "The First State, The Diamond State, The Small Wonder, and Blue Hen State" ], "Wyoming": [ 579315, "Cheyenne", "Cheyenne", "Equality State, Cowboy State, and Big Wyoming" ], "South Dakota": [ 869666, "Pierre", "Sioux Falls", "The Mount Rushmore State" ], "West Virginia": [ 2000000, "Charleston", "Charleston", "Mountain State" ], "Maryland": [ 6000000, "Annapolis", "Baltimore", "Old Line State, Free State, and Little America" ], "Wisconsin": [ 6000000, "Madison", "Milwaukee", "America's Dairyland and Badger State" ], "New Mexico": [ 2000000, "Santa Fe", "Albuquerque", "Land of Enchantment" ], "Maine": [ 1000000, "Augusta", "Portland", "The Pine Tree State" ], "Iowa": [ 3000000, "Des Moines", "Des Moines", "The Hawkeye State" ], "Ohio": [ 12000000, "Colombus", "Colombus", "The Mother of Presidents, The Heart of it All, The Buckeye State, and Birthplace of Aviation" ], "New Jersey": [ 9000000, "Trenton", "Newark", "The Garden State" ], "Washington": [ 7000000,"Olympia", "Seattle", "The Evergreen State" ], "Georgia": [ 1000000, "Atlanta", "Atlanta", "Peach State and Empire State of the South" ], "Missouri": [ 6000000, "Jefferson City", "Saint Louis", "The Show-Me State" ], "Mississippi": [ 3000000, "Jackson", "Jackson", "The Magnolia State and the Hospitality State" ] } <file_sep>/change name l8r.py import random states = { "California": [ 39000000, "Sacramento", "Los Angeles", "The Golden State" ], "New York": [ 8000000, "Albany", "New York City", "The Empire State" ], "Florida": [ 21000000, "Tallahassee", "Maiami", "The Sunshine State" ], "Alaska": [ 739795, "Juneau", "Anchorage", "The Last Frontier" ], "Hawaii": [ 1000000, "Honolulu", "Honolulu", "The Aloha State" ], "Tennessee": [ 7000000, "Nashville", "Nashville", "The Volunteer State" ], "Kentucky": [ 4000000, "Frankfort", "Louisville", "Bluegrass State" ], "Louisiana": [ 5000000, "<NAME>", "New Orleans", "Child of the Mississippi, Creole State, Bayou State, Sugar State, Sportsman's Paradise, and Pelican State" ], "Delaware": [ 961939, "Dover", "Wilmington", "The First State, The Diamond State, The Small Wonder, and Blue Hen State" ], "Wyoming": [ 579315, "Cheyenne", "Cheyenne", "Equality State, Cowboy State, and Big Wyoming" ], "South Dakota": [ 869666, "Pierre", "Sioux Falls", "The Mount Rushmore State" ], "West Virginia": [ 2000000, "Charleston", "Charleston", "Mountain State" ], "Maryland": [ 6000000, "Annapolis", "Baltimore", "Old Line State, Free State, and Little America" ], "Wisconsin": [ 6000000, "Madison", "Milwaukee", "America's Dairyland and Badger State" ], "New Mexico": [ 2000000, "Santa Fe", "Albuquerque", "Land of Enchantment" ], "Maine": [ 1000000, "Augusta", "Portland", "The Pine Tree State" ], "Iowa": [ 3000000, "Des Moines", "Des Moines", "The Hawkeye State" ], "Ohio": [ 12000000, "Colombus", "Colombus", "The Mother of Presidents, The Heart of it All, The Buckeye State, and Birthplace of Aviation" ], "New Jersey": [ 9000000, "Trenton", "Newark", "The Garden State" ], "Washington": [ 7000000,"Olympia", "Seattle", "The Evergreen State" ], "Georgia": [ 1000000, "Atlanta", "Atlanta", "Peach State and Empire State of the South" ], "Missouri": [ 6000000, "Jefferson City", "Saint Louis", "The Show-Me State" ], "Mississippi": [ 3000000, "Jackson", "Jackson", "The Magnolia State and the Hospitality State" ] } def display_menu(): print("Menu: \n", "1. Get US State Population (Rounded Up) \n", "2. Get US State Capitol \n", "3. Get What US State most populated city \n", "4. Get US State Nickname(s) \n", "5. Get All the Information of a Random State \n", "6. Get US Population" ) def user_choice(): user_choice = int(input("Choose What Information List Do You Want To Learn About: ")) while user_choice < 1 or user_choice > 6: user_choice = int(input("Choose What Information List You Want To Learn About: ")) return user_choice def get_state_population(): state = str(input("Enter a US State to get the population: ")) for key in states: if key == state: print("The population in", state, "is:", states[key][0]) def get_state_capitol(): state = str(input("Enter a US State to get the State Capitol: ")) for key in states: if key == state: print("The Capitol of",state,"is:",states[key][1]) def get_state_populated_city(): state = str(input("Enter a US State to get its Most Populated City: ")) for key in states: if key == state: print("The Most Populated City in",state,"is:",states[key][2]) def get_state_nickname(): state = str(input("Enter a US State to get its State Nickname(s): ")) for key in states: if key == state: print("The State Nickname(s) of",state,"is/are:",states[key][3]) def get_random_info(): print(random.choice(list(states.values()))) def get_us_pop(): us_population = 0 for i in states: us_population += states[i][0] print("The US Population Is About:",us_population) def quit_continue(): start = str(input("Press 'c' to continue or 'q' to quit: ")) while start != "c" and start != "q": start = str(input("Press 'c' to continue or 'q' to quit: ")) while algien == True: if start == "c": main() elif start == "q": algien = False def main(): display_menu() choice = user_choice() if choice == 1: get_state_population() elif choice == 2: get_state_capitol() elif choice == 3: get_state_populated_city() elif choice == 4: get_state_nickname() elif choice == 5: get_random_info() elif choice == 6: get_us_pop() start = str(input("Press 'c' to continue or 'q' to quit: ")) while start != "c" and start != "q": start = str(input("Press 'c' to continue or 'q' to quit: ")) while algien == True: if start == "c": main() elif start == "q": algien = False main()
d774eb57a5fd49a10b5d8ebe30fbbf0c0dd9cc23
[ "Python" ]
2
Python
yoseph-buitrago/US-State-Dictionary
d71e96eba4c076ded4e93b3a2c9d68058b56b0a0
afc1c2f23b092443f1bede0fbe5960887453d3ee
refs/heads/master
<repo_name>AkalyaRamanathan/Dummy<file_sep>/SpringMvcTwo/src/com/capg/spring/service/ProductServiceImpl.java package com.capg.spring.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.capg.spring.dao.ProductDao; import com.capg.spring.dto.Product; @Service("productservice") @Transactional public class ProductServiceImpl implements ProductService{ @Autowired ProductDao productdao; @Override public void addProduct(Product p) { productdao.addProduct(p); } @Override public List<Product> showProduct() { return productdao.showProduct(); } @Override public void updateProduct(Product p) { productdao.updateProduct(p); } @Override public Product searchProduct(int productId) { // TODO Auto-generated method stub return null; } @Override public void deleteProduct(int productId) { productdao.deleteProduct(productId); } } <file_sep>/SpringMvcTwo/src/com/capg/spring/service/ProductService.java package com.capg.spring.service; import java.util.List; import com.capg.spring.dto.Product; public interface ProductService { public void addProduct(Product p); public List<Product> showProduct(); public void updateProduct(Product p); public Product searchProduct(int productId); public void deleteProduct(int productId); } <file_sep>/SpringMvcTwo/src/com/capg/spring/controller/ProductController.java package com.capg.spring.controller; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.capg.spring.dto.Product; import com.capg.spring.service.ProductService; @Controller public class ProductController { @Autowired ProductService productService; @RequestMapping(value="/showall",method=RequestMethod.GET) public ModelAndView getAllProducts() { List<Product> list=productService.showProduct(); return new ModelAndView("show","prods",list); } @RequestMapping(value="/add",method=RequestMethod.GET) public String myProduct(@ModelAttribute("prod") Product prod) { return "add_product"; } @RequestMapping(value="/addproduct",method=RequestMethod.POST) public String addProduct(@ModelAttribute("prod") Product prod,BindingResult result) { productService.addProduct(prod); return "redirect:/showall"; } @RequestMapping(value="/delete",method=RequestMethod.GET) public String delete(@ModelAttribute("prod") Product prod) { return "delete"; } @RequestMapping(value="/delete1",method=RequestMethod.POST) public String deleteProduct(@ModelAttribute("prod") Product prod) { int productId=prod.getProductId(); productService.deleteProduct(productId); return "redirect:/showall"; } @RequestMapping(value="/update",method=RequestMethod.GET) public String updateProduct(@ModelAttribute("prod") Product prod) { return "update"; } @RequestMapping(value="/update1",method=RequestMethod.GET) public ModelAndView updateDetails(@ModelAttribute("prod") Product prod) { Product product=productService.searchProduct(prod.getProductId()); return new ModelAndView("update2","empu",product); } @RequestMapping(value="/updateproduct",method=RequestMethod.POST) public String update(@ModelAttribute("prod") Product prod) { productService.updateProduct(prod); return "redirect:/showall"; } } <file_sep>/spring-boot-jpa/spring-boot-jpa/src/main/resources/application.properties spring.jpa.hibernate.ddl-auto=update spring.datasource.url= jdbc:mysql://localhost:3306/fullstack spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name= com.mysql.jdbc.Driver server.port=9012<file_sep>/SpringMvcTwo/src/com/capg/spring/dao/ProductDao.java package com.capg.spring.dao; import java.util.List; import com.capg.spring.dto.Product; public interface ProductDao { public void addProduct(Product p); public List<Product> showProduct(); public void updateProduct(Product p); public void deleteProduct(int productId); public Product searchProduct(int productId); } <file_sep>/PayWallet/src/main/java/com/capg/dao/BankDao.java package com.capg.dao; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import com.capg.bean.Bank; import com.capg.service.BankValidation; public class BankDao implements IBankDao { Bank bank = new Bank(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static HashMap<String,Bank> map = new HashMap<String,Bank>(); static Bank bc; boolean flag; int balance; public boolean create(Bank bank ) { map.put(bank.getName(), bank); System.out.println(map); return true; } public boolean depositAmount(int amount) { bc.setBalance(bc.getBalance()+amount); return true; } public boolean withdrawAmount(int amount) { BankValidation validate = new BankValidation(); boolean isvalid = validate.ValidateWithdraw(amount,bc.getBalance()); if(isvalid) { bc.setBalance(bc.getBalance()-amount); System.out.println(bc.getBalance()); return true; } else{ System.out.println("not sufficient balance"); return false; }} public boolean fundTransfer (int customerId,int amount) { for(String key:map.keySet()) { Bank obj=map.get(key); if(obj.getCustomerId()==customerId) { obj.setBalance(obj.getBalance()+amount); bc.setBalance(bc.getBalance()-amount); return true; } } return true; } public boolean printTransaction(int customerId) { return false; } public boolean loginAccount(String name, String password) { System.out.println(map); for(String key: map.keySet()) { bc=map.get(key); if(bc.getName().equals(name)&& bc.getPassword().equals(password)) { System.out.println(map); return true; } } return false; } public int showBalance() { return bc.getBalance(); } } <file_sep>/PayWallet/src/main/java/com/capg/service/IBankService.java package com.capg.service; import com.capg.bean.Bank; public interface IBankService { boolean create(Bank bank ); boolean deposit(int amount); boolean withdraw(int amount); public int showBalance(); public boolean fundTransfer (int customerId,int amount); boolean printTransaction(int customerId); public boolean loginAccount(String name, String password); }
7c21aa1e623f8bca3bad4249cd89bf5873f50d38
[ "Java", "INI" ]
7
Java
AkalyaRamanathan/Dummy
9cd86a8a1fa1c789855f586c3d06b095095c7743
01731bd0ef3efc2e925ec0e37a250fdcd667de5b
refs/heads/master
<file_sep>var five = require('johnny-five'); var Tessel = require('tessel-io'); var fs = require('fs'); var board = new five.Board({ io: new Tessel() }); var http = require('http'); var os = require('os'); // Config // var hostname = grabInterfaces().pop() var hostname = "192.168.1.101"; var port = 1337; var url = `http://${hostname}:${port}/`; // Helper Functions // Grabs all the interfaces // Imperative // function grabInterfaces() { // var result = []; // var ifaces = os.networkInterfaces(); // Object.keys(ifaces).map(function (key) { return ifaces[key]; }) // .forEach(function (x) { return x.forEach(function (y) { return result.push(y); }); }); // var tmp = result.filter(function (x) { return x.family === 'IPv4' && x.internal === false; }) // .map(function (dev) { return dev.address; }); // return tmp; // } // Page var page = `<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Test App</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div id="app"> <button id="up" style="background-color:red; height:150px; width:150px;">UP</button> <button id="down" style="background-color:blue; height:150px; width:150px;">DOWN</button> <button id="left" style="background-color:green; height:150px; width:150px;">LEFT</button> <button id="right" style="background-color:yellow; height:150px; width:150px;">RIGHT</button> </div> <script type="text/javascript"> var upButton = document.getElementById('up'); var downButton = document.getElementById('down'); var leftButton = document.getElementById('left'); var rightButton = document.getElementById('right'); var up = { "element": upButton, "func": goUp }; var down = { "element": downButton, "func": goDown }; var left = { "element": leftButton, "func": goLeft }; var right = { "element": rightButton, "func": goRight }; function goUp() { console.log('up request'); var oReq = new XMLHttpRequest(); oReq.open("POST", "${url}up"); oReq.send(); } function goDown() { var oReq = new XMLHttpRequest(); oReq.open("POST", "${url}down"); oReq.send(); } function goLeft() { var oReq = new XMLHttpRequest(); oReq.open("POST", "${url}left"); oReq.send(); } function goRight() { var oReq = new XMLHttpRequest(); oReq.open("POST", "${url}right"); oReq.send(); } if ('ontouchstart' in document.documentElement) { var interval; upButton.addEventListener('touchstart', function() { interval = setInterval(goUp(), 450); }); upButton.addEventListener('touchend', function() { clearInterval(interval); }); } else { var interval; upButton.addEventListener('mousedown', function() { interval = setInterval(goUp(), 450); }); upButton.addEventListener('mouseup', function() { clearInterval(interval); }); } // down if ('ontouchstart' in document.documentElement) { var interval; downButton.addEventListener('touchstart', function() { interval = setInterval(goDown(), 450); }); downButton.addEventListener('touchend', function() { clearInterval(interval); }); } else { var interval; downButton.addEventListener('mousedown', function() { interval = setInterval(goDown(), 450); }); downButton.addEventListener('mouseup', function() { clearInterval(interval); }); } // left if ('ontouchstart' in document.documentElement) { var interval; leftButton.addEventListener('touchstart', function() { interval = setInterval(goLeft(), 450); }); leftButton.addEventListener('touchend', function() { clearInterval(interval); }); } else { var interval; leftButton.addEventListener('mousedown', function() { interval = setInterval(goLeft(), 450); }); leftButton.addEventListener('mouseup', function() { clearInterval(interval); }); } // right if ('ontouchstart' in document.documentElement) { var interval; rightButton.addEventListener('touchstart', function() { interval = setInterval(goRight(), 450); }); rightButton.addEventListener('touchend', function() { clearInterval(interval); }); } else { var interval; rightButton.addEventListener('mousedown', function() { interval = setInterval(goRight(), 450); }); rightButton.addEventListener('mouseup', function() { clearInterval(interval); }); } // var commands = [up, down, left, right]; // // commands.forEach(function(command) { // if ('ontouchstart' in document.documentElement) { // var interval; // // command['element'].addEventListener('touchstart', function() { // interval = setInterval(command.func, 450); // }); // // command['element'].addEventListener('touchend', function() { // clearInterval(interval); // }); // } else { // var interval; // // command['element'].addEventListener('mousedown', function() { // interval = setInterval(command.func, 450); // }); // // command['element'].addEventListener('mouseup', function() { // clearInterval(interval); // }); // } // }); </script> </body> </html>`; ///////////////////////////////////////////////////////////////// board.on("ready", function() { var motorA = new five.Motor(["a5", "a4", "a3"]); var motorB = new five.Motor(["b5", "b4", "b3"]); var length = 400; var speed = 255; function down(mA, mB) { mA.forward(speed); mB.forward(speed); board.wait(length, function() { mA.stop(); mB.stop(); }) }; function up(mA, mB) { mA.reverse(speed); mB.reverse(speed); board.wait(length, function() { mA.stop(); mB.stop(); }) }; function right(mA, mB) { mA.reverse(speed); mB.forward(speed); board.wait(length, function() { mA.stop(); mB.stop(); }) }; function left(mA, mB) { mA.forward(speed); mB.reverse(speed); board.wait(length, function() { mA.stop(); mB.stop(); }) }; // function page(response) { // response.writeHead(200, {"Content-Type":"text/html"}); // fs.readFile(__dirname + '/index.html', function(err, content) { // if (err) { // throw err; // } // response.end(content); // }) // } http.createServer(function (req, res) { if (req.method === "GET") { res.writeHead(200, {"Content-Type":"text/html"}); res.end(page); } if (req.method === "POST") { if (req.url === "/up") { console.log('called up'); var requestBody_1 = ''; req.on('data', function (data) { return requestBody_1 += data; }); req.on('end', function () { return up(motorA, motorB); }); res.end(); } else if (req.url === "/down") { var requestBody_2 = ''; req.on('data', function (data) { return requestBody_2 += data; }); req.on('end', function () { return down(motorA, motorB); }); res.end(); } else if (req.url === "/left") { var requestBody_3 = ''; req.on('data', function (data) { return requestBody_3 += data; }); req.on('end', function () { return left(motorA, motorB); }); res.end(); } else if (req.url === "/right") { var requestBody_4 = ''; req.on('data', function (data) { return requestBody_4 += data; }); req.on('end', function () { return right(motorA, motorB); }); res.end(); } } }).listen(port, hostname, function () { console.log("Server is running at http://" + hostname + ":" + port + "/"); }); // motorB.forward(50) // setTimeout(function() { // console.log("waiting") // }, 2000) // motorA.forward(255) }); <file_sep># Sumobot control Tessel code for sumobot control. Uses javascript and nodejs to program and control the bot over wifi. The bot when connected by ip address will serve up a website control interface. The commands are UP DOWN LEFT RIGHT SMASH. ## UP Move forward for 0.4 seconds. Hold button to go forward. ## DOWN Move in reverse for 0.4 seconds. Hold button to go in reverse. ## LEFT Rotate Left for 0.4 seconds. Hold button to rotate left. ## RIGHT Rotate RIGHT for 0.4 seconds. Hold button to rotate right. ## SMASH (Not implemented yet) Charge forward 64 inches. Hold button to charge forward. # License Information *The MIT License (MIT)* Copyright (c) 2016 01 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
d51838a6ee4037b317b7d6136045b3b6e9aff2d5
[ "JavaScript", "Markdown" ]
2
JavaScript
learn01/01-sumobot
c3afc4f62aece5d2269edb824d3f40f49a995bc7
ffa2c1d8e0f9823c604da8eb96027d6621885198
refs/heads/master
<file_sep>#! /bin/bash declare -A dict declare -A dict1 declare -A Dict1 declare -A dict2 echo "---------------Singlet-----------------" t=0 i=0 hc=0 tc=0 while(( $t <= 10 )) do ran=$(( $RANDOM%2 )) if(( $ran == 0 )) then (( hc++ )) #echo "Heads" dict[ $(( i++ )) ]='h' else (( tc++ )) #echo "Tails" dict[ $(( i++ )) ]='t' fi (( t++ )) done echo "Combination--->"${dict[@]} hp=$(echo $(( $hc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') #echo "Head percentaege $hp" tp=$(echo $(( $tc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') #echo "Tail percentaege $tp" Dict1=( ["hp"]=$hp ["tp"]=$tp ) echo "Keys---------->" ${!Dict1[@]} echo "Percentage---->" ${Dict1[@]} echo "-------------------------------------------" echo "----------------Doublet-------------------" t=0 hhc=0 htc=0 thc=0 ttc=0 j=0 while(( $t <= 10 )) do ran1=$(( $RANDOM%4 )) case $ran1 in 0) (( hhc++ )) dict1[ $(( j++ )) ]='hh' ;; 1) (( htc++ )) dict1[ $(( j++ )) ]='ht' ;; 2) (( thc++ )) dict1[ $(( j++ )) ]='th' ;; 3) (( ttc++ )) dict1[ $(( j++ )) ]='tt' ;; *) echo "--" ;; esac (( t++ )) done echo "Combination--->" ${dict1[@]} hhp=$(echo $(( $hhc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') htp=$(echo $(( $htc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') thp=$(echo $(( $thc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') ttp=$(echo $(( $ttc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') Dict1=( ["hhp"]=$hhp ["htp"]=$htp ["thp"]=$thp ["ttp"]=$ttp ) echo "Keys---------->" ${!Dict1[@]} echo "Percentage---->" ${Dict1[@]} echo "--------------------------------------------" echo "------------------Triplet-----------------" t=0 hhhc=0 hhtc=0 hthc=0 httc=0 thhc=0 thtc=0 tthc=0 tttc=0 while(( $t <= 10 )) do ran2=$(( $RANDOM%8 )) case $ran2 in 0)(( hhhc++ )) dict2[ $(( l++ )) ]='hhh' ;; 1)(( hhtc++ )) dict2[ $(( l++ )) ]='hht' ;; 2)(( hthc++ )) dict2[ $(( l++ )) ]='hth' ;; 3)(( httc++ )) dict2[ $(( l++ )) ]='htt' ;; 4)(( thhc++ )) dict2[ $(( l++ )) ]='thh' ;; 5)(( tthc++ )) dict2[ $(( l++ )) ]='tth' ;; 6)(( thtc++ )) dict2[ $(( l++ )) ]='tht' ;; 7)(( tttc++ )) dict2[ $(( l++ )) ]='ttt' ;; *) echo "--" esac (( t++ )) done echo "Combination--->" ${dict2[@]} hhhp=$(echo $(( $hhhc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') hhtp=$(echo $(( $hhtc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') hthp=$(echo $(( $hthc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') http=$(echo $(( $httc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') thhp=$(echo $(( $thhc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') thtp=$(echo $(( $thtc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') tthp=$(echo $(( $tthc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') tttp=$(echo $(( $tttc * 100 )) 11 | awk '{printf"%.2f", $1 / $2}') Dict1=( ["hhhp"]=$hhhp ["hhtp"]=$hhtp ["hthp"]=$hthp ["http"]=$http ["thhp"]=$thhp ["thtp"]=$thtp ["tthp"]=$tthp ["tttp"]=$tttp ) echo "Keys---------->" ${!Dict1[@]} echo "Percentage---->" ${Dict1[@]} Dict1=( ["hp"]=$hp ["tp"]=$tp ["hhp"]=$hhp ["htp"]=$htp ["thp"]=$thp ["ttp"]=$ttp ["hhhp"]=$hhhp ["hhtp"]=$hhtp ["hthp"]=$hthp ["http"]=$http ["thhp"]=$thhp ["thtp"]=$thtp ["tthp"]=$tthp ["tttp"]=$tttp )
22f4b2e8d1ede671d1e52ddde9f4472b7ad4c88a
[ "Shell" ]
1
Shell
souvik1232/flipcoin1
e5d1913ab21674d80429b099b4617ab51695fd4d
6f0420736622a20154fae7a97ee792731fbe0b03
refs/heads/development
<repo_name>SuyashFowdar/baby-tracker-front<file_sep>/src/containers/Login.js import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import query from '../query'; import '../assets/css/Login.scss'; import { setToken } from '../actions'; const Login = () => { const dispatch = useDispatch(); const [signin, setSignin] = useState(true); const [errorMessage, setErrorMessage] = useState(''); const performRequest = (e, url) => { e.preventDefault(); query('POST', url, { name: e.target.name.value, password: e.target.password.value, }, (result) => { if (result.token) { localStorage.token = result.token; dispatch(setToken(result.token)); } else { setErrorMessage(result.error); } }); }; return ( <div className="login"> <div> {signin ? ( <div className="col cross-center main-center"> <form onSubmit={(e) => { performRequest(e, 'sessions'); }} className="col cross-center"> <h2>Sign In</h2> <input type="text" name="name" placeholder="Username" /> <input type="<PASSWORD>" name="<PASSWORD>" placeholder="<PASSWORD>" /> <input type="submit" value="Sign In" className="link w-90" /> <button type="button" onClick={() => { setSignin(false); }} className="link button w-90">or create new account</button> </form> </div> ) : ( <div className="col cross-center main-center"> <form onSubmit={(e) => { performRequest(e, 'users'); }} className="col cross-center"> <h2>Create new account</h2> <input type="text" name="name" placeholder="Username" /> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" /> <input type="submit" value="Sign Up" className="link w-90" /> <button type="button" onClick={() => { setSignin(true); }} className="link button w-90">Go to Sign In page</button> </form> </div> )} <div className="error row main-center cross-center">{errorMessage}</div> </div> </div> ); }; export default Login; <file_sep>/src/test/reducers/measures.test.js import measuresReducer from '../../reducers/measures'; describe('an object', () => { it('checks for default state', () => { const measure = measuresReducer([], { type: 'dummy' }); expect(measure).toEqual([]); }); it('sets measurements', () => { const measure = measuresReducer([], { type: 'SET_MEASURES', result: { measures: [{ item: 'Weight' }, { item: 'Height' }], measurements: [] } }); expect(measure).toEqual([{ item: 'Weight', measurements: [] }, { item: 'Height', measurements: [] }]); }); it('adds measure', () => { const measure = measuresReducer([], { type: 'ADD_MEASURE', measure: { id: 1, item: 'weight', unit: 'Kg', list: [], }, }); expect(measure).toEqual([{ id: 1, item: 'weight', unit: 'Kg', list: [], }]); }); it('adds measurement', () => { const measure = measuresReducer([{ id: 1, item: 'weight', unit: 'Kg', measurements: [], }], { type: 'ADD_MEASUREMENT', measurement: { amount: 3, measure_id: 1 } }); expect(measure).toEqual([{ id: 1, item: 'weight', unit: 'Kg', measurements: [{ amount: 3, measure_id: 1, date: 'Invalid Date' }], }]); }); }); <file_sep>/src/test/components/List.test.js import React from 'react'; import renderer from 'react-test-renderer'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import { BrowserRouter as Router } from 'react-router-dom'; import List from '../../components/List'; import reducer from '../../reducers/index'; it('renders correctly', () => { const store = createStore(reducer); const tree = renderer .create(( <Provider store={store}> <Router><List itemKey="" addItem={() => {}} displayAttr={[]} toAddAttr={[]} /></Router> </Provider> )) .toJSON(); expect(tree).toMatchSnapshot(); }); <file_sep>/src/components/HomeMeasurement.js import React from 'react'; import PropTypes from 'prop-types'; import { HashRouter as Router, Link } from 'react-router-dom'; import '../assets/css/HomeMeasurement.scss'; const HomeMeasurement = ({ measure }) => { const { measurements } = measure; return ( <Router> <Link to={`/measure/${measure.id}`} className="measure link bg-cover col cross-center main-center"> {measurements && measurements.length ? ( <div> <div className="amount">{`${measurements[measurements.length - 1].amount} ${measure.unit}`}</div> {measurements[measurements.length - 2] ? ( <div className="row main-center dif" style={{ color: measurements[measurements.length - 1].amount > measurements[measurements.length - 2].amount ? 'green' : 'red' }}> {measurements[measurements.length - 1].amount > measurements[measurements.length - 2].amount ? '+' : ''} {(measurements[measurements.length - 1].amount - measurements[measurements.length - 2].amount).toFixed(2)} </div> ) : <div />} </div> ) : <div className="amount new">Add new</div>} <div className="type">{measure.item}</div> </Link> </Router> ); }; HomeMeasurement.defaultProps = { measure: {}, }; HomeMeasurement.propTypes = { measure: PropTypes.instanceOf(Object), }; export default HomeMeasurement; <file_sep>/src/reducers/measures.js import _ from 'lodash'; const castMeasurement = (measure, measurement) => { const date = new Date(measurement.created_at); const msmnt = measurement; msmnt.date = date.toLocaleString('default', { day: 'numeric', month: 'long', year: 'numeric' }); measure.measurements.push(msmnt); }; const measuresReducer = (state = [], action) => { switch (action.type) { case 'SET_MEASURES': action.result.measures.forEach((m) => { const measure = m; measure.measurements = []; action.result.measurements.forEach((measurement) => { if (measurement.measure_id === measure.id) { castMeasurement(measure, measurement); } }); }); return action.result.measures; case 'ADD_MEASURE': return [...state, action.measure]; case 'ADD_MEASUREMENT': { const measures = _.cloneDeep(state); measures.forEach((measure) => { if (measure.id === action.measurement.measure_id) { castMeasurement(measure, action.measurement); } }); return measures; } default: return state; } }; export default measuresReducer; <file_sep>/src/actions/index.js export const setMeasures = (result) => ({ type: 'SET_MEASURES', result, }); export const addMeasure = (measure) => ({ type: 'ADD_MEASURE', measure, }); export const addMeasurement = (measurement) => ({ type: 'ADD_MEASUREMENT', measurement, }); export const setToken = (token) => ({ type: 'SET_TOKEN', token, }); <file_sep>/src/containers/App.js import React, { useEffect, useState } from 'react'; import { HashRouter as Router, Link, Switch, Route, } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faSignOutAlt, faHome } from '@fortawesome/free-solid-svg-icons'; import Home from './Home'; import Measure from './Measure'; import Admin from './Admin'; import Login from './Login'; import query from '../query'; import '../assets/css/App.scss'; import { setMeasures, setToken } from '../actions'; const App = () => { const dispatch = useDispatch(); const [errorMessage, setErrorMessage] = useState(''); const token = useSelector((state) => state.token); const logout = () => { localStorage.clear(); dispatch(setToken('')); }; useEffect(() => { if (localStorage.token) { if (!token) dispatch(setToken(localStorage.token)); query('GET', 'measurements', null, (result) => { if (result.measures && result.measurements) { dispatch(setMeasures(result)); } else { setErrorMessage(result.error); } }); } }, [token]); return ( <div> {(localStorage.token || token) ? ( <Router> <div className="error row main-center cross-center">{errorMessage}</div> <header className="row main-space-around"> <Link to="/" className="col cross-center main-center shadow-5 link flex"> <FontAwesomeIcon icon={faHome}>Sign Out</FontAwesomeIcon> <span>Home</span> </Link> <button type="button" onClick={logout} className="link col cross-center main-center flex"> <FontAwesomeIcon icon={faSignOutAlt}>Sign Out</FontAwesomeIcon> <span>Log out</span> </button> </header> <div className="main"> <Switch> <Route exact path="/"><Home /></Route> <Route path="/measure/:id"><Measure /></Route> <Route path="/admin"><Admin /></Route> </Switch> </div> </Router> ) : <Login />} </div> ); }; export default App; <file_sep>/README.md # Baby Measurement Tracker - Front Baby Measurement Tracker is an App that allows you to keep track of the growth of your baby.\ You can take maeasurements like Weight, Height, Head curcumference and Amount of Milk being drunk. ## Demo Link https://SuyashFowdar.github.io/baby-tracker-front ## How to use **Home** - You have to Sign Up to use the App. - Once you sign up and you are logged in, you will get a set of items you can measure. - Tap on the item you wish to add a new measurement, and you will be redirected to the measurement list page. **Measurement** - In this page, you will be presented with a set of measurements that and if you have recorded in the past. - After the list there is a form that you can input new measurements taken. **Admin** - There is no button to go to Admin page. You have to manually add `/admin` in the URL. - You will get access to Admin page only if your account username is 'Admin'. - In the Admin page, you're able to view all existing items and add new items to measure. ## Screenshots ![Screenshot of Baby-Tracker](./src/assets/img/Screenshot_1.png) ![Screenshot of Baby-Tracker](./src/assets/img/Screenshot_2.png) ## Cloning The following commands must be ran on terminal/CMD: - In your desired directory, run `git clone https://github.com/SuyashFowdar/baby-tracker-front`. - Then run `cd baby-tracker-front`. - From the meow project directory the following scripts can be run. - Run `npm install` to install all dependencies for the app to run in local ## Available Scripts In the project directory, you can run: ### `npm start` Make sure you have the local server(baby-tracker-back) running for smooth running of this project.\ Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. (The port number(3000) might vary depending on whether another process is running on the port.) The page will reload if you make edits.\ You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ## Built With - HTML - SCSS - Linter - JS - VScode - React - Router - Redux ## Contributing Contributions, issues and feature requests are welcome! Start by: - Forking the project - Cloning the project to your local machine - cd into the project directory - Run git checkout -b your-branch-name - Make your contributions - Push your branch up to your forked repository - Open a Pull Request with a detailed description to the development branch of the original project for a review ## Author 👤 **<NAME>** - Github: [@SuyashFowdar](https://github.com/SuyashFowdar) - Twitter: [@SuyashFowdar](https://twitter.com/SuyashFowdar) - LinkedIn: [LinkedIn](https://www.linkedin.com/in/suyash-fowdar/) ## Show your Support Give a ⭐ if you like this project! <file_sep>/src/containers/Admin.js import React, { useEffect, useState } from 'react'; import { Redirect } from 'react-router-dom'; import { useSelector, useDispatch } from 'react-redux'; import query from '../query'; import List from '../components/List'; import { addMeasure } from '../actions'; const Admin = () => { const [redirect, setRedirect] = useState(null); const [errorMessage, setErrorMessage] = useState(''); const dispatch = useDispatch(); const measures = useSelector((state) => state.measures); const createMeasure = (e) => { e.preventDefault(); const measure = { item: e.target.item.value, unit: e.target.unit.value, }; query('POST', 'measures', measure, (result) => { if (result.id) { measure.id = result.id; e.target.item.value = ''; e.target.unit.value = ''; dispatch(addMeasure(measure)); } else { setErrorMessage(result.error); } }); }; useEffect(() => { if (localStorage.token) { query('GET', 'admins', null, (result) => { if (result.admin) { setRedirect(false); } else { setRedirect(true); } }); } }); return ( <div> {redirect ? <Redirect to="/" /> : ( <div> {redirect === null ? <div /> : ( <div> <List list={measures} itemKey="item" displayAttr={['item', 'unit']} toAddAttr={['item', 'unit']} addItem={createMeasure} /> <div className="error row main-center cross-center">{errorMessage}</div> </div> )} </div> )} </div> ); }; export default Admin; <file_sep>/src/containers/Measure.js import React, { useEffect, useState } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { useParams } from 'react-router-dom'; import query from '../query'; import List from '../components/List'; import { addMeasurement } from '../actions'; const PetDetail = () => { const dispatch = useDispatch(); const { id } = useParams(); const [measure, setMeasure] = useState({}); const [errorMessage, setErrorMessage] = useState(''); const measures = useSelector((state) => state.measures); const selectMeasure = () => { for (let i = 0; i < measures.length; i += 1) { if (measures[i].id === parseInt(id, 10)) { setMeasure(measures[i]); break; } } }; const createMeasurement = (e) => { e.preventDefault(); query('POST', 'measurements', { amount: e.target.amount.value, measure_id: measure.id, }, (result) => { if (result.measurement) { e.target.amount.value = ''; const { measurement } = result; measurement.measure_id = measure.id; dispatch(addMeasurement(measurement)); } else { setErrorMessage(result.error); } }); }; useEffect(() => { selectMeasure(); }); return ( <> <div className="row cross-center main-center"> <div className="w-100 h-100"> <List list={measure.measurements} itemKey="created_at" displayAttr={['date', 'amount']} toAddAttr={['amount']} unit={measure.unit} addItem={createMeasurement} /> <div className="error row main-center cross-center">{errorMessage}</div> </div> </div> </> ); }; export default PetDetail; <file_sep>/src/query.js const getError = (url) => { switch (url) { case 'users': return "Couldn't Sign Up!"; case 'sessions': return "Couldn't Sign In!"; case 'measurements': return "Couldn't process Measurements!"; case 'measures': return "Couldn't process Measures!"; default: return "Request couldn't be processed!"; } }; export default (method, url, body, cb) => { let res; const host = process.env.NODE_ENV === 'production' ? 'https://suyash-baby-tracker.herokuapp.com/' : 'http://localhost:3000/'; const obj = { method, headers: { 'Content-Type': 'application/json', token: localStorage.token, }, }; if (method === 'POST') { obj.body = JSON.stringify(body); } fetch(new Request(`${host}${url}`, obj)) .then((response) => { if (!response.ok) { res = response; throw Error(response); } return response.json(); }) .then((response) => { cb(response); }) .catch(() => { if (res.json) { res.json().then((err) => { cb({ error: err.error || getError(url) }); }); } else { cb({ error: getError(url) }); } }); }; <file_sep>/src/components/List.js import React from 'react'; import PropTypes from 'prop-types'; import '../assets/css/List.scss'; const List = ({ list, itemKey, displayAttr, toAddAttr, addItem, unit, }) => ( <div className="list"> <div className="items"> {list.map((item) => ( <div key={item[itemKey]} className="row link"> {displayAttr.map((attr) => ( <div key={attr} className="flex item"> <div>{`${item[attr]} ${attr === 'amount' ? unit : ''}`}</div> </div> ))} </div> ))} </div> <form onSubmit={addItem} className="row main-center wrap"> {toAddAttr.map((attr) => ( <input key={attr} type="text" name={attr} placeholder={attr} /> ))} <input type="submit" value="Add New" className="link" /> </form> </div> ); List.defaultProps = { list: [], unit: '', }; List.propTypes = { list: PropTypes.instanceOf(Array), unit: PropTypes.string, itemKey: PropTypes.string.isRequired, addItem: PropTypes.func.isRequired, displayAttr: PropTypes.instanceOf(Array).isRequired, toAddAttr: PropTypes.instanceOf(Array).isRequired, }; export default List; <file_sep>/src/reducers/index.js import { combineReducers } from 'redux'; import measures from './measures'; import token from './token'; export default combineReducers({ measures, token });
ec6a0597a70439e33b331ee367064a57546d37a3
[ "JavaScript", "Markdown" ]
13
JavaScript
SuyashFowdar/baby-tracker-front
72db3649866504643533e3b2f86891bdcb737bd1
effb813b54d221e4bde0bfe3f3a32ddec57ea675
refs/heads/master
<repo_name>xushengj/supp<file_sep>/core/Parser.cpp #include "core/Parser.h" #include "core/IR.h" #include "core/DiagnosticEmitter.h" #include <QQueue> #include <QRegularExpressionMatch> #include <QSet> #include <QStack> #include <QStringRef> #include <algorithm> #include <iterator> #include <memory> Parser* Parser::getParser(const ParserPolicy& policy, const IRRootType& ir, DiagnosticEmitterBase& diagnostic) { bool isValidated = true; DiagnosticPathNode parserNode(diagnostic, tr("Parser")); if(Q_LIKELY(IRNodeType::validateName(diagnostic, policy.name))){ parserNode.setDetailedName(policy.name); }else{ isValidated = false; } std::unique_ptr<Parser> ptr(new Parser); // construct ParseContext // check match pairs: // 1. match pairs should have unique names (and the name must be good) // 2. match pair start strings can not be identical to any other match pair start strings. // HOWEVER: match pair end strings can be identical to any other strings (both match pair start string or end string, even ignore string) // Match pair end determination depends on context QHash<QString, int> matchPairStartToIndex; //!< for each match pair start string, what's the match pair index QHash<QString, int> matchPairNameToIndex; //!< for each match pair name, what's the index int longestMatchPairStartStringLength = 0; QList<int> matchPairScoreList; matchPairScoreList.reserve(policy.matchPairs.size()); ptr->context.matchPairName.reserve(policy.matchPairs.size()); ptr->context.matchPairStarts.reserve(policy.matchPairs.size()); ptr->context.matchPairEnds.reserve(policy.matchPairs.size()); for(int matchPairIndex = 0, n = policy.matchPairs.size(); matchPairIndex < n; ++matchPairIndex){ const auto& mp = policy.matchPairs.at(matchPairIndex); const QString& name = mp.name; DiagnosticPathNode pathNode(diagnostic, tr("MatchPair %1").arg(matchPairIndex)); if(Q_LIKELY(IRNodeType::validateName(diagnostic, name))){ ptr->context.matchPairName.push_back(name); pathNode.setDetailedName(name); auto iter = matchPairNameToIndex.find(name); if(Q_LIKELY(iter == matchPairNameToIndex.end())){ matchPairNameToIndex.insert(name, matchPairIndex); }else{ diagnostic(Diag::Error_Parser_NameClash_MatchPair, name, iter.value(), matchPairIndex); isValidated = false; } }else{ isValidated = false; } QStringList startList; int matchPairStartMinLength = 0; for(int i = 0, n = mp.startEquivalentSet.size(); i < n; ++i){ const QString& start = mp.startEquivalentSet.at(i); if(Q_UNLIKELY(start.isEmpty())){ diagnostic(Diag::Error_Parser_BadMatchPair_EmptyStartString, i); isValidated = false; }else{ if(matchPairStartMinLength == 0 || matchPairStartMinLength > start.length()){ matchPairStartMinLength = start.length(); } auto iter = matchPairStartToIndex.find(start); if(Q_LIKELY(iter == matchPairStartToIndex.end())){ matchPairStartToIndex.insert(start, i); startList.push_back(start); if(start.length() > longestMatchPairStartStringLength){ longestMatchPairStartStringLength = start.length(); } }else{ diagnostic(Diag::Error_Parser_BadMatchPair_StartStringConflict, start, policy.matchPairs.at(iter.value()).name, iter.value(), name, i); isValidated = false; } } } // for end marks, we only require that they are not redundant QStringList endList; int matchPairEndMinLength = 0; for(int i = 0, n = mp.endEquivalentSet.size(); i < n; ++i){ const QString& end = mp.endEquivalentSet.at(i); if(Q_UNLIKELY(end.isEmpty())){ diagnostic(Diag::Error_Parser_BadMatchPair_EmptyEndString, i); isValidated = false; }else{ if (matchPairEndMinLength == 0 || matchPairEndMinLength > end.length()){ matchPairEndMinLength = end.length(); } int firstIndex = endList.indexOf(end); if(Q_LIKELY(firstIndex == -1)){ endList.push_back(end); }else{ diagnostic(Diag::Error_Parser_BadMatchPair_EndStringDuplicated, matchPairIndex, end, firstIndex, i); isValidated = false; } } } // also send an error if a match pair do not have start mark or end mark if(Q_UNLIKELY(matchPairStartMinLength == 0)){ diagnostic(Diag::Error_Parser_BadMatchPair_NoStartString); isValidated = false; } if(Q_UNLIKELY(matchPairEndMinLength == 0)){ diagnostic(Diag::Error_Parser_BadMatchPair_NoEndString); isValidated = false; } ptr->context.matchPairStarts.push_back(startList); ptr->context.matchPairEnds.push_back(endList); int matchPairScore = matchPairStartMinLength + matchPairEndMinLength; matchPairScoreList.push_back(matchPairScore); } ptr->context.longestMatchPairStartStringLength = longestMatchPairStartStringLength; ptr->context.ignoreList.reserve(policy.ignoreList.size()); for(const QString& ignoreStr : policy.ignoreList){ // remove duplicate or empty ones // maybe generate a warning instead? or other tools can simply drop them if(ignoreStr.isEmpty() || ptr->context.ignoreList.contains(ignoreStr)){ continue; } ptr->context.ignoreList.push_back(ignoreStr); } // checks on exprStartMark and exprEndMark // requirement: // 1. none of the marker can be empty string // 2. none of the marker can be identical to one item in ignore list if(Q_UNLIKELY(policy.exprStartMark.isEmpty())){ diagnostic(Diag::Error_Parser_BadExprMatchPair_EmptyStartString); isValidated = false; }else if(Q_UNLIKELY(ptr->context.ignoreList.contains(policy.exprStartMark))){ diagnostic(Diag::Error_Parser_BadExprMatchPair_StartStringInIgnoreList); isValidated = false; }else{ ptr->context.exprStartMark = policy.exprStartMark; } if(Q_UNLIKELY(policy.exprEndMark.isEmpty())){ diagnostic(Diag::Error_Parser_BadExprMatchPair_EmptyEndString); isValidated = false; }else if(Q_UNLIKELY(ptr->context.ignoreList.contains(policy.exprEndMark))){ diagnostic(Diag::Error_Parser_BadExprMatchPair_EndStringInIgnoreList); isValidated = false; }else{ ptr->context.exprEndMark = policy.exprEndMark; } matchPairStartToIndex.clear(); matchPairNameToIndex.clear(); // start processing ParserNode QHash<QString, int> nodeNameToIndex; for(int i = 0, n = policy.nodes.size(); i < n; ++i){ const ParserNode& src = policy.nodes.at(i); Node dest; DiagnosticPathNode pathNode(diagnostic, tr("Node %1").arg(i)); if(Q_LIKELY(IRNodeType::validateName(diagnostic, src.name))){ pathNode.setDetailedName(src.name); dest.nodeName = src.name; auto iter = nodeNameToIndex.find(src.name); if(Q_LIKELY(iter == nodeNameToIndex.end())){ nodeNameToIndex.insert(src.name, i); }else{ diagnostic(Diag::Error_Parser_NameClash_ParserNode, src.name, iter.value(), i); isValidated = false; } }else{ isValidated = false; } dest.paramName.reserve(src.parameterNameList.size()); for(int i = 0, n = src.parameterNameList.size(); i < n; ++i){ const QString& paramName = src.parameterNameList.at(i); if(Q_LIKELY(IRNodeType::validateName(diagnostic, paramName))){ int index = dest.paramName.indexOf(paramName); if(Q_LIKELY(index == -1)){ dest.paramName.push_back(paramName); }else{ diagnostic(Diag::Error_Parser_NameClash_ParserNodeParameter, paramName, index, i); isValidated = false; } }else{ isValidated = false; } } // validate and convert all patterns dest.patterns.reserve(src.patterns.size()); for(int i = 0, n = src.patterns.size(); i < n; ++i){ const ParserNode::Pattern& srcPattern = src.patterns.at(i); dest.patterns.push_back(Parser::Pattern()); Parser::Pattern& destPattern = dest.patterns.back(); DiagnosticPathNode pathNode(diagnostic, tr("Pattern %1").arg(i)); QHash<QString, int> valueNameToIndex; if(Q_UNLIKELY(!ptr->context.parsePatternString(srcPattern.patternString, destPattern.elements, valueNameToIndex, diagnostic))){ // skip this pattern isValidated = false; continue; } // set priority score int patternScore = srcPattern.priorityScore; if(patternScore == 0){ patternScore = computePatternScore(destPattern.elements, matchPairScoreList); } destPattern.priorityScore = patternScore; QHash<QString, int> overwriteValueNameToIndex; // for each overwrite value, what's the overwrite record index QList<QList<PatternValueSubExpression>> overwriteValueTransformList; QSet<QString> referencedValues; for(int i = 0, n = srcPattern.valueOverwriteList.size(); i < n; ++i){ DiagnosticPathNode pathNode(diagnostic, tr("Overwrite record %1").arg(i)); const auto& record = srcPattern.valueOverwriteList.at(i); const QString& valueName = record.paramName; pathNode.setDetailedName(valueName); auto iter = overwriteValueNameToIndex.find(valueName); if(Q_LIKELY(iter == overwriteValueNameToIndex.end())){ overwriteValueNameToIndex.insert(valueName, i); }else{ diagnostic(Diag::Error_Parser_MultipleOverwrite, valueName, iter.value(), i); isValidated = false; } overwriteValueTransformList.push_back(QList<PatternValueSubExpression>()); if(Q_UNLIKELY(!ptr->context.parseValueTransformString( /* transform */ record.valueExpr, /* result */ overwriteValueTransformList.back(), /* referencedValues */ referencedValues, /* isLocalOnly */ true, /* diagnostic */ diagnostic))){ isValidated = false; } } // check if all ParserNode parameters are either overwritten or defined from pattern // give a warning if a parameter is not set destPattern.valueTransform.reserve(dest.paramName.size()); for(int i = 0, n = dest.paramName.size(); i < n; ++i){ const QString& paramName = dest.paramName.at(i); auto iter_overwrite = overwriteValueNameToIndex.find(paramName); if(iter_overwrite != overwriteValueNameToIndex.end()){ destPattern.valueTransform.push_back(overwriteValueTransformList.at(iter_overwrite.value())); overwriteValueNameToIndex.erase(iter_overwrite); }else{ auto iter_def = valueNameToIndex.find(paramName); if(Q_LIKELY(iter_def != valueNameToIndex.end())){ // append an empty transform destPattern.valueTransform.push_back(QList<PatternValueSubExpression>()); referencedValues.insert(paramName); }else{ diagnostic(Diag::Warn_Parser_MissingInitializer, paramName); // initialize the parameter to an empty string QList<PatternValueSubExpression> dummyExpr; PatternValueSubExpression dummy; dummy.ty = PatternValueSubExpression::OpType::Literal; dummyExpr.push_back(dummy); destPattern.valueTransform.push_back(dummyExpr); } } } Q_ASSERT(destPattern.valueTransform.size() == dest.paramName.size()); // if any defined overwrites or values are not referenced, issue a warning for(auto iter = valueNameToIndex.begin(), iterEnd = valueNameToIndex.end(); iter != iterEnd; ++iter){ if(Q_UNLIKELY(!referencedValues.contains(iter.key()))){ diagnostic(Diag::Warn_Parser_Unused_PatternValue, iter.key(), iter.value()); } } // because we remove used overwrites when they are referenced, overwriteValueNameToIndex should only contain unused ones if(Q_UNLIKELY(!overwriteValueNameToIndex.isEmpty())){ for(auto iter = overwriteValueNameToIndex.begin(), iterEnd = overwriteValueNameToIndex.end(); iter != iterEnd; ++iter){ diagnostic(Diag::Warn_Parser_Unused_Overwrite, iter.key(), iter.value()); } } } // Pattern // childNodeNameList from src / allowedChildNodeIndexList from dest is processed in second pass // earlyExitPatterns dest.earlyExitPatterns.reserve(src.earlyExitPatterns.size()); for(int i = 0, n = src.earlyExitPatterns.size(); i < n; ++i){ DiagnosticPathNode pathNode(diagnostic, tr("EarlyExitPattern %1").arg(i)); dest.earlyExitPatterns.push_back(Parser::Pattern()); Parser::Pattern& p = dest.earlyExitPatterns.back(); QHash<QString,int> dummy; if(Q_UNLIKELY(!ptr->context.parsePatternString(src.earlyExitPatterns.at(i), p.elements, dummy, diagnostic))){ isValidated = false; continue; } } // combineToIRNodeTypeName // if it is empty: // set the dest combineToIRNodeTypeName to IRNode name if there is an IRNode with the same name // otherwise leave it empty // if it is not empty: // verify if the IRNode name exists if(!src.combineToNodeTypeName.isEmpty()){ int irNodeIndex = ir.getNodeTypeIndex(src.combineToNodeTypeName); dest.combineToIRNodeIndex = irNodeIndex; if(Q_UNLIKELY(irNodeIndex == -1)){ diagnostic(Diag::Error_Parser_BadReference_IRNodeName, src.combineToNodeTypeName); isValidated = false; } }else{ dest.combineToIRNodeIndex = ir.getNodeTypeIndex(src.name); } // combinedNodeParams if(dest.combineToIRNodeIndex != -1){ const IRNodeType& irNodeTy = ir.getNodeType(dest.combineToIRNodeIndex); int numParams = irNodeTy.getNumParameter(); DiagnosticPathNode pathNode(diagnostic, tr("Conversion To IR Node")); pathNode.setDetailedName(irNodeTy.getName()); if(src.combinedNodeParams.isEmpty()){ // bind all parameters by name; ParserNode should contain parameter that IRNode expects dest.combineValueTransform.clear(); for(int i = 0; i < numParams; ++i){ const QString& paramName = irNodeTy.getParameterName(i); if(Q_UNLIKELY(!dest.paramName.contains(paramName))){ diagnostic(Diag::Error_Parser_BadConversionToIR_IRParamNotInitialized, paramName); isValidated = false; } } }else{ // there are some overwrite entries dest.combineValueTransform.reserve(numParams); for(int i = 0; i < numParams; ++i){ dest.combineValueTransform.push_back(QList<QList<PatternValueSubExpression>>()); } Q_ASSERT(dest.combineValueTransform.size() == numParams); for(auto iter = src.combinedNodeParams.begin(), iterEnd = src.combinedNodeParams.end(); iter != iterEnd; ++iter){ int paramIndex = irNodeTy.getParameterIndex(iter.key()); if(Q_UNLIKELY(paramIndex == -1)){ diagnostic(Diag::Error_Parser_BadConversionToIR_IRParamNotExist, iter.key()); isValidated = false; }else{ // TODO const QStringList& exprList = iter.value(); auto& destList = dest.combineValueTransform[paramIndex]; destList.reserve(exprList.size()); for(int i = 0, n = exprList.size(); i < n; ++i){ QSet<QString> referencedVals; QList<PatternValueSubExpression> curExpr; if(Q_UNLIKELY(!ptr->context.parseValueTransformString( exprList.at(i), curExpr, referencedVals, false, diagnostic))){ isValidated = false; } destList.push_back(curExpr); // we don't check reference made here yet } } } // finished handling all records in src.combinedNodeParams } // finished handling parameter conversion to IR node } Q_ASSERT(ptr->nodes.size() == i); ptr->nodes.push_back(dest); } // ParserNode // check if root node is good // although checking whether child name reference is good is done below, avoid doing here // would cause the entire tree to be unreachable and therefore will produce too many unhelpful warnings. int rootParserNodeIndex = nodeNameToIndex.value(policy.rootParserNodeName, -1); if(Q_UNLIKELY(rootParserNodeIndex == -1)){ diagnostic(Diag::Error_Parser_BadRoot_BadReferenceByParserNodeName, policy.rootParserNodeName); isValidated = false; }else if(Q_UNLIKELY(ptr->nodes.at(rootParserNodeIndex).combineToIRNodeIndex == -1)){ diagnostic(Diag::Error_Parser_BadRoot_NotConvertingToIR, policy.rootParserNodeName); isValidated = false; } if(!isValidated) return nullptr; // second pass: reorder parser nodes in BFS order Q_ASSERT(ptr->nodes.size() == policy.nodes.size()); std::size_t numNodes = static_cast<std::size_t>(ptr->nodes.size()); decltype(ptr->nodes) tmpNodes; tmpNodes.swap(ptr->nodes); ptr->nodes.reserve(tmpNodes.size()); QQueue<int> rawNodeIndexQueue; // for each raw node index. what's the final index std::vector<int> rawNodeIndexToNewIndex(numNodes, -1); // used to check if there is any reference to a raw node index // also used to check if there is any duplicated reference from the same node // the value is the largest new node index making the reference // -2 for unreferenced node, -1 for root node, >=0 for nodes referenced by another node with that index std::vector<int> nodeReferenceChecker(numNodes, -2); rawNodeIndexQueue.enqueue(rootParserNodeIndex); nodeReferenceChecker.at(static_cast<std::size_t>(rootParserNodeIndex)) = -1;// root node is referenced while(!rawNodeIndexQueue.empty()){ int rawIndex = rawNodeIndexQueue.dequeue(); const Node& src = tmpNodes.at(rawIndex); int cookedIndex = ptr->nodes.size(); rawNodeIndexToNewIndex.at(static_cast<std::size_t>(rawIndex))= cookedIndex; ptr->nodes.push_back(src); const ParserNode& srcNode = policy.nodes.at(rawIndex); Node& dest = ptr->nodes.back(); // we will populate child node index here // use the raw index first, then use another pass to correct them afterwards dest.allowedChildNodeIndexList.reserve(srcNode.childNodeNameList.size()); for(int i = 0, n = srcNode.childNodeNameList.size(); i < n; ++i){ const QString& childName = srcNode.childNodeNameList.at(i); int childRawIndex = nodeNameToIndex.value(childName, -1); if(Q_UNLIKELY(childRawIndex == -1)){ diagnostic(Diag::Error_Parser_BadTree_BadChildNodeReference, src.nodeName, childName); isValidated = false; }else{ std::size_t castedChildRawIndex = static_cast<std::size_t>(childRawIndex); int oldval = nodeReferenceChecker.at(castedChildRawIndex); nodeReferenceChecker.at(castedChildRawIndex) = rawIndex; if(Q_UNLIKELY(oldval == rawIndex)){ // duplicated reference diagnostic(Diag::Warn_Parser_DuplicatedReference_ChildParserNode, src.nodeName, childName); }else{ dest.allowedChildNodeIndexList.push_back(childRawIndex); } // add to queue if this node is not referenced before if(oldval == -2){ rawNodeIndexQueue.enqueue(childRawIndex); } } } } // warning on all unreferenced nodes if(Q_UNLIKELY(ptr->nodes.size() != policy.nodes.size())){ int missingCount = 0; for(std::size_t i = 0; i < numNodes; ++i){ // consistency check Q_ASSERT((nodeReferenceChecker.at(i) == -2) == (rawNodeIndexToNewIndex.at(i) == -1)); if(nodeReferenceChecker.at(i) == -2){ missingCount += 1; diagnostic(Diag::Warn_Parser_UnreachableNode, policy.nodes.at(static_cast<int>(i)).name); } } Q_ASSERT(missingCount + ptr->nodes.size() == policy.nodes.size()); } // update all indices to the new one for(auto& node : ptr->nodes){ for(int& childIndex : node.allowedChildNodeIndexList){ childIndex = rawNodeIndexToNewIndex.at(static_cast<std::size_t>(childIndex)); Q_ASSERT(childIndex >= 0); } } // done! return ptr.release(); } int Parser::computePatternScore(const QList<SubPattern>& pattern, const QList<int>& matchPairScore) { // score computation rule: // if we have a literal: score is incremented by 2 * (length of literal) // if we have a match pair, then the score is incremented by the score from matchPairScore // (which should be (minimum length of match pair start + minimum length of match pair end)) // if we have an Auto, the score is incremented by 1 // if we have a regex, the score is incremented by length of regex string int score = 0; for(const SubPattern& p : pattern){ switch(p.ty){ case SubPatternType::Literal:{ score += p.literalData.str.length() * 2; }break; case SubPatternType::MatchPair:{ score += matchPairScore.at(p.matchPairData.matchPairIndex); }break; case SubPatternType::Regex:{ score += p.regexData.regex.pattern().length(); }break; case SubPatternType::Auto:{ score += 1; }break; } } return score; } bool Parser::ParseContext::parsePatternString( const QString& pattern, QList<SubPattern> &result, QHash<QString, int> &valueNameToIndex, DiagnosticEmitterBase& diagnostic) { QStringRef view(&pattern); // keep a copy of first patterns we put int startIndex = result.size(); struct MatchPairFrame{ int index; QStringRef startMarkRef; // used for error reporting }; QList<MatchPairFrame> matchPairStack;// used to report error if the pattern don't have matching match pairs // we will do some fixup if this is true QStringRef lastAutoSubPatternStr; bool isLastPatternAutoNeedFixup = false; while(!view.isEmpty()){ // ignore strings from ignoreList first int ignoredStrLength = removeLeadingIgnoredString(view); if(ignoredStrLength != 0){ if(isLastPatternAutoNeedFixup){ //an auto pattern followed by ignore string Q_ASSERT(!result.isEmpty()); auto& p = result.back(); Q_ASSERT(p.ty == SubPatternType::Auto); p.autoData.isTerminateByIgnoredString = true; if(Q_UNLIKELY(p.autoData.nextSubPatternIncludeLength != 0)){ StringDiagnosticRecord d; d.str = pattern; // info interval is the ignored string d.infoStart = view.position() - ignoredStrLength; d.infoEnd = view.position(); // error interval is the auto mattern d.errorStart = lastAutoSubPatternStr.position(); d.errorEnd = lastAutoSubPatternStr.position() + lastAutoSubPatternStr.length(); diagnostic(Diag::Error_Parser_BadPattern_Expr_InvalidNextPatternForInclusion, d); return false; } } } isLastPatternAutoNeedFixup = false; if(view.isEmpty()) break; if(view.startsWith(exprStartMark)){ // assume exprStartMark = "<" and exprEndMark = ">" // regex: something like <[regex]"**(...)**"> // literal: something like <"**(...)**"> // UpToTerminator: anything left QStringRef bodyStart = view.mid(exprStartMark.length()); QStringRef engineText; QStringRef body; bool isEngineSpecified = false; bool isReferenceExpr = false; if(bodyStart.startsWith('[')){ int endIndex = bodyStart.indexOf(']',1); if(Q_UNLIKELY(endIndex == -1)){ StringDiagnosticRecord d; d.str = pattern; // info interval is everything after exprStartMark d.infoStart = view.position(); d.infoEnd = pattern.length(); // error interval is '[' d.errorStart = bodyStart.position(); d.errorEnd = bodyStart.position()+1; diagnostic(Diag::Error_Parser_BadPattern_Expr_MissingEngineNameEndMark, d); return false; } engineText = bodyStart.mid(1,endIndex-1); bodyStart = bodyStart.mid(endIndex+1); isEngineSpecified = true; } if(Q_UNLIKELY(bodyStart.isEmpty())){ StringDiagnosticRecord d; d.str = pattern; // info interval is everything after exprStartMark d.infoStart = view.position(); d.infoEnd = pattern.length(); // error interval is exprStartMark d.errorStart = view.position(); d.errorEnd = view.position()+1; diagnostic(Diag::Error_Parser_BadPattern_Expr_ExpectingExpressionContent, d); return false; } bool isRawStringLiteral = bodyStart.startsWith('('); bool isDirectQuotedStringLiteral = bodyStart.startsWith('"'); if(isRawStringLiteral || isDirectQuotedStringLiteral){ int tailStartIndex = -1; if(isRawStringLiteral){ // raw string literal style int startQuoteIndex = bodyStart.indexOf('"', 1); if(Q_UNLIKELY(startQuoteIndex == -1)){ StringDiagnosticRecord d; d.str = pattern; // info interval is everything after exprStartMark d.infoStart = view.position(); d.infoEnd = pattern.length(); // error interval is '(' d.errorStart = bodyStart.position(); d.errorEnd = bodyStart.position()+1; diagnostic(Diag::Error_Parser_BadPattern_Expr_RawStringMissingQuoteStart, d); return false; } QStringRef delimitor = bodyStart.mid(1, startQuoteIndex-1); QStringRef quotedContentStart = bodyStart.mid(startQuoteIndex+1); QString expectedTerminator; Q_ASSERT(delimitor.length() == startQuoteIndex-1); expectedTerminator.reserve(startQuoteIndex+1); expectedTerminator.push_back('"'); expectedTerminator.append(delimitor); expectedTerminator.push_back(')'); int contentLength = quotedContentStart.indexOf(expectedTerminator); if(Q_UNLIKELY(contentLength == -1)){ StringDiagnosticRecord d; d.str = pattern; // info interval is everything after exprStartMark d.infoStart = view.position(); d.infoEnd = pattern.length(); // error interval is the delimitor with '(' and '"' d.errorStart = bodyStart.position(); d.errorEnd = bodyStart.position() + startQuoteIndex + 1; diagnostic(Diag::Error_Parser_BadPattern_Expr_UnterminatedQuote, d); return false; } body = quotedContentStart.left(contentLength); tailStartIndex = 2*(startQuoteIndex+1) + contentLength; }else{ // direct quote; use '"' as terminator int bodyEndIndex = bodyStart.indexOf('"', 1); if(Q_UNLIKELY(bodyEndIndex == -1)){ StringDiagnosticRecord d; d.str = pattern; // info interval is everything after exprStartMark d.infoStart = view.position(); d.infoEnd = pattern.length(); // error interval is '"' d.errorStart = bodyStart.position(); d.errorEnd = bodyStart.position()+1; diagnostic(Diag::Error_Parser_BadPattern_Expr_UnterminatedQuote, d); return false; } body = bodyStart.mid(1, bodyEndIndex-1); tailStartIndex = bodyEndIndex + 1; } // make sure the string is not empty if(Q_UNLIKELY(body.isEmpty())){ StringDiagnosticRecord d; d.str = pattern; // info interval is from the exprStartMark to end of quote d.infoStart = view.position(); d.infoEnd = bodyStart.position() + tailStartIndex; // error interval is the quote d.errorStart = bodyStart.position(); d.errorEnd = bodyStart.position() + tailStartIndex; diagnostic(Diag::Error_Parser_BadPattern_Expr_EmptyBody, d); return false; } // make sure there is no garbage before the end mark and after the string QStringRef tail = bodyStart.mid(tailStartIndex); int endMarkIndex = tail.indexOf(exprEndMark); if(Q_UNLIKELY(endMarkIndex == -1)){ // no end marker StringDiagnosticRecord d; d.str = pattern; // info interval is everything after exprStartMark d.infoStart = view.position(); d.infoEnd = pattern.length(); // error interval is everything starting from the tail d.errorStart = tail.position(); d.errorEnd = pattern.length(); diagnostic(Diag::Error_Parser_BadPattern_Expr_UnterminatedExpr, d); return false; }else if(Q_UNLIKELY(endMarkIndex != 0)){ StringDiagnosticRecord d; d.str = pattern; // info interval is the entire expr d.infoStart = view.position(); d.infoEnd = tail.position() + endMarkIndex + exprEndMark.length(); // error interval is the garbage at end d.errorStart = tail.position(); d.errorEnd = tail.position() + endMarkIndex; diagnostic(Diag::Error_Parser_BadPattern_Expr_GarbageAtEnd, d); return false; } // the tail looks good // start to validate this expression SubPattern expr; int subPatternIndex = result.size(); if(isEngineSpecified){ if(engineText == "regex"){ expr.ty = SubPatternType::Regex; expr.regexData.regex.setPattern(body.toString()); if(Q_UNLIKELY(!expr.regexData.regex.isValid())){ StringDiagnosticRecord d; d.str = pattern; // info interval is the regular expression string d.infoStart = body.position(); d.infoEnd = body.position() + body.length(); // error interval is the character marked by patternErrorOffset d.errorStart = body.position() + expr.regexData.regex.patternErrorOffset(); d.errorEnd = d.errorStart + 1; diagnostic(Diag::Error_Parser_BadPattern_Expr_BadRegex, d, expr.regexData.regex.errorString()); return false; } // fill in all named captures made by this regex for(const QString& capture : expr.regexData.regex.namedCaptureGroups()){ if(capture.isEmpty()) continue; auto iter = valueNameToIndex.find(capture); if(Q_UNLIKELY(iter != valueNameToIndex.end())){ diagnostic(Diag::Error_Parser_BadPattern_Expr_DuplicatedDefinition, capture, iter.value(), subPatternIndex); return false; } valueNameToIndex.insert(capture, subPatternIndex); } }else{ StringDiagnosticRecord d; d.str = pattern; // info interval is the entire expr d.infoStart = view.position(); d.infoEnd = tail.position() + endMarkIndex + exprEndMark.length(); // error interval is the engine specifier d.errorStart = engineText.position() - 1; d.errorEnd = engineText.position() + engineText.length() + 1; diagnostic(Diag::Error_Parser_BadPattern_Expr_UnrecognizedEngine, d); return false; } }else{ // literal string expr.ty = SubPatternType::Literal; expr.literalData.str = body.toString(); } // we successfully consumed the expression view = tail.mid(exprEndMark.length()); result.push_back(expr); }else{ // no string literal find; probably a reference expression if(isEngineSpecified){ // if there is an engine specifier, we must use a string literal after it StringDiagnosticRecord d; d.str = pattern; // info interval is the engine text with [] d.infoStart = engineText.position()-1; d.infoEnd = engineText.position() + engineText.length() + 1; // error interval is the character after ']' // we know there is a character there, since we check bodyStart.isEmpty() first d.errorStart = d.infoEnd; d.errorEnd = d.infoEnd + 1; diagnostic(Diag::Error_Parser_BadPattern_Expr_NoRawLiteralAfterEngineSpecifier, d); return false; } isReferenceExpr = true; // direct search on exprEndMark int endMarkIndex = bodyStart.indexOf(exprEndMark); if(Q_UNLIKELY(endMarkIndex == -1)){ StringDiagnosticRecord d; d.str = pattern; // info interval is everything after exprStartMark d.infoStart = view.position(); d.infoEnd = pattern.length(); // error interval is the start mark d.errorStart = view.position(); d.errorEnd = bodyStart.position(); diagnostic(Diag::Error_Parser_BadPattern_Expr_UnterminatedExpr, d); return false; } QStringRef exprFullString = view.left(exprStartMark.length() + endMarkIndex + exprEndMark.length()); // just for error messages QStringRef referencedName = bodyStart.left(endMarkIndex); bool isIncludeSuccessiveTerminator = referencedName.endsWith('*'); if(isIncludeSuccessiveTerminator){ referencedName.chop(1); } bool isIncludeTerminator = referencedName.endsWith('+'); if(isIncludeTerminator){ referencedName.chop(1); } // we require +* at the end for including all successive terminator if(Q_UNLIKELY(isIncludeSuccessiveTerminator && !isIncludeTerminator)){ StringDiagnosticRecord d; d.str = pattern; // info interval is the entire expression d.infoStart = exprFullString.position(); d.infoEnd = exprFullString.position() + exprFullString.length(); // error interval is the terminator Inclusion specifier d.errorStart = referencedName.position() + referencedName.length(); d.errorEnd = d.errorStart + (isIncludeSuccessiveTerminator? 1:0) + (isIncludeTerminator? 1:0); // basically errorStart + 1 diagnostic(Diag::Error_Parser_BadPattern_Expr_BadTerminatorInclusionSpecifier, d); return false; } // check if the name is good QString finalName = referencedName.toString(); // the name can be empty, if the match result is not used if(!finalName.isEmpty()){ if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, finalName))){ StringDiagnosticRecord d; d.str = pattern; // info interval is the entire expression d.infoStart = exprFullString.position(); d.infoEnd = exprFullString.position() + exprFullString.length(); // error interval is the name reference d.errorStart = referencedName.position(); d.errorEnd = referencedName.position() + referencedName.length(); diagnostic(Diag::Error_Parser_BadPattern_Expr_BadNameForReference, d); return false; } } SubPattern expr; expr.ty = SubPatternType::Auto; expr.autoData.valueName = finalName; expr.autoData.isTerminateByIgnoredString = false;// we will correct this in second pass expr.autoData.nextSubPatternIncludeLength = (isIncludeTerminator? (isIncludeSuccessiveTerminator? -1: 1): 0); // if the last sub pattern is also an auto sub pattern, make it terminate by ignored string if(!result.isEmpty()){ auto& p = result.back(); if(p.ty == SubPatternType::Auto){ p.autoData.isTerminateByIgnoredString = true; if(Q_UNLIKELY(p.autoData.nextSubPatternIncludeLength != 0)){ StringDiagnosticRecord d; d.str = pattern; // info interval is the current sub pattern d.infoStart = exprFullString.position(); d.infoEnd = exprFullString.position() + exprFullString.length(); // error interval is the auto mattern d.errorStart = lastAutoSubPatternStr.position(); d.errorEnd = lastAutoSubPatternStr.position() + lastAutoSubPatternStr.length(); diagnostic(Diag::Error_Parser_BadPattern_Expr_InvalidNextPatternForInclusion, d); return false; } } } // we successfully consumed the expression isLastPatternAutoNeedFixup = true; lastAutoSubPatternStr = exprFullString; { int subPatternIndex = result.size(); auto iter = valueNameToIndex.find(finalName); if(Q_UNLIKELY(iter != valueNameToIndex.end())){ diagnostic(Diag::Error_Parser_BadPattern_Expr_DuplicatedDefinition, finalName, iter.value(), subPatternIndex); return false; } valueNameToIndex.insert(finalName, subPatternIndex); } view = view.mid(exprStartMark.length() + endMarkIndex + exprEndMark.length()); result.push_back(expr); } // done processing cases with exprStartMark }else{ // start of a literal, or a match pair marker bool isMatchPairFound = false; if(!matchPairStack.isEmpty()){ // check if it is the matching end int index = matchPairStack.back().index; int maxLen = 0; for(const QString& endMark : matchPairEnds.at(index)){ if(view.startsWith(endMark)){ if(maxLen < endMark.length()){ maxLen = endMark.length(); } } } if(maxLen > 0){ matchPairStack.pop_back(); view = view.mid(maxLen); SubPattern expr; expr.ty = SubPatternType::MatchPair; expr.matchPairData.matchPairIndex = index; expr.matchPairData.isStart = false; result.push_back(expr); isMatchPairFound = true; } } if(!isMatchPairFound){ // check if we are starting a scope int maxLen = 0; int matchPairIndex = -1; for(int i = 0, n = matchPairStarts.size(); i < n; ++i){ for(const QString& startMark : matchPairStarts.at(i)){ if(view.startsWith(startMark)){ if(maxLen < startMark.length()){ maxLen = startMark.length(); matchPairIndex = i; } } } } if(matchPairIndex >= 0){ MatchPairFrame f; f.index = matchPairIndex; f.startMarkRef = view.left(maxLen); matchPairStack.push_back(f); view = view.mid(maxLen); SubPattern expr; expr.ty = SubPatternType::MatchPair; expr.matchPairData.matchPairIndex = matchPairIndex; expr.matchPairData.isStart = true; result.push_back(expr); isMatchPairFound = true; }else{ // check if this is a match pair end without start mark // if yes then report an error int endMaxLen = 0; for(int i = 0, n = matchPairEnds.size(); i < n; ++i){ for(const QString& endMark : matchPairEnds.at(i)){ if(Q_UNLIKELY(view.startsWith(endMark))){ if(endMaxLen < endMark.length()){ endMaxLen = endMark.length(); } } } } if(Q_UNLIKELY(endMaxLen > 0)){ QStringRef endMarkRef = view.left(endMaxLen); StringDiagnosticRecord d; d.str = pattern; // both interval is the end marker string d.errorStart = d.infoStart = endMarkRef.position(); d.errorEnd = d.infoEnd = endMarkRef.position() + endMarkRef.length(); diagnostic(Diag::Error_Parser_BadPattern_Expr_UnexpectedMatchPairEnd, d); return false; } // now we confirm that we are starting a literal // keep extracting characters until a start indicator appears QStringRef literalStart = view; while(true){ view = view.mid(1); if(view.isEmpty()) break; int removedLen = removeLeadingIgnoredString(view); // finding a string from ignored list terminates current implicit string literal if(removedLen > 0) break; if(view.startsWith(exprStartMark)) break; bool isMatchPairFound = false; for(int i = 0, n = matchPairStarts.size(); i < n; ++i){ for(const QString& mark : matchPairStarts.at(i)){ if(view.startsWith(mark)){ isMatchPairFound = true; break; } } if(isMatchPairFound) break; } if(isMatchPairFound) break; for(int i = 0, n = matchPairEnds.size(); i < n; ++i){ for(const QString& mark : matchPairEnds.at(i)){ if(view.startsWith(mark)){ isMatchPairFound = true; break; } } if(isMatchPairFound) break; } if(isMatchPairFound) break; } SubPattern expr; expr.ty = SubPatternType::Literal; expr.literalData.str = literalStart.chopped(view.length()).toString(); result.push_back(expr); } // done cases not ending a match pair enclosure } // done for match pair and literals } } // report error if we don't have matching match pairs if(Q_UNLIKELY(!matchPairStack.isEmpty())){ StringDiagnosticRecord d; d.str = pattern; for(int i = 0, n = matchPairStack.size(); i < n; ++i){ const auto& f = matchPairStack.at(i); d.errorStart = d.infoStart = f.startMarkRef.position(); d.errorEnd = d.infoEnd = f.startMarkRef.position() + f.startMarkRef.length(); diagnostic(Diag::Error_Parser_BadPattern_UnmatchedMatchPairStart, d); } return false; } // no empty pattern accepted if(Q_UNLIKELY(result.size() == startIndex)){ diagnostic(Diag::Error_Parser_BadPattern_EmptyPattern); return false; } // correct the last Auto type sub patterns { auto& p = result.back(); if(p.ty == SubPatternType::Auto){ // make sure we do not set inclusion flag if(Q_UNLIKELY(p.autoData.nextSubPatternIncludeLength != 0)){ StringDiagnosticRecord d; d.str = pattern; // info interval is everything after the auto sub pattern d.infoStart = lastAutoSubPatternStr.position() + lastAutoSubPatternStr.length(); d.infoEnd = pattern.length(); // error interval is the auto mattern d.errorStart = lastAutoSubPatternStr.position(); d.errorEnd = lastAutoSubPatternStr.position() + lastAutoSubPatternStr.length(); diagnostic(Diag::Error_Parser_BadPattern_Expr_InvalidNextPatternForInclusion, d); return false; } p.autoData.isTerminateByIgnoredString = true; } } return true; } bool Parser::ParseContext::parseValueTransformString(const QString& transform, QList<PatternValueSubExpression> &result, QSet<QString> &referencedValues, bool isLocalOnly, DiagnosticEmitterBase &diagnostic) { auto helper_getEnclosedLiteral = [&](QStringRef text, QStringRef& result, int faultInfoStartOffset)->int{ bool isRawStringLiteral = text.startsWith('('); bool isDirectQuotedStringLiteral = text.startsWith('"'); if(Q_UNLIKELY(!isRawStringLiteral && !isDirectQuotedStringLiteral)){ // nothing in expectation StringDiagnosticRecord d; d.str = transform; // info interval is from the offset given by faultInfoStartOffset to first character d.infoStart = faultInfoStartOffset + text.position(); d.infoEnd = text.position() + 1; // error interval is the first character of text d.errorStart = text.position(); d.errorEnd = text.position() + 1; diagnostic(Diag::Error_Parser_BadValueTransform_ExpectingLiteralExpr, d); return -1; } int nextDoubleQuoteIndex = text.indexOf('"',1); if(isDirectQuotedStringLiteral){ if(Q_UNLIKELY(nextDoubleQuoteIndex == -1)){ // unterminated quote StringDiagnosticRecord d; d.str = transform; // info interval is from the offset given by faultInfoStartOffset to first character d.infoStart = faultInfoStartOffset + text.position(); d.infoEnd = text.position() + 1; // error interval is the first character of text d.errorStart = text.position(); d.errorEnd = text.position() + 1; diagnostic(Diag::Error_Parser_BadValueTransform_UnterminatedQuote, d); return -1; } result = text.mid(1).left(nextDoubleQuoteIndex-1); return nextDoubleQuoteIndex+1; } // raw string literal style quote if(Q_UNLIKELY(nextDoubleQuoteIndex == -1)){ // raw string missing starting quote StringDiagnosticRecord d; d.str = transform; // info interval is from the offset given by faultInfoStartOffset to first character d.infoStart = faultInfoStartOffset + text.position(); d.infoEnd = text.position() + 1; // error interval is the first character of text d.errorStart = text.position(); d.errorEnd = text.position() + 1; diagnostic(Diag::Error_Parser_BadValueTransform_RawStringMissingQuoteStart, d); return -1; } QStringRef rawStringStartMark = text.left(nextDoubleQuoteIndex+1); QString rawStringEndMark; rawStringEndMark.reserve(rawStringStartMark.size()); rawStringEndMark.append('"'); rawStringEndMark.append(rawStringStartMark.mid(1).chopped(1)); rawStringEndMark.append(')'); int endIndex = text.indexOf(rawStringEndMark, nextDoubleQuoteIndex+1); if(Q_UNLIKELY(endIndex == -1)){ // unterminated quote StringDiagnosticRecord d; d.str = transform; // info interval is from the offset given by faultInfoStartOffset to end of rawStringStartMark d.infoStart = faultInfoStartOffset + text.position(); d.infoEnd = rawStringStartMark.position() + rawStringStartMark.length(); // error interval is rawStringStartMark d.errorStart = rawStringStartMark.position(); d.errorEnd = rawStringStartMark.position() + rawStringStartMark.length(); diagnostic(Diag::Error_Parser_BadValueTransform_UnterminatedQuote, d); return -1; } result = text.left(endIndex).mid(rawStringStartMark.length()); return endIndex + rawStringEndMark.length(); }; QStringRef text(&transform); while(!text.isEmpty()){ int index = text.indexOf(exprStartMark); if(index == -1){ // no more special patterns to handle PatternValueSubExpression expr; expr.ty = PatternValueSubExpression::OpType::Literal; expr.literalData.str = text.toString(); result.push_back(expr); return true; } if(index != 0){ QStringRef literal = text.left(index); // we will start a special part // add this literal to output first PatternValueSubExpression expr; expr.ty = PatternValueSubExpression::OpType::Literal; expr.literalData.str = literal.toString(); result.push_back(expr); text = text.mid(index); } // now we need to deal with a special block // skip the start mark first Q_ASSERT(text.startsWith(exprStartMark)); QStringRef bodyStart = text.mid(exprStartMark.length()); bool isRawStringLiteral = bodyStart.startsWith('('); bool isDirectQuotedStringLiteral = bodyStart.startsWith('"'); if(isRawStringLiteral || isDirectQuotedStringLiteral){ QStringRef literal; int advanceDist = helper_getEnclosedLiteral(bodyStart, literal, -exprStartMark.length()); if(advanceDist == -1){ return false; } QStringRef textAfterString = bodyStart.mid(advanceDist); if(Q_UNLIKELY(textAfterString.isEmpty())){ // unterminated expr StringDiagnosticRecord d; d.str = transform; // info interval is from start mark to position of textAfterString d.infoStart = text.position(); d.infoEnd = textAfterString.position(); // error interval is the start mark d.errorStart = text.position(); d.errorEnd = text.position() + exprStartMark.length(); diagnostic(Diag::Error_Parser_BadValueTransform_UnterminatedExpr, d); return false; }else if(Q_UNLIKELY(!textAfterString.startsWith(exprEndMark))){ // garbage at end StringDiagnosticRecord d; d.str = transform; // info interval is from start mark to position of textAfterString d.infoStart = text.position(); d.infoEnd = textAfterString.position(); // error interval is the first character of textAfterString d.errorStart = textAfterString.position(); d.errorEnd = textAfterString.position()+1; diagnostic(Diag::Error_Parser_BadValueTransform_GarbageAtExprEnd, d); return false; } PatternValueSubExpression expr; expr.ty = PatternValueSubExpression::OpType::Literal; expr.literalData.str = literal.toString(); result.push_back(expr); text = textAfterString.mid(exprEndMark.length()); }else{ // direct search for end mark, speculatively for extern reference int endMarkIndex = bodyStart.indexOf(exprEndMark); if(Q_UNLIKELY(endMarkIndex == -1)){ StringDiagnosticRecord d; d.str = transform; // info interval is everything after start mark d.infoStart = text.position(); d.infoEnd = transform.length(); // error interval is exprStartMark d.errorStart = text.position(); d.errorEnd = bodyStart.position(); diagnostic(Diag::Error_Parser_BadValueTransform_UnterminatedExpr, d); return false; } QStringRef refVal = bodyStart.left(endMarkIndex); bool isLocalReference = !refVal.contains('.'); if(Q_UNLIKELY(!isLocalReference && isLocalOnly)){ StringDiagnosticRecord d; d.str = transform; // info interval is everything inside expr d.infoStart = text.position(); d.infoEnd = bodyStart.position() + endMarkIndex + exprEndMark.length(); // error interval is refVal d.errorStart = refVal.position(); d.errorEnd = refVal.position() + refVal.length(); diagnostic(Diag::Error_Parser_BadValueTransform_NonLocalAccessInLocalOnlyEnv, d); return false; } PatternValueSubExpression expr; if(isLocalReference){ expr.ty = PatternValueSubExpression::OpType::LocalReference; expr.localReferenceData.valueName = refVal.toString(); if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, expr.localReferenceData.valueName))){ StringDiagnosticRecord d; d.str = transform; // info interval is everything inside expr d.infoStart = text.position(); d.infoEnd = bodyStart.position() + endMarkIndex + exprEndMark.length(); // error interval is refVal d.errorStart = refVal.position(); d.errorEnd = refVal.position() + refVal.length(); diagnostic(Diag::Error_Parser_BadValueTransform_InvalidNameForReference, d); return false; } referencedValues.insert(expr.localReferenceData.valueName); text = bodyStart.mid(endMarkIndex + exprEndMark.length()); }else{ expr.ty = PatternValueSubExpression::OpType::ExternReference; // because we allow string literals in search expression, the endMarkIndex can be invalid // therefore for ExternReference we need to go step by step; parse all node traversal steps then value name QList<PatternValueSubExpression::ExternReferenceData::NodeTraverseStep>& stepResult = expr.externReferenceData.nodeTraversal; QStringRef traverseDistLeft = bodyStart; if(traverseDistLeft.startsWith('/')){ expr.externReferenceData.isTraverseStartFromRoot = true; traverseDistLeft = traverseDistLeft.mid(1); } if(Q_UNLIKELY(traverseDistLeft.isEmpty())){ StringDiagnosticRecord d; d.str = transform; // info interval is bodyStart to current position d.infoStart = bodyStart.position(); d.infoEnd = traverseDistLeft.position(); // error interval is the last character we just consumed d.errorStart = traverseDistLeft.position() - 1; d.errorEnd = traverseDistLeft.position(); diagnostic(Diag::Error_Parser_BadValueTransform_ExpectTraverseExpr, d); return false; } while(true){ Q_ASSERT(!traverseDistLeft.isEmpty()); int stepStart = traverseDistLeft.position(); // for error reporting PatternValueSubExpression::ExternReferenceData::NodeTraverseStep s; if(traverseDistLeft.startsWith('/')){ traverseDistLeft = traverseDistLeft.mid(1); continue; } if(traverseDistLeft.startsWith("./")){ traverseDistLeft = traverseDistLeft.mid(2); continue; } if(traverseDistLeft.startsWith("../")){ s.ty = PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::Parent; stepResult.push_back(s); traverseDistLeft = traverseDistLeft.mid(3); continue; } // everything else is for going to child int openSquareBracketIndex = traverseDistLeft.indexOf('['); if(Q_UNLIKELY(openSquareBracketIndex == -1)){ StringDiagnosticRecord d; d.str = transform; // info interval is everything from bodyStart to current position d.infoStart = bodyStart.position(); d.infoEnd = bodyStart.position()+ bodyStart.length(); // error interval is everything in traverseDistLeft (basically this step) d.errorStart = traverseDistLeft.position(); d.errorEnd = traverseDistLeft.position() + traverseDistLeft.length(); diagnostic(Diag::Error_Parser_BadValueTransform_MissingChildSearchExpr, d); return false; } bool isChildNameProvided = (openSquareBracketIndex > 0); if(isChildNameProvided){ // we have a child name field QStringRef childName = traverseDistLeft.left(openSquareBracketIndex); s.childParserNodeName = childName.toString(); if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, s.childParserNodeName))){ StringDiagnosticRecord d; d.str = transform; // info interval is everything from bodyStart to current position d.infoStart = bodyStart.position(); d.infoEnd = childName.position() + childName.length(); // error interval is the child node name d.errorStart = childName.position(); d.errorEnd = childName.position() + childName.length(); diagnostic(Diag::Error_Parser_BadValueTransform_InvalidNameForReference, d); return false; } traverseDistLeft = traverseDistLeft.mid(openSquareBracketIndex); } traverseDistLeft = traverseDistLeft.mid(1); // skip '[' int closeSquareBracketIndex = traverseDistLeft.indexOf(']'); if(Q_UNLIKELY(closeSquareBracketIndex == -1)){ StringDiagnosticRecord d; d.str = transform; // info interval is everything from bodyStart to current position d.infoStart = bodyStart.position(); d.infoEnd = traverseDistLeft.position(); // error interval is the '[' d.errorStart = stepStart + openSquareBracketIndex; d.errorEnd = stepStart + openSquareBracketIndex + 1; Q_ASSERT(d.infoEnd == d.errorEnd); diagnostic(Diag::Error_Parser_BadValueTransform_UnterminatedChildSearchExpr, d); return false; } // no matter whether we have a literal with ']' included, if we have a key based search, // the "==" string must appear before ']' because the only thing before "==" is the key parameter name QStringRef possibleSearchExprEnclosure = traverseDistLeft.left(closeSquareBracketIndex); int keyEndIndex = possibleSearchExprEnclosure.indexOf("=="); if(keyEndIndex == -1){ // number (index/offset) based search if(isChildNameProvided){ s.ty = PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::ChildByTypeAndOrder; }else{ s.ty = PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::AnyChildByOrder; } QStringRef num = possibleSearchExprEnclosure; s.ioSearchData.isNumIndexInsteadofOffset = !(num.startsWith('+') || num.startsWith('-')); bool isNumberGood = false; s.ioSearchData.lookupNum = num.toInt(&isNumberGood); if(Q_UNLIKELY(!isNumberGood)){ StringDiagnosticRecord d; d.str = transform; // info interval is everything from stepStart to current position d.infoStart = stepStart; d.infoEnd = num.position() + num.length(); // error interval is the number expression d.errorStart = num.position(); d.errorEnd = num.position() + num.length(); diagnostic(Diag::Error_Parser_BadValueTransform_BadNumberExpr, d); return false; } traverseDistLeft = traverseDistLeft.mid(closeSquareBracketIndex+1); }else{ // key value based search // possibleSearchExprEnclosure can be invalid s.ty = PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::ChildByTypeFromLookup; QStringRef keyStr = traverseDistLeft.left(keyEndIndex); s.kvSearchData.key = keyStr.toString(); if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, s.kvSearchData.key))){ StringDiagnosticRecord d; d.str = transform; // info interval is [<key>== d.infoStart = traverseDistLeft.position()-1; d.infoEnd = traverseDistLeft.position()+s.kvSearchData.key.length()+2; // error interval is keyStr d.errorStart = keyStr.position(); d.errorEnd = keyStr.position() + keyStr.length(); diagnostic(Diag::Error_Parser_BadValueTransform_InvalidNameForReference, d); return false; } traverseDistLeft = traverseDistLeft.mid(keyEndIndex+2); // skip "==" QStringRef valueStr; int advanceDist = helper_getEnclosedLiteral(traverseDistLeft, valueStr, stepStart - traverseDistLeft.position()); if(Q_UNLIKELY(advanceDist == -1)){ return false; } s.kvSearchData.value = valueStr.toString(); traverseDistLeft = traverseDistLeft.mid(advanceDist); } stepResult.push_back(s); // consume the '/' after this step, or '.' if we just finished the last level of traversal if(Q_UNLIKELY(traverseDistLeft.isEmpty())){ StringDiagnosticRecord d; d.str = transform; // info interval is everything starting from bodyStart d.infoStart = bodyStart.position(); d.infoEnd = traverseDistLeft.position() + traverseDistLeft.length(); // error interval is the expression start mark d.errorStart = bodyStart.position() - exprStartMark.length(); d.errorEnd = bodyStart.position(); diagnostic(Diag::Error_Parser_BadValueTransform_UnterminatedExpr, d); return false; } if(traverseDistLeft.startsWith('.')){ // node traverse complete traverseDistLeft = traverseDistLeft.mid(1); // consume '.' break; }else if(Q_UNLIKELY(!traverseDistLeft.startsWith('/'))){ StringDiagnosticRecord d; d.str = transform; // info interval is stepStart to first character if traverseDistLeft d.infoStart = stepStart; d.infoEnd = traverseDistLeft.position()+1; // error interval is the first character of traverseDistLeft d.errorStart = traverseDistLeft.position(); d.errorEnd = traverseDistLeft.position()+1; diagnostic(Diag::Error_Parser_BadValueTransform_Traverse_ExpectSlashOrDot, d); return false; } traverseDistLeft = traverseDistLeft.mid(1); // consume '/' if(Q_UNLIKELY(traverseDistLeft.isEmpty())){ StringDiagnosticRecord d; d.str = transform; // info interval is bodyStart to current position d.infoStart = bodyStart.position(); d.infoEnd = traverseDistLeft.position(); // error interval is the last character we just consumed d.errorStart = traverseDistLeft.position() - 1; d.errorEnd = traverseDistLeft.position(); diagnostic(Diag::Error_Parser_BadValueTransform_ExpectTraverseExpr, d); return false; } } // node traversal expression complete // now everything left in traverseDistLeft are beginning of value reference int realEndMarkIndex = traverseDistLeft.indexOf(exprEndMark); if(Q_UNLIKELY(realEndMarkIndex == -1)){ StringDiagnosticRecord d; d.str = transform; // info interval is from bodyStart to current position d.infoStart = bodyStart.position(); d.infoEnd = traverseDistLeft.position(); // error interval is the exprStartMark d.errorStart = bodyStart.position() - exprStartMark.length(); d.errorEnd = bodyStart.position(); diagnostic(Diag::Error_Parser_BadValueTransform_UnterminatedExpr, d); return false; } if(Q_UNLIKELY(realEndMarkIndex == 0)){ // no value reference StringDiagnosticRecord d; d.str = transform; // info interval is from bodyStart to current position d.infoStart = bodyStart.position(); d.infoEnd = traverseDistLeft.position(); // error interval is the last character we consumed and the exprEndMark d.errorStart = traverseDistLeft.position()-1; d.errorEnd = traverseDistLeft.position() + exprEndMark.length(); diagnostic(Diag::Error_Parser_BadValueTransform_ExpectValueName, d); return false; } QStringRef referencedValueName = traverseDistLeft.left(realEndMarkIndex); expr.externReferenceData.valueName = referencedValueName.toString(); if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, expr.externReferenceData.valueName))){ StringDiagnosticRecord d; d.str = transform; // info interval is everything inside expr d.infoStart = bodyStart.position() - exprStartMark.length(); d.infoEnd = referencedValueName.position() + referencedValueName.length() + exprEndMark.length(); // error interval is referencedValueName d.errorStart = referencedValueName.position(); d.errorEnd = referencedValueName.position() + referencedValueName.length(); diagnostic(Diag::Error_Parser_BadValueTransform_InvalidNameForReference, d); return false; } // okay, everything looks good text = traverseDistLeft.mid(realEndMarkIndex + exprEndMark.length()); } // done handling local / extern reference result.push_back(expr); } // done handling any non-literal } // TODO check: // 1. offset based traverse only allowed if going into a peer #ifdef _MSC_VER #pragma message ("warning: check not implemented") #else #warning check not implemented #endif return true; } QList<Parser::ParserNodeData> Parser::patternMatch(QVector<QStringRef> &text, DiagnosticEmitterBase& diagnostic) const { /* * start with root node * initial pattern set is made by all patterns from all possible child nodes * initial head is the beginning of text input * do the following in a loop until all input are processed: * 1. if current head match with anything in ignoreList, advance the head * 2. if current head match with any early exit patterns, pop path to there * 3. otherwise, for each pattern in pattern set, test how many data it can consume * 4. if none of the pattern applies, report error * 4. add the node having longest pattern match to tree * 5. if the node is an inner node, push the node to path * * pushing / poping a node: * 1. replaces pattern set with all patterns from possible child node of current node * 2. push / pops early exit pattern */ QList<ParserNodeData> parserNodes; int currentParentIndex = -1; QVector<QStringRef> textUnits; textUnits.swap(text); // skip all leading ignored string first, then skip lines that now becomes empty // also reverse the order of items in the vector so that we can always read from the back { QVector<QStringRef> tempTextUnits; tempTextUnits.swap(textUnits); textUnits.reserve(tempTextUnits.size()); while(!tempTextUnits.isEmpty()){ QStringRef& in = tempTextUnits.back(); context.removeLeadingIgnoredString(in); if(!in.isEmpty()){ textUnits.push_back(in); } tempTextUnits.pop_back(); } } // if we did not find any pattern match under a ParserNode, we don't bother to check any child with that type for implicit start // this set keeps track of which ParserNode types we don't want to waste time on QSet<int> implicitStartIgnoreTypeSet; // helper function // in should be back of textUnit auto advance = [&](QStringRef& in, int dist)->bool{ implicitStartIgnoreTypeSet.clear(); in = in.mid(dist); context.removeLeadingIgnoredString(in); if(in.isEmpty()){ textUnits.pop_back(); return true; } return false; }; // bootstrap: starting the root node { const auto& root = nodes.at(0); ParserNodeData firstNode; firstNode.nodeTypeIndex = 0; firstNode.parentIndex = -1; firstNode.indexWithinParent = 0; firstNode.childNodeCount = 0; if(root.patterns.empty()){ // if there is no pattern in root parser node, it is implicitly started Q_ASSERT(root.paramName.empty()); }else{ QHash<QString,QString> values; int patternIndex = -1; int advanceDist = 0; QStringRef& in = textUnits.back(); std::tie(patternIndex, advanceDist) = findLongestMatchingPattern(root.patterns, in, values); if(Q_UNLIKELY(patternIndex == -1)){ // cannot start on root return QList<ParserNodeData>(); } advance(in, advanceDist); firstNode.params = performValueTransform(root.paramName, values, root.patterns.at(patternIndex).valueTransform); } parserNodes.push_back(firstNode); currentParentIndex = 0; } // main loop for parsing while(!textUnits.empty() && currentParentIndex >= 0){ QStringRef& in = textUnits.back(); bool isContinueMainLoop = false; // try patterns on all nodes along the tree path int parentIndex = currentParentIndex; while(parentIndex >= 0){ const ParserNodeData& parentData = parserNodes.at(parentIndex); const Node& parent = nodes.at(parentData.nodeTypeIndex); int patternIndex = -1; int advanceDist = 0; QHash<QString,QString> rawValues; // try early exit patterns first std::tie(patternIndex, advanceDist) = findLongestMatchingPattern(parent.earlyExitPatterns, in, rawValues); if(patternIndex >= 0){ advance(in, advanceDist); // we found an early exit pattern currentParentIndex = parentData.parentIndex; isContinueMainLoop = true; break; } // okay, nothing found // try all patterns from child node, and see if anything matches struct PatternMatchRecord{ int nodeTypeIndex; int patternIndex; QHash<QString,QString> rawValues; QList<int> implicitParentNodeTypeIndexOnPath; // list of ParserNode with implicit start that lead to this match }; QList<PatternMatchRecord> candidates; int farthestAdvanceDist = 0; int bestPatternScore = -1; auto helper_tryMatchChild = [&](int childParserNodeTypeIndex, const QList<int>& path)->void{ const Node& childNodeTy = nodes.at(childParserNodeTypeIndex); int childPatternIndex = -1; int childAdvanceDist = 0; std::tie(childPatternIndex, childAdvanceDist) = findLongestMatchingPattern(childNodeTy.patterns, in, rawValues); if(childPatternIndex >= 0){ // we have a pattern that matches int currentPatternScore = childNodeTy.patterns.at(childPatternIndex).priorityScore; bool isAbsolutelyBetter = (childAdvanceDist > farthestAdvanceDist || (childAdvanceDist == farthestAdvanceDist && currentPatternScore > bestPatternScore)); if(isAbsolutelyBetter){ // this pattern is absolutely better than previous one; no need to keep previous results farthestAdvanceDist = childAdvanceDist; bestPatternScore = currentPatternScore; candidates.clear(); } if(isAbsolutelyBetter || (childAdvanceDist == farthestAdvanceDist && currentPatternScore == bestPatternScore)){ // at least not worse than previous ones // save result of this pattern match PatternMatchRecord record; record.nodeTypeIndex = childParserNodeTypeIndex; record.patternIndex = childPatternIndex; record.rawValues.swap(rawValues); record.implicitParentNodeTypeIndexOnPath = path; candidates.push_back(record); } } rawValues.clear(); }; rawValues.clear(); int implicitStartChildCount = 0; for(int child : parent.allowedChildNodeIndexList){ const Node& childNodeTy = nodes.at(child); if(childNodeTy.patterns.isEmpty()){ // these nodes are handled later on Q_ASSERT(childNodeTy.paramName.empty()); implicitStartChildCount += 1; continue; } helper_tryMatchChild(child, QList<int>()); } if(candidates.isEmpty() && implicitStartChildCount > 1){ // check childs that may start implicitly QQueue<QList<int>> pathQueue; pathQueue.reserve(implicitStartChildCount); for(int child : parent.allowedChildNodeIndexList){ // skip those we already exited from if(implicitStartIgnoreTypeSet.contains(child)) continue; const Node& childNodeTy = nodes.at(child); if(childNodeTy.patterns.isEmpty() && !childNodeTy.allowedChildNodeIndexList.isEmpty()){ pathQueue.enqueue(QList<int>({child})); } } while(!pathQueue.isEmpty()){ // WARNING: pathQueue.head() is not safe to "cache" since enqueue can invalidate old one int tailParserNodeTypeIndex = pathQueue.head().back(); const Node& ty = nodes.at(tailParserNodeTypeIndex); // go through all its child // if a child has patterns (not implicit start), try these patterns // otherwise, enqueue another path with that child at back for(int child : ty.allowedChildNodeIndexList){ if(implicitStartIgnoreTypeSet.contains(child)) continue; const Node& childNodeTy = nodes.at(child); if(childNodeTy.patterns.isEmpty()){ Q_ASSERT(childNodeTy.paramName.empty()); QList<int> newPath(pathQueue.head()); newPath.push_back(child); pathQueue.enqueue(newPath); }else{ helper_tryMatchChild(child, pathQueue.head()); } } pathQueue.dequeue(); } } if(candidates.isEmpty()){ // no pattern match // go to parent if(parent.patterns.isEmpty()){ implicitStartIgnoreTypeSet.insert(parentData.nodeTypeIndex); } parentIndex = parentData.parentIndex; continue; }else{ if(Q_UNLIKELY(candidates.size() > 1)){ // ambiguous scenario; we will just select the first pattern // report a warning though QList<QVariant> errorArgs; QStringRef ambiguousText = in.left(farthestAdvanceDist); context.removeTrailingIgnoredString(ambiguousText); errorArgs.push_back(ambiguousText.toString()); for(const auto& data: candidates){ QVariantList vlist; // [NodeName][NodeParamStringList][PatternIndex] const Node& childNodeTy = nodes.at(data.nodeTypeIndex); vlist.push_back(childNodeTy.nodeName); QStringList params = performValueTransform( childNodeTy.paramName, data.rawValues, childNodeTy.patterns.at(data.patternIndex).valueTransform); vlist.push_back(params); vlist.push_back(data.patternIndex); errorArgs.push_back(vlist); } diagnostic.handle(Diag::Warn_Parser_Matching_Ambiguous, errorArgs); } // at least one match; pick the first const PatternMatchRecord& record = candidates.front(); // if there are implicitly started nodes, create them first for(int nodeOnPath : record.implicitParentNodeTypeIndexOnPath){ ParserNodeData intermediateNodeData; intermediateNodeData.parentIndex = parentIndex; intermediateNodeData.nodeTypeIndex = nodeOnPath; intermediateNodeData.indexWithinParent = parserNodes[parentIndex].childNodeCount++; intermediateNodeData.childNodeCount = 0; intermediateNodeData.params.clear();// implicitly started node won't have parameters parentIndex = parserNodes.size(); parserNodes.push_back(intermediateNodeData); } // create the end node const Node& childNodeTy = nodes.at(record.nodeTypeIndex); ParserNodeData endData; endData.parentIndex = parentIndex; endData.nodeTypeIndex = record.nodeTypeIndex; endData.indexWithinParent = parserNodes[parentIndex].childNodeCount++; endData.childNodeCount = 0; endData.params = performValueTransform( childNodeTy.paramName, record.rawValues, childNodeTy.patterns.at(record.patternIndex).valueTransform); if(childNodeTy.allowedChildNodeIndexList.isEmpty()){ // leaf node; no change on parent currentParentIndex = parentIndex; }else{ currentParentIndex = parserNodes.size(); } parserNodes.push_back(endData); advance(in, farthestAdvanceDist); isContinueMainLoop = true; break; } } if(Q_LIKELY(isContinueMainLoop)) continue; // if we reach here, it means that we reached the root and no patterns can be applied so far Q_ASSERT(parentIndex == -1); Q_ASSERT(!textUnits.isEmpty()); diagnostic(Diag::Error_Parser_Matching_NoMatch); return QList<ParserNodeData>(); } // if we reach here, it either means that all texts are consumed, or an early exit pattern of root is found while(!textUnits.empty()){ QStringRef& in = textUnits.back(); int len = context.removeLeadingIgnoredString(in); if(len > 0){ advance(in, len); }else{ if(!in.isEmpty()){ // garbage at the end diagnostic(Diag::Error_Parser_Matching_GarbageAtEnd); return QList<ParserNodeData>(); } } } // now all the text are successfully consumed return parserNodes; } std::pair<bool,QString> Parser::IRBuildContext::solveExternReference(const Parser& p, const PatternValueSubExpression::ExternReferenceData &expr, int nodeIndex) { std::pair<bool,QString> fail(false, QString()); int currentNodeIndex = nodeIndex; if(expr.isTraverseStartFromRoot){ currentNodeIndex = 0; } // at time of writing, 4 traverse type is supported: Parent, ChildByTypeAndOrder, ChildByTypeFromLookup, and AnyChildByOrder for(const auto& step : expr.nodeTraversal){ // handle the easiest case that go to parent first if(step.ty == PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::Parent){ // do not go before root (doing .. on root evaluates to root itself) if(currentNodeIndex > 0){ currentNodeIndex = parserNodes.at(currentNodeIndex).parentIndex; } continue; } // now it is going into child const ParserNodeData& curNode = parserNodes.at(currentNodeIndex); const Node& curNodeTy = p.nodes.at(curNode.nodeTypeIndex); if(step.ty == PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::AnyChildByOrder){ // get the list of candidate nodes const QList<int>& children = getNodeChildList(currentNodeIndex, -1); int childIndex = step.ioSearchData.lookupNum; if(!step.ioSearchData.isNumIndexInsteadofOffset){ // offset based search childIndex += parserNodes.at(nodeIndex).indexWithinParent; } if(childIndex < 0 || childIndex >= children.size()){ // out of bound; bad index return fail; } currentNodeIndex = children.at(childIndex); continue; } // now we must be indexing into child with specific type // we should have a valid child name in this case // get the childTypeIndex by searching through names int childTypeIndex = -1; for(int child : curNodeTy.allowedChildNodeIndexList){ const Node& curChild = p.nodes.at(child); if(curChild.nodeName == step.childParserNodeName){ childTypeIndex = child; break; } } if(childTypeIndex == -1){ // no such child found; error return fail; } // get the list of candidate nodes const QList<int>& children = getNodeChildList(currentNodeIndex, childTypeIndex); if(step.ty == PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::ChildByTypeFromLookup){ const Node& childTy = p.nodes.at(childTypeIndex); int paramIndex = childTy.paramName.indexOf(step.kvSearchData.key); // the validation code should reject code like this Q_ASSERT(paramIndex != -1); // if the parent node is the same: // use the first match "before" current node, if there is one // otherwise, use the first match "after" current node, if there is one // otherwise, fail // if the parent node is not the same: just go through the list from bottom to top and stop at first result int startIndex = children.size() - 1; if(curNode.parentIndex == parserNodes.at(nodeIndex).parentIndex){ // find the first child node in given type that is either before or is current node auto iter = std::upper_bound(children.begin(), children.end(), nodeIndex); startIndex = static_cast<int>(std::distance(children.begin(), iter))-1; } bool isFound = false; for(int i = startIndex; i >= 0; --i){ int child = children.at(i); const ParserNodeData& curChild = parserNodes.at(child); if(curChild.params.at(paramIndex) == step.kvSearchData.value){ currentNodeIndex = child; isFound = true; break; } } if(isFound) continue; // search from the startIndex downward for(int i = startIndex+1; i < children.size(); ++i){ int child = children.at(i); const ParserNodeData& curChild = parserNodes.at(child); if(curChild.params.at(paramIndex) == step.kvSearchData.value){ currentNodeIndex = child; isFound = true; break; } } if(!isFound) return fail; }else{ // otherwise we are just searching by order Q_ASSERT(step.ty == PatternValueSubExpression::ExternReferenceData::NodeTraverseStep::StepType::ChildByTypeAndOrder); int childIndex = step.ioSearchData.lookupNum; if(!step.ioSearchData.isNumIndexInsteadofOffset){ // offset based search auto iter = std::upper_bound(children.begin(), children.end(), nodeIndex); int baseIndex = static_cast<int>(std::distance(children.begin(), iter))-1; childIndex += baseIndex; } if(childIndex < 0 || childIndex >= children.size()){ // out of bound; bad index return fail; } currentNodeIndex = children.at(childIndex); continue; } } // okay, all steps are done // access the member const ParserNodeData& data = parserNodes.at(currentNodeIndex); int paramIndex = p.nodes.at(data.nodeTypeIndex).paramName.indexOf(expr.valueName); if(paramIndex == -1){ // no such member under the node return fail; } Q_ASSERT(paramIndex < data.params.size()); return std::make_pair(true, data.params.at(paramIndex)); #if 0 int splitterIndex = expr.indexOf(QChar(':')); if(splitterIndex == -1){ return fail; } if((splitterIndex == expr.length()-1) || expr.at(splitterIndex+1) != ':'){ // just a single ':', malformed expression return fail; } QStringRef paramName = expr.midRef(splitterIndex+2); QStringRef nodeExpr = expr.leftRef(splitterIndex); QVector<QStringRef> steps = nodeExpr.split('/'); int currentNodeIndex = nodeIndex; for(QStringRef step : steps){ // skip empty parts if(step.isEmpty() || step == ".") continue; const ParserNodeData& curNode = parserNodes.at(currentNodeIndex); if(step == ".."){ // do not go before root (doing .. on root evaluates to root itself) if(currentNodeIndex > 0){ currentNodeIndex = curNode.parentIndex; } }else{ int childTypeIndex = -1; int childIndex = -1; QStringRef childName; QStringRef enclosedExpr; int exprStart = step.indexOf(QChar('[')); if(exprStart == -1){ childName = step; }else{ // either [<IndexExpr>] or <ChildName>[<LookupExpr>] expected if(step.back() != ']'){ // malformed expression return fail; } childName = step.left(exprStart); enclosedExpr = step.mid(exprStart+1).chopped(1);// skip [] } const Node& curNodeTy = p.nodes.at(curNode.nodeTypeIndex); if(!childName.isEmpty()){ // get the childTypeIndex by searching through names for(int child : curNodeTy.allowedChildNodeIndexList){ const Node& curChild = p.nodes.at(child); if(curChild.nodeName == childName){ childTypeIndex = child; break; } } if(childTypeIndex == -1){ // no such child found; error return fail; } } // perform index based search bool isIndexBasedSearch = false; bool isPeerNodeAccess = false; if(enclosedExpr.isEmpty()){ isIndexBasedSearch = true; childIndex = 0; }else{ // it is not a key based search if everything in enclosedExpr is a valid integer bool isGood = false; childIndex = enclosedExpr.toInt(&isGood); if(isGood){ isIndexBasedSearch = true; if(enclosedExpr.front() == '+' || enclosedExpr.front() == '-'){ // offset based index expression; childIndex is not the final value if(childTypeIndex != -1){ // there is a child node type specified // only allowed when we access peers if(currentNodeIndex == parserNodes.at(nodeIndex).parentIndex){ isPeerNodeAccess = true; }else{ return fail; } }else{ // no child node type specified // get the "cooked" index now childIndex += parserNodes.at(nodeIndex).indexWithinParent; } } } } // get the list of candidate nodes const QList<int>& children = getNodeChildList(currentNodeIndex, childTypeIndex); if(isPeerNodeAccess){ // find the first child node in given type that is either before or is current node auto iter = std::upper_bound(children.begin(), children.end(), nodeIndex); int baseIndex = static_cast<int>(std::distance(children.begin(), iter)) - 1; // fix-up the final index childIndex += baseIndex; } if(isIndexBasedSearch){ if(childIndex < 0 || childIndex >= children.size()){ // out of bound; bad index return fail; } currentNodeIndex = children.at(childIndex); continue; } // key based search // extract the key and value field first int equalSignIndex = enclosedExpr.indexOf(QChar('=')); if(equalSignIndex == -1){ // no equal sign found; malformed LookupExor return fail; } if(equalSignIndex+2 >= enclosedExpr.size() || enclosedExpr.at(equalSignIndex+1) != '='){ // it is not a "==" or there is nothing after "=="; malformed LookupExor return fail; } QStringRef lookupKey = enclosedExpr.left(equalSignIndex); QStringRef lookupValue = enclosedExpr.mid(equalSignIndex+2); // for now we require lookupValue to be a '"' enclosed string literal if(!(lookupValue.startsWith('"') && lookupValue.endsWith('"'))){ // malformed return fail; } // remove the quote lookupValue = lookupValue.mid(1); lookupValue.chop(1); // get the parameter index from the lookupKey const Node& childNodeTy = p.nodes.at(childIndex); int paramIndex = -1; for(int i = 0, n = childNodeTy.paramName.size(); i < n; ++i){ if(childNodeTy.paramName.at(i) == lookupKey){ paramIndex = i; break; } } if(paramIndex == -1){ // no parameter with specified name found; fail return fail; } int currentCandidate = -1; for(int child : children){ const ParserNodeData& childData = parserNodes.at(child); if(childData.params.at(paramIndex) == lookupValue){ if(currentCandidate == -1){ currentCandidate = child; }else{ // duplicated search result; fail return fail; } } } currentNodeIndex = currentCandidate; continue; } } // node traversal complete; read the value and done const ParserNodeData& nodeData = parserNodes.at(currentNodeIndex); const Node& nodeTy = p.nodes.at(nodeData.nodeTypeIndex); for(int i = 0, n = nodeTy.paramName.size(); i < n; ++i){ if(nodeTy.paramName.at(i) == paramName){ return std::make_pair(true, nodeData.params.at(i)); } } // no parameter with given name found return fail; #endif } const QList<int>& Parser::IRBuildContext::getNodeChildList(int parentIndex, int childNodeTypeIndex) { auto& nodeCache = parserNodeChildListCache[parentIndex]; { auto iter = nodeCache.find(childNodeTypeIndex); if(iter != nodeCache.end()) return iter.value(); } // okay, it is not in cache // let's compute it if(nodeCache.empty()){ // we have not yet built any list // let's prepare the list of all child nodes at the same time QList<int> allChildList; QList<int> wantedChildList; // we go through all ParserNodes after the node specified by parentIndex: // 1. If a node's parent index is smaller than parentIndex, it means that we already went outside the subtree under parent // and allChildList is already complete // 2. If a node's parent index is equal to parentIndex, add it to allChildList since it is a direct child // 3. If a node's parent index is larger than parentIndex, it is an indirect child for(int curNodeIndex = parentIndex+1, numNode = parserNodes.size(); curNodeIndex < numNode; ++curNodeIndex){ const auto& d = parserNodes.at(curNodeIndex); if(d.parentIndex == parentIndex){ allChildList.push_back(curNodeIndex); // if we also looks for child with specific type, we add them here if(childNodeTypeIndex != -1 && d.nodeTypeIndex == childNodeTypeIndex){ wantedChildList.push_back(curNodeIndex); } }else if(d.parentIndex < parentIndex){ break; } } nodeCache.insert(-1, allChildList); if(childNodeTypeIndex != -1){ nodeCache.insert(childNodeTypeIndex, wantedChildList); } // we may have childNodeTypeIndex == -1 here return nodeCache[childNodeTypeIndex]; }else{ // we already have the list of all children // build the wanted list from the list of all direct childs Q_ASSERT(childNodeTypeIndex != -1); auto iter_allChild = nodeCache.find(-1); Q_ASSERT(iter_allChild != nodeCache.end()); QList<int> wantedChildList; for(int child: iter_allChild.value()){ const auto& d = parserNodes.at(child); if(d.nodeTypeIndex == childNodeTypeIndex){ wantedChildList.push_back(child); } } return nodeCache.insert(childNodeTypeIndex, wantedChildList).value(); } } IRRootInstance* Parser::parse(QVector<QStringRef> &text, const IRRootType& ir, DiagnosticEmitterBase& diagnostic) const { IRBuildContext ctx; ctx.parserNodes = patternMatch(text, diagnostic); if(ctx.parserNodes.empty()) return nullptr; // start to build IR tree std::unique_ptr<IRRootInstance> ptr(new IRRootInstance(ir)); // root node to root node const ParserNodeData& rootData = ctx.parserNodes.front(); const Node& rootNodeTy = nodes.at(rootData.nodeTypeIndex); auto helper_buildIRNode = [&](int parserNodeIndex, int irNodeTypeIndex, int parentIRNodeIndex)->int{ const IRNodeType& irNodeTy = ptr->getType().getNodeType(irNodeTypeIndex); // step 1: insert node int irNodeIndex = ptr->addNode(irNodeTypeIndex); auto& node = ptr->getNode(irNodeIndex); node.setParent(parentIRNodeIndex); if(parentIRNodeIndex != -1){ ptr->getNode(parentIRNodeIndex).addChildNode(irNodeIndex); } // step 2: prepare value transform QList<QVariant> params; const ParserNodeData& nodeData = ctx.parserNodes.at(parserNodeIndex); const Node& nodeTy = nodes.at(nodeData.nodeTypeIndex); Q_ASSERT(nodeTy.combineValueTransform.empty() || nodeTy.combineValueTransform.size() == irNodeTy.getNumParameter()); QHash<QString,QString> nodeStrData; for(int i = 0, n = nodeTy.paramName.size(); i < n; ++i){ nodeStrData.insert(nodeTy.paramName.at(i), nodeData.params.at(i)); } for(int i = 0, n = irNodeTy.getNumParameter(); i < n; ++i){ QString value; QString irParamName = irNodeTy.getParameterName(i); if(nodeTy.combineValueTransform.empty() || nodeTy.combineValueTransform.at(i).empty()){ // search for ParserNode parameter with the same name // use it as the final value int idx = nodeTy.paramName.indexOf(irParamName); value = nodeData.params.at(idx); }else{ const auto& exprList = nodeTy.combineValueTransform.at(i); bool isAnyExprGood = false; for(const auto& expr : exprList){ bool isExprGood = true; value = performValueTransform(irParamName, nodeStrData, expr, [&](const PatternValueSubExpression::ExternReferenceData& e)->QString{ QString retVal; bool isThisOneGood = true; std::tie(isThisOneGood, retVal) = ctx.solveExternReference(*this, e, parserNodeIndex); isExprGood = isExprGood && isThisOneGood; return retVal; }); if(isExprGood){ isAnyExprGood = true; break; } } if(Q_UNLIKELY(!isAnyExprGood)){ diagnostic(Diag::Error_Parser_IRBuild_BadTransform, nodeTy.nodeName, irNodeTy.getName(), irParamName); return -1; } } // cast value to IR type QVariant irValue; ValueType irValTy = irNodeTy.getParameterType(i); switch(irValTy){ default: Q_UNREACHABLE(); break; case ValueType::String:{ irValue = value; }break; case ValueType::Int64:{ bool isGood = true; irValue.setValue(value.toLongLong(&isGood)); if(!isGood){ diagnostic(Diag::Error_Parser_IRBuild_BadCast, nodeTy.nodeName, irNodeTy.getName(), irParamName, irValTy, value); return -1; } }break; } params.push_back(irValue); } node.setParameters(params); return irNodeIndex; }; int rootNodeIRIndex = helper_buildIRNode(0, rootNodeTy.combineToIRNodeIndex, -1); Q_ASSERT(rootNodeIRIndex == 0); struct NodeIndexRecord{ int parserNodeIndex; int irNodeIndex; }; QList<NodeIndexRecord> parentStack; parentStack.push_back(NodeIndexRecord{0,0}); for(int parserNodeIndex = 1, n = ctx.parserNodes.size(); parserNodeIndex < n; ++parserNodeIndex){ const ParserNodeData& nodeData = ctx.parserNodes.at(parserNodeIndex); const Node& nodeTy = nodes.at(nodeData.nodeTypeIndex); // ignore parser-only nodes int irNodeTypeIndex = nodeTy.combineToIRNodeIndex; if(irNodeTypeIndex == -1) continue; Q_ASSERT(irNodeTypeIndex >= 0); // find the correct parent IR node // keep popping parentStack until the stack top appears in the parent of current parser node int curParentParserNodeIndex = nodeData.parentIndex; while(!parentStack.isEmpty() && (parentStack.back().parserNodeIndex != curParentParserNodeIndex)){ if(parentStack.back().parserNodeIndex > curParentParserNodeIndex){ parentStack.pop_back(); }else{ curParentParserNodeIndex = ctx.parserNodes.at(curParentParserNodeIndex).parentIndex; } } Q_ASSERT(!parentStack.isEmpty()); Q_ASSERT(parentStack.back().parserNodeIndex == curParentParserNodeIndex); int irNodeIndex = helper_buildIRNode(parserNodeIndex, irNodeTypeIndex, parentStack.back().irNodeIndex); if(irNodeIndex == -1){ // error occurred return nullptr; } parentStack.push_back(NodeIndexRecord{parserNodeIndex, irNodeIndex}); } if(ptr->validate(diagnostic)){ return ptr.release(); } // IR fails to validate in this case return nullptr; } std::pair<int,int> Parser::findLongestMatchingPattern(const QList<Pattern>& patterns, QStringRef text, QHash<QString,QString>& values) const { int bestPatternIndex = -1; int bestPatternScore = -1; int numConsumed = 0; QHash<QString, QString> curRawValue; for(int i = 0, num = patterns.size(); i < num; ++i){ int curConsumeCount = match(text, curRawValue, context, patterns.at(i).elements); if(curConsumeCount > 0){ if(curConsumeCount > numConsumed || (curConsumeCount == numConsumed && patterns.at(i).priorityScore > bestPatternScore)){ bestPatternIndex = i; bestPatternScore = patterns.at(i).priorityScore; numConsumed = curConsumeCount; values.swap(curRawValue); } } curRawValue.clear(); } return std::make_pair(bestPatternIndex, numConsumed); } std::pair<int,int> Parser::ParseContext::getMatchingEndAdvanceDistance(QStringRef text, int matchPairIndex)const { // for each candidate end string, find their first occurrence int pos = -1; int reach = -1; const QStringList& list = matchPairEnds.at(matchPairIndex); for(const QString& candidateEnd : list){ int curIndex = text.indexOf(candidateEnd); if(curIndex != -1){ if(pos == -1 || curIndex < pos || ((curIndex == pos) && (curIndex + candidateEnd.length() > reach))){ pos = curIndex; reach = curIndex + candidateEnd.length(); } } } // no any match pair end found if(pos == -1) return std::make_pair(-1,-1); // try to find if there is any match pair start mark between 0 and pos // if there is, recursively find its end mark, and start searching from there again int searchTextLen = reach - 1 + longestMatchPairStartStringLength; int nextMatchPairPos = -1; int nextMatchPairIndex = -1; int nextMatchPairStartLength = -1; std::tie(nextMatchPairPos, nextMatchPairIndex, nextMatchPairStartLength) = getMatchingStartAdvanceDistance(text.left(searchTextLen)); if(nextMatchPairPos == -1 || nextMatchPairPos > pos || (nextMatchPairPos == pos && nextMatchPairStartLength <= (reach - pos))){ // no match pair start found, or the match pair start is not "early" in text enough (partial overlap with end marker) // done return std::make_pair(reach, reach - pos); } // we found a match pair start // find its end then int nextSearchStart = nextMatchPairPos + nextMatchPairStartLength; int endAdvance = getMatchingEndAdvanceDistance(text.mid(nextSearchStart), nextMatchPairIndex).first; if(endAdvance == -1){ // no match for nested match pair; fail return std::make_pair(-1,-1); } int recurseStart = nextSearchStart + endAdvance; int endLen = -1; int recurseAdvance = -1; std::tie(recurseAdvance, endLen) = getMatchingEndAdvanceDistance(text.mid(recurseStart), matchPairIndex); if(recurseAdvance == -1){ // no match for this match pair return std::make_pair(-1,-1); } Q_ASSERT(endLen > 0); return std::make_pair(recurseStart + recurseAdvance, endLen); } std::tuple<int, int, int> Parser::ParseContext::getMatchingStartAdvanceDistance(QStringRef text)const { int pos = -1; int matchPairIndex = -1; int matchPairStartLength = -1; for(int i = 0, n = matchPairStarts.size(); i < n; ++i){ for(const QString& str : matchPairStarts.at(i)){ int index = text.indexOf(str); if(index != -1){ if(pos == -1 || index < pos || (index == pos && matchPairStartLength < str.length())){ pos = index; matchPairIndex = i; matchPairStartLength = str.length(); } } } } return std::make_tuple(pos, matchPairIndex, matchPairStartLength); } int Parser::ParseContext::removeTrailingIgnoredString(QStringRef& ref)const { bool isChangeMade = true; int trimLen = 0; while(isChangeMade && !ref.isEmpty()){ isChangeMade = false; for(const QString& ignore : ignoreList){ while(ref.endsWith(ignore)){ ref.chop(ignore.length()); trimLen += ignore.length(); isChangeMade = true; } } } return trimLen; } int Parser::ParseContext::removeLeadingIgnoredString(QStringRef& ref)const { bool isChangeMade = true; int trimLen = 0; while(isChangeMade && !ref.isEmpty()){ isChangeMade = false; for(const QString& ignore : ignoreList){ while(ref.startsWith(ignore)){ ref = ref.mid(ignore.length()); trimLen += ignore.length(); isChangeMade = true; } } } return trimLen; } int Parser::match(QStringRef input, QHash<QString,QString>& values, const ParseContext &ctx, const QList<SubPattern>& pattern) { values.clear(); if(pattern.empty()) return 0; // helper function auto regexExtractMatchValues = [&](const QStringList& namedCaptureGroups, const QRegularExpressionMatch& matchResult)->void{ // the first capture should have no name Q_ASSERT(namedCaptureGroups.front().isEmpty()); for(int i = 1; i < namedCaptureGroups.size(); ++i){ const QString& name = namedCaptureGroups.at(i); if(!name.isEmpty()){ values.insert(name, matchResult.captured(i)); } } }; // helper function // return number of characters consumed if successful; used inside Auto type subpattern auto autoSubPattern_checkNextPattern = [&regexExtractMatchValues](const SubPattern& p, QStringRef text, const ParseContext& ctx)->int{ switch(p.ty){ case SubPatternType::Auto:{ Q_UNREACHABLE(); }break; case SubPatternType::Literal:{ if(text.startsWith(p.literalData.str)) return p.literalData.str.length(); return 0; } case SubPatternType::Regex:{ auto regexResult = p.regexData.regex.match(text, 0, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); if(!regexResult.hasMatch()){ // no matches return 0; } regexExtractMatchValues(p.regexData.regex.namedCaptureGroups(), regexResult); return regexResult.capturedEnd(0); } case SubPatternType::MatchPair:{ const auto& data = p.matchPairData; int forwardDist = 0; const QStringList& matchPairMarkerList = (data.isStart? ctx.matchPairStarts : ctx.matchPairEnds).at(data.matchPairIndex); for(const QString& mark : matchPairMarkerList){ if(text.startsWith(mark)){ if(mark.length() > forwardDist){ forwardDist = mark.length(); } } } return forwardDist; } } Q_UNREACHABLE(); }; QStringRef text = input; for(int patternIndex = 0, n = pattern.size(); patternIndex < n; ++patternIndex){ ctx.removeLeadingIgnoredString(text); if(text.isEmpty()) return 0; const SubPattern& p = pattern.at(patternIndex); switch(p.ty){ case SubPatternType::Literal:{ if(!text.startsWith(p.literalData.str)){ // match fail return 0; } text = text.mid(p.literalData.str.length()); }break; case SubPatternType::Regex:{ auto result = p.regexData.regex.match(text, 0, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); if(!result.hasMatch()){ // match fail return 0; } regexExtractMatchValues(p.regexData.regex.namedCaptureGroups(), result); text = text.mid(result.capturedRef(0).length()); }break; case SubPatternType::MatchPair:{ const auto& data = p.matchPairData; int forwardDist = 0; const QStringList& matchPairMarkerList = (data.isStart? ctx.matchPairStarts : ctx.matchPairEnds).at(data.matchPairIndex); for(const QString& mark : matchPairMarkerList){ if(text.startsWith(mark)){ if(mark.length() > forwardDist){ forwardDist = mark.length(); } } } if(forwardDist == 0){ // we did not find the match pair start/end string // match fail return 0; } text = text.mid(forwardDist); }break; case SubPatternType::Auto:{ const SubPattern::AutoData& data = p.autoData; QStringRef valueBody = text; // make a copy at starting position QStringRef nextMatchData; bool isMatchMade = false; while(!text.isEmpty()){ // check if the stop condition is reached if(data.isTerminateByIgnoredString){ for(const QString& ignored : ctx.ignoreList){ if(text.startsWith(ignored)){ valueBody.chop(text.length()); text = text.mid(ignored.length()); isMatchMade = true; break; } } if(isMatchMade) break; }else{ int dist = autoSubPattern_checkNextPattern(pattern.at(patternIndex+1), text, ctx); if(dist != 0){ valueBody.chop(text.length()); nextMatchData = text.left(dist); text = text.mid(dist); ctx.removeTrailingIgnoredString(valueBody); isMatchMade = true; break; } } // no match for next pattern // see if we have a starting match pair, if yes then fast forward until the end of match pair int matchPairStartMaxLen = 0; int matchPairIndex = -1; for(int i = 0, n = ctx.matchPairStarts.size(); i < n; ++i){ for(const QString& start : ctx.matchPairStarts.at(i)){ if(text.startsWith(start)){ if(matchPairIndex == -1 || matchPairStartMaxLen < start.length()){ matchPairIndex = i; matchPairStartMaxLen = start.length(); } } } } if(matchPairIndex == -1){ // not starting a match pair enclosed block // just forward one character text = text.mid(1); }else{ // starting a match pair text = text.mid(matchPairStartMaxLen); auto resultPair = ctx.getMatchingEndAdvanceDistance(text, matchPairIndex); if(resultPair.first == -1){ // no end found; bad match return 0; } text = text.mid(resultPair.first); ctx.removeLeadingIgnoredString(text); } } if(!isMatchMade){ // we allow termination by ignored string to end without finding an ignored string // but not for others if(!data.isTerminateByIgnoredString){ return 0; } } // also increment the patternIndex here since we consumed the next pattern already if(!data.isTerminateByIgnoredString){ patternIndex += 1; } // extract value if needed if(!data.valueName.isEmpty()){ QString value = valueBody.toString(); if(data.nextSubPatternIncludeLength != 0){ if(data.nextSubPatternIncludeLength == -1){ value.append(nextMatchData); }else{ value.append(nextMatchData.left(data.nextSubPatternIncludeLength)); } } values.insert(data.valueName, value); } }break; } } // if we reach here then all patterns are successfully matched // WARNING: QStringRef will give zero position and length if text is empty return input.length() - text.length(); } QStringList Parser::performValueTransform(const QStringList& paramName, const QHash<QString,QString>& rawValues, const QList<QList<PatternValueSubExpression> > &valueTransform) { QStringList result; Q_ASSERT(paramName.size() == valueTransform.size()); for(int i = 0, num = paramName.size(); i < num; ++i){ const QString& param = paramName.at(i); const auto& list = valueTransform.at(i); QString value; if(list.isEmpty()){ // direct search from raw values value = rawValues.value(param); }else{ for(const auto& expr : list){ switch(expr.ty){ case PatternValueSubExpression::OpType::Literal:{ value.append(expr.literalData.str); }break; case PatternValueSubExpression::OpType::LocalReference:{ Q_ASSERT(rawValues.count(expr.localReferenceData.valueName) > 0); value.append(rawValues.value(expr.localReferenceData.valueName)); }break; case PatternValueSubExpression::OpType::ExternReference:{ Q_UNREACHABLE(); } } } } result.push_back(value); } return result; } QString Parser::performValueTransform(const QString &paramName, const QHash<QString,QString>& rawValues, const QList<PatternValueSubExpression> &valueTransform, std::function<QString(const PatternValueSubExpression::ExternReferenceData&)> externReferenceSolver) { if(valueTransform.isEmpty()) return rawValues.value(paramName); QString value; for(const auto& expr : valueTransform){ switch(expr.ty){ case PatternValueSubExpression::OpType::Literal:{ value.append(expr.literalData.str); }break; case PatternValueSubExpression::OpType::LocalReference:{ Q_ASSERT(rawValues.count(expr.localReferenceData.valueName) > 0); value.append(rawValues.value(expr.localReferenceData.valueName)); }break; case PatternValueSubExpression::OpType::ExternReference:{ value.append(externReferenceSolver(expr.externReferenceData)); }break; } } return value; } <file_sep>/core/XML.h #ifndef XML_H #define XML_H #include <QIODevice> #include <QXmlStreamReader> #include <QXmlStreamWriter> class DiagnosticEmitterBase; class IRRootType; class IRRootInstance; class Parser; class ParserPolicy; namespace XML{ void writeIRInstance(const IRRootInstance& ir, QIODevice* dest); IRRootInstance* readIRInstance(const IRRootType& ty, DiagnosticEmitterBase& diagnostic, QIODevice* src); // xml should be at StartElement and the element is Parser void writeParser(const ParserPolicy& p, QXmlStreamWriter& xml); Parser* readParser(const IRRootType& ty, DiagnosticEmitterBase& diagnostic, QXmlStreamReader& xml); } #endif // XML_H <file_sep>/core/XML_Parser.cpp #include "core/XML.h" #include "core/Value.h" #include "core/IR.h" #include "core/DiagnosticEmitter.h" #include "core/Parser.h" #include <QXmlStreamReader> #include <QXmlStreamWriter> #include <memory> namespace{ const QString STR_NAME = QStringLiteral("Name"); const QString STR_INDEX = QStringLiteral("ID"); const QString STR_PARSER = QStringLiteral("Parser"); const QString STR_EXPR_START = QStringLiteral("ExprStart"); const QString STR_EXPR_END = QStringLiteral("ExprEnd"); const QString STR_ROOTNODE_NAME = QStringLiteral("RootNodeName"); const QString STR_MATCHPAIR_LIST = QStringLiteral("MatchPairList"); const QString STR_MATCHPAIR = QStringLiteral("MatchPair"); const QString STR_MATCHPAIR_START = QStringLiteral("Start"); const QString STR_MATCHPAIR_END = QStringLiteral("End"); const QString STR_IGNORE_LIST = QStringLiteral("IgnoreList"); const QString STR_IGNORE = QStringLiteral("Ignore"); const QString STR_PARSERNODE_LIST = QStringLiteral("ParserNodeList"); const QString STR_PARSERNODE = QStringLiteral("ParserNode"); const QString STR_PARAMETER_LIST = QStringLiteral("ParameterList"); const QString STR_PARAMETER = QStringLiteral("Parameter"); const QString STR_PATTERN_LIST = QStringLiteral("PatternList"); const QString STR_PATTERN = QStringLiteral("Pattern"); const QString STR_PATTERNSTRING = QStringLiteral("PatternString"); const QString STR_PRIORITY_OVERRIDE = QStringLiteral("PriorityOverride"); const QString STR_VALUE_OVERWRITE_LIST = QStringLiteral("ValueOverwriteList"); const QString STR_OVERWRITE = QStringLiteral("Overwrite"); const QString STR_CHILD_LIST = QStringLiteral("ChildList"); const QString STR_CHILD = QStringLiteral("Child"); const QString STR_EXIT_PATTERN_LIST = QStringLiteral("ExitPatternList"); const QString STR_EXIT_PATTERN = QStringLiteral("ExitPattern"); const QString STR_TO_IRNODE = QStringLiteral("ToIRNode"); const QString STR_VALUE_TRANSFORM_LIST = QStringLiteral("ValueTransformList"); const QString STR_VALUE_TRANSFORM = QStringLiteral("Transform"); const QString STR_IRNODE_PARAM = QStringLiteral("DestinationIRNodeParameter"); void writeAsElement(QXmlStreamWriter& xml, const QString& name, const QString& value) { xml.writeStartElement(name); xml.writeCharacters(value); xml.writeEndElement(); } void writeAsElement(QXmlStreamWriter& xml, const QString& name, int id, const QString& value) { xml.writeStartElement(name); xml.writeAttribute(STR_INDEX, QString::number(id)); xml.writeCharacters(value); xml.writeEndElement(); } } // end of anonymous namespace void XML::writeParser(const ParserPolicy& p, QXmlStreamWriter& xml) { xml.writeStartElement(STR_PARSER); xml.writeAttribute(STR_NAME, p.name); // other attributes written as element writeAsElement(xml, STR_EXPR_START, p.exprStartMark); writeAsElement(xml, STR_EXPR_END, p.exprEndMark); writeAsElement(xml, STR_ROOTNODE_NAME, p.rootParserNodeName); // match pairs xml.writeStartElement(STR_MATCHPAIR_LIST); for(int i = 0, n = p.matchPairs.size(); i < n; ++i){ const auto& m = p.matchPairs.at(i); xml.writeStartElement(STR_MATCHPAIR); xml.writeAttribute(STR_NAME, m.name); xml.writeAttribute(STR_INDEX, QString::number(i)); for(const auto& start : m.startEquivalentSet){ writeAsElement(xml, STR_MATCHPAIR_START, start); } for(const auto& end : m.endEquivalentSet){ writeAsElement(xml, STR_MATCHPAIR_END, end); } xml.writeEndElement(); // MatchPair element } xml.writeEndElement(); // MatchPairList element // ignore list xml.writeStartElement(STR_IGNORE_LIST); for(const auto& ignore : p.ignoreList){ writeAsElement(xml, STR_IGNORE, ignore); } xml.writeEndElement(); // IgnoreList element // parser node list xml.writeStartElement(STR_PARSERNODE_LIST); for(int i = 0, n = p.nodes.size(); i < n; ++i){ const auto& node = p.nodes.at(i); xml.writeStartElement(STR_PARSERNODE); xml.writeAttribute(STR_NAME, node.name); xml.writeAttribute(STR_INDEX, QString::number(i)); // node parameters xml.writeStartElement(STR_PARAMETER_LIST); for(int i = 0, n = node.parameterNameList.size(); i < n; ++i){ xml.writeStartElement(STR_PARAMETER); xml.writeAttribute(STR_NAME, node.parameterNameList.at(i)); xml.writeAttribute(STR_INDEX, QString::number(i)); xml.writeEndElement(); // Parameter element } xml.writeEndElement(); // ParameterList element // patterns xml.writeStartElement(STR_PATTERN_LIST); for(int i = 0, n = node.patterns.size(); i < n; ++i){ const auto& p = node.patterns.at(i); xml.writeStartElement(STR_PATTERN); xml.writeAttribute(STR_INDEX, QString::number(i)); // pattern string writeAsElement(xml, STR_PATTERNSTRING, p.patternString); // priority override writeAsElement(xml, STR_PRIORITY_OVERRIDE, QString::number(p.priorityScore)); xml.writeStartElement(STR_VALUE_OVERWRITE_LIST); for(int i = 0, n = p.valueOverwriteList.size(); i < n; ++i){ const auto& record = p.valueOverwriteList.at(i); xml.writeStartElement(STR_OVERWRITE); xml.writeAttribute(STR_PARAMETER, record.paramName); xml.writeCharacters(record.valueExpr); xml.writeEndElement(); } xml.writeEndElement(); // ValueOverwriteList element xml.writeEndElement(); // Pattern element } xml.writeEndElement(); // PatternList element xml.writeStartElement(STR_CHILD_LIST); for(int i = 0, n = node.childNodeNameList.size(); i < n; ++i){ writeAsElement(xml, STR_CHILD, i, node.childNodeNameList.at(i)); } xml.writeEndElement(); // ChildList element xml.writeStartElement(STR_EXIT_PATTERN_LIST); for(int i = 0, n = node.earlyExitPatterns.size(); i < n; ++i){ writeAsElement(xml, STR_EXIT_PATTERN, node.earlyExitPatterns.at(i)); } xml.writeEndElement(); // ExitPatternList element writeAsElement(xml, STR_TO_IRNODE, node.combineToNodeTypeName); xml.writeStartElement(STR_VALUE_TRANSFORM_LIST); for(auto iter = node.combinedNodeParams.begin(), iterEnd = node.combinedNodeParams.end(); iter != iterEnd; ++iter){ xml.writeStartElement(STR_VALUE_TRANSFORM); writeAsElement(xml, STR_IRNODE_PARAM, iter.key()); for(int i = 0, n = iter.value().size(); i < n; ++i){ writeAsElement(xml, STR_IRNODE_PARAM, i, iter.value().at(i)); } xml.writeEndElement(); // ValueTransform element } xml.writeEndElement(); // ValueTransformList element xml.writeEndElement(); // ParserNode element } xml.writeEndElement(); // ParserNodeList element xml.writeEndElement(); // Parser element } Parser* XML::readParser(const IRRootType& ty, DiagnosticEmitterBase& diagnostic, QXmlStreamReader& xml) { Q_UNUSED(ty) Q_UNUSED(diagnostic) Q_UNUSED(xml) return nullptr; } <file_sep>/core/test.cpp #include "core/XML.h" #include "core/Bundle.h" #include "core/DiagnosticEmitter.h" #include "core/Expression.h" #include "core/IR.h" #include "core/Task.h" #include "core/CLIDriver.h" #include "core/OutputHandlerBase.h" #include "core/ExecutionContext.h" #include "core/Parser.h" #include <QDebug> #include <stdexcept> #include <memory> void testWriteXML(){ ConsoleDiagnosticEmitter diag; IRRootType* ty = new IRRootType("test"); { IRNodeType speech("speech"); speech.addParameter("character", ValueType::String, false); speech.addParameter("dummy", ValueType::Int64, false); speech.addParameter("text", ValueType::String, false); IRNodeType back("back"); back.addParameter("text", ValueType::String, false); IRNodeType root("root"); root.addChildNode("speech"); root.addChildNode("back"); ty->addNodeTypeDefinition(root); ty->addNodeTypeDefinition(speech); ty->addNodeTypeDefinition(back); ty->setRootNodeType("root"); } Q_ASSERT(ty->validate(diag)); int speechTyIndex = ty->getNodeTypeIndex("speech"); int backTyIndex = ty->getNodeTypeIndex("back"); IRRootInstance* inst = new IRRootInstance(*ty); int rootIdx = inst->addNode(ty->getNodeTypeIndex("root")); auto& root = inst->getNode(rootIdx); int s1 = inst->addNode(speechTyIndex); { auto& s1n = inst->getNode(s1); s1n.setParent(rootIdx); root.addChildNode(s1); QList<QVariant> args; args.push_back(QVariant("TA")); args.push_back(QVariant(0ll)); args.push_back(QVariant("Hello world!\nUmm..")); s1n.setParameters(args); } int b1 = inst->addNode(backTyIndex); { auto& b1n = inst->getNode(b1); b1n.setParent(rootIdx); root.addChildNode(b1); QList<QVariant> args; args.push_back(QVariant("")); b1n.setParameters(args); } Q_ASSERT(inst->validate(diag)); QFile f("test.txt"); Q_ASSERT(f.open(QIODevice::WriteOnly)); XML::writeIRInstance(*inst, &f); f.close(); Q_ASSERT(f.open(QIODevice::ReadOnly)); IRRootInstance* readBack = XML::readIRInstance(*ty, diag, &f); Q_ASSERT(readBack != nullptr); f.close(); f.setFileName("test2.txt"); Q_ASSERT(f.open(QIODevice::WriteOnly)); XML::writeIRInstance(*readBack, &f); f.close(); delete readBack; delete inst; delete ty; } void testParser(){ ConsoleDiagnosticEmitter diag; IRRootType* ty = new IRRootType("test"); { IRNodeType speech("speech"); speech.addParameter("character", ValueType::String, false); speech.addParameter("dummy", ValueType::Int64, false); speech.addParameter("text", ValueType::String, false); IRNodeType back("back"); back.addParameter("text", ValueType::String, false); IRNodeType root("root"); root.addChildNode("speech"); root.addChildNode("back"); ty->addNodeTypeDefinition(root); ty->addNodeTypeDefinition(speech); ty->addNodeTypeDefinition(back); ty->setRootNodeType("root"); } Q_ASSERT(ty->validate(diag)); ParserPolicy policy; policy.name = QStringLiteral("TestParser"); ParserPolicy::MatchPairRecord quote; quote.name = QStringLiteral("Quote"); QString quoteStr = QStringLiteral("\""); quote.startEquivalentSet.push_back(quoteStr); quote.endEquivalentSet.push_back(quoteStr); policy.matchPairs.push_back(quote); policy.exprStartMark = QStringLiteral("<"); policy.exprEndMark = QStringLiteral(">"); policy.ignoreList.push_back(QStringLiteral(" ")); policy.rootParserNodeName = QStringLiteral("root"); ParserNode speechNode; speechNode.name = QStringLiteral("speech"); ParserNode backNode; backNode.name = QStringLiteral("back"); ParserNode speechNode2; speechNode2.name = QStringLiteral("speech2"); { ParserNode rootNode; rootNode.name = policy.rootParserNodeName; rootNode.childNodeNameList.push_back(speechNode.name); rootNode.childNodeNameList.push_back(backNode.name); rootNode.childNodeNameList.push_back(speechNode2.name); policy.nodes.push_back(rootNode); } speechNode.parameterNameList.push_back(QStringLiteral("character")); speechNode.parameterNameList.push_back(QStringLiteral("dummy")); speechNode.parameterNameList.push_back(QStringLiteral("text")); speechNode2.parameterNameList.push_back(QStringLiteral("text")); backNode.parameterNameList.push_back(QStringLiteral("text")); { ParserNode::Pattern speechPattern; speechPattern.patternString = QStringLiteral("<character>:\"<text>\""); ParserNode::Pattern::ParamValueOverwriteRecord dummyRecord; dummyRecord.paramName = QStringLiteral("dummy"); dummyRecord.valueExpr = QStringLiteral("1"); speechPattern.valueOverwriteList.push_back(dummyRecord); speechNode.patterns.push_back(speechPattern); policy.nodes.push_back(speechNode); } { ParserNode::Pattern speech2Pattern; speech2Pattern.patternString = QStringLiteral("\"<text>\""); speechNode2.patterns.push_back(speech2Pattern); speechNode2.combineToNodeTypeName = QStringLiteral("speech"); QStringList dummyList; dummyList.push_back(QStringLiteral("2")); QStringList characterValList; characterValList.push_back(QStringLiteral("<../speech[-0].character>")); speechNode2.combinedNodeParams.insert(QStringLiteral("dummy"), dummyList); speechNode2.combinedNodeParams.insert(QStringLiteral("character"), characterValList); policy.nodes.push_back(speechNode2); } { ParserNode::Pattern backPattern; backPattern.patternString = QStringLiteral("<text>"); backNode.patterns.push_back(backPattern); policy.nodes.push_back(backNode); } QFile f("policy.txt"); Q_ASSERT(f.open(QIODevice::WriteOnly)); QXmlStreamWriter xml(&f); xml.setAutoFormatting(true); xml.setAutoFormattingIndent(2); xml.writeStartDocument(); XML::writeParser(policy, xml); xml.writeEndDocument(); f.close(); Parser* p = Parser::getParser(policy, *ty, diag); Q_ASSERT(p != nullptr); QString l1("TA:\"Hello guys...\""); QString l2("umm.. not many people is here."); QString l3("\"Okay lets get started\""); QVector<QStringRef> tu; tu.push_back(QStringRef(&l1)); tu.push_back(QStringRef(&l2)); tu.push_back(QStringRef(&l3)); IRRootInstance* ir = p->parse(tu, *ty, diag); Q_ASSERT(ir != nullptr); f.setFileName("ir.txt"); Q_ASSERT(f.open(QIODevice::WriteOnly)); XML::writeIRInstance(*ir, &f); f.close(); } void bundleTest(){ Bundle* ptr = nullptr; IRRootInstance* instPtr = nullptr; { QFile f(QStringLiteral("../test.json")); if(!f.open(QIODevice::ReadOnly)){ qDebug()<< "test.json open failed"; return; } QByteArray ba = f.readAll(); f.close(); ConsoleDiagnosticEmitter diagnostic; ptr = Bundle::fromJson(ba, diagnostic); if(ptr){ qDebug()<<"bundle read success"; }else{ qDebug()<<"bundle read fail"; return; } } { QFile f(QStringLiteral("../instance.json")); if(!f.open(QIODevice::ReadOnly)){ qDebug()<< "instance.json open failed"; return; } QByteArray ba = f.readAll(); f.close(); ConsoleDiagnosticEmitter diagnostic; instPtr = ptr->readIRFromJson(0, ba, diagnostic); if(instPtr){ qDebug()<<"instance read success"; }else{ qDebug()<<"instance read fail"; return; } } TextOutputHandler handler("utf-8"); const Task& t = ptr->getTask(0); ConsoleDiagnosticEmitter diagnostic; ExecutionContext* ctx = new ExecutionContext(t, *instPtr, diagnostic, handler); ctx->continueExecution(); delete ctx; qDebug()<< handler.getResult(); } void testerEntry(){ testParser(); return; } <file_sep>/core/IR.h #ifndef IR_H #define IR_H #include <QCoreApplication> #include <QVariant> #include <QString> #include <QList> #include <QStringList> #include <QHash> #include "core/Value.h" class DiagnosticEmitterBase; class IRNodeType; class IRRootType; class IRNodeInstance; class IRRootInstance; class IRNodeType{ Q_DECLARE_TR_FUNCTIONS(IRNodeType) public: explicit IRNodeType(QString name) : name(name) {} //------------------------------------------------------------------------- // const interface QString getName() const {return name;} int getNumParameter() const {return parameterList.size();} int getNumChildNode() const {return childNodeList.size();} const QString& getChildNodeName(int index) const {return childNodeList.at(index);} QString getParameterName (int parameterIndex) const {return parameterNameList.at(parameterIndex);} ValueType getParameterType (int parameterIndex) const {return parameterList.at(parameterIndex).paramType;} bool getParameterIsUnique(int parameterIndex) const {return parameterList.at(parameterIndex).isUnique;} int getPrimaryKeyParameterIndex()const{return primaryKeyIndex;} int getParameterIndex (const QString& name) const{return parameterNameToIndex.value(name, -1);} int getChildNodeTypeIndex(const QString& name) const{return childNodeNameToIndex.value(name, -1);} bool operator==(const IRNodeType& rhs) const{ return (this == &rhs) || (name == rhs.name && parameterList == rhs.parameterList && parameterNameList == rhs.parameterNameList && childNodeList == rhs.childNodeList); } //------------------------------------------------------------------------- void addChildNode(QString childNodeName) {childNodeList.push_back(childNodeName);} void setPrimaryKey(QString paramName) {primaryKeyName = paramName;} void addParameter(QString name, ValueType paramType, bool isUnique){ parameterNameList.push_back(name); Parameter param; param.paramType = paramType; param.isUnique = isUnique; parameterList.push_back(param); } bool validate(DiagnosticEmitterBase& diagnostic, IRRootType& root); static bool validateName(DiagnosticEmitterBase& diagnostic, const QString& name); private: struct Parameter{ ValueType paramType; bool isUnique; bool operator==(const Parameter& rhs)const{ return paramType == rhs.paramType && isUnique == rhs.isUnique; } }; QString name; int primaryKeyIndex = -1; QString primaryKeyName; QList<Parameter> parameterList; QStringList parameterNameList; QStringList childNodeList; // constructed during validate() QHash<QString, int> parameterNameToIndex; QHash<QString, int> childNodeNameToIndex; // index into childNodeList }; class IRRootType { Q_DECLARE_TR_FUNCTIONS(IRRootType) public: explicit IRRootType(const QString& name) : name(name) {} // no copy or move because this class would be taken reference by others IRRootType(const IRRootType&) = delete; IRRootType(IRRootType&&) = delete; //------------------------------------------------------------------------- // const interface const QString& getName() const {return name;} int getNodeTypeIndex(const QString& nodeName) const {return nodeNameToIndex.value(nodeName, -1);} int getNumNodeType() const {return nodeList.size();} bool isNodeTypeIndexValid(int index) const {return (index >= 0) && (index < nodeList.size());} const IRNodeType& getNodeType (int index) const {return nodeList.at(index);} const IRNodeType& getNodeType (const QString& nodeName) const {return nodeList.at(getNodeTypeIndex(nodeName));} bool operator==(const IRRootType& rhs) const { return nodeList == rhs.nodeList && rootNodeName == rhs.rootNodeName; } //------------------------------------------------------------------------- void addNodeTypeDefinition (const IRNodeType& node) {isValidated = false; nodeList.push_back(node);} void setRootNodeType (const QString& nodeName) {isValidated = false; rootNodeName = nodeName;} bool validated() const {return isValidated;} bool validate(DiagnosticEmitterBase& diagnostic); private: QString name; QList<IRNodeType> nodeList; QString rootNodeName; QHash<QString, int> nodeNameToIndex; int rootNodeIndex = -1; bool isValidated = false; }; class IRNodeInstance { Q_DECLARE_TR_FUNCTIONS(IRNodeInstance) public: explicit IRNodeInstance(int typeIndex, int nodeIndex) : typeIndex(typeIndex), nodeIndex(nodeIndex){} //------------------------------------------------------------------------- // const interface const QVariant& getParameter(int parameterIndex) const {return parameters.at(parameterIndex);} int getTypeIndex() const {return typeIndex;} int getParentIndex() const {return parentIndex;} int getLocalTypeIndex (int tyIndex) const {return childNodeTypeIndexToLocalIndex.value(tyIndex, -1);} int getNumChildNode() const {return childNodeList.size();} int getChildNodeByOrder (int nodeIndex) const {return childNodeList.at(nodeIndex);} int getNumChildNodeUnderType(int nodeLocalTypeIndex)const {return childTypeList.at(nodeLocalTypeIndex).nodeList.size();} int getChildNodeIndex(int nodeLocalTypeIndex, int nodeParamIndex, const QVariant& key)const{ return childTypeList.at(nodeLocalTypeIndex).perParamHash.at(nodeParamIndex).value(key, -1); } int getChildNodeIndex(int nodeLocalTypeIndex, int nodeIndexUnderType)const{ return childTypeList.at(nodeLocalTypeIndex).nodeList.at(nodeIndexUnderType); } //------------------------------------------------------------------------- void addChildNode (int childIndex) {childNodeList.append(childIndex);} void setParent (int index) {parentIndex = index;} void setParameters (const QList<QVariant>& parameters) {this->parameters = parameters;} bool validate(DiagnosticEmitterBase& diagnostic, IRRootInstance& root); private: struct ChildTypeRecord{ QList<QHash<QVariant, int>> perParamHash; //!< lazily constructed hash table; [paramIndex][unique'd param value] -> [child node] QList<int> nodeList; //!< node index list }; const int typeIndex; const int nodeIndex; int parentIndex = -1; QList<QVariant> parameters; QList<int> childNodeList; // constructed during validate() QHash<int, int> childNodeTypeIndexToLocalIndex; // childnode.getTypeIndex() --> ty.childIndex QList<ChildTypeRecord> childTypeList;// one per child node type }; class IRRootInstance { Q_DECLARE_TR_FUNCTIONS(IRRootInstance) friend class IRNodeInstance; public: explicit IRRootInstance(const IRRootType& ty): ty(ty){Q_ASSERT(ty.validated());} // no copy or move because this class would be taken reference by others IRRootInstance(const IRRootInstance&) = delete; IRRootInstance(IRRootInstance&&) = delete; //------------------------------------------------------------------------- // const interface int getNumNode() const {return nodeList.size();} const IRNodeInstance& getNode(int nodeIndex) const {return nodeList.at(nodeIndex);} const IRRootType& getType() const {return ty;} //------------------------------------------------------------------------- int addNode(int typeIndex){ isValidated = false; int index = nodeList.size(); nodeList.append(IRNodeInstance(typeIndex, index)); return index; } IRNodeInstance& getNode(int nodeIndex){ isValidated = false; if(nodeIndex < 0 || nodeList.size() <= nodeIndex){ throw std::out_of_range("Invalid Node Index"); } return nodeList[nodeIndex]; } bool validated() const {return isValidated;} bool validate(DiagnosticEmitterBase& diagnostic); private: const IRRootType& ty; bool isValidated = false; QList<IRNodeInstance> nodeList;// must be stored in pre-order; node 0 is root }; #endif // IR_H <file_sep>/core/Expression.h #ifndef EXPRESSION_H #define EXPRESSION_H #include <QtGlobal> #include <QString> #include <QVariant> #include <QList> #include "core/Value.h" class ExecutionContext; /** * @brief The ExpressionBase class is an interface for any expression that do not have side effects */ class ExpressionBase { Q_DECLARE_TR_FUNCTIONS(ExpressionBase) public: virtual ~ExpressionBase(){} /** * @brief clone return a new instance of expression, needed when copying parent functions around * @return pointer to new instance */ virtual ExpressionBase* clone() const = 0; virtual ValueType getExpressionType() const = 0; /** * @brief getVariableNameReference populates a list of variable names that resolving this expression would need to lookup * @param name the list of variable names to populate */ virtual void getVariableNameReference(QList<QString>& name) const {Q_UNUSED(name)} /** * @brief getDependency get list of expression indices that this expression depends upon * @param dependentExprIndexList */ virtual void getDependency(QList<int>& dependentExprIndexList, QList<ValueType>& exprTypeList) const{ Q_UNUSED(dependentExprIndexList) Q_UNUSED(exprTypeList) } /** * @brief evaluate evaluates the expression * @param ctx the environment of evaluation * @param retVal the return value * @param dependentExprResults dependent expression evaluation results * @return true if execution is successful; false if there is any fatal error that should abort the evaluation */ virtual bool evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const = 0; }; // an expression list that use deep copy class ExprList : public QList<ExpressionBase*> { public: ExprList(): QList<ExpressionBase*>(){} ~ExprList(){ for(ExpressionBase* ptr : *this){ delete ptr; } } ExprList(ExprList&&) = default; ExprList(const ExprList& rhs){ clear(); for(ExpressionBase* ptr : rhs){ push_back(ptr->clone()); } } }; /** * @brief The LiteralExpression class * * Literal value as expression */ class LiteralExpression: public ExpressionBase { public: explicit LiteralExpression(ValueType ty, QVariant val) : ty(ty), val(val) {} explicit LiteralExpression(qint64 val) : ty(ValueType::Int64), val(val) {} explicit LiteralExpression(QString str) : ty(ValueType::String), val(str) {} virtual ~LiteralExpression() override{} virtual LiteralExpression* clone() const override{return new LiteralExpression(ty, val);} virtual ValueType getExpressionType() const override {return ty;} virtual bool evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const override; private: ValueType ty; QVariant val; }; /** * @brief The VariableAddressExpression class * * Create a pointer from variable name lookup */ class VariableAddressExpression: public ExpressionBase { public: explicit VariableAddressExpression(QString varName) : variableName(varName) {} virtual ~VariableAddressExpression() override {} virtual VariableAddressExpression* clone() const override{return new VariableAddressExpression(variableName);} virtual ValueType getExpressionType() const override {return ValueType::ValuePtr;} virtual void getVariableNameReference(QList<QString>& name) const override {name.push_back(variableName);} virtual bool evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const override; private: QString variableName; }; /** * @brief The VariableReadExpression class * * Just read the value by name */ class VariableReadExpression: public ExpressionBase { public: explicit VariableReadExpression(ValueType ty, QString varName) : ty(ty), variableName(varName) {} virtual ~VariableReadExpression() override {} virtual VariableReadExpression* clone() const override {return new VariableReadExpression(ty, variableName);} virtual ValueType getExpressionType() const override {return ty;} virtual void getVariableNameReference(QList<QString>& name) const override {name.push_back(variableName);} virtual bool evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const override; private: ValueType ty; QString variableName; }; /** * @brief The NodeReferenceExpression class * * Create a node pointer */ class NodePtrExpression: public ExpressionBase { public: enum class NodeSpecifier{ CurrentNode, RootNode }; explicit NodePtrExpression(NodeSpecifier specifier) : specifier(specifier) {} virtual ~NodePtrExpression() override {} virtual NodePtrExpression* clone() const override {return new NodePtrExpression(specifier);} virtual ValueType getExpressionType() const override {return ValueType::NodePtr;} virtual bool evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const override; private: NodeSpecifier specifier; }; #endif // EXPRESSION_H <file_sep>/util/ADT.h #ifndef ADT_H #define ADT_H #include <QtGlobal> #include <deque> #include <memory> #include <stdexcept> #include <type_traits> // a run time sized array that can take both int and std::size_t index template<typename T, std::size_t EmbedArraySize = (64-sizeof(std::size_t)-sizeof(T* const))/sizeof(T), typename AllocTy = std::allocator<T> > class RunTimeSizeArray{ static_assert (std::is_pod<T>::value, "Element type of RunTimeSizeArray should be pod" ); public: RunTimeSizeArray(std::size_t size, const T& initializer) : count(size), ptr((size <= EmbedArraySize)? array: (alloc.allocate(size))) { for(std::size_t i = 0; i < size; ++i){ ptr[i] = initializer; } } ~RunTimeSizeArray(){ if(count > EmbedArraySize){ alloc.deallocate(ptr, count); } } std::size_t size() const{return count;} const T& at(int index) const{ if(Q_UNLIKELY(index < 0 || index >= static_cast<int>(count))){ throw std::out_of_range("RunTimeSizeArray.at(): bad index"); } return ptr[index]; } T& at(int index){ if(Q_UNLIKELY(index < 0 || index >= static_cast<int>(count))){ throw std::out_of_range("RunTimeSizeArray.at(): bad index"); } return ptr[index]; } const T& at(std::size_t index) const{ if(Q_UNLIKELY(index >= count)){ throw std::out_of_range("RunTimeSizeArray.at(): bad index"); } return ptr[index]; } T& at(std::size_t index){ if(Q_UNLIKELY(index >= count)){ throw std::out_of_range("RunTimeSizeArray.at(): bad index"); } return ptr[index]; } private: AllocTy alloc; const std::size_t count; T* const ptr; T array[EmbedArraySize]; }; // a stack that both provides int and std::size_t at() and stack interface (top(), push(), pop()) template<typename T> class Stack: public std::deque<T> { public: T& at(int index){ return std::deque<T>::at(static_cast<std::size_t>(index)); } const T& at(int index)const{ return std::deque<T>::at(static_cast<std::size_t>(index)); } T& top(){ return std::deque<T>::back(); } const T& top() const{ return std::deque<T>::back(); } void push(const T& v){ std::deque<T>::push_back(v); } void pop(){ std::deque<T>::pop_back(); } }; #endif // ADT_H <file_sep>/core/XML_IR.cpp #include "core/XML.h" #include "core/Value.h" #include "core/IR.h" #include "core/DiagnosticEmitter.h" #include "util/ADT.h" #include <QDebug> #include <QXmlStreamReader> #include <QXmlStreamWriter> #include <memory> #define XML_INDENT_SPACE 2 namespace{ const QString STR_XML_IRROOTINST = QStringLiteral("IRInstance"); const QString STR_XML_IRROOTINST_TYPENAME = QStringLiteral("TypeName"); const QString STR_XML_IRNODEINST = QStringLiteral("Node"); const QString STR_XML_IRNODEINST_INDEX = QStringLiteral("ID"); const QString STR_XML_IRNODEINST_TYPENAME = QStringLiteral("TypeName"); const QString STR_XML_IRNODEINST_PARAM = QStringLiteral("Parameter"); const QString STR_XML_IRNODEINST_PARAM_NAME = QStringLiteral("Name"); const QString STR_XML_IRNODEINST_PARAM_TYPE = QStringLiteral("Type"); const QString XML_TY_VOID = QStringLiteral("Void"); const QString XML_TY_INT64 = QStringLiteral("Int64"); const QString XML_TY_STRING = QStringLiteral("String"); const QString XML_TY_NODEPTR = QStringLiteral("NodePtr"); const QString XML_TY_VALUEPTR = QStringLiteral("ValuePtr"); QString getValueTypeName(ValueType ty) { switch(ty){ case ValueType::Void: return XML_TY_VOID; case ValueType::Int64: return XML_TY_INT64; case ValueType::String: return XML_TY_STRING; case ValueType::NodePtr: return XML_TY_NODEPTR; case ValueType::ValuePtr: return XML_TY_VALUEPTR; } Q_UNREACHABLE(); } std::pair<bool,ValueType> getValueTypeFromName(QStringRef name) { if(name == XML_TY_STRING) return std::make_pair(true, ValueType::String); if(name == XML_TY_INT64) return std::make_pair(true, ValueType::Int64); if(name == XML_TY_NODEPTR) return std::make_pair(true, ValueType::NodePtr); if(name == XML_TY_VALUEPTR) return std::make_pair(true, ValueType::ValuePtr); if(name == XML_TY_VOID) return std::make_pair(true, ValueType::Void); return std::make_pair(false, ValueType::Void); } } namespace { void writeToXML_IRNode(QXmlStreamWriter& xml, const IRRootInstance& ir, int nodeIndex) { const auto& nodeInst = ir.getNode(nodeIndex); int tyIndex = nodeInst.getTypeIndex(); const auto& nodeTy = ir.getType().getNodeType(tyIndex); xml.writeStartElement(STR_XML_IRNODEINST); xml.writeAttribute(STR_XML_IRNODEINST_TYPENAME, nodeTy.getName()); xml.writeAttribute(STR_XML_IRNODEINST_INDEX, QString::number(nodeIndex)); for(int i = 0, n = nodeTy.getNumParameter(); i < n; ++i){ const QString& paramName = nodeTy.getParameterName(i); xml.writeStartElement(STR_XML_IRNODEINST_PARAM); xml.writeAttribute(STR_XML_IRNODEINST_PARAM_NAME, paramName); ValueType valTy = nodeTy.getParameterType(i); xml.writeAttribute(STR_XML_IRNODEINST_PARAM_TYPE, getValueTypeName(valTy)); const QVariant& val = nodeInst.getParameter(i); switch(valTy){ case ValueType::String: xml.writeCharacters(val.toString()); break; case ValueType::Int64: xml.writeCharacters(QString::number(val.toLongLong())); break; default: Q_UNREACHABLE(); } xml.writeEndElement(); // parameter } if(nodeInst.getNumChildNode() > 0){ for(int i = 0, n = nodeInst.getNumChildNode(); i < n; ++i){ writeToXML_IRNode(xml, ir, nodeInst.getChildNodeByOrder(i)); } } xml.writeEndElement(); // node instance } } void XML::writeIRInstance(const IRRootInstance& ir, QIODevice* dest) { Q_ASSERT(ir.validated()); QXmlStreamWriter xml(dest); xml.setAutoFormatting(true); xml.setAutoFormattingIndent(XML_INDENT_SPACE); xml.writeStartDocument(); const auto& rootTy = ir.getType(); xml.writeStartElement(STR_XML_IRROOTINST); xml.writeAttribute(STR_XML_IRROOTINST_TYPENAME, rootTy.getName()); writeToXML_IRNode(xml, ir, 0); xml.writeEndElement(); // root instance xml.writeEndDocument(); } namespace{ bool readFromXML_IRNodeInstance(QXmlStreamReader& xml, DiagnosticEmitterBase& diagnostic, const IRRootType& ty, IRRootInstance& root, int parentIndex, int& nodeIndex){ Q_ASSERT(xml.isStartElement()); if(Q_UNLIKELY(xml.name() != STR_XML_IRNODEINST)){ diagnostic(Diag::Error_XML_UnexpectedElement, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), STR_XML_IRNODEINST, xml.name().toString()); return false; } QString tyName; for(const auto& attr : xml.attributes()){ if(attr.name() == STR_XML_IRNODEINST_TYPENAME){ tyName = attr.value().toString(); }else if(attr.name() == STR_XML_IRNODEINST_INDEX){ // do nothing; this is ignored and is always recomputed }else{ diagnostic(Diag::Warn_XML_UnexpectedAttribute, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), STR_XML_IRNODEINST, attr.name().toString(), attr.value().toString()); } } DiagnosticPathNode pathNode(diagnostic, QCoreApplication::tr("Node %1").arg(nodeIndex)); int nodeTyIndex = ty.getNodeTypeIndex(tyName); if(Q_UNLIKELY(nodeTyIndex == -1)){ diagnostic(Diag::Error_XML_UnknownIRNodeType, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), tyName); return false; } pathNode.setDetailedName(tyName); const IRNodeType& nodeTy = ty.getNodeType(nodeTyIndex); int numParams = nodeTy.getNumParameter(); QList<QVariant> args; args.reserve(numParams); for(int i = 0; i < numParams; ++i){ args.push_back(QVariant()); } RunTimeSizeArray<bool> isArgSet(static_cast<std::size_t>(numParams), false); // deal with all parameters bool isEndElementFound = false; while(!xml.atEnd()){ xml.readNext(); if(Q_UNLIKELY(xml.hasError())){ diagnostic(Diag::Error_XML_InvalidXML, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), xml.errorString()); return false; } if(xml.isComment() || xml.isCharacters()) continue; if(xml.isEndElement()){ isEndElementFound = true; break; } if(Q_UNLIKELY(!xml.isStartElement())){ diagnostic(Diag::Error_XML_ExpectingStartElement, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), xml.tokenString()); return false; } QStringRef elementName = xml.name(); if(elementName == STR_XML_IRNODEINST){ break; } if(Q_UNLIKELY(elementName != STR_XML_IRNODEINST_PARAM)){ diagnostic(Diag::Error_XML_UnexpectedElement, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), STR_XML_IRNODEINST_PARAM, elementName.toString()); return false; } // deal with parameter here QString paramName; ValueType paramType = ValueType::Void; bool isParamTypeSet = false; for(const auto& attr : xml.attributes()){ if(attr.name() == STR_XML_IRNODEINST_PARAM_NAME){ paramName = attr.value().toString(); }else if(attr.name() == STR_XML_IRNODEINST_PARAM_TYPE){ auto p = getValueTypeFromName(attr.value()); if(Q_UNLIKELY(!p.first)){ diagnostic(Diag::Error_XML_UnknownValueType, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), paramType); return false; } paramType = p.second; isParamTypeSet = true; }else{ diagnostic(Diag::Warn_XML_UnexpectedAttribute, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), STR_XML_IRNODEINST_PARAM, attr.name().toString(), attr.value().toString()); } } if(Q_UNLIKELY(paramName.isEmpty())){ diagnostic(Diag::Error_XML_IRNode_Param_MissingName, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber())); return false; } int paramIndex = nodeTy.getParameterIndex(paramName); if(Q_UNLIKELY(paramIndex == -1)){ diagnostic(Diag::Error_XML_IRNode_Param_UnknownParam, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), paramName); return false; } if(Q_UNLIKELY(!isParamTypeSet)){ diagnostic(Diag::Error_XML_IRNode_Param_MissingType, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber())); return false; } ValueType expectedTy = nodeTy.getParameterType(paramIndex); if(Q_UNLIKELY(paramType != expectedTy)){ diagnostic(Diag::Error_XML_IRNode_Param_TypeMismatch, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), paramName, expectedTy, paramType); return false; } xml.readNext(); // if the string is empty, we may have EndElement right after StartElement QString paramData; if(xml.isCharacters()){ paramData = xml.text().toString(); xml.readNext(); } if(Q_UNLIKELY(!xml.isEndElement())){ diagnostic(Diag::Error_XML_IRNode_Param_ExpectEndElement, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), paramName); return false; } QVariant data; switch(paramType){ case ValueType::String:{ data = paramData; }break; case ValueType::Int64:{ bool isGood = false; data = paramData.toLongLong(&isGood); if(Q_UNLIKELY(!isGood)){ diagnostic(Diag::Error_XML_IRNode_Param_InvalidValue, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), paramName, paramType, paramData); return false; } }break; default: Q_UNREACHABLE(); } // write back parameter bool isArgSetBefore = isArgSet.at(paramIndex); isArgSet.at(paramIndex) = true; if(Q_UNLIKELY(isArgSetBefore)){ diagnostic(Diag::Error_XML_IRNode_Param_MultipleValue, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), paramName); return false; } args[paramIndex] = data; } // check if all parameters are initialized for(int i = 0; i < numParams; ++i){ if(!isArgSet.at(i)){ // generate a warning and default initialize it diagnostic(Diag::Warn_XML_IRNode_MissingParameter, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber())); switch(nodeTy.getParameterType(i)){ case ValueType::String:{ args[i] = QString(); }break; case ValueType::Int64:{ args[i] = static_cast<qlonglong>(0); }break; default: Q_UNREACHABLE(); } } } if(parentIndex != -1){ root.getNode(parentIndex).addChildNode(nodeIndex); } int currentNodeIndex = root.addNode(nodeTyIndex); Q_ASSERT(currentNodeIndex == nodeIndex); nodeIndex += 1; IRNodeInstance& inst = root.getNode(currentNodeIndex); inst.setParent(parentIndex); inst.setParameters(args); // skip first readNext(); that is done when trying to find end of parameters bool isFirstReadAfterParameter = true; if(!isEndElementFound){ // deal with all child elements while(!xml.atEnd()){ if(isFirstReadAfterParameter){ isFirstReadAfterParameter = false; }else{ xml.readNext(); } if(Q_UNLIKELY(xml.hasError())){ diagnostic(Diag::Error_XML_InvalidXML, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), xml.errorString()); return false; } if(xml.isComment() || xml.isCharacters()) continue; if(xml.isEndElement()){ isEndElementFound = true; break; } if(Q_UNLIKELY(!xml.isStartElement())){ diagnostic(Diag::Error_XML_ExpectingStartElement, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), xml.tokenString()); return false; } if(Q_UNLIKELY(xml.name() == STR_XML_IRNODEINST_PARAM)){ diagnostic(Diag::Error_XML_IRNode_ParamAfterChildNode, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber())); return false; } // child node bool isChildGood = readFromXML_IRNodeInstance(xml, diagnostic, ty, root, currentNodeIndex, nodeIndex); if(Q_UNLIKELY(!isChildGood)) return false; } } return true; } } IRRootInstance* XML::readIRInstance(const IRRootType &ty, DiagnosticEmitterBase& diagnostic, QIODevice* src) { Q_ASSERT(ty.validated()); QXmlStreamReader xml(src); std::unique_ptr<IRRootInstance> ptr; // loop till the StartElement of IRRootInstance while(!xml.atEnd()){ xml.readNext(); if(xml.hasError()) break; if(!xml.isStartElement()) continue; if(Q_UNLIKELY(xml.name() != STR_XML_IRROOTINST)){ diagnostic(Diag::Error_XML_UnexpectedElement, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), STR_XML_IRROOTINST, xml.name().toString()); return nullptr; } bool isTypeNameFound = false; for(const auto& attr : xml.attributes()){ if(Q_LIKELY(attr.name() == STR_XML_IRROOTINST_TYPENAME)){ auto tyName = attr.value(); if(tyName != ty.getName()){ diagnostic(Diag::Warn_XML_MismatchedIRTypeName, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), ty.getName(), tyName.toString()); } isTypeNameFound = true; }else{ diagnostic(Diag::Warn_XML_UnexpectedAttribute, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), STR_XML_IRROOTINST, attr.name().toString(), attr.value().toString()); } } ptr.reset(new IRRootInstance(ty)); break; } if(Q_UNLIKELY(!ptr)){ // something is wrong if(xml.hasError()){ diagnostic(Diag::Error_XML_InvalidXML, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), xml.errorString()); return nullptr; } // otherwise we did not find any element (including IRRootInstance) diagnostic(Diag::Error_XML_ExpectingIRRootInstance, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber())); return nullptr; } // seek to the root node while(!xml.atEnd()){ if(xml.readNext() == QXmlStreamReader::StartElement) break; } // make sure we are indeed at QXmlStreamReader::StartElement instead of an error if(Q_UNLIKELY(xml.hasError())){ diagnostic(Diag::Error_XML_InvalidXML, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), xml.errorString()); return nullptr; } Q_ASSERT(xml.isStartElement()); DiagnosticPathNode pathNode(diagnostic, QCoreApplication::tr("IR Root")); int nodeIndex = 0; bool isRootGood = readFromXML_IRNodeInstance(xml, diagnostic, ty, *ptr, -1, nodeIndex); if(!isRootGood){ return nullptr; } while(!xml.atEnd()){ if(xml.readNext() == QXmlStreamReader::EndElement) break; if(xml.isComment()) continue; } if(Q_UNLIKELY(xml.hasError())){ diagnostic(Diag::Error_XML_InvalidXML, static_cast<int>(xml.lineNumber()), static_cast<int>(xml.columnNumber()), xml.errorString()); return nullptr; } if(Q_UNLIKELY(!(ptr->validate(diagnostic)))){ return nullptr; } return ptr.release(); } <file_sep>/ui/DocumentWidget.cpp #include "ui/DocumentWidget.h" #include "ui/PlainTextDocumentWidget.h" DocumentWidget* DocumentWidget::createInstance(QString filePath) { return new PlainTextDocumentWidget(filePath, nullptr); } QString DocumentWidget::getTabDisplayName() const { QString name; if(isDirty()) name.append('*'); if(isReadOnly()){ name.append(tr("[R]")); name.append(' '); } name.append(getFileName()); return name; } QString DocumentWidget::getTitleDisplayName() const { QString absolutePath = getAbsoluteFilePath(); if(absolutePath.isEmpty()) return getTabDisplayName(); QString name; if(isDirty()) name.append('*'); if(isReadOnly()){ name.append(tr("[R]")); name.append(' '); } name.append(absolutePath); return name; } void DocumentWidget::checkFileUpdate() { fileRecheck(); } <file_sep>/core/Task.h #ifndef TASK_H #define TASK_H #include <QString> #include <QStack> #include <memory> #include "core/Value.h" #include "core/Expression.h" class DiagnosticEmitterBase; class ExecutionContext; class IRRootType; class Task; enum class StatementType{ Unreachable, //!< trigger execution abort Assignment, //!< write to a value reference Output, //!< write result to output Call, //!< call a function Return, //!< function return Branch //!< any branch within function }; struct Statement{ StatementType ty; int statementIndexInType; }; // no data for unreachable statement struct AssignmentStatement{ int lvalueExprIndex; //!< expression index of left hand side; -1 for name based assignment int rvalueExprIndex; //!< expression index of right hand side QString lvalueName; //!< name of variable at left hand size; only used if expr index is -1 }; struct OutputStatement{ int exprIndex; //!< expression for output }; struct CallStatement{ QString functionName; QList<int> argumentExprList; }; struct BranchStatement{ struct BranchCase{ int exprIndex; int stmtIndex; //!< statement index to jump to if the expression evaluates to true; -2 if unreachable, -1 if fall through }; int defaultStmtIndex; //!< stmt to go to if none of the condition applies; -2 if unreachable, -1 if fall through QList<BranchCase> cases; }; // the struct to add branch before label names are resolved struct BranchStatementTemp{ enum class BranchActionType{ Unreachable, Fallthrough, Jump }; struct BranchCase{ int exprIndex; BranchActionType action; QString labelName; }; BranchActionType defaultAction; QString defaultJumpLabelName; QList<BranchCase> cases; }; /** * @brief The Function class */ class Function{ Q_DECLARE_TR_FUNCTIONS(Function) public: explicit Function(QString name): functionName(name){} ~Function(){} //------------------------------------------------------------------------- // const interface const QString& getName()const{return functionName;} int getNumExternVariableUsed() const {return externVariableNameList.size();} int getExternVariableIndex(const QString& name) const {return externVariableNameToIndex.value(name, -1);} ValueType getExternVariableType(int externVarIndex) const {return externVariableTypeList.at(externVarIndex);} ValueType getExternVariableType(const QString& name) const {return externVariableTypeList.at(externVariableNameToIndex.value(name, -1));} // note that function parameter is implicitly a local variable // (local variable count >= total parameter count >= required parameter count) int getNumParameter() const {return paramCount;} int getNumRequiredParameter() const {return requiredParamCount;} int getNumLocalVariable() const {return localVariableNames.size();} int getLocalVariableIndex (const QString& varName) const {return localVariableNameToIndex.value(varName, -1);} const QString& getLocalVariableName (int localVarIndex) const {return localVariableNames.at(localVarIndex);} ValueType getLocalVariableType (int localVarIndex) const {return localVariableTypes.at(localVarIndex);} const QVariant& getLocalVariableInitializer (int localVarIndex) const {return localVariableInitializer.at(localVarIndex);} int getNumExpression() const {return exprList.size();} int getNumStatement() const {return stmtList.size();} const ExpressionBase* getExpression(int exprIndex) const {return exprList.at(exprIndex);} const Statement& getStatement (int stmtIndex) const {return stmtList.at(stmtIndex);} const AssignmentStatement& getAssignmentStatement (int assignStmtIndex) const {return assignStmtList.at(assignStmtIndex);} const OutputStatement& getOutputStatement (int outputStmtIndex) const {return outputStmtList.at(outputStmtIndex);} const CallStatement& getCallStatement (int callStmtIndex) const {return callStmtList.at(callStmtIndex);} const BranchStatement& getBranchStatement (int branchStmtIndex) const {return branchStmtList.at(branchStmtIndex);} int getNumLabel() const {return labels.size();} const QString& getLabelName (int labelIndex) const {return labels.at(labelIndex);} int getLabelAddress (int labelIndex) const {return labeledStmtIndexList.at(labelIndex);} const QStringList& getReferencedFunctionList() const {return calledFunctions;} //------------------------------------------------------------------------- /** * @brief addLocalVariable add a local variable (or function formal argument) definition * @param name name of local variable to add * @param ty type of local variable * @param initializer the initial value of local variable, default value for argument */ void addLocalVariable(const QString& name, ValueType ty, QVariant initializer = QVariant()) { int index = localVariableNames.size(); localVariableNames.push_back(name); localVariableTypes.push_back(ty); localVariableInitializer.push_back(initializer); localVariableNameToIndex.insert(name, index); } void setParamCount(int cnt){paramCount = cnt;} void setRequiredParamCount(int cnt){requiredParamCount = cnt;} void addExternVariable(const QString& name, ValueType ty) { int index = externVariableNameList.size(); externVariableNameList.push_back(name); externVariableTypeList.push_back(ty); externVariableNameToIndex.insert(name, index); } /** * @brief addExpression adds the expression to the function. Function will take over the object ownership * @param ptr pointer to expression being passed * @return expression index */ int addExpression(ExpressionBase* ptr){ int index = exprList.size(); exprList.push_back(ptr); return index; } int addUnreachableStatement(){ int stmtIndex = stmtList.size(); stmtList.push_back(Statement{StatementType::Unreachable, -1}); return stmtIndex; } int addReturnStatement(){ int stmtIndex = stmtList.size(); stmtList.push_back(Statement{StatementType::Return, -1}); return stmtIndex; } int addStatement(const AssignmentStatement& stmt){ int stmtIndex = stmtList.size(); Statement stmtInst = { StatementType::Assignment, assignStmtList.size() }; stmtList.push_back(stmtInst); assignStmtList.push_back(stmt); return stmtIndex; } int addStatement(const OutputStatement& stmt){ int stmtIndex = stmtList.size(); Statement stmtInst = { StatementType::Output, outputStmtList.size() }; stmtList.push_back(stmtInst); outputStmtList.push_back(stmt); return stmtIndex; } int addStatement(const CallStatement& stmt){ int stmtIndex = stmtList.size(); Statement stmtInst = { StatementType::Call, callStmtList.size() }; stmtList.push_back(stmtInst); callStmtList.push_back(stmt); return stmtIndex; } int addStatement(const BranchStatementTemp& stmt){ int stmtIndex = stmtList.size(); Statement stmtInst = { StatementType::Branch, branchTempStmtList.size() }; stmtList.push_back(stmtInst); branchTempStmtList.push_back(stmt); return stmtIndex; } int addLabel(QString labelName){ int index = labels.size(); labels.push_back(labelName); labeledStmtIndexList.push_back(stmtList.size()); return index; } bool validate(DiagnosticEmitterBase& diagnostic, const Task& task); private: ExprList exprList; QList<Statement> stmtList; // unreachable statement do not have additional data QList<AssignmentStatement> assignStmtList; QList<OutputStatement> outputStmtList; QList<CallStatement> callStmtList; QList<BranchStatement> branchStmtList; QList<BranchStatementTemp> branchTempStmtList; // one to one conversion to branchStmtList during validate QStringList labels; QList<int> labeledStmtIndexList; // any reference to variables that are not local variables // (node members / parameters, global variables) QStringList externVariableNameList; QList<ValueType> externVariableTypeList; int paramCount = 0; int requiredParamCount = 0; //!< number of parameters without initializer QString functionName; QStringList localVariableNames; QList<ValueType> localVariableTypes; QList<QVariant> localVariableInitializer; // constructed during construction QHash<QString, int> externVariableNameToIndex; QHash<QString, int> localVariableNameToIndex; // constructed during validate() QStringList calledFunctions;// debug / error checking purpose only }; class Task { Q_DECLARE_TR_FUNCTIONS(Task) public: Task(const IRRootType& root); // no copy or move because this class would be taken reference by others Task(const Task&) = delete; Task(Task&&) = delete; void addGlobalVariable(QString varName, ValueType ty, QVariant initializer = QVariant()){ isValidated = false; globalVariables.varNameList.push_back(varName); globalVariables.varTyList.push_back(ty); globalVariables.varInitializerList.push_back(initializer); } void addNodeMember(int nodeIndex, QString memberName, ValueType ty, QVariant initializer = QVariant()){ isValidated = false; if(Q_UNLIKELY(nodeIndex < 0 || nodeIndex >= nodeMemberDecl.size())){ throw std::out_of_range("Bad node index"); } MemberDecl& decl = nodeMemberDecl[nodeIndex]; decl.varNameList.push_back(memberName); decl.varTyList.push_back(ty); decl.varInitializerList.push_back(initializer); } int addFunction(const Function& f){ int index = functions.size(); functions.push_back(f); functionNameToIndex.insert(f.getName(), index); return index; } enum class CallbackType{ OnEntry, OnExit }; void setNodeCallback(int nodeIndex, const QString& functionName, CallbackType ty){ if(Q_UNLIKELY(nodeIndex < 0 || nodeIndex >= nodeCallbacks.size())){ throw std::out_of_range("Bad node index"); } NodeCallbackRecord& record = nodeCallbacks.back()[nodeIndex]; int functionIndex = getFunctionIndex(functionName); switch(ty){ case CallbackType::OnEntry: record.onEntryFunctionIndex = functionIndex; break; case CallbackType::OnExit: record.onExitFunctionIndex = functionIndex; break; } } int getNodeCallback(int nodeIndex, CallbackType ty, int passIndex)const{ const NodeCallbackRecord& record = nodeCallbacks.at(passIndex).at(nodeIndex); switch(ty){ case CallbackType::OnEntry: return record.onEntryFunctionIndex; case CallbackType::OnExit: return record.onExitFunctionIndex; } Q_UNREACHABLE(); } int addNewPass(); //------------------------------------------------------------------------- // const interface int getNumGlobalVariable()const{return globalVariables.varNameList.size();} int getGlobalVariableIndex (const QString& name) const {return globalVariables.getIndex(name);} const QString& getGlobalVariableName (int index) const {return globalVariables.varNameList.at(index);} ValueType getGlobalVariableType (int index) const {return globalVariables.varTyList.at(index);} const QVariant& getGlobalVariableInitializer(int index) const {return globalVariables.varInitializerList.at(index);} int getNumNodeMember (int nodeTypeIndex) const {return nodeMemberDecl.at(nodeTypeIndex).varNameList.size();} int getNodeMemberIndex (int nodeTypeIndex, const QString& name)const {return nodeMemberDecl.at(nodeTypeIndex).getIndex(name);} const QString& getNodeMemberName (int nodeTypeIndex, int memberIndex) const {return nodeMemberDecl.at(nodeTypeIndex).varNameList.at(memberIndex);} ValueType getNodeMemberType (int nodeTypeIndex, int memberIndex) const {return nodeMemberDecl.at(nodeTypeIndex).varTyList.at(memberIndex);} const QVariant& getNodeMemberInitializer(int nodeTypeIndex, int memberIndex) const {return nodeMemberDecl.at(nodeTypeIndex).varInitializerList.at(memberIndex);} int getNumPass()const{return nodeCallbacks.size();} int getNumFunction()const{return functions.size();} int getFunctionIndex(const QString& functionName) const {return functionNameToIndex.value(functionName, -1);} const Function& getFunction (int functionIndex) const {return functions.at(functionIndex);} const IRRootType& getRootType() const {return root;} //------------------------------------------------------------------------- bool validated() const {return isValidated;} bool validate(DiagnosticEmitterBase& diagnostic); private: struct MemberDecl{ QHash<QString, int> varNameToIndex; QStringList varNameList; QList<ValueType> varTyList; QList<QVariant> varInitializerList; int getIndex(const QString& name)const{ auto iter = varNameToIndex.find(name); if(Q_UNLIKELY(iter == varNameToIndex.end())){ return -1; } return iter.value(); } }; struct NodeCallbackRecord{ int onEntryFunctionIndex; int onExitFunctionIndex; }; const IRRootType& root; bool isValidated = false; MemberDecl globalVariables; // indexed by nodeIndex as in IRRoot QList<MemberDecl> nodeMemberDecl; QList<QList<NodeCallbackRecord>> nodeCallbacks; QList<Function> functions; // constructed during validation QHash<QString, int> functionNameToIndex; }; #endif // TASK_H <file_sep>/core/Bundle.h #ifndef BUNDLE_H #define BUNDLE_H #include <QList> #include "core/OutputHandlerBase.h" class IRRootType; class IRRootInstance; class Task; class DiagnosticEmitterBase; // work in progress class Bundle { Q_DECLARE_TR_FUNCTIONS(Bundle) public: Bundle(){} int getNumIR()const{return irTypes.size();} int getNumTask()const{return taskInfo.size();} const IRRootType& getIR(int irIndex)const{return *irTypes.at(irIndex);} const Task& getTask(int taskIndex)const{return *taskInfo.at(taskIndex).ptr;} static Bundle* fromJson(const QByteArray& json, DiagnosticEmitterBase& diagnostic); IRRootInstance* readIRFromJson(int irIndex, const QByteArray& json, DiagnosticEmitterBase &diagnostic); private: struct TaskRecord{ Task* ptr; //!< ptr to task object int inputIRType; //!< which input type the task can work on enum class TaskOutputType{ NoOutput, //!< no output (e.g. validation) IR, //!< the task performs IR-to-IR transform External, //!< the task outputs external format }; int outputTypeIndex;//!< index in outputTypes if it writes External output, index in irTypes if it writes IR output }; QList<OutputDescriptor> outputTypes; QList<IRRootType*> irTypes; QList<TaskRecord> taskInfo; QHash<QString, int> irNameToIndex; //!< IR name -> index in irTypes QHash<QString, int> outputNameToIndex; //!< Output name -> index in outputTypes }; #endif // BUNDLE_H <file_sep>/ui/main.cpp #include "ui/MainWindow.h" #include "core/CLIDriver.h" #include <QApplication> #include <QCoreApplication> #include <QCommandLineParser> int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName( "SUPP Development Team" ); QCoreApplication::setApplicationName( "supp" ); QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication a(argc, argv); QCommandLineParser parser; QCommandLineOption testOption(QStringList() << "t" << "test", QCoreApplication::tr("Run self test")); parser.addOption(testOption); parser.process(a); bool isTest = parser.isSet(testOption); if(isTest){ // any test (assertion) failure will trigger abort testerEntry(); return 0; } MainWindow w; w.show(); return a.exec(); } <file_sep>/ui/DocumentEdit.h #ifndef DOCUMENTEDIT_H #define DOCUMENTEDIT_H #include <QObject> #include <QWidget> #include <QPlainTextEdit> // reference: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html class DocumentLineNumberArea; class DocumentEdit : public QPlainTextEdit { Q_OBJECT friend class DocumentLineNumberArea; public: DocumentEdit(QWidget *parent = nullptr); protected: void resizeEvent(QResizeEvent *e) override; private slots: void updateLineNumberAreaWidth(int newBlockCount); void updateLineNumberArea(const QRect &, int); void highlightCurrentLine(); private: int lineNumberAreaWidth() const; void lineNumberAreaPaintEvent(QPaintEvent *event); private: DocumentLineNumberArea* lineNumberArea; }; class DocumentLineNumberArea : public QWidget { Q_OBJECT public: DocumentLineNumberArea(DocumentEdit* editor) : QWidget(editor), editor(editor) {} QSize sizeHint() const override { return QSize(editor->lineNumberAreaWidth(), 0); } protected: void paintEvent(QPaintEvent *event) override { editor->lineNumberAreaPaintEvent(event); } private: DocumentEdit* editor; }; #endif // DOCUMENTEDIT_H <file_sep>/core/DiagnosticEmitter.cpp #include "core/DiagnosticEmitter.h" #include <QDebug> DiagnosticPathNode::DiagnosticPathNode(DiagnosticEmitterBase& d, const QString& pathName) : d(d), prev(d.head), pathName(pathName), hierarchyIndex(d.hierarchyCount) { d.head = this; d.hierarchyCount += 1; } void DiagnosticPathNode::release() { Q_ASSERT(hierarchyIndex >= 0); Q_ASSERT(d.hierarchyCount == hierarchyIndex + 1); d.head = prev; d.hierarchyCount = hierarchyIndex; hierarchyIndex = -1; } namespace{ // just for test purpose void testDump( const QStringList& path, const QString& msgType, const QString& msgCategory, const QString& msg, const QString& optionalText) { QString finalmsg; finalmsg.append(msgType); finalmsg.append(" ["); finalmsg.append(msgCategory); finalmsg.append("]: "); finalmsg.append(msg); finalmsg.append("\nPath: "); finalmsg.append(path.join(QString())); if(!optionalText.isEmpty()){ finalmsg.append("\nAdditional Info: "); finalmsg.append(optionalText); } qWarning() << finalmsg; } }// anonymous namespace void ConsoleDiagnosticEmitter::diagnosticHandle(Diag::ID id, const QList<QVariant>& data) { Q_UNUSED(data) QStringList pathList; auto ptr = currentHead(); while(ptr){ QString name = ptr->getPathName(); QString detail = ptr->getDetailedName(); if(!detail.isEmpty()){ name.append(" ("); name.append(detail); name.append(')'); } pathList.push_front(name); ptr = ptr->getPrev(); } QString optionalText; for(const auto& item : data){ switch(static_cast<QMetaType::Type>(item.type())){ default:{ int ty = item.userType(); if(ty == qMetaTypeId<ValueTypeWrapper>()){ optionalText.append("[ValueType: "); ValueType vty = item.value<ValueTypeWrapper>().ty; optionalText.append(getTypeNameString(vty)); optionalText.append(']'); }else if(ty == qMetaTypeId<StringDiagnosticRecord>()){ StringDiagnosticRecord record = item.value<StringDiagnosticRecord>(); optionalText.append("[StringDiagnostic: str=\""); optionalText.append(record.str); optionalText.append("\", info=\""); optionalText.append(record.str.mid(record.infoStart, record.infoEnd - record.infoStart)); optionalText.append("\"("); optionalText.append(QString::number(record.infoStart)); optionalText.append(','); optionalText.append(QString::number(record.infoEnd)); optionalText.append("), err=\""); optionalText.append(record.str.mid(record.errorStart, record.errorEnd - record.errorStart)); optionalText.append("\"("); optionalText.append(QString::number(record.errorStart)); optionalText.append(','); optionalText.append(QString::number(record.errorEnd)); optionalText.append(")]"); }else{ optionalText.append("[UnknownType]"); } }break; case QMetaType::Type::Int:{ optionalText.append("[int: "); optionalText.append(QString::number(item.toInt())); optionalText.append("]"); }break; case QMetaType::Type::QString:{ optionalText.append("[string: "); optionalText.append(item.toString()); optionalText.append("]"); }break; case QMetaType::Type::QStringList:{ optionalText.append("[stringlist: "); QStringList list = item.toStringList(); for(const auto& str : list){ optionalText.append(' '); optionalText.append('"'); optionalText.append(str); optionalText.append('"'); } optionalText.append("]"); }break; } } testDump(pathList, QStringLiteral("Diagnostic"), Diag::getString(id), QString(), optionalText); } /* DiagnosticEmitter::DiagnosticEmitter(QObject *parent) : QObject(parent) { } */ <file_sep>/ui/MainWindow.cpp #include "ui/MainWindow.h" #include "ui_MainWindow.h" #include "ui/DocumentWidget.h" #include <QtGlobal> #include <QMessageBox> #include <QFileDialog> #include <QCloseEvent> #include <QTabBar> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), tabWidget(nullptr) { ui->setupUi(this); ForwardingTabWidget* tab = new ForwardingTabWidget(this); tabWidget = tab; tabWidget->setMovable(true); tabWidget->setTabsClosable(true); ui->centralwidget->layout()->addWidget(tabWidget); // create a temporary one newRequested(); connect(tabWidget, &QTabWidget::currentChanged, this, &MainWindow::updateTitle); connect(tabWidget, &QTabWidget::currentChanged, this, &MainWindow::fileCheckRelaySlot); connect(tabWidget, &QTabWidget::tabCloseRequested, this, &MainWindow::tabCloseSlot); connect(ui->actionNew, &QAction::triggered, this, &MainWindow::newRequested); connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::openRequested); connect(ui->actionSave, &QAction::triggered, this, &MainWindow::saveRequested); connect(ui->actionSaveAs, &QAction::triggered, this, &MainWindow::saveAsRequested); connect(ui->actionSaveAll, &QAction::triggered, this, &MainWindow::saveAllRequested); connect(ui->actionClose, &QAction::triggered, this, &MainWindow::closeRequested); setFocusPolicy(Qt::StrongFocus); tab->setTabBarEventFilter(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::focusInEvent(QFocusEvent *event) { getCurrentDocumentWidget()->checkFileUpdate(); QMainWindow::focusInEvent(event); } void MainWindow::closeEvent(QCloseEvent *event) { if(!closeWindowConfirmation()){ event->ignore(); return; } QMainWindow::closeEvent(event); } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // return false to pass through the event and true to intercept it // get right click event on tab if(obj == static_cast<QObject*>(tabWidget->tabBar())){ if(event->type() == QEvent::MouseButtonPress){ QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); QPoint pos = mouseEvent->pos(); int index = tabWidget->currentIndex(); for(int i = 0, num = tabWidget->count(); i < num; ++i){ if(tabWidget->tabBar()->tabRect(i).contains(pos)){ index = i; break; } } if(mouseEvent->button() == Qt::RightButton){ QMenu* menu = getDocumentWidget(index)->getMenu(); if(menu){ menu->exec(mouseEvent->globalPos()); delete menu; return true; } } } } return false; } void MainWindow::installNewDocumentWidget(DocumentWidget* doc) { tabWidget->addTab(doc, doc->getTabDisplayName()); connect(doc, &DocumentWidget::stateChanged, [=](){ // update display name int index = tabWidget->indexOf(doc); tabWidget->setTabText(index, doc->getTabDisplayName()); if(index == tabWidget->currentIndex()){ updateTitle(); } }); tabWidget->setCurrentWidget(doc); updateTitle(); } void MainWindow::newRequested() { installNewDocumentWidget(DocumentWidget::createInstance(QString())); } void MainWindow::openRequested() { QString path = QFileDialog::getOpenFileName(this, /* title */ tr("Open file"), /* dir */ getDefaultOpenPath(), /* filter */tr("Any file (*.*)")); if(path.isEmpty()) return; lastOpenPath = path; bool dummy = false; DocumentWidget* doc = findAlreadyOpenedWidget(path, nullptr, dummy); if(doc){ tabWidget->setCurrentWidget(doc); return; } // if there is only one document opening and it is not associated with any file yet, remove that page after opening the specified document DocumentWidget* docToDelete = nullptr; if(tabWidget->count() == 1){ DocumentWidget* curDoc = getCurrentDocumentWidget(); if(curDoc->getAbsoluteFilePath().isEmpty() && curDoc->isEmpty()){ docToDelete = curDoc; } } doc = DocumentWidget::createInstance(path); if(doc->getAbsoluteFilePath().isEmpty()){ QMessageBox::warning(this, tr("Open fail"), tr("Specified file cannot be opened")); delete doc; return; } installNewDocumentWidget(doc); if(docToDelete){ tabWidget->removeTab(tabWidget->indexOf(docToDelete)); docToDelete->deleteLater(); } updateTitle(); } void MainWindow::tabCloseSlot(int index) { handleCloseDocument(getDocumentWidget(index)); } void MainWindow::closeRequested() { handleCloseDocument(getCurrentDocumentWidget()); } void MainWindow::handleCloseDocument(DocumentWidget* doc) { if(doc->isDirty()){ if(!closeDirtyDocumentConfirmation(doc)){ return; } } // trying to remove the last widget will cause a crash // create a new one first if this is the case if(tabWidget->count() <= 1){ Q_ASSERT(static_cast<QWidget*>(doc) == tabWidget->currentWidget()); newRequested(); } tabWidget->removeTab(tabWidget->indexOf(static_cast<QWidget*>(doc))); doc->deleteLater(); } void MainWindow::updateTitle() { DocumentWidget* doc = getCurrentDocumentWidget(); QString title = doc->getTitleDisplayName(); title.append(tr(" - ","concatenation string between current file and application name")); title.append(QCoreApplication::applicationName()); setWindowTitle(title); } void MainWindow::fileCheckRelaySlot(int index) { getDocumentWidget(index)->checkFileUpdate(); } bool MainWindow::closeWindowConfirmation() { int dirtyCount = 0; for(int i = 0, count = tabWidget->count(); i < count; ++i){ if(getDocumentWidget(i)->isDirty()){ dirtyCount += 1; } } if(dirtyCount > 0){ if(QMessageBox::warning(this, /* title */ tr("Close without save"), /* text */ tr("%1 file(s) have unsaved changes. Discard all changes and exit?", "", dirtyCount).arg(dirtyCount), /* button */ QMessageBox::Discard | QMessageBox::Cancel, /* default */ QMessageBox::Cancel ) != QMessageBox::Discard){ return false; } } return true; } void MainWindow::saveRequested() { trySaveDocument(getCurrentDocumentWidget(), false); } void MainWindow::saveAsRequested() { trySaveDocument(getCurrentDocumentWidget(), true); } void MainWindow::saveAllRequested() { for(int i = 0, count = tabWidget->count(); i < count; ++i){ DocumentWidget* doc = getDocumentWidget(i); if(doc->isDirty()){ // stop upon first failure tabWidget->setCurrentIndex(i); if(!trySaveDocument(doc, false)){ return; } } } } bool MainWindow::closeDirtyDocumentConfirmation(DocumentWidget* doc) { auto result = QMessageBox::question(this, /* title */ tr("Save file"), /* text */ tr("Save file \"%1\"?").arg(doc->getFileName()), /* button */ QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, /* default */ QMessageBox::Yes); if(result == QMessageBox::Cancel) return false; if(result == QMessageBox::Yes){ return trySaveDocument(doc, false); } return true; } bool MainWindow::trySaveDocument(DocumentWidget* doc, bool saveAs) { QString path = doc->getAbsoluteFilePath(); if(path.isEmpty() || saveAs){ QString startPath = doc->getAbsoluteFilePath(); if(startPath.isEmpty()){ startPath = getDefaultSavePath(); } path = QFileDialog::getSaveFileName(this, /* title */ tr("Save file"), /* dir */ startPath, /* filter */tr("Any file (*.*)")); if(path.isEmpty()) return false; lastSavePath = path; } // make sure no other DocumentWidget is referencing the same file bool isSrcDocMatch = false; if(findAlreadyOpenedWidget(path, doc, isSrcDocMatch)){ QMessageBox::critical(this, tr("Error"), tr("The file is already opened in supp!")); return false; } // let doc know that we are just saving to the same file if this is the case if(isSrcDocMatch) path.clear(); if(!doc->saveToFile(path)){ QMessageBox::critical(this, tr("Error"), tr("File save failed. Please check permission, available disk space, and existence of parent directories.")); return false; } return true; } DocumentWidget* MainWindow::findAlreadyOpenedWidget(QString path, DocumentWidget* srcDoc, bool& srcDocMatch) { QFileInfo f(path); QString absolutePath = f.absoluteFilePath(); for(int i = 0, count = tabWidget->count(); i < count; ++i){ DocumentWidget* currentDoc = getDocumentWidget(i); if(currentDoc->getAbsoluteFilePath() == absolutePath){ if(currentDoc == srcDoc){ srcDocMatch = true; continue; } return currentDoc; } } return nullptr; } <file_sep>/core/Parser.h #ifndef PARSER_H #define PARSER_H #include <QCoreApplication> #include <QString> #include <QList> #include <QHash> #include <QSet> #include <QStringList> #include <QStringRef> #include <QRegularExpression> #include <QVector> #include <functional> #include <utility> class DiagnosticEmitterBase; class IRRootType; class IRRootInstance; struct ParserNode { QString name; QStringList parameterNameList; //!< parameters needed from patterns (all in string) struct Pattern{ // we don't explicitly extract list of parameters/arguments; they are detected at validation time QString patternString; //!< the pattern, specified as string //!< first of all, all substrings in ignore list are ignored //!< if a match pair starts: //!< if the match pair is parameter match pair, interpret the enclosed content as follows: //!< assume the param match pair is <>: (note that characters inside <> should be exact match) //!< regex: //!< <[regex](**"..."**)> (C++ raw string literal style enclosure with '(',')' and '"' reversed) //!< <[regex]"..."> (direct quote; first '"' is the end) //!< literal: //!< <(**"..."**)> //!< <"..."> //!< This form allows literals to include something in ignore list and make them mandatory for matching //!< Auto: //!< No next sub pattern inclusion: <MyParam>. //!< Include first character from the next literal: <MyParam+>. //!< Include entire next sub pattern: <MyParam+*>. //!< //!< otherwise, start a hierarchy with MatchPair //!< otherwise, get it as literal int priorityScore = 0; //!< priority score override; set to 0 if it should be auto computed. /** * @brief The ParamValueOverwriteRecord struct describes an overwrite on ParserNode parameter * * If a pattern do not have fields for a parameter, if the user wants to initialize the parameter, there needs to be an overwrite record for that */ struct ParamValueOverwriteRecord{ QString paramName; //!< the name of parameter to overwrite QString valueExpr; //!< the value expression used for overwriting. Cannot reference any variables outside current ParserNode. //!< Assume parameter match pair is "<" and ">": //!< explicit literal: <(**"..."**)>, <"..."> (only useful for including parameter match pair strings inside final value) //!< value reference: <Expr> (Expr is guaranteed not starting with '(' or '"') }; QList<ParamValueOverwriteRecord> valueOverwriteList; }; QList<Pattern> patterns; QStringList childNodeNameList; //!< names of child ParserNode QStringList earlyExitPatterns; //!< if the node can have children, finding anything inside this during matching children will pop path up to parent QString combineToNodeTypeName; //!< the IRNodeType name that this node be converted to after the end of parsing //!< if this parser node has name matching with one from IR, this can be empty //!< this can also be empty if the node do not get lowered to IR (e.g. comments) QHash<QString, QStringList> combinedNodeParams; //!< for each IR node parameter, //!< what list of expression to try for it //!< final result will be from the first successful evaluation }; struct ParserPolicy { /** * @brief The MatchPairRecord struct describe strings that should appear in pairs * * For paired characters like quotation "" and parenthesis (), we want to match them in pairs * Each MatchPairRecord describes what should appear in pairs * Each equivalent set describes all equivalent strings that can be used as the mark of the match pair * For example: * match quotation mark: start = {"\""}, end = {"\""} * match parenthesis: start = {"("}, end = {")"} * match string "begin"/"begins" and "end"/"ends": start = {"begin", "begins"}, end = {"end", "ends"} * During "expansion" of parameter/subtree, When any string in a start set is encountered, * the parser will jump to the end of matching end marker, then looking for end of subtree. * The order of string in each equivalent set do not matter during matching. */ struct MatchPairRecord{ QString name; QStringList startEquivalentSet; QStringList endEquivalentSet; }; QString name; QList<MatchPairRecord> matchPairs; //!< What should appear in pairs // what do patterns and value transform expressions use to enclose something that is not a literal // for minimal surprises the match pair for parameters must only have 1 string each for start and end marker QString exprStartMark; QString exprEndMark; QStringList ignoreList; //!< any string appear in ignoreList will be ignored before testing other patterns (whitespace, etc) QList<ParserNode> nodes; QString rootParserNodeName; }; class Parser { Q_DECLARE_TR_FUNCTIONS(Parser) public: /** * @brief getParser get an instance of parser. return nullptr if parser is not valid * @param policy the ParserPolicy taking effect * @param ir the IR the parser will be generating * @param diagnostic the diagnostic for validating ParserPolicy * @return parser instance. Caller takes the ownership. nullptr if validation fails. */ static Parser* getParser(const ParserPolicy& policy, const IRRootType& ir, DiagnosticEmitterBase& diagnostic); /** * @brief parse parse the text input and produce the IR tree instance. * @param text the text input to pass in. Each item is a text unit (where no pattern can match across unit boundary). * @param ir the ir that this parser would generate. This must match with ir from getParser() * @param diagnostic the diagnostic where warnings / errors are reported to. * @return Pointer to the new'ed IR tree. The caller takes ownership of returned IR tree. */ IRRootInstance* parse(QVector<QStringRef>& text, const IRRootType& ir, DiagnosticEmitterBase& diagnostic) const; private: // private constructor so that only getParser() can create instance Parser() = default; private: /** * @brief The TerminatorInclusionMode enum determines how the terminator character is handled when an Auto type sub pattern ends. */ enum class TerminatorInclusionMode{ NoTerminator, //!< the sub pattern is the last in a subtree; no terminator for it Avoid, //!< the sub pattern should stop before the terminator; no text for it is consumed. IncludeOne, //!< the sub pattern includes one instance of terminator. IncludeSuccessive //!< the sub pattern includes all instances of terminator in the chain. ( "<text>." on "umm....." leaves text to "umm.....") }; /* * Note on auto mode: * Sub pattern with "Auto" type will generally peek next sub pattern to decide how much text to match * If the next sub pattern is also an Auto type sub pattern, then any substring in ignore list can finish this pattern * Otherwise, this pattern match until first match of next sub pattern * If there is no "next sub pattern", it matches until the end of text unit * Auto sub pattern can optionally include content of the next sub pattern, * if there is a "next sub pattern" and the next sub pattern is not another sub pattern * In all cases, the matched content will be trimmed so that it do not start / end with a string in ignore list */ enum class SubPatternType{ Literal, //!< the sub pattern match with a string literal Regex, //!< the sub pattern match with a regular expression Auto, //!< the sub pattern match with everything up to next sub pattern. Boundary is automatically detected. MatchPair, //!< the sub pattern match with a match pair start or end marker }; struct SubPattern{ SubPatternType ty = SubPatternType::Literal; //!< the type of sub pattern struct LiteralData{ QString str; }; struct RegexData{ QRegularExpression regex; }; struct AutoData{ QString valueName; bool isTerminateByIgnoredString = false; //!< set to true if there is no "next sub pattern" int nextSubPatternIncludeLength = 0; //!< how many characters from the next sub pattern is included in this pattern; -1 for including the entire match }; struct MatchPairData{ int matchPairIndex = -1; //!< the match pair index to match bool isStart = true; //!< whether the match pair }; LiteralData literalData; RegexData regexData; AutoData autoData; MatchPairData matchPairData; }; /** * @brief The PatternValueTransformNode struct describes a sub expression for parser node value transformation */ struct PatternValueSubExpression{ enum class OpType{ Literal, LocalReference, ExternReference }; OpType ty; struct LiteralData{ QString str; }; struct LocalReferenceData{ QString valueName; }; /** * @brief The ExternReferenceData struct describes a non-local reference, made by a node traversal path and parameter name pair * * each reference should be in the form <NodeExpr>.<ParamName> * no other expression allowed * <NodeExpr>: * parent node: .. * child node: * <ChildNodeName> (for accessing the only child) * <ChildNodeName>[<LookupExpr>] (for accessing child in that type or for lookup) * [<index expr>] (for accessing child by order / occurrence) * * <LookupExpr>: * pure number (no +/-): index (0 based) of child node in given type * <ParamName>=="<ParamValue>": key based lookup * (+/-)pure number: (only when accessing ../<Child>[+/-offset]) index based search; 0 is the last node with given type BEFORE or IS current node * <index expr>: * pure number (no +/-): index (0 based) of node in given parent, no matter which type * (+/-)pure number: offset of node in given parent (index = <index of this node under parent> + offset) * * chaining node reference: use '/', e.g. ../../Child1[0]/Child2[Key="Value"] */ struct ExternReferenceData{ struct NodeTraverseStep{ enum class StepType{ Parent, ChildByTypeAndOrder, ChildByTypeFromLookup, AnyChildByOrder }; struct IndexOrderSearchData{ int lookupNum = 0; bool isNumIndexInsteadofOffset = false; }; struct KeyValueSearchData{ QString key; QString value; }; StepType ty = StepType::Parent; QString childParserNodeName; IndexOrderSearchData ioSearchData; KeyValueSearchData kvSearchData; }; QList<NodeTraverseStep> nodeTraversal; bool isTraverseStartFromRoot = false; QString valueName; }; LiteralData literalData; LocalReferenceData localReferenceData; ExternReferenceData externReferenceData; }; struct Pattern{ QList<SubPattern> elements; QList<QList<PatternValueSubExpression>> valueTransform;//!< for each parameter of parser node (outer index), //!< how is the final value made by concatenating sub expressions int priorityScore; //!< a score calculated based on complexity of pattern //!< (number of sub patterns, length of literals, etc) //!< A pattern with higher score is chosen if it matches same length of text with other patterns }; struct ParseContext{ QList<QStringList> matchPairStarts; QList<QStringList> matchPairEnds; QStringList matchPairName; // just for debugging purpose QStringList ignoreList; QString exprStartMark; // exprStartMark and exprEndMark is not used after parser is initialized QString exprEndMark; int longestMatchPairStartStringLength; /** * @brief getMatchingEndAdvanceDistance returns how many characters to skip so that one jumps to the first character after the end mark of matching match pair * @param text the text to search on. The start marker should already be consumed. * @param matchPairIndex the match pair index for skipping. * @return pair of <number of characters to skip (-1 if no match found), length of match pair end string> */ std::pair<int,int> getMatchingEndAdvanceDistance(QStringRef text, int matchPairIndex)const; /** * @brief getMatchingStartAdvanceDistance finds the first match pair start mark and return its pos within text * @param text the text to search on. The start marker should not be consumed. * @param matchPairIndex the index of match pair; will be written for result * @param matchPairStartLength the length of match pair start string * @return tuple of <position or advance distance (-1 if none found), match pair index, match pair start length> */ std::tuple<int,int,int> getMatchingStartAdvanceDistance(QStringRef text)const; int removeTrailingIgnoredString(QStringRef& ref)const; int removeLeadingIgnoredString(QStringRef& ref)const; /** * @brief parsePatternString convert pattern string in ParserNode::Pattern style to Parser::Pattern * * Caller should make sure that all containers are cleared before the function is called. * If parse fails, containers may contain arbitrary garbage value; caller should backup data if needed. * * @param pattern the source pattern string to convert * @param result the result pattern * @param valueNameToIndex the result [ValueName]->[SubPatternIndex] mapping * @param diagnostic destination of diagnostic from environment * @return true if the string is parsed successfully, false otherwise */ bool parsePatternString(const QString& pattern, QList<SubPattern>& result, QHash<QString,int>& valueNameToIndex, DiagnosticEmitterBase &diagnostic); /** * @brief parseValueTransformString convert value transform string in ParserNode::Pattern style to Parser::Pattern format * * Caller should make sure that all containers are cleared before the function is called. * If parse fails, containers may contain arbitrary garbage value; caller should backup data if needed. * * @param transform the source transform string to convert * @param result the result transform * @param referencedValues which local values are referenced by this transform; this function only inserts to it * @param isLocalOnly whether value transform is allowed to reference values outside current node * @param diagnostic destination of diagnostic from environment * @return true if the string is parsed successfully, false otherwise */ bool parseValueTransformString(const QString& transform, QList<PatternValueSubExpression>& result, QSet<QString>& referencedValues, bool isLocalOnly, DiagnosticEmitterBase &diagnostic); }; /** * @brief match perform matching on given input text * @param input the text input * @param values the values for write back * @return number of characters this pattern can consume. 0 if pattern does not apply */ static int match(QStringRef input, QHash<QString,QString>& values, const ParseContext& ctx, const QList<SubPattern>& pattern); /** * @brief performValueTransform is for transforming the parsed raw value to parser node parameters * @param paramName list of parameter names * @param rawValues the raw values populated by match() * @param valueTransform describes how each parameters get their value from rawValues * @return list of parameter values */ static QStringList performValueTransform( const QStringList& paramName, const QHash<QString,QString>& rawValues, const QList<QList<PatternValueSubExpression>>& valueTransform ); /** * @brief performValueTransform variant that take an expression solver callback. This must only work with one parameter at a time. * @param paramName the name of parameter * @param rawValues the raw values populated by match() * @param valueTransform describes how the parameter get its value from rawValues * @param externReferenceSolver used to resolve variable references that are not in rawValues * @return */ static QString performValueTransform(const QString& paramName, const QHash<QString,QString>& rawValues, const QList<PatternValueSubExpression>& valueTransform, std::function<QString(const PatternValueSubExpression::ExternReferenceData &)> externReferenceSolver ); /** * @brief findLongestMatchingPattern tries all listed pattern on beginning of text and find the one that consumes more characters than others * @param patterns the list of patterns to try on * @param text input text * @param values the raw values retrieved when doing the matching * @return pair of <pattern index, # characters consumed>; <-1,0> if no pattern applies */ std::pair<int,int> findLongestMatchingPattern(const QList<Pattern>& patterns, QStringRef text, QHash<QString,QString>& values) const; static int computePatternScore(const QList<SubPattern>& pattern, const QList<int>& matchPairScore); /** * @brief The ParserNodeData struct contains record of a parser node generated during pattern matching */ struct ParserNodeData{ int nodeTypeIndex; //!< index in Parser::nodes int parentIndex; //!< parent parser node in the list containning this item int indexWithinParent; //!< index of node within parent int childNodeCount; //!< How many child node do this node has QStringList params; }; QList<ParserNodeData> patternMatch(QVector<QStringRef>& text, DiagnosticEmitterBase& diagnostic) const; struct IRBuildContext{ QList<ParserNodeData> parserNodes; QHash<int,QHash<int,QList<int>>> parserNodeChildListCache;//!< [ParserNodeIndex][ChildParserNodeTypeIndex] -> [list of child node index in parserNodes] /** * @brief getNodeChildList helper function to access parserNodeChildListCache; build the list if not found in cache * @param parentIndex parent index where list of child is needed * @param childNodeTypeIndex child parser node type index; -1 if all child is needed * @return reference to child node index (in parserNodes) list */ const QList<int>& getNodeChildList(int parentIndex, int childNodeTypeIndex); /** * @brief solveExternReference helper function for solve extern variable reference from parser node specified by nodeIndex * @param p the Parser parent * @param expr the extern variable reference expression * @param nodeIndex the parser node index in parserNodes where the expr is evaluated * @return pair of <isGood, result string> */ std::pair<bool,QString> solveExternReference(const Parser &p, const PatternValueSubExpression::ExternReferenceData& expr, int nodeIndex); }; private: // actual data struct Node{ QString nodeName; QList<Pattern> patterns; //!< nodes with no pattern starts implicitly, i.e. when child node pattern matches. //!< These nodes should not have parameters QList<Pattern> earlyExitPatterns; QStringList paramName; int combineToIRNodeIndex; //!< the IRNode index to tranform to; -1 if this is a parser-only node QList<QList<QList<PatternValueSubExpression>>> combineValueTransform; //!< [ParamIndex][ExprIndex][List of sub expressions] //!< for combine value transform, for each parameter, we allow multiple expression //!< the result of first successful evaluation is used as final result QList<int> allowedChildNodeIndexList; }; // node 0 is the root node; if the root node has patterns, it must be matched first, otherwise the root node implicitly starts QList<Node> nodes; ParseContext context; }; #endif // PARSER_H <file_sep>/core/Value.h #ifndef VALUE_H #define VALUE_H #include <QtGlobal> #include <QCoreApplication> #include <QVariant> #include <QMetaType> class DiagnosticEmitterBase; enum class ValueType{ Void, //!< runtime only; not for IR; basically just used to mark invalid type NodePtr, //!< runtime only; not for IR; node index in IRRootInstance stored as int ValuePtr, //!< runtime only; not for IR String, Int64 }; struct PtrCommon{ int functionIndex; //!< function index when the pointer is created int stmtIndex; //!< statement index that creates this pointer int activationIndex; //!< function activation index when the pointer is created //!< for detection of dangling pointer to local variable, as well as debug }; struct NodePtrType{ PtrCommon head; //!< pointer common head int nodeIndex; //!< node index in IRRootInstance }; Q_DECLARE_METATYPE(NodePtrType); struct ValuePtrType{ // name resolution order: local variable, writable node member, read-only node member(node parameter), global variables enum PtrType{ LocalVariable, NodeRWMember, NodeROParameter, GlobalVariable, NullPointer }; PtrCommon head; //!< pointer common head PtrType ty; //!< type of this pointer int valueIndex; //!< index of value being pointed int nodeIndex; //!< only used for node variable }; Q_DECLARE_METATYPE(ValuePtrType); inline QMetaType::Type getQMetaType(ValueType ty){ switch(ty){ case ValueType::Void: return QMetaType::UnknownType; case ValueType::NodePtr: return static_cast<QMetaType::Type>(qMetaTypeId<NodePtrType>()); case ValueType::ValuePtr: return static_cast<QMetaType::Type>(qMetaTypeId<ValuePtrType>()); case ValueType::String: return QMetaType::QString; case ValueType::Int64: return QMetaType::LongLong; } Q_UNREACHABLE(); } inline ValueType getValueType(QMetaType::Type ty){ switch(ty){ case QMetaType::QString: return ValueType::String; case QMetaType::LongLong: return ValueType::Int64; default: if(ty == static_cast<QMetaType::Type>(qMetaTypeId<NodePtrType>())) return ValueType::NodePtr; if(ty == static_cast<QMetaType::Type>(qMetaTypeId<ValuePtrType>())) return ValueType::ValuePtr; return ValueType::Void; } } // we only use int and string as key inline uint qHash(const QVariant& key, uint seed){ switch(static_cast<QMetaType::Type>(key.userType())){ case QMetaType::UnknownType: return 0; case QMetaType::QString: return qHash(key.toString(), seed); case QMetaType::LongLong: return qHash(key.toLongLong(), seed); default: Q_UNREACHABLE(); } } inline bool isValidIRValueType(ValueType ty){ switch(ty){ default: return false; case ValueType::String: case ValueType::Int64: return true; } } inline QString getTypeNameString(ValueType ty){ switch(ty){ case ValueType::Void: return QCoreApplication::tr("Void", "Value type name"); case ValueType::NodePtr: return QCoreApplication::tr("NodePtr", "Value type name"); case ValueType::ValuePtr: return QCoreApplication::tr("ValuePtr", "Value type name"); case ValueType::String: return QCoreApplication::tr("String", "Value type name"); case ValueType::Int64: return QCoreApplication::tr("Int64", "Value type name"); } Q_UNREACHABLE(); } #endif // VALUE_H <file_sep>/core/Expression.cpp #include "core/Expression.h" #include "core/DiagnosticEmitter.h" #include "core/ExecutionContext.h" bool LiteralExpression::evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const { Q_UNUSED(ctx) Q_UNUSED(dependentExprResults) retVal = val; return true; } bool VariableAddressExpression::evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const { Q_UNUSED(dependentExprResults) ValuePtrType val = {}; if(ctx.takeAddress(variableName, val)){ retVal.setValue(val); return true; } return false; } bool VariableReadExpression::evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const { Q_UNUSED(dependentExprResults) ValueType actualTy; QVariant val; if(ctx.read(variableName, actualTy, val)){ if(Q_LIKELY(actualTy == ty)){ retVal = val; return true; }else{ ctx.getDiagnostic()(Diag::Error_Exec_TypeMismatch_ReadByName, ty, actualTy, variableName); return false; } } // read fail; ctx should already emitted diagnostic return false; } bool NodePtrExpression::evaluate(ExecutionContext& ctx, QVariant& retVal, const QList<QVariant>& dependentExprResults) const { Q_UNUSED(dependentExprResults) NodePtrType ptr = {}; bool getNodeRetVal = false; switch(specifier){ case NodeSpecifier::CurrentNode: getNodeRetVal = ctx.getCurrentNodePtr(ptr); break; case NodeSpecifier::RootNode: getNodeRetVal = ctx.getRootNodePtr(ptr); break; } Q_ASSERT(getNodeRetVal); retVal.setValue(ptr); return true; } <file_sep>/core/Bundle.cpp #include "core/Bundle.h" #include "core/DiagnosticEmitter.h" #include "core/Expression.h" #include "core/IR.h" #include "core/Task.h" #include "core/CLIDriver.h" #include "core/OutputHandlerBase.h" #include "core/ExecutionContext.h" #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QDebug> #include <stdexcept> #include <memory> namespace{ const QString STR_NAME = QStringLiteral("Name"); const QString STR_TYPE = QStringLiteral("Type"); const QString STR_TY_INT = QStringLiteral("Int"); const QString STR_TY_STRING = QStringLiteral("String"); const QString STR_TY_NODEPTR = QStringLiteral("NodePtr"); const QString STR_TY_VALUEPTR = QStringLiteral("ValuePtr"); const QString STR_EXPR_TYPE = QStringLiteral("ExprType"); const QString STR_EXPR_TYPE_LITERAL = QStringLiteral("Literal"); const QString STR_EXPR_TYPE_VAR_READ = QStringLiteral("VariableRead"); const QString STR_EXPR_TYPE_VAR_ADDR = QStringLiteral("VariableAddress"); const QString STR_EXPR_LITERAL_VALUE = QStringLiteral("LiteralValue"); const QString STR_EXPR_VAR_NAME = QStringLiteral("VariableName"); const QString STR_DECL_INITIALIZER = QStringLiteral("Initializer"); const QString STR_FUNCTION_PARAM_REQ = QStringLiteral("ParameterRequired"); const QString STR_FUNCTION_PARAM_OPT = QStringLiteral("ParameterOptional"); const QString STR_FUNCTION_LOCALVAR = QStringLiteral("LocalVariable"); const QString STR_FUNCTION_EXTVARREF = QStringLiteral("ExternVariableReference"); const QString STR_FUNCTION_STMT = QStringLiteral("Statement"); const QString STR_STMT_UNREACHABLE = QStringLiteral("Unreachable"); const QString STR_STMT_ASSIGN = QStringLiteral("Assignment"); const QString STR_STMT_ASSIGN_LHS = QStringLiteral("AssignmentLHS"); const QString STR_STMT_ASSIGN_RHS = QStringLiteral("AssignmentRHS"); const QString STR_STMT_OUTPUT = QStringLiteral("Output"); const QString STR_STMT_OUTPUT_EXPR = QStringLiteral("OutputExpr"); const QString STR_STMT_CALL = QStringLiteral("Call"); const QString STR_STMT_CALL_FUNC = QStringLiteral("CallFunction"); const QString STR_STMT_CALL_ARG = QStringLiteral("CallArgument"); const QString STR_STMT_RETURN = QStringLiteral("Return"); const QString STR_STMT_BRANCH = QStringLiteral("Branch"); const QString STR_STMT_BRANCH_D = QStringLiteral("BranchDefault"); const QString STR_STMT_BRANCH_CASE = QStringLiteral("BranchCase"); const QString STR_STMT_BRANCH_ACTTY = QStringLiteral("ActionType"); const QString STR_STMT_BRANCH_UR = QStringLiteral("Unreachable"); const QString STR_STMT_BRANCH_FT = QStringLiteral("Fallthrough"); const QString STR_STMT_BRANCH_J = QStringLiteral("Jump"); const QString STR_STMT_BRANCH_LABEL = QStringLiteral("Label"); const QString STR_STMT_BRANCH_COND = QStringLiteral("Condition"); const QString STR_STMT_BRANCH_ACT = QStringLiteral("Action"); const QString STR_STMT_LABEL = QStringLiteral("LabelPseudoStatement"); const QString STR_STMT_LABEL_NAME = QStringLiteral("LabelName"); const QString STR_IRNODE_PARAM = QStringLiteral("Parameter"); const QString STR_IRNODE_PARAM_UNIQUE= QStringLiteral("Unique"); const QString STR_IRNODE_KEY = QStringLiteral("PrimaryKey"); const QString STR_IRNODE_CHILD = QStringLiteral("Child"); const QString STR_IRROOT_NODE = QStringLiteral("Node"); const QString STR_IRROOT_ROOT = QStringLiteral("Root"); const QString STR_TOP_IRSET = QStringLiteral("IRSet"); const QString STR_TOP_OUTPUTSET = QStringLiteral("OutputSet"); const QString STR_TOP_TASKSET = QStringLiteral("TaskSet"); const QString STR_OUTPUT_BASETYPE = QStringLiteral("BaseType"); const QString STR_OUTPUT_TEXT_MIME = QStringLiteral("TextMIME"); const QString STR_OUTPUT_TEXT_CODEC = QStringLiteral("TextCodec"); const QString STR_TASK_INPUT = QStringLiteral("Input"); const QString STR_TASK_OUTPUT = QStringLiteral("Output"); const QString STR_TASK_GLOBALVAR = QStringLiteral("GlobalVariable"); const QString STR_TASK_NODEMEMBER = QStringLiteral("NodeMember"); const QString STR_TASK_FUNCTION = QStringLiteral("Function"); const QString STR_TASK_PASS = QStringLiteral("Pass"); const QString STR_TASK_PASS_ONENTRY = QStringLiteral("OnEntry"); const QString STR_TASK_PASS_ONEXIT = QStringLiteral("OnExit"); const QString STR_INSTANCE_PARENT = QStringLiteral("Parent"); const QString STR_INSTANCE_PARAM = QStringLiteral("Parameter"); // for all functions, we throw when any error is encountered // use std::unique_ptr to avoid memory leak ValueType getValueTypeFromString(DiagnosticEmitterBase& diagnostic, const QString& ty){ if(ty == STR_TY_INT) return ValueType::Int64; if(ty == STR_TY_STRING) return ValueType::String; if(ty == STR_TY_NODEPTR) return ValueType::NodePtr; if(ty == STR_TY_VALUEPTR) return ValueType::ValuePtr; diagnostic(Diag::Error_Json_UnknownType_String, ty); throw std::runtime_error("Unknown type"); } int getExpression(DiagnosticEmitterBase& diagnostic, const QJsonObject& json, Function& f) { Q_UNUSED(f) QString exprTy = json.value(STR_EXPR_TYPE).toString(); if(exprTy == STR_EXPR_TYPE_LITERAL){ QJsonValue val = json.value(STR_EXPR_LITERAL_VALUE); if(val.isString()){ return f.addExpression(new LiteralExpression(val.toString())); }else if(val.isDouble()){ int value = val.toInt(); return f.addExpression(new LiteralExpression(static_cast<qint64>(value))); }else{ diagnostic(Diag::Error_Json_UnsupportedLiteralType); throw std::runtime_error("Unhandled literal type"); } }else if(exprTy == STR_EXPR_TYPE_VAR_READ){ QString name = json.value(STR_EXPR_VAR_NAME).toString(); ValueType ty = ValueType::Void; int refIndex = f.getLocalVariableIndex(name); if(refIndex >= 0){ ty = f.getLocalVariableType(refIndex); }else{ refIndex = f.getExternVariableIndex(name); if(Q_UNLIKELY(refIndex == -1)){ diagnostic(Diag::Error_Json_BadReference_Variable, name); throw std::runtime_error("Unknown variable"); } ty = f.getExternVariableType(refIndex); } return f.addExpression(new VariableReadExpression(ty, name)); }else if(exprTy == STR_EXPR_TYPE_VAR_ADDR){ QString name = json.value(STR_EXPR_VAR_NAME).toString(); return f.addExpression(new VariableAddressExpression(name)); } diagnostic(Diag::Error_Json_UnknownType_String, exprTy); throw std::runtime_error("Unknown expression"); } struct MemberDeclarationEntry{ QString name; ValueType ty; QVariant initializer; }; void getMemberDeclaration(DiagnosticEmitterBase& diagnostic, const QJsonArray& json, QList<MemberDeclarationEntry>& members) { for(auto iter = json.begin(), iterEnd = json.end(); iter != iterEnd; ++iter){ QJsonObject obj = iter->toObject(); MemberDeclarationEntry entry; entry.name = obj.value(STR_NAME).toString(); entry.ty = getValueTypeFromString(diagnostic, obj.value(STR_TYPE).toString()); entry.initializer = QVariant(); QJsonValue initializer = obj.value(STR_DECL_INITIALIZER); if(!initializer.isUndefined()){ switch (entry.ty) { default:{ diagnostic(Diag::Error_Json_UnexpectedInitializer, entry.name, entry.ty); throw std::runtime_error("Unhandled initializer type"); }/*break;*/ case ValueType::Int64: entry.initializer = initializer.toInt(); break; case ValueType::String: entry.initializer = initializer.toString(); break; } } members.push_back(entry); } } Function getFunction(DiagnosticEmitterBase& diagnostic, const QJsonObject& json) { QString name = json.value(STR_NAME).toString(); DiagnosticPathNode dnode(diagnostic, name); Function func(name); // parameters and local variables { QList<MemberDeclarationEntry> vars; getMemberDeclaration(diagnostic, json.value(STR_FUNCTION_PARAM_REQ).toArray(), vars); for(const auto& record : vars){ func.addLocalVariable(record.name, record.ty, record.initializer); } int requiredParamCount = vars.size(); func.setRequiredParamCount(requiredParamCount); vars.clear(); getMemberDeclaration(diagnostic, json.value(STR_FUNCTION_PARAM_OPT).toArray(), vars); for(const auto& record : vars){ func.addLocalVariable(record.name, record.ty, record.initializer); } func.setParamCount(requiredParamCount + vars.size()); vars.clear(); getMemberDeclaration(diagnostic, json.value(STR_FUNCTION_LOCALVAR).toArray(), vars); for(const auto& record : vars){ func.addLocalVariable(record.name, record.ty, record.initializer); } vars.clear(); getMemberDeclaration(diagnostic, json.value(STR_FUNCTION_EXTVARREF).toArray(), vars); for(const auto& record : vars){ func.addExternVariable(record.name, record.ty); } vars.clear(); } // statements and labels QJsonArray array = json.value(STR_FUNCTION_STMT).toArray(); for(auto iter = array.begin(), iterEnd = array.end(); iter != iterEnd; ++iter){ QJsonObject obj = iter->toObject(); QString stmtTy = obj.value(STR_TYPE).toString(); if(stmtTy == STR_STMT_UNREACHABLE){ func.addUnreachableStatement(); }else if(stmtTy == STR_STMT_ASSIGN){ QJsonValue lhs = obj.value(STR_STMT_ASSIGN_LHS); AssignmentStatement stmt; if(lhs.isString()){ stmt.lvalueName = lhs.toString(); stmt.lvalueExprIndex = -1; }else{ stmt.lvalueExprIndex = getExpression(diagnostic, lhs.toObject(), func); } stmt.rvalueExprIndex = getExpression(diagnostic, obj.value(STR_STMT_ASSIGN_RHS).toObject(), func); func.addStatement(stmt); }else if(stmtTy == STR_STMT_OUTPUT){ OutputStatement stmt; stmt.exprIndex = getExpression(diagnostic, obj.value(STR_STMT_OUTPUT_EXPR).toObject(), func); func.addStatement(stmt); }else if(stmtTy == STR_STMT_CALL){ CallStatement stmt; stmt.functionName = obj.value(STR_STMT_CALL_FUNC).toString(); QJsonArray args = obj.value(STR_STMT_CALL_ARG).toArray(); for(auto iter = args.begin(), iterEnd = args.end(); iter != iterEnd; ++iter){ stmt.argumentExprList.push_back(getExpression(diagnostic, iter->toObject(), func)); } func.addStatement(stmt); }else if(stmtTy == STR_STMT_RETURN){ func.addReturnStatement(); }else if(stmtTy == STR_STMT_BRANCH){ BranchStatementTemp stmt; auto setAction = [&](const QJsonObject& actionObject, BranchStatementTemp::BranchActionType& ty, QString& labelName)->void{ QString actTy = actionObject.value(STR_STMT_BRANCH_ACTTY).toString(); if(actTy == STR_STMT_BRANCH_J){ ty = BranchStatementTemp::BranchActionType::Jump; labelName = actionObject.value(STR_STMT_BRANCH_LABEL).toString(); }else if(actTy == STR_STMT_BRANCH_FT){ ty = BranchStatementTemp::BranchActionType::Fallthrough; labelName.clear(); }else if(actTy == STR_STMT_BRANCH_UR){ ty = BranchStatementTemp::BranchActionType::Unreachable; labelName.clear(); }else{ diagnostic(Diag::Error_Json_UnknownBranchAction, actTy); throw std::runtime_error("Unhandled branch action type"); } }; setAction(obj.value(STR_STMT_BRANCH_D).toObject(), stmt.defaultAction, stmt.defaultJumpLabelName); QJsonArray caseArray = obj.value(STR_STMT_BRANCH_CASE).toArray(); for(auto iter = caseArray.begin(), iterEnd = caseArray.end(); iter != iterEnd; ++iter){ BranchStatementTemp::BranchCase c; QJsonObject caseObj = iter->toObject(); c.exprIndex = getExpression(diagnostic, caseObj.value(STR_STMT_BRANCH_COND).toObject(), func); setAction(caseObj.value(STR_STMT_BRANCH_ACT).toObject(), c.action, c.labelName); stmt.cases.push_back(c); } func.addStatement(stmt); }else if(stmtTy == STR_STMT_LABEL){ QString labelName = obj.value(STR_STMT_LABEL_NAME).toString(); func.addLabel(labelName); }else{ diagnostic(Diag::Error_Json_UnknownStatementType, stmtTy); throw std::runtime_error("Unhandled statement type"); } } dnode.pop(); return func; } IRNodeType* getIRNodeType(DiagnosticEmitterBase& diagnostic, const QJsonObject& json) { QString name = json.value(STR_NAME).toString(); DiagnosticPathNode dnode(diagnostic,name); std::unique_ptr<IRNodeType> ptr(new IRNodeType(name)); QJsonArray param = json.value(STR_IRNODE_PARAM).toArray(); for(auto iter = param.begin(), iterEnd = param.end(); iter != iterEnd; ++iter){ QJsonObject entry = iter->toObject(); QString paramName = entry.value(STR_NAME).toString(); ValueType paramTy = getValueTypeFromString(diagnostic, entry.value(STR_TYPE).toString()); bool isUnique = entry.value(STR_IRNODE_PARAM_UNIQUE).toBool(false); ptr->addParameter(paramName, paramTy, isUnique); } QJsonValue primaryKeyVal = json.value(STR_IRNODE_KEY); if(primaryKeyVal.isString()){ ptr->setPrimaryKey(primaryKeyVal.toString()); } QJsonArray child = json.value(STR_IRNODE_CHILD).toArray(); for(auto c: child){ ptr->addChildNode(c.toString()); } dnode.pop(); return ptr.release(); } IRRootType* getIRRootType(DiagnosticEmitterBase& diagnostic, const QJsonObject& json) { QString name = json.value(STR_NAME).toString(); DiagnosticPathNode dnode(diagnostic,name); std::unique_ptr<IRRootType> ptr(new IRRootType(name)); QJsonArray nodeArray = json.value(STR_IRROOT_NODE).toArray(); for(auto node: nodeArray){ IRNodeType* nodePtr = getIRNodeType(diagnostic, node.toObject()); ptr->addNodeTypeDefinition(*nodePtr); delete nodePtr; } ptr->setRootNodeType(json.value(STR_IRROOT_ROOT).toString()); dnode.pop(); return ptr.release(); } }// end of anonymous namespace Bundle* Bundle::fromJson(const QByteArray& json, DiagnosticEmitterBase &diagnostic) { QJsonDocument doc = QJsonDocument::fromJson(json); QJsonObject docObj = doc.object(); if(docObj.isEmpty()){ qDebug()<< "json read fail"; return nullptr; } try { std::unique_ptr<Bundle> ptr(new Bundle); // IR first DiagnosticPathNode dnode(diagnostic,tr("IR")); QJsonArray irArray = docObj.value(STR_TOP_IRSET).toArray(); for(auto ir : irArray){ IRRootType* irRoot = getIRRootType(diagnostic, ir.toObject()); if(irRoot->validate(diagnostic)){ int index = ptr->irTypes.size(); ptr->irTypes.push_back(irRoot); ptr->irNameToIndex.insert(irRoot->getName(), index); }else{ delete irRoot; return nullptr; } } dnode.pop(); // then outputs QJsonArray outputArray = docObj.value(STR_TOP_OUTPUTSET).toArray(); for(auto iter = outputArray.begin(), iterEnd = outputArray.end(); iter != iterEnd; ++iter){ QJsonObject obj = iter->toObject(); OutputDescriptor out; out.name = obj.value(STR_NAME).toString(); out.baseTy = OutputDescriptor::OutputBaseType::Text; out.textInfo.mimeType = obj.value(STR_OUTPUT_TEXT_MIME).toString(); out.textInfo.codecName = obj.value(STR_OUTPUT_TEXT_CODEC).toString(QStringLiteral("utf-8")); int outputIndex = ptr->outputTypes.size(); ptr->outputTypes.push_back(out); ptr->outputNameToIndex.insert(out.name, outputIndex); } // then tasks QJsonArray taskArray = docObj.value(STR_TOP_TASKSET).toArray(); for(auto iter = taskArray.begin(), iterEnd = taskArray.end(); iter != iterEnd; ++iter){ QJsonObject obj = iter->toObject(); QString inputIRName = obj.value(STR_TASK_INPUT).toString(); QString outputName = obj.value(STR_TASK_OUTPUT).toString(); int irIndex = -1; { auto iter = ptr->irNameToIndex.find(inputIRName); if(Q_LIKELY(iter != ptr->irNameToIndex.end())){ irIndex = iter.value(); } } if(Q_UNLIKELY(irIndex == -1)){ diagnostic(Diag::Error_Json_BadReference_IR, inputIRName); return nullptr; } TaskRecord record; record.ptr = nullptr; record.inputIRType = irIndex; record.outputTypeIndex = ptr->outputNameToIndex.value(outputName, -1); if(Q_UNLIKELY(record.outputTypeIndex == -1)){ diagnostic(Diag::Error_Json_BadReference_Output, outputName); return nullptr; } const IRRootType& irRoot = *ptr->irTypes.at(irIndex); std::unique_ptr<Task> taskPtr(new Task(irRoot)); QJsonArray functionArray = obj.value(STR_TASK_FUNCTION).toArray(); for(auto iter = functionArray.begin(), iterEnd = functionArray.end(); iter != iterEnd; ++iter){ taskPtr->addFunction(getFunction(diagnostic, iter->toObject())); } QList<MemberDeclarationEntry> vars; getMemberDeclaration(diagnostic, obj.value(STR_TASK_GLOBALVAR).toArray(), vars); for(const auto& record : vars){ taskPtr->addGlobalVariable(record.name, record.ty, record.initializer); } vars.clear(); QJsonObject nodeMember = obj.value(STR_TASK_NODEMEMBER).toObject(); for(auto iter = nodeMember.begin(), iterEnd = nodeMember.end(); iter != iterEnd; ++iter){ QString nodeName = iter.key(); int nodeIndex = irRoot.getNodeTypeIndex(nodeName); if(Q_UNLIKELY(nodeIndex < 0)){ diagnostic(Diag::Error_Json_BadReference_IRNodeType, nodeName); return nullptr; } getMemberDeclaration(diagnostic, iter.value().toArray(), vars); for(const auto& record : vars){ taskPtr->addNodeMember(nodeIndex, record.name, record.ty, record.initializer); } vars.clear(); } QJsonArray passArray = obj.value(STR_TASK_PASS).toArray(); for(auto iter = passArray.begin(), iterEnd = passArray.end(); iter != iterEnd; ++iter){ QJsonObject passObj = iter->toObject(); taskPtr->addNewPass(); for(auto iter = passObj.begin(), iterEnd = passObj.end(); iter != iterEnd; ++iter){ QString nodeName = iter.key(); int nodeIndex = irRoot.getNodeTypeIndex(nodeName); if(Q_UNLIKELY(nodeIndex < 0)){ diagnostic(Diag::Error_Json_BadReference_IRNodeType, nodeName); return nullptr; } QJsonObject callbackObj = iter.value().toObject(); QJsonValue onEntryCB = callbackObj.value(STR_TASK_PASS_ONENTRY); if(onEntryCB.isString()){ taskPtr->setNodeCallback(nodeIndex, onEntryCB.toString(), Task::CallbackType::OnEntry); } QJsonValue onExitCB = callbackObj.value(STR_TASK_PASS_ONEXIT); if(onExitCB.isString()){ taskPtr->setNodeCallback(nodeIndex, onExitCB.toString(), Task::CallbackType::OnExit); } } } if(taskPtr->validate(diagnostic)){ ptr->taskInfo.push_back(record); ptr->taskInfo.back().ptr = taskPtr.release(); }else{ return nullptr; } } return ptr.release(); } catch (...) { return nullptr; } } IRRootInstance* Bundle::readIRFromJson(int irIndex, const QByteArray& json, DiagnosticEmitterBase &diagnostic) { QJsonDocument doc = QJsonDocument::fromJson(json); QJsonArray nodeArray = doc.array(); if(nodeArray.isEmpty()){ qDebug()<< "json read fail"; return nullptr; } try { const IRRootType& rootTy = *irTypes.at(irIndex); std::unique_ptr<IRRootInstance> ptr(new IRRootInstance(rootTy)); for(auto iter = nodeArray.begin(), iterEnd = nodeArray.end(); iter != iterEnd; ++iter){ QJsonObject node = iter->toObject(); QString nodeTypeName = node.value(STR_TYPE).toString(); int typeIndex = rootTy.getNodeTypeIndex(nodeTypeName); int nodeIndex = ptr->addNode(typeIndex); IRNodeInstance& inst = ptr->getNode(nodeIndex); int parentIndex = node.value(STR_INSTANCE_PARENT).toInt(); inst.setParent(parentIndex); inst.setParameters(node.value(STR_INSTANCE_PARAM).toArray().toVariantList()); if(parentIndex >= 0){ ptr->getNode(parentIndex).addChildNode(nodeIndex); } } if(ptr->validate(diagnostic)){ return ptr.release(); } return nullptr; } catch (...) { return nullptr; } } <file_sep>/core/IRValidate.cpp #include "core/IR.h" #include "core/DiagnosticEmitter.h" #include "util/ADT.h" #include <QtGlobal> #include <QObject> #include <QQueue> #include <QDebug> namespace{ const char ILLEGAL_CHARS_1[] = { '.', '[', ']', '(', ')', '<', '>', '\\', '/', '+', '=', '*', '~', '`', '\'', '"', ',', '?', '@', '#', '$', '%', '^', '&', '|', ':', ';', ' ' }; struct EscapedIllegalCharRecord{ char c; char escapeChar; }; const EscapedIllegalCharRecord ILLEGAL_CHARS_2[] = { {'\t', 't'}, {'\n', 'n'}, {'\r', 'r'}, {'\f', 'f'}, {'\a', 'a'}, {'\b', 'b'}, {'\0', '0'} }; } bool IRNodeType::validateName(DiagnosticEmitterBase& diagnostic, const QString &name) { // any character sequence is allowed, except ones in ILLEGAL_CHARS bool isValid = true; int len = name.length(); if(Q_UNLIKELY(len == 0)){ diagnostic(Diag::Error_BadName_EmptyString); return false; } for(int i = 0, len = sizeof(ILLEGAL_CHARS_1)/sizeof(char); i < len; ++i){ QChar c(ILLEGAL_CHARS_1[i]); if(Q_UNLIKELY(name.contains(c, Qt::CaseInsensitive))){ diagnostic(Diag::Error_BadName_IllegalChar, QString(c), name); isValid = false; } } for(int i = 0, len = sizeof(ILLEGAL_CHARS_2)/sizeof(decltype(ILLEGAL_CHARS_2[0])); i < len; ++i){ QChar c(ILLEGAL_CHARS_2[i].c); if(Q_UNLIKELY(name.contains(c, Qt::CaseInsensitive))){ QString charStr('\''); charStr.append(ILLEGAL_CHARS_2[i].escapeChar); diagnostic(Diag::Error_BadName_IllegalChar, charStr, name); isValid = false; } } for(const auto& c: name){ if(Q_UNLIKELY(!c.isPrint())){ diagnostic(Diag::Error_BadName_UnprintableChar); isValid = false; break; } } bool isPureNumber = false; // check if it is a number, even if it overflows int num = static_cast<int>(name.toLongLong(&isPureNumber)); if(Q_UNLIKELY(isPureNumber)){ diagnostic(Diag::Error_BadName_PureNumber, name, num); isValid = false; } return isValid; } bool IRNodeType::validate(DiagnosticEmitterBase& diagnostic, IRRootType &root) { bool isValidated = true; // check if name of this node is valid bool isNameValid = validateName(diagnostic, name); isValidated = isNameValid; // if name is valid, update it to diagnostic if(Q_LIKELY(isNameValid)){ diagnostic.setDetailedName(name); } // should never happen during correct execution Q_ASSERT(parameterList.size() == parameterNameList.size()); parameterNameToIndex.clear(); // check all parameters for(int i = 0, len = parameterNameList.size(); i < len; ++i){ DiagnosticPathNode dnode(diagnostic, tr("Parameter %1").arg(i)); const QString& paramName = parameterNameList.at(i); // check if parameter names are valid bool isNameValid = validateName(diagnostic, paramName); if(Q_LIKELY(isNameValid)){ dnode.setDetailedName(paramName); } isValidated = isValidated && isNameValid; // check if parameter type is valid if(Q_UNLIKELY(!isValidIRValueType(getParameterType(i)))){ diagnostic(Diag::Error_IR_BadType_BadTypeForNodeParam, paramName, getParameterType(i)); isValidated = false; } // check if there is a name clash auto iter = parameterNameToIndex.find(paramName); if(Q_LIKELY(iter == parameterNameToIndex.end())){ parameterNameToIndex.insert(paramName, i); }else{ diagnostic(Diag::Error_IR_NameClash_NodeParam, paramName, iter.value(), i); isValidated = false; } // we do not implement other checks (e.g. parameter value constraint) yet dnode.pop(); } // check primary key if(primaryKeyName.isEmpty()){ primaryKeyIndex = -1; }else{ primaryKeyIndex = getParameterIndex(primaryKeyName); if(Q_UNLIKELY(primaryKeyIndex == -1)){ diagnostic(Diag::Error_IR_BadPrimaryKey_KeyNotFound, primaryKeyName); isValidated = false; }else if(Q_UNLIKELY(!(parameterList.at(primaryKeyIndex).isUnique))){ diagnostic(Diag::Error_IR_BadPrimaryKey_KeyNotUnique, primaryKeyName); isValidated = false; } } // check children childNodeNameToIndex.clear(); for(int i = 0, len = childNodeList.size(); i < len; ++i){ const QString& str = childNodeList.at(i); int index = root.getNodeTypeIndex(str); if(Q_UNLIKELY(index == -1)){ diagnostic(Diag::Error_IR_BadReference_ChildNodeType, str); isValidated = false; }else{ auto iter = childNodeNameToIndex.find(str); if(Q_LIKELY(iter == childNodeNameToIndex.end())){ childNodeNameToIndex.insert(str, i); }else{ diagnostic(Diag::Error_IR_DuplicatedReference_ChildNodeType, str); isValidated = false; } } } return isValidated; } bool IRRootType::validate(DiagnosticEmitterBase& diagnostic) { isValidated = true; if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, name))){ isValidated = false; } nodeNameToIndex.clear(); for(int i = 0, len = nodeList.size(); i < len; ++i){ QString name = nodeList.at(i).getName(); auto iter = nodeNameToIndex.find(name); if(Q_LIKELY(iter == nodeNameToIndex.end())){ nodeNameToIndex.insert(name, i); }else{ diagnostic(Diag::Error_IR_NameClash_NodeType, name); isValidated = false; } } if(rootNodeName.isEmpty()){ rootNodeIndex = -1; }else{ rootNodeIndex = getNodeTypeIndex(rootNodeName); if(Q_UNLIKELY(rootNodeIndex == -1)){ diagnostic(Diag::Error_IR_BadReference_RootNodeType, rootNodeName); isValidated = false; } } // must happen after nodeNameToIndex is properly initialized for(int i = 0, len = nodeList.size(); i < len; ++i){ DiagnosticPathNode dnode(diagnostic, tr("Node Type %1").arg(i)); // no short circuit isValidated = nodeList[i].validate(diagnostic, *this) && isValidated; dnode.pop(); } return isValidated; } bool IRNodeInstance::validate(DiagnosticEmitterBase& diagnostic, IRRootInstance& root) { // note that broken tree and invalid node type should already been catched in IRRootInstance::validate() // therefore here it is safe to assume that type index is valid and tree structure is well formed bool isValidated = true; const IRRootType& rootTy = root.getType(); const IRNodeType& ty = rootTy.getNodeType(typeIndex); diagnostic.setDetailedName(ty.getName()); // check if parameter is good if(Q_UNLIKELY(ty.getNumParameter() != parameters.size())){ diagnostic(Diag::Error_IR_BadParameterList_Count, ty.getNumParameter(), parameters.size()); isValidated = false; }else{ // number of parameters match // check if their type is matching for(int i = 0, len = parameters.size(); i < len; ++i){ const QVariant& val = parameters.at(i); ValueType valTy = ty.getParameterType(i); ValueType givenTy = getValueType(static_cast<QMetaType::Type>(val.userType())); if(Q_UNLIKELY(valTy != givenTy)){ diagnostic(Diag::Error_IR_BadParameterList_Type, i, valTy, givenTy); isValidated = false; } } } // check if children are good int numChildNodeType = ty.getNumChildNode(); RunTimeSizeArray<bool> isChildTypeGood(static_cast<std::size_t>(numChildNodeType), true); childNodeTypeIndexToLocalIndex.clear(); for(int i = 0; i < numChildNodeType; ++i){ int globalNodeTyIndex = rootTy.getNodeTypeIndex(ty.getChildNodeName(i)); childNodeTypeIndexToLocalIndex.insert(globalNodeTyIndex, i); } childTypeList.clear(); childTypeList.reserve(numChildNodeType); for(int i = 0; i < numChildNodeType; ++i){ childTypeList.push_back(ChildTypeRecord()); } Q_ASSERT(childTypeList.size() == numChildNodeType); // when checking whether children are good, // fatal errors are tracked by isValidated // non-fatal errors are tracked by isChildTypeGood for(int i = 0, cnt = childNodeList.size(); i < cnt; ++i){ int childNodeIndex = childNodeList.at(i); DiagnosticPathNode dnode(diagnostic, tr("Child %1").arg(i)); IRNodeInstance& child = root.getNode(childNodeIndex); bool isChildGood = child.validate(diagnostic, root); int localTyIndex = getLocalTypeIndex(child.getTypeIndex()); if(Q_UNLIKELY(localTyIndex == -1)){ diagnostic(Diag::Error_IR_BadTree_UnexpectedChild, rootTy.getNodeType(child.getTypeIndex()).getName()); isValidated = false; }else{ Q_ASSERT(localTyIndex >= 0 && localTyIndex < childTypeList.size()); childTypeList[localTyIndex].nodeList.push_back(childNodeIndex); if(Q_UNLIKELY(!isChildGood)){ isChildTypeGood.at(localTyIndex) = false; } } dnode.pop(); } // check for key unique constraints and construct perParamHash in childTypeList // do not check this property if anything is already failed if(isValidated){ for(int i = 0; i < numChildNodeType; ++i){ if(Q_LIKELY(isChildTypeGood.at(i))){ ChildTypeRecord& record = childTypeList[i]; record.perParamHash.clear(); const IRNodeType& nodeTy = rootTy.getNodeType(rootTy.getNodeTypeIndex(ty.getChildNodeName(i))); for(int i = 0, numParam = nodeTy.getNumParameter(); i < numParam; ++i){ record.perParamHash.push_back(QHash<QVariant,int>()); if(nodeTy.getParameterIsUnique(i)){ QHash<QVariant,int>& hash = record.perParamHash.back(); for(int nodeIndex : record.nodeList){ const IRNodeInstance& inst = root.getNode(nodeIndex); const QVariant& val = inst.parameters.at(i); auto iter = hash.find(val); if(Q_LIKELY(iter == hash.end())){ hash.insert(val, nodeIndex); }else{ diagnostic(Diag::Error_IR_BadTree_BrokenConstraint_ParamNotUnique, nodeTy.getName(), nodeTy.getParameterName(i), iter.value(), nodeIndex, val.toString()); isValidated = false; } } } } Q_ASSERT(record.perParamHash.size() == nodeTy.getNumParameter()); }else{ // isChildTypeGood.at(i) == false isValidated = false; } } } return isValidated; } bool IRRootInstance::validate(DiagnosticEmitterBase& diagnostic) { DiagnosticPathNode dnode(diagnostic, tr("Root")); if(nodeList.empty()){ diagnostic(Diag::Error_IR_BadTree_EmptyTree); isValidated = false; return isValidated; } isValidated = true; // first of all, do a reachability analysis RunTimeSizeArray<int> isNodeReachable(static_cast<std::size_t>(nodeList.size()), -2); struct Entry{ int parent; int child; }; QQueue<Entry> pendingNodes; pendingNodes.enqueue(Entry{-1,0}); while(!pendingNodes.empty()){ Entry curEntry = pendingNodes.dequeue(); int parentIndex = curEntry.parent; int currentIndex = curEntry.child; Q_ASSERT(currentIndex < nodeList.size()); bool isCurrentNodeGood = true; if(Q_UNLIKELY(isNodeReachable.at(currentIndex) != -2)){ diagnostic(Diag::Error_IR_BadTree_DuplicatedReference_ChildNode, currentIndex, isNodeReachable.at(currentIndex), parentIndex); isCurrentNodeGood = false; }else{ isNodeReachable.at(currentIndex) = parentIndex; } if(Q_UNLIKELY(currentIndex <= parentIndex)){ diagnostic(Diag::Error_IR_BadTree_BadNodeOrder, currentIndex, parentIndex); isCurrentNodeGood = false; } const IRNodeInstance& child = nodeList.at(currentIndex); if(Q_UNLIKELY(child.getParentIndex() != parentIndex)){ diagnostic(Diag::Error_IR_BadTree_ConflictingParentReference, currentIndex, child.getParentIndex(), parentIndex); isCurrentNodeGood = false; } if(Q_UNLIKELY(!ty.isNodeTypeIndexValid(child.getTypeIndex()))){ diagnostic(Diag::Error_IR_BadTree_BadNodeTypeIndex, currentIndex, child.getTypeIndex()); isCurrentNodeGood = false; } isValidated = isValidated && isCurrentNodeGood; if(Q_LIKELY(isCurrentNodeGood)){ for(int i = 0, num = child.getNumChildNode(); i < num; ++i){ int childIndex = child.getChildNodeByOrder(i); pendingNodes.enqueue(Entry{currentIndex, childIndex}); } } } for(int i = 0, num = nodeList.size(); i < num; ++i){ if(Q_UNLIKELY(isNodeReachable.at(i) == -2)){ diagnostic(Diag::Error_IR_BadTree_UnreachableNode, i); isValidated = false; } } if(Q_LIKELY(isValidated)){ isValidated = nodeList.front().validate(diagnostic, *this); } dnode.pop(); return isValidated; } <file_sep>/core/OutputHandler.cpp #include "core/OutputHandlerBase.h" TextOutputHandler::TextOutputHandler(const QByteArray& codecName) : encoder(QTextCodec::codecForName(codecName)->makeEncoder(QTextCodec::IgnoreHeader|QTextCodec::ConvertInvalidToNull)) { Q_ASSERT(encoder); buffer.open(QIODevice::WriteOnly); } TextOutputHandler::~TextOutputHandler() { delete encoder; } void TextOutputHandler::getAllowedOutputTypeList(QList<ValueType>& tys) const { tys.clear(); tys.push_back(ValueType::String); } bool TextOutputHandler::isOutputGoodSoFar() { return !encoder->hasFailure(); } bool TextOutputHandler::addOutput(const QString& data) { QByteArray out = encoder->fromUnicode(data); buffer.write(out); return !encoder->hasFailure(); } const QByteArray& TextOutputHandler::getResult() { Q_ASSERT(buffer.isOpen()); buffer.close(); return buffer.data(); } <file_sep>/core/DiagnosticEmitter.h #ifndef DIAGNOSTICEMITTER_H #define DIAGNOSTICEMITTER_H #include <QObject> #include <QString> #include <QStringList> #include <QVariant> #include <QVariantList> #include <QMetaEnum> #include <QCoreApplication> #include "core/Value.h" /** * @brief The Diag class lists all the possible diagnostics that the program can generate * * The description beside enum can be shown as tooltip in QtCreator */ class Diag : private QObject { Q_OBJECT public: enum ID{// [Diagnostic type] [Module] (Scenario]) [Major problem] ([Scenario / Cause]...) Warn_Exec_UninitializedRead, //!< (no argument) Warn_Task_UnreachableFunction, //!< [FunctionName] Error_BadName_EmptyString, //!< (no argument) Error_BadName_IllegalChar, //!< [CharAsString][NameString] Error_BadName_UnprintableChar, //!< (no argument) Error_BadName_PureNumber, //!< [NameString][NumberInt] Error_IR_BadType_BadTypeForNodeParam, //!< [ParamName][ParamType] Error_IR_NameClash_NodeParam, //!< [ParamName][FirstParamIndex][SecondParamIndex] Error_IR_NameClash_NodeType, //!< [NodeTypeName] Error_IR_BadPrimaryKey_KeyNotFound, //!< [ParamName] Error_IR_BadPrimaryKey_KeyNotUnique, //!< [ParamName] Error_IR_BadReference_ChildNodeType, //!< [ChildNodeTypeName] Error_IR_BadReference_RootNodeType, //!< [RootNodeTypeName] Error_IR_DuplicatedReference_ChildNodeType, //!< [ChildNodeTypeName] Error_IR_BadParameterList_Count, //!< [ExpectedParamCount][ProvidedParamCount] Error_IR_BadParameterList_Type, //!< [ParamIndex][ExpectedParamType][ProvidedParamCount] Error_IR_BadTree_UnexpectedChild, //!< [ChildNodeTypeName] Error_IR_BadTree_BrokenConstraint_ParamNotUnique, //!< [ChildNodeTypeName][ParamName][FirstNodeIndex][SecondNodeIndex][ParamValueAsString] Error_IR_BadTree_EmptyTree, //!< (no argument) Error_IR_BadTree_DuplicatedReference_ChildNode, //!< [NodeIndex][FirstParent][SecondParent] Error_IR_BadTree_BadNodeOrder, //!< [ChildNodeIndex][ParentNodeIndex] Error_IR_BadTree_ConflictingParentReference, //!< [ChildNodeIndex][ParentIndexFromChild][ParentIndexFromTraversal] Error_IR_BadTree_BadNodeTypeIndex, //!< [NodeIndex][NodeTypeIndex] Error_IR_BadTree_UnreachableNode, //!< [NodeIndex] Error_Task_BadInitializer_ExternVariable, //!< [VarName][VarType][InitializerType] Error_Task_NameClash_ExternVariable, //!< [VarName][FirstDeclIndex][SecondDeclIndex] Error_Task_NameClash_Function, //!< [FunctionName][FirstIndex][SecondIndex] Error_Task_BadFunctionIndex_NodeTraverseCallback, //!< [NodeTypeName][PassIndex][FunctionIndex] Error_Task_NoCallback, //!< (no argument) Error_Func_NameClash_ExternVariable, //!< [VarName][FirstDeclIndex][SecondDeclIndex] Error_Func_NameClash_LocalVariable, //!< [VarName][FirstDeclIndex][SecondDeclIndex] Error_Func_BadType_ExternVariableVoid, //!< [VarName] Error_Func_BadType_LocalVariableVoid, //!< [VarName] Error_Func_InvalidValue_TotalParamCount, //!< [TotalParamCount] Error_Func_InvalidValue_RequiredParamCount, //!< [RequiredParamCount] Error_Func_MissingInitializer_OptionalParam, //!< [ParamIndex][ParamName] Error_Func_BadInitializer_LocalVariable, //!< [ParamIndex][ParamName][ParamType][InitializerType] Error_Func_BadExprDependence_BadIndex, //!< [DependentExprIndex][DependedExprIndex] Error_Func_BadExprDependence_TypeMismatch, //!< [DependentExprIndex][DependedExprIndex][ExpectedType][DependedExprType] Error_Func_BadExpr_BadNameReference, //!< [ExprIndex][VarName] Error_Func_Stmt_BadExprIndex, //!< [ExprIndex] Error_Func_Stmt_BadExprIndex_BranchCondition, //!< [ExprIndex][BranchCaseIndex] Error_Func_Assign_BadRHS_RHSVoid, //!< [ExprIndex] Error_Func_Assign_BadRHS_VariableTypeMismatch, //!< [VarName][VarType][ExprIndex][ExprType] Error_Func_Assign_BadLHS_Type, //!< [ExprIndex][ExprType] Error_Func_Assign_BadLHS_BadNameReference, //!< [VarName] Error_Func_Output_BadRHS_Type, //!< [ExprIndex][ExprType] Error_Func_Call_CalleeNotFound, //!< [FunctionName] Error_Func_Call_BadParamList_Count, //!< [FunctionName][TotalParamCount][RequiredParamCount][ProvidedArgumentCount] Error_Func_Call_BadParamList_Type, //!< [FunctionName][ParamIndex][ParamName][ParamType][ProvidedArgumentType] Error_Func_Branch_BadLabelReference, //!< [LabelName][BranchCaseIndex] Error_Func_Branch_BadConditionType, //!< [BranchCaseIndex][BranchConditionExprIndex][BranchConditionExprType] Error_Func_DuplicateLabel, //!< [LabelName][FirstLabelAddress][SecondLabelAddress] Error_Exec_TypeMismatch_ReadByName, //!< [ExpectedTy][VarTy][VarName] Error_Exec_TypeMismatch_WriteByName, //!< [ExpectedTy][VarTy][VarName] Error_Exec_TypeMismatch_WriteByPointer, //!< [ExpectedTy][VarTy][PtrDescriptionString] Error_Exec_TypeMismatch_ExpressionDependency, //!< [ExpectedTy][EvaluatedTy][DependentExprIndex][DependedExprIndex] Error_Exec_BadReference_VariableRead, //!< [VarName] Error_Exec_BadReference_VariableWrite, //!< [VarName] Error_Exec_BadReference_VariableTakeAddress, //!< [VarName] Error_Exec_NullPointerException_ReadValue, //!< [PtrDescriptionString] Error_Exec_NullPointerException_WriteValue, //!< [PtrDescriptionString] Error_Exec_DanglingPointerException_ReadValue, //!< [PtrDescriptionString] Error_Exec_DanglingPointerException_WriteValue, //!< [PtrDescriptionString] Error_Exec_WriteToConst_WriteNodeParamByName, //!< [VarName] Error_Exec_WriteToConst_WriteNodeParamByPointer, //!< [PtrDescriptionString] Error_Exec_BadNodePointer_TraverseToParent, //!< [PtrDescriptionString] Error_Exec_BadNodePointer_TraverseToChild, //!< [PtrDescriptionString] Error_Exec_BadTraverse_ChildWithoutPrimaryKey, //!< [ChildNodeTypeName][PtrDescriptionString] Error_Exec_BadTraverse_PrimaryKeyTypeMismatch, //!< [ProvidedKeyTy][ActualKeyTy][ChildNodeTypeName][KeyName][PtrDescriptionString] Error_Exec_BadTraverse_ParameterNotFound, //!< [ChildNodeTypeName][KeyName][PtrDescriptionString] Error_Exec_BadTraverse_ParameterNotUnique, //!< [ChildNodeTypeName][KeyName][PtrDescriptionString] Error_Exec_BadTraverse_UniqueKeyTypeMismatch, //!< [ProvidedKeyTy][ActualKeyTy][ChildNodeTypeName][KeyName][PtrDescriptionString] Error_Exec_Unreachable, //!< (no argument) Error_Exec_Assign_InvalidLHSType, //!< [ProvidedLHSType] Error_Exec_Output_Unknown_String, //!< [OutputString] Error_Exec_Output_InvalidType, //!< [ProvidedType] Error_Exec_Call_BadReference, //!< [FunctionName] Error_Exec_Call_BadArgumentList_Count, //!< [FunctionName][RequiredParamCount][TotalParamCount][ProvidedArgumentCount] Error_Exec_Call_BadArgumentList_Type, //!< [FunctionName][ParameterIndex][ParameterName][ParameterType][ProvidedArgumentType] Error_Exec_Branch_InvalidConditionType, //!< [CaseIndex][ProvidedType] Error_Exec_Branch_InvalidLabelAddress, //!< [CaseIndex][LabelMarkedStatementIndex] Error_Exec_Branch_Unreachable, //!< [CaseIndex] Error_Parser_NameClash_MatchPair, //!< [MatchPairName][FirstIndex][SecondIndex] Error_Parser_NameClash_ParserNode, //!< [NodeName][1stIndex][2ndIndex] Error_Parser_NameClash_ParserNodeParameter, //!< [ParameterName][1stIndex][2ndIndex] Error_Parser_BadMatchPair_EmptyStartString, //!< [StartStringIndex] Error_Parser_BadMatchPair_EmptyEndString, //!< [EndStringIndex] Error_Parser_BadMatchPair_StartStringConflict, //!< [StartString][1stMatchPairName][1stMatchPair1Index][2ndMatchPairName][2ndMatchPairIndex] Error_Parser_BadMatchPair_EndStringDuplicated, //!< [MatchPairIndex][EndString][FirstIndex][SecondIndex] Error_Parser_BadMatchPair_NoStartString, //!< (no argument) Error_Parser_BadMatchPair_NoEndString, //!< (no argument) Error_Parser_BadExprMatchPair_EmptyStartString, //!< (no argument) Error_Parser_BadExprMatchPair_EmptyEndString, //!< (no argument) Error_Parser_BadExprMatchPair_StartStringInIgnoreList, //!< (no argument) Error_Parser_BadExprMatchPair_EndStringInIgnoreList, //!< (no argument) Error_Parser_BadReference_IRNodeName, //!< [IRNodeName] Error_Parser_BadReference_ParserNodeName, //!< [ParserNodeName] Error_Parser_MultipleOverwrite, //!< [ValueName][FirstIndex][SecondIndex] Error_Parser_BadConversionToIR_IRParamNotInitialized, //!< [ParameterName] Error_Parser_BadConversionToIR_IRParamNotExist, //!< [ParameterName] Error_Parser_BadRoot_BadReferenceByParserNodeName, //!< [RootParserNodeName] Error_Parser_BadRoot_NotConvertingToIR, //!< [RootParserNodeName] Error_Parser_BadTree_BadChildNodeReference, //!< [ParentParserNodeName][ChildParserNodeName] Error_Parser_BadPattern_Expr_MissingEngineNameEndMark, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_NoRawLiteralAfterEngineSpecifier, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_ExpectingExpressionContent, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_UnterminatedQuote, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_RawStringMissingQuoteStart, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_UnterminatedExpr, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_EmptyBody, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_GarbageAtEnd, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_UnrecognizedEngine, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_BadRegex, //!< [StringDiagnostic][RegexErrorString] Error_Parser_BadPattern_Expr_DuplicatedDefinition, //!< [ValueName][FirstSubpatternIndex][SecondSubpatternIndex] Error_Parser_BadPattern_Expr_BadTerminatorInclusionSpecifier, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_BadNameForReference, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_InvalidNextPatternForInclusion, //!< [StringDiagnostic] Error_Parser_BadPattern_Expr_UnexpectedMatchPairEnd, //!< [StringDiagnostic] Error_Parser_BadPattern_UnmatchedMatchPairStart, //!< [StringDiagnostic] Error_Parser_BadPattern_EmptyPattern, //!< (no argument) Error_Parser_BadValueTransform_UnterminatedExpr, //!< [StringDiagnostic] Error_Parser_BadValueTransform_NonLocalAccessInLocalOnlyEnv, //!< [StringDiagnostic] Error_Parser_BadValueTransform_InvalidNameForReference, //!< [StringDiagnostic] Error_Parser_BadValueTransform_MissingChildSearchExpr, //!< [StringDiagnostic] Error_Parser_BadValueTransform_UnterminatedChildSearchExpr, //!< [StringDiagnostic] Error_Parser_BadValueTransform_BadNumberExpr, //!< [StringDiagnostic] Error_Parser_BadValueTransform_ExpectingLiteralExpr, //!< [StringDiagnostic] Error_Parser_BadValueTransform_UnterminatedQuote, //!< [StringDiagnostic] Error_Parser_BadValueTransform_RawStringMissingQuoteStart, //!< [StringDiagnostic] Error_Parser_BadValueTransform_GarbageAtExprEnd, //!< [StringDiagnostic] Error_Parser_BadValueTransform_Traverse_ExpectSlashOrDot, //!< [StringDiagnostic] Error_Parser_BadValueTransform_ExpectTraverseExpr, //!< [StringDiagnostic] Error_Parser_BadValueTransform_ExpectValueName, //!< [StringDiagnostic] Warn_Parser_MissingInitializer, //!< [ParameterName] Warn_Parser_Unused_Overwrite, //!< [OverwriteValueName][OverwriteRecordIndex] Warn_Parser_Unused_PatternValue, //!< [PatternValueName][SubPatternIndex] Warn_Parser_DuplicatedReference_ChildParserNode, //!< [ParentParserNodeName][ChildParserNodeName] Warn_Parser_UnreachableNode, //!< [ParserNodeName] Warn_Parser_Matching_Ambiguous, //!< [InputString], [list of tuple of [NodeName][NodeParamStringList][PatternIndex]] Error_Parser_Matching_NoMatch, //!< (no argument) Error_Parser_Matching_GarbageAtEnd, //!< (no argument) Error_Parser_IRBuild_BadTransform, //!< [ParserNodeName][IRNodeName][IRNodeParamName] Error_Parser_IRBuild_BadCast, //!< [ParserNodeName][IRNodeName][IRNodeParamName][IRNodeParameterType][ParserNodeDataString] Error_Json_UnknownType_String, //!< [TypeString] Error_Json_UnsupportedLiteralType, //!< (no argument) Error_Json_UnexpectedInitializer, //!< [VarName][VarType] Error_Json_UnknownBranchAction, //!< [ActString] Error_Json_UnknownStatementType, //!< [StmtString] Error_Json_BadReference_Variable, //!< [VarName] Error_Json_BadReference_IR, //!< [IRName] Error_Json_BadReference_Output, //!< [OutputName] Error_Json_BadReference_IRNodeType, //!< [IRNodeTypeName] Warn_XML_MismatchedIRTypeName, //!< [LineNumber][ColumnNumber][ExpectedIRRootTypeName][ActualIRRootTypeName] Warn_XML_UnexpectedAttribute, //!< [LineNumber][ColumnNumber][ElementName][AttributeName][AttributeValue] Warn_XML_IRNode_MissingParameter, //!< [LineNumber][ColumnNumber] Error_XML_UnexpectedElement, //!< [LineNumber][ColumnNumber][ExpectedElementName][ActualElementName] Error_XML_InvalidXML, //!< [LineNumber][ColumnNumber][ErrorString] Error_XML_ExpectingIRRootInstance, //!< [LineNumber][ColumnNumber] Error_XML_UnknownIRNodeType, //!< [LineNumber][ColumnNumber][IRNodeTypeName] Error_XML_ExpectingStartElement, //!< [LineNumber][ColumnNumber][TokenString] Error_XML_IRNode_Param_MissingName, //!< [LineNumber][ColumnNumber] Error_XML_IRNode_Param_MissingType, //!< [LineNumber][ColumnNumber] Error_XML_IRNode_Param_UnknownParam, //!< [LineNumber][ColumnNumber][ParameterName] Error_XML_UnknownValueType, //!< [LineNumber][ColumnNumber][ValueTypeName] Error_XML_IRNode_Param_MissingData, //!< [LineNumber][ColumnNumber][ParameterName] Error_XML_IRNode_Param_ExpectEndElement, //!< [LineNumber][ColumnNumber][ParameterName] Error_XML_IRNode_Param_TypeMismatch, //!< [LineNumber][ColumnNumber][ParameterName][ExpectedType][ActualType] Error_XML_IRNode_Param_InvalidValue, //!< [LineNumber][ColumnNumber][ParameterName][ParameterType][ValueString] Error_XML_IRNode_Param_MultipleValue, //!< [LineNumber][ColumnNumber][ParameterName] Error_XML_IRNode_ParamAfterChildNode, //!< [LineNumber][ColumnNumber] InvalidID }; Q_ENUM(ID) static QString getString(ID id){ return QMetaEnum::fromType<ID>().valueToKey(id); } private: Diag(){} // you should not create instance }; // we want to be able to put ValueType into QVariant for diagnostic only struct ValueTypeWrapper{ ValueType ty; }; Q_DECLARE_METATYPE(ValueTypeWrapper) /** * @brief The ExpressionDiagnosticRecord struct describes a diagnostic to an expression string * * Each diagnostic can carry an error interval and an info interval. * Info interval may and may not overlap with error interval. * If it makes no sense for an interval, both start and end index should be zero. */ struct StringDiagnosticRecord{ QString str; int infoStart; int infoEnd; int errorStart; int errorEnd; }; Q_DECLARE_METATYPE(StringDiagnosticRecord) class DiagnosticPathNode { friend class DiagnosticEmitterBase; public: DiagnosticPathNode(DiagnosticEmitterBase& d, const QString& pathName); DiagnosticPathNode(const DiagnosticPathNode&) = delete; DiagnosticPathNode(DiagnosticPathNode&&) = delete; ~DiagnosticPathNode(){ if(hierarchyIndex >= 0){ release(); } } void pop(){ if(hierarchyIndex >= 0){ release(); } } void setDetailedName(const QString& name){ detailedName = name; } const QString& getPathName()const {return pathName;} const QString& getDetailedName()const {return detailedName;} const DiagnosticPathNode* getPrev()const {return prev;} int getHierarchyIndex() const {return hierarchyIndex;} private: void release(); DiagnosticEmitterBase& d; DiagnosticPathNode* prev; QString pathName; QString detailedName; int hierarchyIndex; }; class DiagnosticEmitterBase { friend class DiagnosticPathNode; public: virtual ~DiagnosticEmitterBase(){} /** * @brief setDetailedName set detailed name on last pushed node * @param name the detailed name to put */ void setDetailedName(const QString& name){Q_ASSERT(head); head->setDetailedName(name);} template<typename... Args> void operator()(Diag::ID id, Args&&... arg){ QList<QVariant> params; appendParam(params, std::forward<Args>(arg)...); diagnosticHandle(id, params); } void operator()(Diag::ID id){ diagnosticHandle(id, QList<QVariant>()); } // the form that directly passes the arguments void handle(Diag::ID id, const QList<QVariant>& arg){ diagnosticHandle(id, arg); } protected: /** * @brief currentHead get most recently pushed node. Intended for child * @return pointer to path node; null if no node pushed */ const DiagnosticPathNode* currentHead(){return head;} private: // we now only accept following types as parameter to diagnostic void appendParam(QList<QVariant>& param, const ValueType& val){ QVariant v; v.setValue(ValueTypeWrapper{val}); param.push_back(v); } void appendParam(QList<QVariant>& param, const int& val){ param.push_back(QVariant(val)); } void appendParam(QList<QVariant>& param, const QString& val){ param.push_back(QVariant(val)); } void appendParam(QList<QVariant>& param, const QStringList& val){ param.push_back(val); } void appendParam(QList<QVariant>& param, const StringDiagnosticRecord& val){ QVariant v; Q_ASSERT(val.infoStart >= 0); Q_ASSERT(val.infoStart <= val.infoEnd); Q_ASSERT(val.infoEnd <= val.str.length()); Q_ASSERT(val.errorStart >= 0); Q_ASSERT(val.errorStart <=val.errorEnd); Q_ASSERT(val.errorEnd <= val.str.length()); v.setValue(val); param.push_back(v); } template<typename T, typename... Args> void appendParam(QList<QVariant>& param, const T& val, Args&&... arg){ appendParam(param, val); appendParam(param, std::forward<Args>(arg)...); } protected: virtual void diagnosticHandle(Diag::ID id, const QList<QVariant>& data){Q_UNUSED(id) Q_UNUSED(data)} private: DiagnosticPathNode* head = nullptr; int hierarchyCount = 0; }; // just for testing purpose; we will have GUI oriented implementation later on class ConsoleDiagnosticEmitter: public DiagnosticEmitterBase { public: virtual ~ConsoleDiagnosticEmitter() override {} virtual void diagnosticHandle(Diag::ID id, const QList<QVariant>& data) override; }; /* class DiagnosticEmitter : public QObject { Q_OBJECT public: explicit DiagnosticEmitter(QObject *parent = nullptr); signals: public slots: }; */ #endif // DIAGNOSTICEMITTER_H <file_sep>/ui/PlainTextDocumentWidget.cpp #include "ui/PlainTextDocumentWidget.h" #include "ui/DocumentEdit.h" #include <QHBoxLayout> #include <QFileInfo> #include <QSaveFile> #include <QTextStream> #include <QDebug> #include <QRegularExpression> #include <QTextCodec> #ifndef FILE_READ_FLAG #define FILE_READ_FLAG (QIODevice::ReadOnly | QIODevice::Text) #endif #ifndef FILE_WRITE_FLAG #define FILE_WRITE_FLAG (QIODevice::WriteOnly | QIODevice::Text) #endif PlainTextDocumentWidget::PlainTextDocumentWidget(QString filePath, QWidget *parent) : DocumentWidget(parent), ui_editor(nullptr), rawFilePath(filePath), absoluteFilePath(), fileName(), lastAccessTimeStamp(), lastAccessFileSize(0) { ui_editor = new DocumentEdit(this); QHBoxLayout* layout = new QHBoxLayout(); layout->addWidget(ui_editor); layout->setMargin(0); setLayout(layout); initialize(); connect(ui_editor, &QPlainTextEdit::textChanged, this, &PlainTextDocumentWidget::setDirtyFlag); } bool PlainTextDocumentWidget::initialize() { if(rawFilePath.isEmpty()) return true; QFile file(rawFilePath); if(!file.open(FILE_READ_FLAG)){ // failed to open the file for any reasons return false; } // now we know for sure we can access it QFileInfo f(file); lastAccessTimeStamp = QDateTime::currentDateTime(); lastAccessFileSize = f.size(); readOnlyFlag = !f.isWritable(); followFlag = true; absoluteFilePath = f.absoluteFilePath(); fileName = f.fileName(); // do not bother to read file if it is zero sized if(f.size() == 0) return true; setDocumentContent(&file); file.close(); dirtyFlag = false; return true; } void PlainTextDocumentWidget::setDocumentContent(QIODevice *src) { QTextStream ts(src); ts.setCodec(QTextCodec::codecForName("UTF-8")); ui_editor->setPlainText(ts.readAll()); } QByteArray PlainTextDocumentWidget::getDocumentContent() { return ui_editor->toPlainText().toUtf8(); } void PlainTextDocumentWidget::setDirtyFlag() { if(!dirtyFlag){ dirtyFlag = true; emit stateChanged(); } } void PlainTextDocumentWidget::setReadOnly(bool isReadOnly) { readOnlyFlag = isReadOnly; ui_editor->setReadOnly(isReadOnly); emit stateChanged(); } void PlainTextDocumentWidget::fileRecheck() { if(absoluteFilePath.isEmpty()){ // the file do not exist yet if(initialize()){ // initialization successful emit stateChanged(); } return; } // the file already exist and we already loaded a copy // first of all, do nothing if dirty flag is set if(dirtyFlag) return; QFileInfo f(absoluteFilePath); if(!f.exists()){ // the file stops to exist // set dirty flag and stop now dirtyFlag = true; emit stateChanged(); return; } // if file is modified, perform different action under different mode QFile file(absoluteFilePath); QByteArray newHash; // check file size first bool isFileModified = false; if(lastAccessFileSize == f.size()){ // empty files are all the same if(lastAccessFileSize == 0) return; QDateTime currentTimestamp = f.lastModified(); if(lastAccessTimeStamp < currentTimestamp){ // we have a more recent modify // check if hash matches isFileModified = true; } // modification should already been pulled in }else{ // file size mismatch; file must already been modified isFileModified = true; } if(isFileModified){ if(followFlag){ // reload file content if(!file.isOpen()){ if(!file.open(FILE_READ_FLAG)){ dirtyFlag = true; emit stateChanged(); return; } }else{ if(!file.reset()){ dirtyFlag = true; emit stateChanged(); return; } } // save current cursor position QTextCursor currentCursor = ui_editor->textCursor(); int blockNum = currentCursor.blockNumber(); int columnNum = currentCursor.positionInBlock(); DirtySignalDisabler lock(this); setDocumentContent(&file); file.close(); int currentBlockCount = ui_editor->blockCount(); QTextCursor newCursor = ui_editor->textCursor(); if(blockNum >= currentBlockCount){ // scroll to end of document newCursor.movePosition(QTextCursor::End); }else{ if(blockNum > 0){ newCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, blockNum); } newCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, columnNum); } ui_editor->setTextCursor(newCursor); dirtyFlag = false; }else{ // !followFlag dirtyFlag = true; emit stateChanged(); return; } } } bool PlainTextDocumentWidget::saveToFile(QString filePath) { bool isNewFile = !filePath.isEmpty(); QString newAbsolutePath; QString newFileName; if(!filePath.isEmpty()){ QFileInfo f(filePath); newAbsolutePath = f.absoluteFilePath(); if(newAbsolutePath == absoluteFilePath){ isNewFile = false; }else{ newFileName = f.fileName(); } } QSaveFile file((isNewFile? newAbsolutePath: absoluteFilePath)); if(!file.open(FILE_WRITE_FLAG)){ return false; } QByteArray data = getDocumentContent(); file.write(data); if(!file.commit()){ return false; } data.clear(); if(isNewFile){ rawFilePath = filePath; absoluteFilePath = newAbsolutePath; fileName = newFileName; } QFileInfo f(absoluteFilePath); lastAccessFileSize = f.size(); lastAccessTimeStamp = f.lastModified(); if(dirtyFlag || isNewFile){ dirtyFlag = false; emit stateChanged(); } return true; } QMenu* PlainTextDocumentWidget::getMenu() { QMenu* ptr = new QMenu; QAction* readonlyAct = new QAction(tr("Read-only")); readonlyAct->setCheckable(true); readonlyAct->setChecked(readOnlyFlag); connect(readonlyAct, &QAction::triggered, [=]()->void{ setReadOnly(!readOnlyFlag); }); ptr->addAction(readonlyAct); return ptr; } QString PlainTextDocumentWidget::getFileName() const { if(!fileName.isEmpty()){ return fileName; }else if(!rawFilePath.isEmpty()){ // probably impossible.. int dashIndex = rawFilePath.lastIndexOf(QRegularExpression("[/\\\\]"), -2); if(dashIndex >= 0){ return rawFilePath.mid(dashIndex+1); }else{ return rawFilePath; } }else{ return tr("Unnamed","Tab display name for document without file associated"); } } DirtySignalDisabler::DirtySignalDisabler(PlainTextDocumentWidget* doc) : doc(doc) { QObject::disconnect(doc->ui_editor, &QPlainTextEdit::textChanged, doc, &PlainTextDocumentWidget::setDirtyFlag); } DirtySignalDisabler::~DirtySignalDisabler() { QObject::connect(doc->ui_editor, &QPlainTextEdit::textChanged, doc, &PlainTextDocumentWidget::setDirtyFlag); } <file_sep>/ui/DocumentWidget.h #ifndef DOCUMENTWIDGET_H #define DOCUMENTWIDGET_H #include <QWidget> #include <QMenu> #include <QString> class DocumentWidget : public QWidget { Q_OBJECT public: /** * @brief createInstance * @param filePath * @return */ static DocumentWidget* createInstance(QString filePath); DocumentWidget(QWidget* parent = nullptr) : QWidget(parent) {} virtual bool isDirty() const = 0; /** * @brief getAbsoluteFilePath get the absolute file path (for duplicate opening detection) * @return absolute file path if this DocumentWidget is associated with a file; empty string otherwise */ virtual QString getAbsoluteFilePath() const = 0; /** * @brief getFileName get only the file name (for close dialog warning purpose) * @return file name without path */ virtual QString getFileName() const = 0; /** * @brief saveToFile try to save the document to specified file path * @param filePath the new path to save to. Empty if saving to currently associated one * @return true if save is successful, false otherwise */ virtual bool saveToFile(QString filePath = QString()) = 0; /** * @brief getMenu return a menu for right click pop-up menu * @return pointer to a new menu object for this document */ virtual QMenu* getMenu() {return nullptr;} //------------------------------------------------------------------------- // optional public functions virtual bool isReadOnly() const {return false;} /** * @brief isEmpty returns if it is safe to remove this DocumentWidget if an open request succeeds * @return true if the DocumentWidget do not have unsaved data and is not associated with any file, false otherwise */ virtual bool isEmpty() const {return !isDirty() && getAbsoluteFilePath().isEmpty();} /** * @brief getTabDisplayName get the string for showing file name on tab * @return string for tab name */ virtual QString getTabDisplayName() const; /** * @brief getTitleDisplayName get the string for showing file path on window title * @return string for window title prefix */ virtual QString getTitleDisplayName() const; signals: /** * @brief stateChanged emitted when open mode, file association, or dirty flag changes */ void stateChanged(); public slots: /** * @brief checkFileUpdate request for checking the status of associated file */ void checkFileUpdate(); protected: /** * @brief fileRecheck will be called from checkFileUpdate() */ virtual void fileRecheck() = 0; }; #endif // DOCUMENTWIDGET_H <file_sep>/core/OutputHandlerBase.h #ifndef OUTPUTHANDLERBASE_H #define OUTPUTHANDLERBASE_H #include <QtGlobal> #include <QBuffer> #include <QTextCodec> #include <QTextEncoder> #include "core/Value.h" struct OutputDescriptor{ // the base type of output // for now we only support text enum OutputBaseType{ Text }; struct TextOutputInfo{ QString mimeType; //!< the mime type that goes to clipboard; empty for text/plain QString codecName; //!< the name of output codec }; QString name; OutputBaseType baseTy; TextOutputInfo textInfo; }; class OutputHandlerBase { public: virtual ~OutputHandlerBase(){} /** * @brief getAllowedOutputTypeList sets the type that can be accepted by output * @param tys the wb list for types being accepted */ virtual void getAllowedOutputTypeList(QList<ValueType>& tys) const = 0; virtual bool isOutputGoodSoFar() {return true;} // it is the execution context's duty not to call addOutput with wrong type // return true if the output data is good, false otherwise virtual bool addOutput(const QString& data) {Q_UNUSED(data) Q_ASSERT(0); return false;} }; class TextOutputHandler : public OutputHandlerBase { public: TextOutputHandler(const QByteArray& codecName); virtual ~TextOutputHandler() override; /** * @brief getResult stop the output and get output * @return reference to QByteArray output */ const QByteArray& getResult(); virtual void getAllowedOutputTypeList(QList<ValueType>& tys) const override; virtual bool isOutputGoodSoFar() override; virtual bool addOutput(const QString& data) override; private: QBuffer buffer; QTextEncoder* encoder; }; #endif // OUTPUTHANDLERBASE_H <file_sep>/core/CLIDriver.h #ifndef CLIDRIVER_H #define CLIDRIVER_H // currently in core/test.cpp void testerEntry(); #endif // CLIDRIVER_H <file_sep>/core/ExecutionContext.cpp #include "core/ExecutionContext.h" #include "core/DiagnosticEmitter.h" #include "core/Expression.h" #include "core/IR.h" #include "core/OutputHandlerBase.h" #include "core/Task.h" #include <stdexcept> ExecutionContext::ExecutionContext(const Task& t, const IRRootInstance &root, DiagnosticEmitterBase& diagnostic, OutputHandlerBase& out, QObject* parent) : QObject(parent), t(t), root(root), diagnostic(diagnostic), out(out) { Q_ASSERT(t.validated()); Q_ASSERT(root.validated()); // initialize global variables int gvCnt = t.getNumGlobalVariable(); globalVariables.clear(); globalVariables.reserve(gvCnt); for(int i = 0; i < gvCnt; ++i){ globalVariables.push_back(t.getGlobalVariableInitializer(i)); } // initialize node variables //const auto& rootTy = t.getRootType(); int nodeCount = root.getNumNode(); nodeMembers.clear(); nodeMembers.reserve(nodeCount); QHash<int, QList<QVariant>> initializerListTemplate;//[nodeTypeIndex] -> combined member initialization list for(int i = 0; i < nodeCount; ++i){ int typeIndex = root.getNode(i).getTypeIndex(); auto iter = initializerListTemplate.find(typeIndex); if(iter == initializerListTemplate.end()){ QList<QVariant> initializerList; int nodeMemberCount = t.getNumNodeMember(typeIndex); initializerList.reserve(nodeMemberCount); for(int i = 0; i < nodeMemberCount; ++i){ initializerList.push_back(t.getNodeMemberInitializer(typeIndex, i)); } initializerListTemplate.insert(typeIndex, initializerList); nodeMembers.push_back(initializerList); }else{ nodeMembers.push_back(iter.value()); } } out.getAllowedOutputTypeList(allowedOutputTypes); currentActivationCount = 0; } bool ExecutionContext::read(const QString& name, ValueType& ty, QVariant& val) { Q_ASSERT(!stack.empty()); const auto& frame = stack.top(); { int localVariableIndex = frame.f.getLocalVariableIndex(name); if(localVariableIndex >= 0){ ty = frame.f.getLocalVariableType(localVariableIndex); val = frame.localVariables.at(localVariableIndex); checkUninitializedRead(ty, val); return true; } } { int nodeMemberIndex = t.getNodeMemberIndex(frame.irNodeTypeIndex, name); if(nodeMemberIndex >= 0){ ty = t.getNodeMemberType(frame.irNodeTypeIndex, nodeMemberIndex); val = nodeMembers.at(frame.irNodeIndex).at(nodeMemberIndex); checkUninitializedRead(ty, val); return true; } } { const auto& nodeTy = root.getType().getNodeType(frame.irNodeTypeIndex); int nodeParameterIndex = nodeTy.getParameterIndex(name); if(nodeParameterIndex >= 0){ const auto& nodeInst = root.getNode(frame.irNodeIndex); ty = nodeTy.getParameterType(nodeParameterIndex); val = nodeInst.getParameter(nodeParameterIndex); checkUninitializedRead(ty, val); return true; } } { int globalVariableIndex = t.getGlobalVariableIndex(name); if(globalVariableIndex >= 0){ ty = t.getGlobalVariableType(globalVariableIndex); val = globalVariables.at(globalVariableIndex); checkUninitializedRead(ty, val); return true; } } diagnostic(Diag::Error_Exec_BadReference_VariableRead, name); return false; } bool ExecutionContext::read(const ValuePtrType& valuePtr, ValueType& ty, QVariant& val) { Q_ASSERT(!stack.empty()); const auto& frame = stack.top();// index is stack.size()-1 switch(valuePtr.ty){ case ValuePtrType::PtrType::NullPointer:{ diagnostic(Diag::Error_Exec_NullPointerException_ReadValue, getValuePtrDescription(valuePtr)); return false; }/*break;*/ case ValuePtrType::PtrType::LocalVariable:{ int ptrAcivationIndex = valuePtr.head.activationIndex; if(frame.activationIndex != ptrAcivationIndex){ // walk over the stack to see if the activation is still alive for(int i = static_cast<int>(stack.size())-2; i >= 0; ++i){ const auto& curFrame = stack.at(i); if(curFrame.activationIndex == ptrAcivationIndex){ // okay we found it ty = curFrame.f.getLocalVariableType(valuePtr.valueIndex); val = curFrame.localVariables.at(valuePtr.valueIndex); checkUninitializedRead(ty, val); return true; } } diagnostic(Diag::Error_Exec_DanglingPointerException_ReadValue, getValuePtrDescription(valuePtr)); return false; }else{ ty = frame.f.getLocalVariableType(valuePtr.valueIndex); val = frame.localVariables.at(valuePtr.valueIndex); checkUninitializedRead(ty, val); return true; } }/*break;*/ case ValuePtrType::PtrType::NodeRWMember:{ ty = t.getNodeMemberType( /* node type index */root.getNode(valuePtr.nodeIndex).getTypeIndex(), /* member index */valuePtr.valueIndex); val = nodeMembers.at(valuePtr.nodeIndex).at(valuePtr.valueIndex); checkUninitializedRead(ty, val); return true; }/*break;*/ case ValuePtrType::PtrType::NodeROParameter:{ const auto& nodeTy = root.getType().getNodeType(valuePtr.nodeIndex); ty = nodeTy.getParameterType(valuePtr.valueIndex); val = root.getNode(valuePtr.nodeIndex).getParameter(valuePtr.valueIndex); checkUninitializedRead(ty, val); return true; }/*break;*/ case ValuePtrType::PtrType::GlobalVariable:{ ty = t.getGlobalVariableType(valuePtr.valueIndex); val = globalVariables.at(valuePtr.valueIndex); checkUninitializedRead(ty, val); return true; }/*break;*/ } Q_UNREACHABLE(); } void ExecutionContext::checkUninitializedRead(ValueType ty, QVariant& readVal) { if(readVal.isValid()) return; diagnostic(Diag::Warn_Exec_UninitializedRead); //default initialize it switch (ty) { case ValueType::Void: Q_UNREACHABLE(); case ValueType::Int64: readVal = qint64(0); break; case ValueType::String: readVal = QString(); break; case ValueType::NodePtr:{ NodePtrType ptr; ptr.head = getPtrSrcHead(); ptr.nodeIndex = -1; readVal.setValue(ptr); }break; case ValueType::ValuePtr:{ ValuePtrType ptr; ptr.head = getPtrSrcHead(); ptr.ty = ValuePtrType::PtrType::NullPointer; ptr.nodeIndex = -1; ptr.valueIndex = -1; readVal.setValue(ptr); }break; } } bool ExecutionContext::takeAddress(const QString& name, ValuePtrType& val) { Q_ASSERT(!stack.empty()); const auto& frame = stack.top(); val.head = getPtrSrcHead(); { int localVariableIndex = frame.f.getLocalVariableIndex(name); if(localVariableIndex >= 0){ val.ty = ValuePtrType::PtrType::LocalVariable; val.nodeIndex = -1; val.valueIndex = localVariableIndex; return true; } } { int nodeMemberIndex = t.getNodeMemberIndex(frame.irNodeTypeIndex, name); if(nodeMemberIndex >= 0){ val.ty = ValuePtrType::PtrType::NodeRWMember; val.nodeIndex = frame.irNodeIndex; val.valueIndex = nodeMemberIndex; return true; } } { const auto& nodeTy = root.getType().getNodeType(frame.irNodeTypeIndex); int nodeParameterIndex = nodeTy.getParameterIndex(name); if(nodeParameterIndex >= 0){ val.ty = ValuePtrType::PtrType::NodeROParameter; val.nodeIndex = frame.irNodeIndex; val.valueIndex = nodeParameterIndex; return true; } } { int globalVariableIndex = t.getGlobalVariableIndex(name); if(globalVariableIndex >= 0){ val.ty = ValuePtrType::PtrType::GlobalVariable; val.nodeIndex = -1; val.valueIndex = globalVariableIndex; return true; } } diagnostic(Diag::Error_Exec_BadReference_VariableTakeAddress, name); return false; } bool ExecutionContext::write(const QString& name, const ValueType& ty, const QVariant& val) { Q_ASSERT(!stack.empty()); auto& frame = stack.top(); ValueType actualTy = ValueType::Void; QVariant* valPtr = nullptr; { int localVariableIndex = frame.f.getLocalVariableIndex(name); if(localVariableIndex >= 0){ actualTy = frame.f.getLocalVariableType(localVariableIndex); valPtr = &frame.localVariables[localVariableIndex]; } } if(!valPtr){ int nodeMemberIndex = t.getNodeMemberIndex(frame.irNodeTypeIndex, name); if(nodeMemberIndex >= 0){ actualTy = t.getNodeMemberType(frame.irNodeTypeIndex, nodeMemberIndex); valPtr = &nodeMembers[frame.irNodeIndex][nodeMemberIndex]; } } // we block write to read-only node parameters if(!valPtr){ const auto& nodeTy = root.getType().getNodeType(frame.irNodeTypeIndex); int nodeParameterIndex = nodeTy.getParameterIndex(name); if(Q_UNLIKELY(nodeParameterIndex >= 0)){ diagnostic(Diag::Error_Exec_WriteToConst_WriteNodeParamByName, name); return false; } } if(!valPtr){ int globalVariableIndex = t.getGlobalVariableIndex(name); if(globalVariableIndex >= 0){ actualTy = t.getGlobalVariableType(globalVariableIndex); valPtr = &globalVariables[globalVariableIndex]; } } if(Q_UNLIKELY(!valPtr)){ diagnostic(Diag::Error_Exec_BadReference_VariableWrite, name); return false; }else if(Q_UNLIKELY(actualTy != ty)){ diagnostic(Diag::Error_Exec_TypeMismatch_WriteByName, ty, actualTy, name); return false; }else{ *valPtr = val; return true; } } bool ExecutionContext::write(const ValuePtrType& valuePtr, const ValueType& ty, const QVariant& dest) { Q_ASSERT(!stack.empty()); auto& frame = stack.top();// index is stack.size()-1 ValueType actualTy = ValueType::Void; QVariant* valPtr = nullptr; switch(valuePtr.ty){ case ValuePtrType::PtrType::NullPointer:{ diagnostic(Diag::Error_Exec_NullPointerException_WriteValue, getValuePtrDescription(valuePtr)); return false; }/*break;*/ case ValuePtrType::PtrType::LocalVariable:{ int ptrAcivationIndex = valuePtr.head.activationIndex; if(frame.activationIndex != ptrAcivationIndex){ // walk over the stack to see if the activation is still alive for(int i = static_cast<int>(stack.size())-2; i >= 0; ++i){ auto& curFrame = stack.at(i); if(curFrame.activationIndex == ptrAcivationIndex){ // okay we found it actualTy = curFrame.f.getLocalVariableType(valuePtr.valueIndex); valPtr = &curFrame.localVariables[valuePtr.valueIndex]; break; } } diagnostic(Diag::Error_Exec_DanglingPointerException_WriteValue, getValuePtrDescription(valuePtr)); return false; }else{ actualTy = frame.f.getLocalVariableType(valuePtr.valueIndex); valPtr = &frame.localVariables[valuePtr.valueIndex]; } }break; case ValuePtrType::PtrType::NodeRWMember:{ actualTy = t.getNodeMemberType( /* node type index */root.getNode(valuePtr.nodeIndex).getTypeIndex(), /* member index */valuePtr.valueIndex); valPtr = &nodeMembers[valuePtr.nodeIndex][valuePtr.valueIndex]; }break; case ValuePtrType::PtrType::NodeROParameter:{ diagnostic(Diag::Error_Exec_WriteToConst_WriteNodeParamByPointer, getValuePtrDescription(valuePtr)); return false; }/*break;*/ case ValuePtrType::PtrType::GlobalVariable:{ actualTy = t.getGlobalVariableType(valuePtr.valueIndex); valPtr = &globalVariables[valuePtr.valueIndex]; }break; } if(Q_UNLIKELY(actualTy != ty)){ diagnostic(Diag::Error_Exec_TypeMismatch_WriteByPointer, ty, actualTy, getValuePtrDescription(valuePtr)); return false; }else{ *valPtr = dest; return true; } } bool ExecutionContext::getCurrentNodePtr(NodePtrType& result) { Q_ASSERT(!stack.empty()); result.head = getPtrSrcHead(); result.nodeIndex = stack.top().irNodeIndex; return true; } bool ExecutionContext::getRootNodePtr(NodePtrType& result) { Q_ASSERT(!stack.empty()); result.head = getPtrSrcHead(); result.nodeIndex = 0; return true; } bool ExecutionContext::getParentNode(const NodePtrType& src, NodePtrType& result) { Q_ASSERT(!stack.empty()); if(Q_UNLIKELY(src.nodeIndex < 0)){ diagnostic(Diag::Error_Exec_BadNodePointer_TraverseToParent, getPointerSrcDescription(src.head)); return false; } result.head = getPtrSrcHead(); result.nodeIndex = root.getNode(src.nodeIndex).getParentIndex(); return true; } bool ExecutionContext::getChildNode(const NodePtrType& src, const QString& childName, NodePtrType& result, ValueType keyTy, const QVariant& primaryKey) { if(Q_UNLIKELY(src.nodeIndex < 0)){ diagnostic(Diag::Error_Exec_BadNodePointer_TraverseToChild, getPointerSrcDescription(src.head)); return false; } int childTyIndex = root.getType().getNodeTypeIndex(childName); const IRNodeType& childTy = root.getType().getNodeType(childTyIndex); int primaryKeyIndex = childTy.getPrimaryKeyParameterIndex(); if(Q_UNLIKELY(primaryKeyIndex < 0)){ diagnostic(Diag::Error_Exec_BadTraverse_ChildWithoutPrimaryKey, childName, getNodePtrDescription(src)); return false; } if(Q_UNLIKELY(childTy.getParameterType(primaryKeyIndex) != keyTy)){ diagnostic(Diag::Error_Exec_BadTraverse_PrimaryKeyTypeMismatch, keyTy, childTy.getParameterType(primaryKeyIndex), childTy.getName(), childTy.getParameterName(primaryKeyIndex), getNodePtrDescription(src)); return false; } const IRNodeInstance& inst = root.getNode(src.nodeIndex); int childTyLocalIndex = inst.getLocalTypeIndex(childTyIndex); int childIndex = inst.getChildNodeIndex(childTyLocalIndex, primaryKeyIndex, primaryKey); result.head = getPtrSrcHead(); result.nodeIndex = childIndex; return true; } bool ExecutionContext::getChildNode(const NodePtrType& src, const QString& childName, NodePtrType& result, const QString& keyField, ValueType keyTy, const QVariant& keyValue) { if(Q_UNLIKELY(src.nodeIndex < 0)){ diagnostic(Diag::Error_Exec_BadNodePointer_TraverseToChild, getPointerSrcDescription(src.head)); return false; } int childTyIndex = root.getType().getNodeTypeIndex(childName); const IRNodeType& childTy = root.getType().getNodeType(childTyIndex); int paramIndex = childTy.getParameterIndex(keyField); if(Q_UNLIKELY(paramIndex < 0)){ diagnostic(Diag::Error_Exec_BadTraverse_ParameterNotFound, childName, keyField, getNodePtrDescription(src)); return false; } if(Q_UNLIKELY(!childTy.getParameterIsUnique(paramIndex))){ diagnostic(Diag::Error_Exec_BadTraverse_ParameterNotUnique, childName, keyField, getNodePtrDescription(src)); return false; } if(Q_UNLIKELY(childTy.getParameterType(paramIndex) != keyTy)){ diagnostic(Diag::Error_Exec_BadTraverse_UniqueKeyTypeMismatch, keyTy, childTy.getParameterType(paramIndex), childName, keyField, getNodePtrDescription(src)); return false; } const IRNodeInstance& inst = root.getNode(src.nodeIndex); int childTyLocalIndex = inst.getLocalTypeIndex(childTyIndex); int childIndex = inst.getChildNodeIndex(childTyLocalIndex, paramIndex, keyValue); result.head = getPtrSrcHead(); result.nodeIndex = childIndex; return true; } void ExecutionContext::continueExecution() { // we havn't implement pausing execution yet Q_ASSERT(!isInExecution); if(!isInExecution){ try { mainExecutionEntry(); emit executionFinished(0); } catch (...) { emit executionFinished(-1); } }else{ eventLoop.quit(); } } void ExecutionContext::mainExecutionEntry() { // reset state first currentActivationCount = 0; nodeTraverseStack.clear(); stack.clear(); isInExecution = true; for(int passIndex = 0, numPass = t.getNumPass(); passIndex < numPass; ++passIndex){ DiagnosticPathNode dnode(diagnostic, tr("Pass %1").arg(passIndex)); DiagnosticPathNode dnodeRoot(diagnostic, tr("Root")); nodeTraverseEntry(passIndex, 0); dnodeRoot.pop();// "Root" dnode.pop();// "Pass %1" } } void ExecutionContext::nodeTraverseEntry(int passIndex, int nodeIndex) { const IRNodeInstance& inst = root.getNode(nodeIndex); int nodeTypeIndex = inst.getTypeIndex(); const IRNodeType& ty = root.getType().getNodeType(nodeTypeIndex); diagnostic.setDetailedName(ty.getName()); int entryCB = t.getNodeCallback(nodeTypeIndex, Task::CallbackType::OnEntry, passIndex); int exitCB = t.getNodeCallback(nodeTypeIndex, Task::CallbackType::OnExit, passIndex); if(entryCB >= 0){ DiagnosticPathNode dnode(diagnostic, tr("Entry callback (%1)").arg(entryCB)); pushFunctionStackframe(entryCB, nodeIndex); functionMainLoop(); dnode.pop(); } for(int i = 0, numChild = inst.getNumChildNode(); i < numChild; ++i){ DiagnosticPathNode dnode(diagnostic, tr("Child %1").arg(i)); nodeTraverseEntry(passIndex, inst.getChildNodeByOrder(i)); dnode.pop(); } if(exitCB >= 0){ DiagnosticPathNode dnode(diagnostic, tr("Exit callback (%1)").arg(exitCB)); pushFunctionStackframe(exitCB, nodeIndex); functionMainLoop(); dnode.pop(); } } void ExecutionContext::pushFunctionStackframe(int functionIndex, int nodeIndex, QList<QVariant> params) { int activationIndex = currentActivationCount++; // do not push the frame if the function has no statements in it // (just for performance) const Function& f = t.getFunction(functionIndex); if(f.getNumStatement() > 0){ diagnostic.setDetailedName(f.getName()); CallStackEntry entry(f, functionIndex, nodeIndex, root.getNode(nodeIndex).getTypeIndex(), activationIndex); int localVariableCnt = f.getNumLocalVariable(); entry.localVariables.reserve(localVariableCnt); for(int i = 0; i < localVariableCnt; ++i){ entry.localVariables.push_back(f.getLocalVariableInitializer(i)); } for(int i = 0, num = params.size(); i < num; ++i){ entry.localVariables[i] = params.at(i); } stack.push(entry); } } void ExecutionContext::functionMainLoop() { while(!stack.empty()){ auto& frame = stack.top(); if(frame.stmtIndex >= frame.f.getNumStatement()){ // implicit return Q_ASSERT(frame.stmtIndex == frame.f.getNumStatement()); stack.pop(); continue; } int stmtIndex = frame.stmtIndex; const auto& stmt = frame.f.getStatement(stmtIndex); frame.stmtIndex += 1; switch(stmt.ty){ case StatementType::Unreachable:{ diagnostic(Diag::Error_Exec_Unreachable); throw std::runtime_error("Unreachable"); }/*break;*/ case StatementType::Assignment:{ const AssignmentStatement& assign = frame.f.getAssignmentStatement(stmt.statementIndexInType); // evaluate the expression first ValueType rhsTy = ValueType::Void; QVariant rhsVal; bool isGood = evaluateExpression(assign.rvalueExprIndex, rhsTy, rhsVal); if(Q_UNLIKELY(!isGood)){ throw std::runtime_error("Expression evaluation fail"); } if(assign.lvalueExprIndex == -1){ isGood = write(assign.lvalueName, rhsTy, rhsVal); }else{ ValueType lhsTy = ValueType::Void; QVariant lhsVal; isGood = evaluateExpression(assign.lvalueExprIndex, lhsTy, lhsVal); if(Q_UNLIKELY(!isGood)){ throw std::runtime_error("Expression evaluation fail"); } if(Q_UNLIKELY(lhsTy != ValueType::ValuePtr)){ diagnostic(Diag::Error_Exec_Assign_InvalidLHSType, lhsTy); throw std::runtime_error("Expression type mismatch"); } ValuePtrType ptr = lhsVal.value<ValuePtrType>(); isGood = write(ptr, rhsTy, rhsVal); } if(Q_UNLIKELY(!isGood)){ throw std::runtime_error("Expression evaluation fail"); } }break; case StatementType::Output:{ const OutputStatement& outstmt = frame.f.getOutputStatement(stmt.statementIndexInType); ValueType rhsTy = ValueType::Void; QVariant rhsVal; bool isGood = evaluateExpression(outstmt.exprIndex, rhsTy, rhsVal); if(Q_UNLIKELY(!isGood)){ throw std::runtime_error("Expression evaluation fail"); } if(Q_LIKELY(allowedOutputTypes.contains(rhsTy))){ bool isGood = true; switch (rhsTy) { default: Q_UNREACHABLE(); case ValueType::String: isGood = out.addOutput(rhsVal.toString()); break; } if(Q_UNLIKELY(!isGood)){ diagnostic(Diag::Error_Exec_Output_Unknown_String, rhsVal.toString()); throw std::runtime_error("Output failure"); } }else{ diagnostic(Diag::Error_Exec_Output_InvalidType, rhsTy); throw std::runtime_error("Invalid output expression type"); } }break; case StatementType::Call:{ const CallStatement& call = frame.f.getCallStatement(stmt.statementIndexInType); int functionIndex = t.getFunctionIndex(call.functionName); if(Q_UNLIKELY(functionIndex < 0)){ diagnostic(Diag::Error_Exec_Call_BadReference, call.functionName); throw std::runtime_error("Function not found"); } const Function& f = t.getFunction(functionIndex); int numParam = f.getNumParameter(); int numRequiredParam = f.getNumRequiredParameter(); int numPassed = call.argumentExprList.size(); if(Q_UNLIKELY(numPassed > numParam || numPassed < numRequiredParam)){ diagnostic(Diag::Error_Exec_Call_BadArgumentList_Count, call.functionName, numRequiredParam, numParam, numPassed); throw std::runtime_error("Invalid call"); }else{ QList<QVariant> params; params.reserve(numPassed); for(int i = 0; i < numPassed; ++i){ params.push_back(QVariant()); int exprIndex = call.argumentExprList.at(i); ValueType ty = ValueType::Void; bool isGood = evaluateExpression(exprIndex, ty, params.back()); if(Q_UNLIKELY(!isGood)){ throw std::runtime_error("Expression evaluation fail"); } if(Q_UNLIKELY(ty != f.getLocalVariableType(i))){ //Error_Exec_Call_BadArgumentList_Type diagnostic(Diag::Error_Exec_Call_BadArgumentList_Type, call.functionName, i, f.getLocalVariableName(i), f.getLocalVariableType(i), ty); throw std::runtime_error("Type mismatch"); } } pushFunctionStackframe(functionIndex, frame.irNodeIndex, params); // WARNING: frame should no longer be accessed, since pushing another stack frame may cause a relocation } }break; case StatementType::Branch:{ const BranchStatement& branch = frame.f.getBranchStatement(stmt.statementIndexInType); bool isHandled = false; int labelAddress = -3; int caseIndex = -2; for(int i = 0, num = branch.cases.size(); i < num; ++i){ const auto& brCase = branch.cases.at(i); ValueType ty = ValueType::Void; QVariant val; bool isGood = evaluateExpression(brCase.exprIndex, ty, val); if(Q_UNLIKELY(!isGood)){ throw std::runtime_error("Expression evaluation fail"); } switch (ty) { default:{ diagnostic(Diag::Error_Exec_Branch_InvalidConditionType, i, ty); throw std::runtime_error("Type mismatch"); }/*break;*/ case ValueType::Int64:{ if(val.toLongLong() != 0){ isHandled = true; labelAddress = brCase.stmtIndex; caseIndex = i; break; } }break; case ValueType::ValuePtr:{ if(val.value<ValuePtrType>().ty != ValuePtrType::PtrType::NullPointer){ isHandled = true; labelAddress = brCase.stmtIndex; caseIndex = i; break; } } } if(isHandled) break; } if(!isHandled){ caseIndex = -1; labelAddress = branch.defaultStmtIndex; } if(Q_UNLIKELY(labelAddress < -2 || labelAddress >= frame.f.getNumStatement())){ diagnostic(Diag::Error_Exec_Branch_InvalidLabelAddress, caseIndex, labelAddress); throw std::runtime_error("Invalid label"); } if(labelAddress >= 0){ frame.stmtIndex = labelAddress; }else if(Q_UNLIKELY(labelAddress == -2)){ diagnostic(Diag::Error_Exec_Branch_Unreachable, caseIndex); throw std::runtime_error("Unreachable"); } // labelIndex == -1 is fall-through }break; case StatementType::Return:{ stack.pop(); }break; }// end of switch of statement type }// end of for loop } bool ExecutionContext::evaluateExpression(int expressionIndex, ValueType& ty, QVariant& val) { Q_ASSERT(!stack.empty()); const auto& frame = stack.top(); const ExpressionBase* expr = frame.f.getExpression(expressionIndex); QList<int> dependencies; QList<ValueType> dependTys; expr->getDependency(dependencies, dependTys); QList<QVariant> dependentVals; Q_ASSERT(dependencies.size() == dependTys.size()); dependentVals.reserve(dependencies.size()); for(int i = 0, num = dependencies.size(); i < num; ++i){ dependentVals.push_back(QVariant()); ValueType actualTy = ValueType::Void; if(Q_UNLIKELY(!evaluateExpression(dependencies.at(i), actualTy, dependentVals.back()))) return false; if(Q_UNLIKELY(actualTy != dependTys.at(i))){ diagnostic(Diag::Error_Exec_TypeMismatch_ExpressionDependency, dependTys.at(i), actualTy, expressionIndex, dependencies.at(i)); return false; } } ty = expr->getExpressionType(); return expr->evaluate(*this, val, dependentVals); } QString ExecutionContext::getNodeDescription(int nodeIndex) { if(nodeIndex < 0){ return tr("invalid node"); } QString result = tr("node %1 ~").arg(nodeIndex); QStringList path; int currentNodeIndex = nodeIndex; while(currentNodeIndex > 0){ const IRNodeInstance& inst = root.getNode(currentNodeIndex); const IRNodeType& ty = root.getType().getNodeType(inst.getTypeIndex()); const QString& name = ty.getName(); int parent = inst.getParentIndex(); const IRNodeInstance& parentInst = root.getNode(parent); const IRNodeType& parentTy = root.getType().getNodeType(parentInst.getTypeIndex()); int localTyIndex = parentTy.getChildNodeTypeIndex(name); int index = 0; int numInst = parentInst.getNumChildNodeUnderType(localTyIndex); while(index < numInst){ if(parentInst.getChildNodeIndex(localTyIndex, index) == currentNodeIndex) break; ++index; } Q_ASSERT(index < numInst); path.push_back(tr("/%1[%2]").arg(name,QString::number(index))); currentNodeIndex = parent; } for(int i = path.size() -1; i >= 0; --i){ result.append(path.at(i)); } return result; } QString ExecutionContext::getPointerSrcDescription(const PtrCommon& head) { return tr("[ptr created from function %1 [%2], statement %3]").arg( t.getFunction(head.functionIndex).getName(), QString::number(head.activationIndex), QString::number(head.stmtIndex)); } QString ExecutionContext::getValuePtrDescription(const ValuePtrType& ptr) { QString result; switch(ptr.ty){ case ValuePtrType::PtrType::NullPointer:{ result = tr("null"); }break; case ValuePtrType::PtrType::LocalVariable:{ const Function& f = t.getFunction(ptr.head.functionIndex); result = tr("&%1 in %2() [%3]").arg( f.getLocalVariableName(ptr.valueIndex), f.getName(), QString::number(ptr.head.activationIndex)); }break; case ValuePtrType::PtrType::NodeRWMember:{ const IRNodeInstance& inst = root.getNode(ptr.nodeIndex); result = tr("&%1 in %2").arg( t.getNodeMemberName(inst.getTypeIndex(), ptr.valueIndex), getNodeDescription(ptr.nodeIndex)); }break; case ValuePtrType::PtrType::NodeROParameter:{ const IRNodeInstance& inst = root.getNode(ptr.nodeIndex); const IRNodeType& ty = root.getType().getNodeType(inst.getTypeIndex()); result = tr("&%1 in %2").arg( ty.getParameterName(ptr.valueIndex), getNodeDescription(ptr.nodeIndex)); }break; case ValuePtrType::PtrType::GlobalVariable:{ result = tr("&%1").arg(t.getGlobalVariableName(ptr.valueIndex)); }break; } result.append(' '); result.append(getPointerSrcDescription(ptr.head)); return result; } QString ExecutionContext::getNodePtrDescription(const NodePtrType& ptr) { return tr("&[%1] ").arg(getNodeDescription(ptr.nodeIndex)) + getPointerSrcDescription(ptr.head); } <file_sep>/core/ExecutionContext.h #ifndef EXECUTIONCONTEXT_H #define EXECUTIONCONTEXT_H #include <QObject> #include <QString> #include <QVariant> #include <QStack> #include <QEventLoop> #include <memory> #include "core/Value.h" #include "util/ADT.h" class DiagnosticEmitterBase; class OutputHandlerBase; class Function; class Task; class IRRootInstance; // you probably want to move ExecutionContext to another thread class ExecutionContext: public QObject { Q_OBJECT public: ExecutionContext(const Task& t, const IRRootInstance& root, DiagnosticEmitterBase& diagnostic, OutputHandlerBase& out, QObject* parent = nullptr); virtual ~ExecutionContext() override{} // interface exposed to everyone const Task& getTask()const{return t;} DiagnosticEmitterBase& getDiagnostic(){return diagnostic;} QString getNodeDescription(int nodeIndex); QString getPointerSrcDescription(const PtrCommon& head); QString getValuePtrDescription(const ValuePtrType& ptr); QString getNodePtrDescription(const NodePtrType& ptr); //************************************************************************* // interface exposed to ExpressionBase // there must be a stack frame set /** * @brief read read from local variable, node member, or global variable by name reference * @param name variable name for lookup * @param ty value type of result * @param dest read value * @return true if read is successful; false otherwise */ bool read(const QString& name, ValueType& ty, QVariant& val); /** * @brief read read a value by dereferencing a pointer * @param valuePtr pointer to dereference * @param ty value type of result * @param dest read value * @return true if read is successful; false otherwise */ bool read(const ValuePtrType& valuePtr, ValueType& ty, QVariant& dest); /** * @brief takeAddress create a pointer from variable name lookup * @param name variable name for lookup * @param val pointer value * @return true if lookup successful; false otherwise */ bool takeAddress(const QString& name, ValuePtrType& val); // used to construct node reference // these three never fails bool getCurrentNodePtr(NodePtrType& result); bool getRootNodePtr(NodePtrType& result); bool getParentNode(const NodePtrType& src, NodePtrType& result); bool getChildNode(const NodePtrType &src, const QString& childName, NodePtrType& result, ValueType keyTy, const QVariant& primaryKey); bool getChildNode(const NodePtrType& src, const QString& childName, NodePtrType& result, const QString& keyField, ValueType keyTy, const QVariant& keyValue); // no indexing by child node index yet.. should be there later on //************************************************************************* // interface exposed to environment /** * @brief addBreakpoint adds a breakpoint at specified location. Duplicate breakpoints are ignored * @param functionIndex index of the function to break at * @param stmtIndex index of the statement to break at * @return index of breakpoint; if there is a duplicate then the index of existing one is added */ int addBreakpoint(int functionIndex, int stmtIndex); /** * @brief removeBreakpoint removes the specified breakpoint. If index is -1 then all breakpoints are removed * @param breakpointIndex the index of breakpoint to remove */ void removeBreakpoint(int breakpointIndex); signals: void executionFinished(int retval);// 0: success; -1: fail void executionPaused(); public slots: void continueExecution(); private: void mainExecutionEntry(); void nodeTraverseEntry(int passIndex, int nodeIndex); void pushFunctionStackframe(int functionIndex, int nodeIndex, QList<QVariant> params = QList<QVariant>()); void functionMainLoop(); void checkUninitializedRead(ValueType ty, QVariant& readVal); bool write(const QString& name, const ValueType& ty, const QVariant& val); bool write(const ValuePtrType& valuePtr, const ValueType& ty, const QVariant& dest); /** * @brief evaluateExpression evaluates the expression in current stack frame's current function * @param expressionIndex the root expression index to evaluate * @param ty the final type of root expression * @param val the final value of root expression * @return true if the evaluation is successful, false otherwise */ bool evaluateExpression(int expressionIndex, ValueType& ty, QVariant& val); PtrCommon getPtrSrcHead(){ PtrCommon result; const auto& frame = stack.top(); result.functionIndex = frame.functionIndex; result.activationIndex = frame.activationIndex; result.stmtIndex = frame.stmtIndex; return result; } private: struct CallStackEntry{ const Function& f; const int functionIndex; const int irNodeIndex; const int irNodeTypeIndex; //!< node global type index const int activationIndex; //!< detect dangling pointer to stack variable int stmtIndex; QList<QVariant> localVariables; CallStackEntry(const Function& f, int functionIndex, int nodeIndex, int nodeTypeIndex, int activationIndex) : f(f), functionIndex(functionIndex), irNodeIndex(nodeIndex), irNodeTypeIndex(nodeTypeIndex), activationIndex(activationIndex), stmtIndex(0) {} CallStackEntry(const CallStackEntry&) = default; CallStackEntry(CallStackEntry&&) = default; }; struct BreakPoint{ int functionIndex; int stmtIndex; }; struct TraverseState{ enum class NodeTraverseState{ Entry, Traverse, Exit }; NodeTraverseState nodeState; int passIndex; int nodeIndex; int childIndex; }; // states Stack<CallStackEntry> stack; QList<QVariant> globalVariables; QList<QList<QVariant>> nodeMembers;// read-writeable variables only; constant ones are still in IRNodeInstance QStack<TraverseState> nodeTraverseStack; int currentActivationCount = 0; bool isInExecution = false; QHash<int, BreakPoint> breakpoints; bool isBreakpointUpdated = false; //!< set if breakpoints are changed QList<ValueType> allowedOutputTypes; QEventLoop eventLoop; // references const Task& t; const IRRootInstance& root; DiagnosticEmitterBase& diagnostic; OutputHandlerBase& out; }; #endif // EXECUTIONCONTEXT_H <file_sep>/core/Task.cpp #include "core/Task.h" #include "core/DiagnosticEmitter.h" #include "core/Expression.h" #include "core/IR.h" #include "util/ADT.h" #include <QQueue> #include <functional> bool Function::validate(DiagnosticEmitterBase& diagnostic, const Task& task) { // POSSIBLE IMPROVEMENT: // 1. find unreachable expression // 2. find unreachable statement (maybe just statically unreachable statements) bool isValidated = true; // check if name is good if(Q_LIKELY(IRNodeType::validateName(diagnostic, functionName))){ diagnostic.setDetailedName(functionName); }else{ isValidated = false; } // check if extern variable reference is good // (i.e. no name conflict) // for now we do not attempt to check if the name resolve to given type, because it requires runtime data Q_ASSERT(externVariableNameList.size() == externVariableTypeList.size()); for(int i = 0, num = externVariableNameList.size(); i < num; ++i){ // check if searching for this name result in the correct index const QString& varName = externVariableNameList.at(i); int searchResult = externVariableNameToIndex.value(varName, -1); if(Q_UNLIKELY(searchResult != i)){ diagnostic(Diag::Error_Func_NameClash_ExternVariable, varName, searchResult, i); isValidated = false; } // no void extern reference ValueType expectedTy = externVariableTypeList.at(i); if(Q_UNLIKELY(expectedTy == ValueType::Void)){ diagnostic(Diag::Error_Func_BadType_ExternVariableVoid, varName); isValidated = false; } } if(isValidated){ Q_ASSERT(externVariableNameToIndex.size() == externVariableNameList.size()); } // check if local variables are good if(Q_UNLIKELY(paramCount < 0 || paramCount > localVariableNames.size())){ diagnostic(Diag::Error_Func_InvalidValue_TotalParamCount, paramCount); isValidated = false; } if(Q_UNLIKELY(requiredParamCount < 0 || requiredParamCount > paramCount)){ diagnostic(Diag::Error_Func_InvalidValue_RequiredParamCount, requiredParamCount); isValidated = false; }else{ // the rest of parameters should all have default initializer for(int i = requiredParamCount+1; i < qMin(paramCount, localVariableInitializer.size()); ++i){ if(Q_UNLIKELY(!localVariableInitializer.at(i).isValid())){ diagnostic(Diag::Error_Func_MissingInitializer_OptionalParam, i, localVariableNames.at(i)); isValidated = false; } } } localVariableNameToIndex.clear(); for(int i = 0, num = localVariableNames.size(); i < num; ++i){ const QString& name = localVariableNames.at(i); if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, name))){ isValidated = false; }else{ auto iter = localVariableNameToIndex.find(name); if(Q_LIKELY(iter == localVariableNameToIndex.end())){ localVariableNameToIndex.insert(name, i); // no void local variables ValueType expectedTy = localVariableTypes.at(i); if(Q_UNLIKELY(expectedTy == ValueType::Void)){ diagnostic(Diag::Error_Func_BadType_LocalVariableVoid, name); isValidated = false; } // check if the initializer is good const QVariant& initializer = localVariableInitializer.at(i); if(initializer.isValid()){ ValueType initTy = getValueType(static_cast<QMetaType::Type>(initializer.userType())); if(Q_UNLIKELY(initTy != expectedTy)){ diagnostic(Diag::Error_Func_BadInitializer_LocalVariable, i, name, expectedTy, initTy); isValidated = false; } } }else{ diagnostic(Diag::Error_Func_NameClash_LocalVariable, name, iter.value(), i); isValidated = false; } } } // check if all expressions are good // 1. no circular dependence (just check if any expression is referencing another expression with larger index) // 2. type expectation should match // 3. if the expression need to reference variable by name, the name should either appear in local variable or in extern variable list for(int index = 0, len = exprList.size(); index < len; ++index){ const ExpressionBase* ptr = exprList.at(index); QList<int> dependentExprIndices; QList<ValueType> dependentExprTypes; ptr->getDependency(dependentExprIndices, dependentExprTypes); Q_ASSERT(dependentExprIndices.size() == dependentExprTypes.size()); for(int i = 0, len = dependentExprIndices.size(); i < len; ++i){ int exprIndex = dependentExprIndices.at(i); if(Q_UNLIKELY(exprIndex < 0 || exprIndex >= exprList.size() || exprIndex >= index)){ diagnostic(Diag::Error_Func_BadExprDependence_BadIndex, index, exprIndex); isValidated = false; }else{ if(Q_UNLIKELY(ptr->getExpressionType() != dependentExprTypes.at(i))){ diagnostic(Diag::Error_Func_BadExprDependence_TypeMismatch, index, exprIndex, dependentExprTypes.at(i), ptr->getExpressionType()); isValidated = false; } } } QList<QString> nameReference; ptr->getVariableNameReference(nameReference); if(!nameReference.empty()){ for(const auto& name : nameReference){ if(localVariableNameToIndex.value(name, -1) == -1){ if(Q_UNLIKELY(externVariableNameToIndex.value(name, -1) == -1)){ diagnostic(Diag::Error_Func_BadExpr_BadNameReference, index, name); isValidated = false; } } } } } // check if all statements are good // 1. all referenced expression indices are valid and the expression generates correct type // 2. (for branch) all label references are valid // we do not check stmtList because it is impossible to be valid if only the addUnreachableStatement() addStatement() is used for(const auto& stmt: assignStmtList){ if(stmt.lvalueExprIndex == -1){ // check if the name reference is good if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, stmt.lvalueName))){ isValidated = false; } }else{ // lhs should be valueptr if(Q_UNLIKELY(stmt.lvalueExprIndex < 0 || stmt.lvalueExprIndex >= exprList.size())){ diagnostic(Diag::Error_Func_Stmt_BadExprIndex, stmt.lvalueExprIndex); isValidated = false; }else if(Q_UNLIKELY(exprList.at(stmt.lvalueExprIndex)->getExpressionType() != ValueType::ValuePtr)){ diagnostic(Diag::Error_Func_Assign_BadLHS_Type, stmt.lvalueExprIndex, exprList.at(stmt.lvalueExprIndex)->getExpressionType()); isValidated = false; } } if(Q_UNLIKELY(stmt.rvalueExprIndex < 0 || stmt.rvalueExprIndex >= exprList.size())){ diagnostic(Diag::Error_Func_Stmt_BadExprIndex, stmt.rvalueExprIndex); isValidated = false; }else{ ValueType ty = exprList.at(stmt.rvalueExprIndex)->getExpressionType(); if(Q_UNLIKELY(ty == ValueType::Void)){ diagnostic(Diag::Error_Func_Assign_BadRHS_RHSVoid, stmt.rvalueExprIndex); isValidated = false; }else if(stmt.lvalueExprIndex == -1){ // we only test rhs type match if the assignment is by name ValueType expectedTy = ValueType::Void; int localVarIndex = localVariableNameToIndex.value(stmt.lvalueName, -1); if(localVarIndex < 0){ int externVarIndex = externVariableNameToIndex.value(stmt.lvalueName, -1); if(Q_UNLIKELY(externVarIndex < 0)){ diagnostic(Diag::Error_Func_Assign_BadLHS_BadNameReference, stmt.lvalueName); isValidated = false; }else{ expectedTy = externVariableTypeList.at(externVarIndex); } }else{ expectedTy = localVariableTypes.at(localVarIndex); } if(Q_UNLIKELY(ty != expectedTy)){ diagnostic(Diag::Error_Func_Assign_BadRHS_VariableTypeMismatch, stmt.lvalueName, expectedTy, stmt.rvalueExprIndex, ty); isValidated = false; } } } } for(const auto& stmt: outputStmtList){ // for now we only output text, so output statement should only accept string expression // later on we may check output type based on configuration from Task or ExecutionContext int exprIndex = stmt.exprIndex; if(Q_UNLIKELY(exprIndex < 0 || exprIndex >= exprList.size())){ diagnostic(Diag::Error_Func_Stmt_BadExprIndex, exprIndex); isValidated = false; }else{ const ExpressionBase* ptr = exprList.at(exprIndex); if(Q_UNLIKELY(ptr->getExpressionType() != ValueType::String)){ diagnostic(Diag::Error_Func_Output_BadRHS_Type, exprIndex, ptr->getExpressionType()); isValidated = false; } } } calledFunctions.clear(); QHash<QString, int> calledFunctionNameToIndex; // actually just use it as a set for(const auto& stmt: callStmtList){ int functionIndex = task.getFunctionIndex(stmt.functionName); if(Q_UNLIKELY(functionIndex == -1)){ diagnostic(Diag::Error_Func_Call_CalleeNotFound, stmt.functionName); isValidated = false; }else{ const Function& f = task.getFunction(functionIndex); const QString& functionName = f.getName(); if(calledFunctionNameToIndex.count(functionName) == 0){ calledFunctionNameToIndex.insert(functionName, calledFunctions.size()); calledFunctions.push_back(functionName); } int paramPassed = stmt.argumentExprList.size(); int paramCount = f.getNumParameter(); int requiredParamCount = f.getNumRequiredParameter(); if(Q_UNLIKELY(paramPassed < requiredParamCount || paramPassed > paramCount)){ diagnostic(Diag::Error_Func_Call_BadParamList_Count, stmt.functionName, paramCount, requiredParamCount, paramPassed); isValidated = false; }else{ for(int i = 0; i < paramPassed; ++i){ int exprIndex = stmt.argumentExprList.at(i); if(Q_UNLIKELY(exprIndex < 0 || exprIndex >= exprList.size())){ diagnostic(Diag::Error_Func_Stmt_BadExprIndex, exprIndex); isValidated = false; }else{ QString paramName = f.getLocalVariableName(i); ValueType expectedTy = f.getLocalVariableType(i); ValueType actualTy = exprList.at(exprIndex)->getExpressionType(); if(Q_UNLIKELY(expectedTy != actualTy)){ diagnostic(Diag::Error_Func_Call_BadParamList_Type, stmt.functionName, i, paramName, expectedTy, actualTy); isValidated = false; } } } } } } QHash<QString, int> labelNameToStatementIndex; Q_ASSERT(labels.size() == labeledStmtIndexList.size()); for(int i = 0, num = labels.size(); i < num; ++i){ const QString& name = labels.at(i); int stmtIndex = labeledStmtIndexList.at(i); auto iter = labelNameToStatementIndex.find(name); if(Q_LIKELY(iter == labelNameToStatementIndex.end())){ labelNameToStatementIndex.insert(name, stmtIndex); }else{ diagnostic(Diag::Error_Func_DuplicateLabel, name, iter.value(), stmtIndex); isValidated = false; } } branchStmtList.clear(); branchStmtList.reserve(branchTempStmtList.size()); auto resolveLabel = [&](BranchStatementTemp::BranchActionType ty, int caseIndex, const QString& labelName, int& stmtIndex)->void{ switch(ty){ case BranchStatementTemp::BranchActionType::Unreachable: stmtIndex = -2; break; case BranchStatementTemp::BranchActionType::Fallthrough: stmtIndex = -1; break; case BranchStatementTemp::BranchActionType::Jump:{ auto iter = labelNameToStatementIndex.find(labelName); if(Q_LIKELY(iter != labelNameToStatementIndex.end())){ stmtIndex = iter.value(); }else{ diagnostic(Diag::Error_Func_Branch_BadLabelReference, labelName, caseIndex); isValidated = false; } }break; } }; for(const auto& stmt: branchTempStmtList){ BranchStatement cooked; resolveLabel(stmt.defaultAction, -1, stmt.defaultJumpLabelName, cooked.defaultStmtIndex); cooked.cases.reserve(stmt.cases.size()); for(int i = 0, num = stmt.cases.size(); i < num; ++i){ const auto& brcase = stmt.cases.at(i); BranchStatement::BranchCase c; c.exprIndex = brcase.exprIndex; resolveLabel(brcase.action, i, brcase.labelName, c.stmtIndex); cooked.cases.push_back(c); // we currently expect Int64 or ValuePtr as branch condition int exprIndex = c.exprIndex; if(Q_UNLIKELY(exprIndex < 0 || exprIndex >= exprList.size())){ diagnostic(Diag::Error_Func_Stmt_BadExprIndex_BranchCondition, exprIndex, i); isValidated = false; }else{ ValueType ty = exprList.at(exprIndex)->getExpressionType(); if(Q_UNLIKELY(ty != ValueType::Int64 && ty != ValueType::ValuePtr)){ diagnostic(Diag::Error_Func_Branch_BadConditionType, i, exprIndex, ty); isValidated = false; } } } branchStmtList.push_back(cooked); } return isValidated; } Task::Task(const IRRootType& root) : root(root) { Q_ASSERT(root.validated()); int num = root.getNumNodeType(); // dummy ones NodeCallbackRecord record = {-1,-1}; MemberDecl decl; nodeCallbacks.push_back(QList<NodeCallbackRecord>()); nodeCallbacks.back().reserve(num); nodeMemberDecl.reserve(num); for(int i = 0; i < num; ++i){ nodeCallbacks.back().push_back(record); nodeMemberDecl.push_back(decl); } } int Task::addNewPass() { int passIndex = nodeCallbacks.size(); NodeCallbackRecord record = {-1,-1}; nodeCallbacks.push_back(QList<NodeCallbackRecord>()); auto& ref = nodeCallbacks.back(); for(int i = 0, num = root.getNumNodeType(); i < num; ++i){ ref.push_back(record); } return passIndex; } bool Task::validate(DiagnosticEmitterBase& diagnostic) { isValidated = true; auto checkDomain = [&](MemberDecl& decl)->void{ decl.varNameToIndex.clear(); for(int i = 0, len = decl.varNameList.size(); i < len; ++i){ const QString& str = decl.varNameList.at(i); if(Q_UNLIKELY(!IRNodeType::validateName(diagnostic, str))){ isValidated = false; continue; } auto iter = decl.varNameToIndex.find(str); if(Q_LIKELY(iter == decl.varNameToIndex.end())){ decl.varNameToIndex.insert(str, i); // also check initializer type error const QVariant& initializer = decl.varInitializerList.at(i); if(initializer.isValid()){ ValueType ty = decl.varTyList.at(i); ValueType initializerTy = getValueType(static_cast<QMetaType::Type>(initializer.userType())); if(Q_UNLIKELY(initializerTy != ty)){ diagnostic(Diag::Error_Task_BadInitializer_ExternVariable, str, ty, initializerTy); isValidated = false; } } }else{ diagnostic(Diag::Error_Task_NameClash_ExternVariable, str, iter.value(), i); isValidated = false; } } }; // check if there is a name clash among global variables DiagnosticPathNode dnode_gv(diagnostic, tr("Global Variable")); checkDomain(globalVariables); dnode_gv.pop(); // check if there is a name clash among functions functionNameToIndex.clear(); DiagnosticPathNode dnode_func(diagnostic, tr("Function")); for(int i = 0, len = functions.size(); i < len; ++i){ const QString& name = functions.at(i).getName(); if(!IRNodeType::validateName(diagnostic, name)){ isValidated = false; continue; } auto iter = functionNameToIndex.find(name); if(Q_LIKELY(iter == functionNameToIndex.end())){ functionNameToIndex.insert(name, i); }else{ diagnostic(Diag::Error_Task_NameClash_Function, name, iter.value(), i); isValidated = false; } } dnode_func.pop(); QQueue<int> reachableFunctions; RunTimeSizeArray<bool> functionReachable(static_cast<std::size_t>(functions.size()), false); auto tryEnqueue = [&](int index)->void{ if(!functionReachable.at(index)){ reachableFunctions.enqueue(index); functionReachable.at(index) = true; } }; // check if any callback reference is invalid bool isAnyCallbackSet = false; DiagnosticPathNode dnode_cb(diagnostic, tr("Callback")); for(int passIndex = 0, numPass = nodeCallbacks.size(); passIndex < numPass; ++passIndex){ const auto& list = nodeCallbacks.at(passIndex); DiagnosticPathNode dnode_pass(diagnostic, tr("Pass %1").arg(passIndex)); for(int i = 0, len = root.getNumNodeType(); i < len; ++i){ const auto& cbs = list.at(i); if(cbs.onEntryFunctionIndex >= 0){ if(Q_UNLIKELY(cbs.onEntryFunctionIndex >= functions.size())){ diagnostic(Diag::Error_Task_BadFunctionIndex_NodeTraverseCallback, root.getNodeType(i).getName(), passIndex, cbs.onEntryFunctionIndex); isValidated = false; }else{ tryEnqueue(cbs.onEntryFunctionIndex); isAnyCallbackSet = true; } } if(cbs.onExitFunctionIndex >= 0){ if(Q_UNLIKELY(cbs.onExitFunctionIndex >= functions.size())){ diagnostic(Diag::Error_Task_BadFunctionIndex_NodeTraverseCallback, root.getNodeType(i).getName(), passIndex, cbs.onExitFunctionIndex); isValidated = false; }else{ tryEnqueue(cbs.onExitFunctionIndex); isAnyCallbackSet = true; } } } dnode_pass.pop(); } dnode_cb.pop(); if(Q_UNLIKELY(!isAnyCallbackSet)){ diagnostic(Diag::Error_Task_NoCallback); isValidated = false; } if(Q_UNLIKELY(!isValidated)) return isValidated; for(int i = 0, len = functions.size(); i < len; ++i){ DiagnosticPathNode dnode(diagnostic, tr("Function %1").arg(QString::number(i))); // no short circuit isValidated = functions[i].validate(diagnostic, *this) && isValidated; dnode.pop(); } // check if any function is unreachable (warning only) while(!reachableFunctions.empty()){ int index = reachableFunctions.dequeue(); const Function& f = functions.at(index); const auto& list = f.getReferencedFunctionList(); for(const auto& str : list){ int index = getFunctionIndex(str); tryEnqueue(index); } } for(int i = 0, len = functions.size(); i < len; ++i){ if(!functionReachable.at(i)){ diagnostic(Diag::Warn_Task_UnreachableFunction, functions.at(i).getName()); } } return isValidated; } <file_sep>/ui/PlainTextDocumentWidget.h #ifndef PLAINTEXTDOCUMENTWIDGET_H #define PLAINTEXTDOCUMENTWIDGET_H #include <QObject> #include <QPlainTextEdit> #include <QTextDocument> #include <QDateTime> #include <QByteArray> #include "ui/DocumentWidget.h" class DocumentEdit; class DirtySignalDisabler; class PlainTextDocumentWidget : public DocumentWidget { Q_OBJECT friend class DirtySignalDisabler; public: enum class OpenMode{ ReadWrite, //!< the most basic mode that reads and writes selected file; set dirty flag when file changed ReadOnly, //!< disable editing on the file; set dirty flag when file changed ReadFollow, //!< disable editing on the file; auto reload when file changed RWFollow, //!< same as ReadWrite except that if dirty flag is not set, this mode also do auto reload when file changed }; /** * @brief DocumentWidget create instance with file association. open mode is automatically determined * @param filePath the raw path to file to be associated * @param parent parameter to QPlainTextEdit constructor */ explicit PlainTextDocumentWidget(QString filePath, QWidget *parent = nullptr); QString getAbsoluteFilePath() const override {return absoluteFilePath;} QString getFileName() const override; bool isDirty() const override {return dirtyFlag;} bool isReadOnly() const override {return readOnlyFlag;} bool saveToFile(QString filePath) override; QMenu* getMenu() override; protected: void fileRecheck() override; private slots: void setDirtyFlag(); void setReadOnly(bool isReadOnly); private: DocumentEdit* ui_editor; //!< pointer to main editor widget; never null QString rawFilePath; //!< raw file path (only used before the file exists) QString absoluteFilePath; //!< file path used for duplicate avoidance QString fileName; //!< file name, no path (e.g. for on-tab text) QDateTime lastAccessTimeStamp; //!< timestamp of last access on file qint64 lastAccessFileSize; //!< file size at last time it is accessed bool dirtyFlag = false; //!< dirty flag of current document bool readOnlyFlag = false; //!< whether current document is read only bool followFlag = true; //!< whether update the content if the file is changed while dirty flag is not set /** * @brief initialize try to initialize the document by accessing the file * @return true if the file is successfully read; false otherwise */ bool initialize(); /** * @brief setDocumentContent initialize document content from given source * @param src source of content (an open, initialized QFile probably) */ void setDocumentContent(QIODevice *src); /** * @brief getDocumentContent get document content as byte array */ QByteArray getDocumentContent(); }; class DirtySignalDisabler{ friend class PlainTextDocumentWidget; private: DirtySignalDisabler(PlainTextDocumentWidget* doc); ~DirtySignalDisabler(); PlainTextDocumentWidget* doc; }; #endif // PLAINTEXTDOCUMENTWIDGET_H <file_sep>/ui/MainWindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGlobal> #include <QMainWindow> #include <QTabWidget> #include <QTabBar> #include <QEvent> #include "ui/DocumentWidget.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); virtual ~MainWindow() override; protected: void focusInEvent(QFocusEvent *event) override; void closeEvent(QCloseEvent *event) override; bool eventFilter(QObject *obj, QEvent *event) override; public slots: void newRequested(); void openRequested(); void saveRequested(); void saveAsRequested(); void saveAllRequested(); void closeRequested(); void updateTitle(); private slots: void tabCloseSlot(int index); void fileCheckRelaySlot(int index); private: /** * @brief closeDirtyDocumentConfirmation ask user operation if trying to close a dirty document * @param doc DocumentWidget with dirty flag set * @return true if dirty state is resolved (saved or confirm close), false otherwise */ bool closeDirtyDocumentConfirmation(DocumentWidget* doc); bool trySaveDocument(DocumentWidget* doc, bool saveAs); bool closeWindowConfirmation(); /** * @brief findAlreadyOpenedWidget given a path, check if one document is already associated with the file * @param path the file path for testing; not necessarily absolute * @param srcDoc the source document to exclude from returning * @param srcDocMatch written to true if srcDoc is found to have matching absolute path * @return pointer to the DocumentWidget that is not srcDoc and has the same absolute path */ DocumentWidget* findAlreadyOpenedWidget(QString path, DocumentWidget* srcDoc, bool& srcDocMatch); DocumentWidget* getCurrentDocumentWidget() { QWidget* widget = tabWidget->currentWidget(); Q_ASSERT(widget && "Broken invariant: tabWidget->currentWidget() returns nullptr!"); DocumentWidget* doc = qobject_cast<DocumentWidget*>(widget); Q_ASSERT(doc && "Broken invariant: tabWidget->currentWidget() returns QWidget other than DocumentWidget!"); return doc; } DocumentWidget* getDocumentWidget(int index) { QWidget* widget = tabWidget->widget(index); Q_ASSERT(widget && "Broken invariant: tabWidget->widget() returns nullptr!"); DocumentWidget* doc = qobject_cast<DocumentWidget*>(widget); Q_ASSERT(doc && "Broken invariant: tabWidget->currentWidget() returns QWidget other than DocumentWidget!"); return doc; } QString getDefaultSavePath() {return lastSavePath;} QString getDefaultOpenPath() {return lastOpenPath;} void installNewDocumentWidget(DocumentWidget* doc); void handleCloseDocument(DocumentWidget* doc); private: Ui::MainWindow *ui; QTabWidget* tabWidget; QString lastSavePath; QString lastOpenPath; }; class ForwardingTabBar: public QTabBar { Q_OBJECT public: ForwardingTabBar(QWidget* parent = nullptr) : QTabBar(parent) {} void setFilter(QObject* filterObj){installEventFilter(filterObj);} }; class ForwardingTabWidget : public QTabWidget { Q_OBJECT public: ForwardingTabWidget(QWidget* parent = nullptr) : QTabWidget(parent) { setTabBar(new ForwardingTabBar(nullptr)); } void setTabBarEventFilter(QObject* filterObj){qobject_cast<ForwardingTabBar*>(tabBar())->setFilter(filterObj);} }; #endif // MAINWINDOW_H
3142c6a996549f10fc74f50444673a8972393f13
[ "C", "C++" ]
31
C++
xushengj/supp
4779abb2b1958c2e3cc14bac45ee970ea32f7030
b28a50bb00b3add98b70d2fec0ed38a16253ccc8
refs/heads/master
<file_sep>// // Created by andy on 11/15/2018. // #ifndef WHIST_DECK_H #define WHIST_DECK_H #include <vector> #include "Card.h" #include <iostream> #include <stdlib.h> #include <algorithm> class Deck { private: std::vector <Card> deck; public: Deck(int players); void shuffle(); Card nextCard(); bool empty(); }; #endif //WHIST_DECK_H <file_sep>// // Created by andy on 11/15/2018. // #include "Deck.h" Deck::Deck(int players) { // Max 6 players; Min 1 player; if (players > 6 || players < 1){ throw std::invalid_argument("Invalid number of players; Valid : 1-6"); } for (int f = ACE; f < players * 2; f++){ for (int s = CLUBS; s <= SPADES; s++){ deck.emplace_back((Face) f, (Suit) s); } } } void Deck::shuffle() { for (auto &c : deck) { std::swap(deck[rand() % deck.size()], c); } } Card Deck::nextCard() { Card temp = deck.back(); deck.pop_back(); return temp; } bool Deck::empty() { return deck.empty(); }<file_sep>// // Created by andy on 11/15/2018. // #ifndef WHIST_DEALER_H #define WHIST_DEALER_H #include "Player.h" #include "Card.h" #include "Deck.h" #include <vector> #include <stdlib.h> class Player; class Dealer{ public: explicit Dealer(std::vector <Player>* players); void dealCard(Player* p); void dealRound(int cards); void pickTrump(); // 2016 lol void showTrump(); void playTrick(); void showTable(); void playRound(int i); void getWagers(int roundSize); const Card &getTrickSuit() const; const Card &getTrump() const; Player getWinner(); private: Deck deck; std::vector <Player>* players; Card trump; Card fCard; std::vector <Card> trick; std::string secSep; int playerShift; }; #endif //WHIST_DEALER_H <file_sep>// // Created by andy on 11/15/2018. // #include "Dealer.h" Dealer::Dealer( std::vector <Player>* players ) : players(players), deck(Deck((int) players->size())) { secSep = "---------------------\n"; playerShift = 0; } void Dealer::dealCard(Player* p) { p->beDealt(deck.nextCard()); } void Dealer::dealRound(int cards) { deck = Deck((int) players->size()); deck.shuffle(); for( int i = 0; i < cards; i++) { for (auto &p : *players) { dealCard(&p); } } pickTrump(); } const Card &Dealer::getTrump() const { return trump; } void Dealer::pickTrump() { if( !deck.empty() ){ trump = deck.nextCard(); } } void Dealer::showTrump() { std::cout << "Trump" << "\t:\t"; if (trump.getFace()){ std::cout << trump.getName() << '\n'; }else{ std::cout << "No Trump" << '\n'; } } void Dealer::showTable() { std::cout << "Table" << "\t:\t"; for(auto &c :trick){ std::cout << c.getName() << ' '; } std::cout << '\n'; } void Dealer::playTrick() { Player* winningPlayer = &players->front(); Card winningCard; for( auto &p : *players){ trick.push_back(p.playTrick(*this)); if(!winningCard.betterFaceThan(trick.back()) && trick.back().sameSuit(trump)){ winningCard = trick.back(); winningPlayer = &p; }else if(!winningCard.betterFaceThan(trick.back()) && trick.back().sameSuit(trick.front())){ winningCard = trick.back(); winningPlayer = &p; } showTable(); } std::cout << winningPlayer->getName() << " won the trick with : " << winningCard.getName() << '\n'; winningPlayer->winTrick(); int shift = (int) (winningPlayer - &players->front()); playerShift = (playerShift - shift) % (int) players->size(); std::rotate(players->begin(),players->begin()+shift,players->end()); std::cout << secSep; } const Card &Dealer::getTrickSuit() const { if (!trick.empty()) { Card fCard = trick.front(); } return fCard; } void Dealer::getWagers(int roundSize) { std::cout << secSep; std::cout << "Wagers" << "\n"; std::cout << "Round Size" << "\t:\t" << roundSize << '\n'; showTrump(); std::cout << secSep; int sum = 0; for (auto &p : *players){ p.showHand(); std::cout << p.getName() << "\t:\t"; int w; std::cin >> w; sum += w; p.setWager(w); } while(sum == roundSize){ std::cout << "There cannot be the same number of tricks wagered as tricks available.\n"; Player *p = &players->back(); sum -= p->getWager(); std::cout << p->getName() << "\t:\t"; int w; std::cin >> w; sum += w; p->setWager(w); } std::cout << secSep; } void Dealer::playRound(int roundSize) { std::rotate(players->begin(),players->begin()+playerShift,players->end()); for(auto &p : *players){ p.newRound(); } dealRound(roundSize); getWagers(roundSize); for(int i = 0; i < roundSize; i++) { trick.clear(); fCard = Card(); playTrick(); } for(auto &p : *players){ std::cout << p.getName() << " won " << p.getTricksWon() << " tricks and wagered " << p.getWager() << " tricks.\n"; } std::cout << secSep; for(auto &p: *players){ if (p.getWager() == p.getTricksWon()) { int scoreDif = 5 + p.getWager(); p.addScore(scoreDif); std::cout << p.getName() << "\t:" << "(+" << scoreDif << ") " << p.getScore() << '\n'; }else{ int scoreDif = abs(p.getWager() - p.getTricksWon()); p.addScore(-scoreDif); std::cout << p.getName() << "\t:" << "(-" << scoreDif<< ") " << p.getScore() << "\n"; } } playerShift++; } Player Dealer::getWinner() { Player winner = players->front(); for(auto &p : *players){ if(p.getScore() >= winner.getScore() ){ winner = p; } } return winner; } <file_sep>// // Created by andy on 11/15/2018. // #ifndef WHIST_PLAYER_H #define WHIST_PLAYER_H #include <vector> #include <iostream> #include <string> #include <fstream> #include "Card.h" #include "Dealer.h" class Dealer; class Player { public: Player(std::string); Player(); void beDealt(Card); void showHand(); void winTrick(); void addScore(int points); void newRound(); const std::string &getName() const; Card playTrick(Dealer d); int getTricksWon() const; int getScore() const; private: std::string name; std::vector <Card> hand; bool hasSuitOf(Card a); int tricksWon; int wager; public: int getWager() const; void setWager(int wager); private: int score; }; #endif //WHIST_PLAYER_H <file_sep>#include <iostream> #include<string> #include <vector> #include "Card.h" #include "Deck.h" #include "Dealer.h" #include "Player.h" int main() { std::string names[3] = {"Alice","Bob ","Charlie"}; std::vector <Player> players; for(auto &n: names){ players.push_back( Player(n) ); } Dealer d = Dealer(&players); for(auto &n : names){ d.playRound(1); } for(int i = 2; i < 8; i++){ d.playRound(i); } for(auto &n : names){ d.playRound(8); } for(int i = 7; i > 1; i++){ d.playRound(i); } for(auto &n : names){ d.playRound(1); } std::cout << "GAME OVER\n"; std::cout << d.getWinner().getName() << "wins with a score of" << d.getWinner().getScore() << "!"; return 0; }<file_sep>// // Created by andy on 11/15/2018. // #include "Player.h" void Player::beDealt(Card c) { hand.push_back(c); } Player::Player() : hand( std::vector <Card>() ), name("") { score = 0; tricksWon = 0; } Player::Player(std::string name){ score = 0; tricksWon = 0; this->name = name; } void Player::showHand() { remove("hand.txt"); std::ofstream fout; fout.open("hand.txt"); fout << name << "\t:\t"; for(auto &c :hand){ fout << c.getName() << ' '; } fout << '\n'; } bool Player::hasSuitOf(Card a) { for( auto &c : hand ){ if(c.sameSuit(a)) { return true;} } return false; } Card Player::playTrick(Dealer d) { showHand(); int a; while(true){ std::cout << name << "\t:\t"; std::cin >> a; a--; if( a >= hand.size() || a < 0){ std::cout << "Bad Index" << '\n'; continue; } Card c = hand[a]; if( !c.sameSuit(d.getTrump()) && hasSuitOf(d.getTrump()) ){ std::cout << "If you have a trump, you must play it" << '\n'; continue; } if( !c.sameSuit(d.getTrickSuit()) && hasSuitOf(d.getTrickSuit()) ){ std::cout << "If you can, you must follow suit" << '\n'; continue; } hand.erase( hand.begin() + a ); return c; } } const std::string &Player::getName() const { return name; } int Player::getTricksWon() const { return tricksWon; } void Player::winTrick() { Player::tricksWon++; } void Player::newRound() { Player::tricksWon = 0; } int Player::getScore() const { return score; } void Player::addScore(int points) { Player::score += points; } void Player::setWager(int wager) { Player::wager = wager; } int Player::getWager() const { return wager; } <file_sep>set(CMAKE_ASM_COMPILER "/usr/bin/cc") set(CMAKE_ASM_COMPILER_ARG1 "") set(CMAKE_AR "/usr/bin/ar.exe") set(CMAKE_ASM_COMPILER_AR "/usr/bin/gcc-ar.exe") set(CMAKE_RANLIB "/usr/bin/ranlib.exe") set(CMAKE_ASM_COMPILER_RANLIB "/usr/bin/gcc-ranlib.exe") set(CMAKE_LINKER "/usr/bin/ld.exe") set(CMAKE_ASM_COMPILER_LOADED 1) set(CMAKE_ASM_COMPILER_ID "GNU") set(CMAKE_ASM_COMPILER_VERSION "") set(CMAKE_ASM_COMPILER_ENV_VAR "ASM") set(CMAKE_ASM_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) set(CMAKE_ASM_LINKER_PREFERENCE 0) <file_sep>// // Created by andy on 11/15/2018. // #ifndef WHIST_CARD_H #define WHIST_CARD_H #include <string> enum Suit {CLUBS,DIAMONDS,HEARTS,SPADES,NOSUIT}; enum Face {ACE,KING,QUEEN,JACK,TEN,NINE,EIGHT,SEVEN,SIX,FIVE,FOUR,THREE,TWO,NOFACE}; class Card { private: Face face; Suit suit; std::string name; public: const std::string &getName() const; public: Card(Face face, Suit suit); Card(); const Face getFace() const; const Suit getSuit() const; bool betterFaceThan(Card a); bool sameSuit(Card a); }; #endif //WHIST_CARD_H <file_sep>file(REMOVE_RECURSE "CMakeFiles/whist.dir/main.cpp.o" "CMakeFiles/whist.dir/Card.cpp.o" "CMakeFiles/whist.dir/Deck.cpp.o" "CMakeFiles/whist.dir/Player.cpp.o" "CMakeFiles/whist.dir/Dealer.cpp.o" "whist.pdb" "whist.exe" "libwhist.dll.a" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/whist.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>// // Created by andy on 11/15/2018. // #include "Card.h" #include <string> #include <iostream> Card::Card(Face face, Suit suit) : face(face), suit(suit) { name = ""; switch (face) { case ACE: name += 'A'; break; case KING: name += 'K'; break; case QUEEN: name += 'Q'; break; case JACK: name += 'J'; break; case TEN: name += 'T'; break; case NINE: name += '9'; break; case EIGHT: name += '8'; break; case SEVEN: name += '7'; break; case SIX: name += '6'; break; case FIVE: name += '5'; break; case FOUR: name += '4'; break; case THREE: name += '3'; break; case TWO: name += '2'; break; case NOFACE: name += 'N'; break; } switch (suit) { case CLUBS: name += 'C'; break; case DIAMONDS: name += 'D'; break; case HEARTS: name += 'H'; break; case SPADES: name += 'S'; break; case NOSUIT: name += 'N'; break; } } Card::Card() : face(NOFACE), suit(NOSUIT){} const Face Card::getFace() const { return face; } const Suit Card::getSuit() const { return suit; } const std::string &Card::getName() const { return name; } bool Card::betterFaceThan(Card a) { return getFace() < a.getFace(); } bool Card::sameSuit(Card a) { return a.getSuit() == getSuit(); }<file_sep>cmake_minimum_required(VERSION 3.12) project(whist) set(CMAKE_CXX_STANDARD 14) add_executable(whist main.cpp Card.cpp Card.h Deck.cpp Deck.h Player.cpp Player.h Dealer.cpp Dealer.h)
b9eb9604df1f12f260376d37f6623719ce37e636
[ "CMake", "C++" ]
12
C++
AndoBando/whist
55b18469cb75715be14a35806e797c9faa9ebec3
72650447bd4255885036591dfc6afca21ac0436e
refs/heads/master
<file_sep>""" from django.shortcuts import render """ from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello, World! You're at the manager home page.")
02233dfc528a322fd88b5518d98ebf7871a50ab4
[ "Python" ]
1
Python
murankar/mtg_collection
8bd902abbb639bb888eb3a1da200f2035bbe2e69
83702dab733ae94181c3c3ab5a113be4102f76c1
refs/heads/master
<file_sep>#include "plan.h" int main() { schedule file; file.extract(); // file.display(); return 1; } <file_sep>#include <iostream> #include <fstream> #include <cstring> #include <cctype> using namespace std; class schedule { public: schedule(); ~schedule(); int extract();//extracts from a file txt int set(char a_day[],char a_e[], char a_m[], char a_l[], char a_escheduled_event[], char a_mscheduled_event[], char a_lscheduled_event[], int x); int display(); protected: int n; char *day; char *e; char *m; char *l;//scheduled events receiver char *escheduled_event; char *mscheduled_event; char *lscheduled_event; }; <file_sep>#include "plan.h" schedule :: schedule(): n(0), day(NULL), e(NULL), m(NULL), l(NULL), escheduled_event(NULL), mscheduled_event(NULL), lscheduled_event(NULL) {} schedule ::~schedule() { //cout << "n" << n << endl; delete [] day; delete[] e; delete[] m; delete[] l; delete[] escheduled_event; delete[] mscheduled_event; delete[] lscheduled_event; } int schedule :: extract() { char a_day[100]; char a_e[100]; char a_m[100]; char a_l[100]; char a_escheduled_event[100]; char a_mscheduled_event[100]; char a_lscheduled_event[100]; int x = 0; ifstream file_in; file_in.open("schedule.txt"); if(!file_in) { cout << "error" <<endl; } while(!file_in.eof()) { file_in.get(a_day, 100, '{'); file_in.ignore(); file_in.get(a_e, 100, ':'); file_in.ignore(); file_in.get(a_escheduled_event, 100, ':'); file_in.ignore(); file_in.get(a_m, 100, ':'); file_in.ignore(); file_in.get(a_mscheduled_event, 100, ':'); file_in.ignore(); file_in.get(a_l, 100, ':'); file_in.ignore(); file_in.get(a_lscheduled_event, 100, '\n'); file_in.ignore(); file_in.get(); set(a_day, a_e, a_m, a_l, a_escheduled_event, a_mscheduled_event, a_lscheduled_event,x); display(); ++x; } file_in.close(); return 1; } int schedule :: set(char a_day[], char a_e[], char a_m[], char a_l[], char a_escheduled_event[], char a_mscheduled_event[], char a_lscheduled_event[], int x) { n = x; if(day ){delete [] day;} day = new char[strlen(a_day)+1]; strcpy(day , a_day); if(e ){delete [] e;} e = new char[strlen(a_e)+1]; strcpy(e, a_e); if(m ){delete [] m;} m= new char[strlen(a_m)]; strcpy(m, a_m); if(l ){delete [] l;} l = new char[strlen(a_l)+1]; strcpy(l , a_l); if(escheduled_event){delete [] escheduled_event;} escheduled_event = new char[strlen(a_escheduled_event)+1]; strcpy(escheduled_event , a_escheduled_event); if(mscheduled_event){delete [] mscheduled_event;} mscheduled_event = new char[strlen(a_mscheduled_event)+1]; strcpy(mscheduled_event , a_mscheduled_event); if(lscheduled_event){delete [] lscheduled_event;} lscheduled_event = new char[strlen(a_lscheduled_event)+1]; strcpy(lscheduled_event , a_lscheduled_event); return 1; } int schedule:: display() { cout << "day" << day << endl; cout << "e" << e <<endl; //event_movie_lecture cout << "m" << m <<endl; //event_movie_lecture cout << "l" << l <<endl; //event_movie_lecture cout << "esched" << escheduled_event << endl; cout << "msched" << mscheduled_event << endl; cout << "lsched" << lscheduled_event << endl; return 1; }
d4dfcf9593984652cc541cb16040031451bac54c
[ "C++" ]
3
C++
zarater/summer_2018
772bae68ec8c7f7152dde9c9431f4c2f0bc75aca
7397552c89e4866ad762adc2f965852860af539d
refs/heads/main
<file_sep>from django.urls import path from demoapp import views urlpatterns = [ path("", views.ListInterviewAPIView.as_view(), name="interview_list"), path("create/", views.CreateInterviewAPIView.as_view(), name="interview_create"), path("update/<int:pk>/", views.UpdateInterviewAPIView.as_view(), name="update_interview"), path("delete/<int:pk>/", views.DeleteInterviewAPIView.as_view(), name="delete_interview"), path("test/", views.ApiEndpoint.as_view()), ] <file_sep>from rest_framework import serializers from demoapp.models import Interview class InterviewSerializer(serializers.ModelSerializer): class Meta: model = Interview fields = "__all__" <file_sep>FROM python:3 RUN apt-get update \ && apt-get -y install libpq-dev gcc \ && pip install psycopg2 \ && pip install django-oauth-toolkit \ && pip install djangorestframework \ && pip install django-cors-headers ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/<file_sep>from django.db import models # Create your models here. class Interview(models.Model): id = models.CharField(max_length=100, primary_key=True) greeting = models.TextField()<file_sep>from django.db.models import query from django.shortcuts import render from rest_framework import serializers from rest_framework.generics import ListAPIView from rest_framework.generics import CreateAPIView from rest_framework.generics import DestroyAPIView from rest_framework.generics import UpdateAPIView from rest_framework import permissions from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope from demoapp.serializers import InterviewSerializer from demoapp.models import Interview from oauth2_provider.views.generic import ProtectedResourceView from django.http import HttpResponse # Create your views here. class ListInterviewAPIView(ListAPIView): permission_classes = [TokenHasScope] required_scopes = ['read'] queryset = Interview.objects.all() serializer_class = InterviewSerializer class CreateInterviewAPIView(CreateAPIView): #permission_classes = [permissions.IsAuthenticated] queryset = Interview.objects.all() serializer_class = InterviewSerializer class UpdateInterviewAPIView(UpdateAPIView): permission_classes = [TokenHasScope] required_scopes = ['write'] queryset = Interview.objects.all() serializer_class = InterviewSerializer class DeleteInterviewAPIView(DestroyAPIView): queryset = Interview.objects.all() serializer_class = InterviewSerializer class ApiEndpoint(ProtectedResourceView): def get(self, request, *args, **kwargs): return HttpResponse('Hello, OAuth2!') def interview_view(request): return render(request, "", {})
493fb1fe6e554716fd82c710905e4176a79f66ca
[ "Python", "Dockerfile" ]
5
Python
bnsoni/django_dock
d1386815362e53995dbdb7f5abca1a6dd0f65bb8
328b9cccd3fc70d167774027b279e76f59d956c0
refs/heads/master
<repo_name>tiffany831101/TestForRakuten<file_sep>/src/Table.js import React, { Component } from 'react' import Tableitem from "./Tableitem"; const Tabletitle = () => ( <thead> <tr> <th scope="col" className="thead__id">ID</th> <th scope="col">Name</th> <th scope="col">Phone</th> <th scope="col">Email</th> <th scope="col" className="thead__action">Action</th> </tr> </thead> ) export default class Table extends Component { constructor(props) { super(props) this.state = { deleteId: 0, initialId: 0, //由子層傳上來要改的id editId: 0, // 要修改的tableitem editChange: { name: "", phone: "", email: "", }, // 是否要顯示modal輸入框,當要修改時才會出現modal modalShow: false, // 上面輸入攔的部分 inputValue: { name: "", phone: "", email: "", }, inputError: { phone: false, email: true, name: false, }, inputColor: { phone: false, email: false, name: false, }, modifyColor: { phone: false, email: false, name: false, }, modifyError: { phone: false, email: true, name: false, }, // 表格裡的內容 tableItem: [], } this.handleChange = this.handleChange.bind(this); this.handleClick = this.handleClick.bind(this); this.getItemId = this.getItemId.bind(this); this.handleShow = this.handleShow.bind(this); this.handleClose = this.handleClose.bind(this); this.editChange = this.editChange.bind(this); this.editClick = this.editClick.bind(this); this.deleteItem = this.deleteItem.bind(this); this.checkInvalid = this.checkInvalid.bind(this); this.changeColor = this.changeColor.bind(this); this.editChangeColor = this.editChangeColor.bind(this); this.modifyInvalid = this.modifyInvalid.bind(this); } deleteItem(deleteId) { let id = Number(deleteId); // console.log(deleteId); // console.log(this.state.deleteId); // console.log() if (deleteId == this.state.deleteId) return; this.setState({ deleteId: deleteId, tableItem: this.state.tableItem.filter((item, key) => { // console.log(item.id == deleteId) return Number(item.id) !== id }), }) } editChange(e) { // console.log(e); e.preventDefault(); // console.log(e.target.value); let value = e.target.value; // let inputType = e.target.name; this.setState({ editChange: { ...this.state.editChange, [e.target.name]: value, } }) } editClick(e) { if (this.state.modifyError.email || this.state.modifyError.phone || this.state.modifyError.name) return // console.log(e.target); // console.log(this.state.editId); this.setState(prevState => ({ modalShow: false, tableItem: this.state.tableItem.map((item, key) => { if (item.id == this.state.editId) { return ({ ...this.state.editChange, id: this.state.editId }) } else { return item } }), editChange: { name: "", phone: "", email: "", id: 0, }, modifyError: { email: true, phone: false, name: false, } })) } handleChange(e) { e.preventDefault(); // console.log(e.target.value); let value = e.target.value; console.log(e.target.name); //check for regular expression // 2. phone // 3. email // if (e.target.name == "phone") { // if (!(/^0\d{1,3}-\d{5,8}$/.test(e.target.value))) { // alert("號碼有誤,請重填"); // return false; // } // } // let inputType = e.target.name; this.setState({ inputValue: { ...this.state.inputValue, [e.target.name]: value, } }) } // 這邊可以取得到要修改哪一筆的資料 getItemId(id) { this.setState(prevState => { // console.log(prevState.editId) // console.log(id) if (id == prevState.editId) { // console.log("已經更改過了") return } else { return ( { modalShow: true, editId: id, } ) } }) } handleShow(e) { // console.log(e); this.setState({ modalShow: true, }) } //change borderColor when focus on input changeColor(e) { console.log("changing..."); let inputName = e.target.name; this.setState(prevState => { return ({ inputColor: { ...prevState.inputColor, [inputName]: true, } }) }) } // onblur // check if valid before submit checkInvalid(e) { console.log("checking...") // check phone // console.log(e.target.value); if (e.target.name === "phone") { if (!(/^0\d{1,3}-\d{5,8}$/.test(e.target.value))) { if (e.target.value == "") { console.log("here is empty...") this.setState(prevState => { return ({ inputError: { ...prevState.inputError, phone: false, }, inputColor: { ...prevState.inputColor, phone: false, } }) }) } else { this.setState(prevState => { return ({ inputError: { ...prevState.inputError, phone: true, }, inputColor: { ...prevState.inputColor, phone: false, } }) }) } } else { this.setState(prevState => { return ({ inputError: { ...prevState.inputError, phone: false, }, inputColor: { ...prevState.inputColor, phone: false, } }) }) } } //check email if (e.target.name === "email") { if (!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(e.target.value))) { this.setState(prevState => { return ({ inputError: { ...prevState.inputError, email: true, }, inputColor: { ...prevState.inputColor, email: false, } }) }) } else { this.setState(prevState => { return ({ inputError: { ...prevState.inputError, email: false, }, inputColor: { ...prevState.inputColor, email: false, } }) }) } } //check if duplicate name if (e.target.name === "name") { if (this.state.tableItem.map(item => item.name).indexOf(e.target.value) !== (-1)) { this.setState(prevState => { return ({ inputError: { ...prevState.inputError, name: true, }, inputColor: { ...prevState.inputColor, name: false, } }) }) } else { this.setState(prevState => { return ({ inputError: { ...prevState.inputError, name: false, }, inputColor: { ...prevState.inputColor, name: false, } }) }) } } } // click to submit handleClick(e) { if (this.state.inputError.email || this.state.inputError.phone || this.state.inputError.name) return this.setState(prevState => ({ tableItem: [ ...prevState.tableItem, { ...this.state.inputValue, id: (this.state.initialId + 1), } // this.state.inputValue, // this.state.initialId, ], initialId: (prevState.initialId + 1), })) this.setState({ inputValue: { name: "", email: "", phone: "", }, inputError: { name: false, phone: false, email: true, } }) } handleClose(e) { this.setState({ modalShow: false, }) } editChangeColor(e) { console.log("modify changing..."); let modifyInput = e.target.name; this.setState(prevState => { return ({ modifyColor: { ...prevState.modifyColor, [modifyInput]: true, } }) }) } modifyInvalid(e) { console.log("checking...") // check phone // console.log(e.target.value); if (e.target.name === "phone") { if (!(/^0\d{1,3}-\d{5,8}$/.test(e.target.value))) { if (e.target.value == "") { console.log("here is empty...") this.setState(prevState => { return ({ modifyError: { ...prevState.modifyError, phone: false, }, modifyColor: { ...prevState.modifyColor, phone: false, } }) }) } else { this.setState(prevState => { return ({ modifyError: { ...prevState.modifyError, phone: true, }, modifyColor: { ...prevState.modifyColor, phone: false, } }) }) } } else { this.setState(prevState => { return ({ modifyError: { ...prevState.modifyError, phone: false, }, modifyColor: { ...prevState.modifyColor, phone: false, } }) }) } } //check email if (e.target.name === "email") { if (!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(e.target.value))) { this.setState(prevState => { return ({ modifyError: { ...prevState.modifyError, email: true, }, modifyColor: { ...prevState.modifyColor, email: false, } }) }) } else { this.setState(prevState => { return ({ modifyError: { ...prevState.modifyError, email: false, }, modifyColor: { ...prevState.modifyColor, email: false, } }) }) } } //check if duplicate name if (e.target.name === "name") { console.log(this.state.editId); console.log(this.state.tableItem .filter(item => (Number(item.id) !== Number(this.state.editId))) .map(item => item.name) .indexOf(e.target.value)); // console.log(this.state.tableItem.filter(item => (Number(item.id) !== Number(this.state.editId)))).map(item => item.name)) if (this.state.tableItem.filter(item => (Number(item.id) !== Number(this.state.editId))).map(item => item.name).indexOf(e.target.value) !== (-1)) { this.setState(prevState => { return ({ modifyError: { ...prevState.modifyError, name: true, }, modifyColor: { ...prevState.modifyColor, name: false, } }) }) } else { this.setState(prevState => { return ({ modifyError: { ...prevState.modifyError, name: false, }, modifyColor: { ...prevState.modifyColor, name: false, } }) }) } } } render() { const style = { borderColor: "#1abc9c", } console.log(this.state.modifyColor); console.log(this.state.modifyError); return ( <div> <div className="col-lg-5 col-md-6 col-sm-8 col-12 mt-5"> <div className="input__box"> <div className={(this.state.inputColor.name && "input__box__area--active") + " input__box__area"}> <input name="name" type="text" className="" onChange={this.handleChange} onFocus={this.changeColor} value={this.state.inputValue.name} onBlur={this.checkInvalid} placeholder='Enter Your Name' /> <i className="fas fa-user" style={this.state.inputColor.name ? { color: "#1abc9c" } : {}}></i> </div> <p className={this.state.inputError.name ? "error" : "valid"}>Name already exists</p> <div className={(this.state.inputColor.phone && "input__box__area--active") + " input__box__area"}> <input name="phone" type="text" className="" onChange={this.handleChange} onFocus={this.changeColor} value={this.state.inputValue.phone} onBlur={this.checkInvalid} placeholder='Enter Your Phone ex:02-111111' /> <i className="fas fa-phone" style={this.state.inputColor.phone ? { color: "#1abc9c" } : {}}></i> </div> <p className={this.state.inputError.phone ? "error" : "valid"}>Enter a valid Phone Number</p> <div className={(this.state.inputColor.email && "input__box__area--active") + " input__box__area"}> <input name="email" type="email" className="" onChange={this.handleChange} onFocus={this.changeColor} value={this.state.inputValue.email} onBlur={this.checkInvalid} placeholder='Enter Your Email*' /> <i className="fas fa-envelope-open" style={this.state.inputColor.email ? { color: "#1abc9c" } : {}}></i> </div> <p className={this.state.inputError.email ? "error" : "valid"}>必填*</p> <button onClick={this.handleClick} className="input__box__btn">Add</button> </div> </div> <div className="col-lg-12 col-md-10 col-12 mx-auto mt-4"> {/* table */} <div className="table__wrapper"> <table className="table"> <Tabletitle /> <Tableitem tableItem={this.state.tableItem} getItemId={this.getItemId} deleteItem={this.deleteItem} handleShow={this.handleShow} /> </table> </div> {/*modal */} <div className={(this.state.modalShow ? "d-block " : "d-none ") + "modal"} tabIndex="-1" role="dialog"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title">Modify</h5> {/* 消失 */} <button type="button" className="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true" onClick={this.handleClose}>&times;</span> </button> </div> <div className="modal-body py-5"> <input name="name" type="text" className={(this.state.modifyColor.name && "modify__input--active")} onChange={this.editChange} value={this.state.editChange.name} onFocus={this.editChangeColor} onBlur={this.modifyInvalid} placeholder="name" /> <p className={(this.state.modifyError.name ? "error" : "valid") + " mb-1"}>Name already exists</p> <input name="phone" type="text" className={(this.state.modifyColor.phone && "modify__input--active")} onChange={this.editChange} value={this.state.editChange.phone} onFocus={this.editChangeColor} onBlur={this.modifyInvalid} placeholder="phone" /> <p className={(this.state.modifyError.phone ? "error" : "valid") + " mb-1"}>Invalid Phone Number</p> <input name="email" type="email" className={(this.state.modifyColor.email && "modify__input--active")} onChange={this.editChange} value={this.state.editChange.email} onFocus={this.editChangeColor} onBlur={this.modifyInvalid} placeholder="email" /> <p className={(this.state.modifyError.email ? "error" : "valid") + " mb-1"}>必填*</p> </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-dismiss="modal" onClick={this.handleClose}>Close</button> <button type="button" className="btn btn-primary" onClick={this.editClick}>Save changes</button> </div> </div> </div> </div> </div> </div > ) } } <file_sep>/src/Tableitem.js import React, { Component } from 'react' export default class Tableitem extends Component { constructor(props) { super(props); console.log(props); this.state = { id: 0, deleteId: 0, } this.sendID = this.sendID.bind(this); this.deleteItem = this.deleteItem.bind(this); } deleteItem(e) { this.setState({ deleteId: e.target.dataset.id, }) } componentWillMount() { this.props.getItemId(this.state.id); this.props.deleteItem(this.state.deleteId); } componentDidUpdate() { this.props.getItemId(this.state.id); this.props.deleteItem(this.state.deleteId); } handleClick(e) { this.setState({ id: e.target.dataset.id }) } sendID(e) { this.setState({ id: e.target.dataset.id, }) } render() { console.log(this.state); return ( <tbody> {this.props.tableItem.length !== 0 && this.props.tableItem.map((item, key) => ( <tr key={key}> <th scope="row">{item.id}</th> <td>{item.name}</td> <td>{item.phone}</td> <td>{item.email}</td> <td> <i data-id={item.id} className="fas fa-pen" onClick={(e) => { this.sendID(e) this.props.handleShow() }}> </i> <i data-id={item.id} onClick={this.deleteItem} className="far fa-trash-alt"></i> </td> </tr> ))} </tbody> ) } }
a1036c857e84a189ae2c5f0669a32acc483da754
[ "JavaScript" ]
2
JavaScript
tiffany831101/TestForRakuten
a063c7023c9c1ba17dce12a73832c7932c6d5d39
6834948c0f300b4e3014a03eb6a27329f3f5d403
refs/heads/master
<repo_name>TimCompany-prog/telegrambot_Xmoney<file_sep>/prog.py import telebot import requests from time import time bot = telebot.TeleBot('Token') from telebot import types a = types.ReplyKeyboardMarkup(resize_keyboard=True) a1 = types.KeyboardButton("заработать🏧") a2 = types.KeyboardButton("вывод💳") a3 = types.KeyboardButton("разработчик👨‍💻") a4 = types.KeyboardButton("чат📝") a.add(a1,a2,a3,a4) ab = types.InlineKeyboardMarkup() a5 = types.InlineKeyboardButton(text="чат📝",url='https://t.me/chatpeo') ab.add(a5) af = types.InlineKeyboardMarkup(row_width=2) a6 = types.InlineKeyboardButton(text="посмотреть рекламу",callback_data='as') a7 = types.InlineKeyboardButton(text="подписаться на канал",url='https://t.me/chatpeo') af.add(a6,a7) @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Привет, я бот, узнать команды - /help',reply_markup=a) @bot.message_handler(commands=['help']) def start_message(message): bot.send_message(message.chat.id, '') @bot.message_handler(content_types=['text']) def send_text(message): if message.text.lower() == 'вывод💳': bot.send_message(message.chat.id, 'У тебя 0, но скоро будет 10000$') if message.text.lower() == 'заработать🏧': bot.send_message(message.chat.id,"Способы заработать🏧",reply_markup=af) if message.text.lower() == 'разработчик👨‍💻': bot.send_message(message.chat.id, 'Мой разработчик @timproger') if message.text.lower() == 'чат📝': bot.send_message(message.chat.id,'Сcылка на групу',reply_markup=ab) @bot.callback_query_handler(func=lambda call: True) def callback_inline(call): try: if call.message: if call.data == 'as': bot.send_message(call.message.chat.id, 'зарегистрируйся и смотри рекламу\nhttps://globus-inter.com/uk/land/people?invite=7671830') except Exception as e: print(repr(e)) bot.polling(none_stop=True)
94008a381015b6575fb25799092e07b8efc5ad5f
[ "Python" ]
1
Python
TimCompany-prog/telegrambot_Xmoney
df9ee34e2e2bd16e1d7176ea31cb97c041083501
2d5a45e1a499b3f9e9cc4e419d4d30141c9f8330
refs/heads/master
<file_sep>package com.frostwire.gui.components; import java.util.List; public class SlideList { public boolean randomStart; public List<Slide> slides; } <file_sep>package com.frostwire.alexandria.db; import java.util.List; import com.frostwire.alexandria.PlaylistItem; public class PlaylistItemDB extends ObjectDB<PlaylistItem> { public PlaylistItemDB(LibraryDatabase db) { super(db); } public void fill(PlaylistItem obj) { List<List<Object>> result = db .query("SELECT playlistItemId, filePath, fileName, fileSize, fileExtension, trackTitle, trackDurationInSecs, trackArtist, trackAlbum, coverArtPath, trackBitrate, trackComment, trackGenre, trackNumber, trackYear, starred " + "FROM PlaylistItems WHERE playlistItemId = ?", obj.getId()); if (result.size() > 0) { List<Object> row = result.get(0); fill(row, obj); } } public void fill(List<Object> row, PlaylistItem obj) { int id = (Integer) row.get(0); String filePath = (String) row.get(1); String fileName = (String) row.get(2); long fileSize = (Long) row.get(3); String fileExtension = (String) row.get(4); String trackTitle = (String) row.get(5); float trackDurationInSecs = (Float) row.get(6); String trackArtist = (String) row.get(7); String trackAlbum = (String) row.get(8); String coverArtPath = (String) row.get(9); String trackBitrate = (String) row.get(10); String trackComment = (String) row.get(11); String trackGenre = (String) row.get(12); String trackNumber = (String) row.get(13); String trackYear = (String) row.get(14); boolean starred = (Boolean) row.get(15); obj.setId(id); obj.setFilePath(filePath); obj.setFileName(fileName); obj.setFileSize(fileSize); obj.setFileExtension(fileExtension); obj.setTrackTitle(trackTitle); obj.setTrackDurationInSecs(trackDurationInSecs); obj.setTrackArtist(trackArtist); obj.setTrackAlbum(trackAlbum); obj.setCoverArtPath(coverArtPath); obj.setTrackBitrate(trackBitrate); obj.setTrackComment(trackComment); obj.setTrackGenre(trackGenre); obj.setTrackNumber(trackNumber); obj.setTrackYear(trackYear); obj.setStarred(starred); } public void save(PlaylistItem obj) { if (obj.getId() == LibraryDatabase.OBJECT_INVALID_ID || obj.getPlaylist() == null) { return; } if (obj.getId() == LibraryDatabase.OBJECT_NOT_SAVED_ID) { obj.setStarred(isStarred(obj) || obj.isStarred()); Object[] sqlAndValues = createPlaylistItemInsert(obj); int id = db.insert((String) sqlAndValues[0], (Object[]) sqlAndValues[1]); obj.setId(id); sqlAndValues = updateStarred(obj); db.update((String) sqlAndValues[0], (Object[]) sqlAndValues[1]); } else { Object[] sqlAndValues = createPlaylistItemUpdate(obj); db.update((String) sqlAndValues[0], (Object[]) sqlAndValues[1]); sqlAndValues = updateStarred(obj); db.update((String) sqlAndValues[0], (Object[]) sqlAndValues[1]); } } public void delete(PlaylistItem obj) { db.update("DELETE FROM PlaylistItems WHERE playlistItemId = ?", obj.getId()); } private Object[] createPlaylistItemInsert(PlaylistItem item) { String sql = "INSERT INTO PlaylistItems (playlistId, filePath, fileName, fileSize, fileExtension, trackTitle, trackDurationInSecs, trackArtist, trackAlbum, coverArtPath, trackBitrate, trackComment, trackGenre, trackNumber, trackYear, starred) " + " VALUES (?, LEFT(?, 10000), LEFT(?, 500), ?, LEFT(?, 10), LEFT(?, 500), ?, LEFT(?, 500), LEFT(?, 500), LEFT(?, 10000), LEFT(?, 10), LEFT(?, 500), LEFT(?, 20), LEFT(?, 6), LEFT(?, 6), ?)"; Object[] values = new Object[] { item.getPlaylist().getId(), item.getFilePath(), item.getFileName(), item.getFileSize(), item.getFileExtension(), item.getTrackTitle(), item.getTrackDurationInSecs(), item.getTrackArtist(), item.getTrackAlbum(), item.getCoverArtPath(), item.getTrackBitrate(), item.getTrackComment(), item.getTrackGenre(), item.getTrackNumber(), item.getTrackYear(), item.isStarred() }; return new Object[] { sql, values }; } private Object[] createPlaylistItemUpdate(PlaylistItem item) { String sql = "UPDATE PlaylistItems SET filePath = LEFT(?, 10000), fileName = LEFT(?, 500), fileSize = ?, fileExtension = LEFT(?, 10), trackTitle = LEFT(?, 500), trackDurationInSecs = ?, trackArtist = LEFT(?, 500), trackAlbum = LEFT(?, 500), coverArtPath = LEFT(?, 10000), trackBitrate = LEFT(?, 10), trackComment = LEFT(?, 500), trackGenre = LEFT(?, 20), trackNumber = LEFT(?, 6), trackYear = LEFT(?, 6), starred = ? WHERE playlistItemId = ?"; Object[] values = new Object[] { item.getFilePath(), item.getFileName(), item.getFileSize(), item.getFileExtension(), item.getTrackTitle(), item.getTrackDurationInSecs(), item.getTrackArtist(), item.getTrackAlbum(), item.getCoverArtPath(), item.getTrackBitrate(), item.getTrackComment(), item.getTrackGenre(), item.getTrackNumber(), item.getTrackYear(), item.isStarred(), item.getId() }; return new Object[] { sql, values }; } private Object[] updateStarred(PlaylistItem item) { String sql = "UPDATE PlaylistItems SET starred = ? WHERE filePath = LEFT(?, 10000)"; Object[] values = new Object[] { item.isStarred(), item.getFilePath() }; return new Object[] { sql, values }; } private boolean isStarred(PlaylistItem item) { List<List<Object>> result = db .query("SELECT starred FROM PlaylistItems WHERE filePath = ? LIMIT 1", item.getFilePath()); if (result.size() > 0) { return (Boolean) result.get(0).get(0); } return false; } } <file_sep>/* * Created by <NAME> (@gubatron), <NAME> (aldenml) * Copyright (c) 2011, 2012, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frostwire.gui.components; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.swing.JPanel; import org.limewire.util.OSUtils; import com.frostwire.HttpFetcher; import com.frostwire.ImageCache; import com.frostwire.ImageCache.OnLoadedListener; import com.frostwire.JsonEngine; import com.limegroup.gnutella.gui.GUIMediator; import com.limegroup.gnutella.settings.ApplicationSettings; /** * * @author gubatron * @author aldenml * */ public class SlideshowPanel extends JPanel { private static final long serialVersionUID = -1964953870003850981L; private List<Slide> _slides; private boolean _randomStart; private int _currentSlideIndex; private BufferedImage _currentImage; private BufferedImage _lastImage; private BufferedImage _masterImage1; private BufferedImage _masterImage2; private boolean masterFlag; private boolean _loadingNextImage; private FadeSlideTransition _transition; private long _transitionTime; private boolean _started; private boolean _stoppedTransitions; public interface SlideshowListener { public void onSlideChanged(); } private List<SlideshowListener> _listeners; /** * Last time stamp a slide was loaded */ private long _lastTimeSlideLoaded; /** * Timer to check if we need to switch slides */ private Timer _timer; private JPanel _controlsContainer; private boolean _useControls; public SlideshowPanel(List<Slide> slides, boolean randomStart) { setup(slides, false); } public SlideshowPanel(final String url) { new Thread(new Runnable() { public void run() { load(url); } }).start(); } private void load(final String url) { try { HttpFetcher fetcher = new HttpFetcher(new URI(url)); byte[] jsonBytes = fetcher.fetch(); if (jsonBytes != null) { final SlideList slideList = new JsonEngine().toObject(new String(jsonBytes), SlideList.class); GUIMediator.safeInvokeLater(new Runnable() { public void run() { try { setup(slideList.slides, slideList.randomStart); repaint(); } catch (Exception e) { System.out.println("Failed load of Slide Show:" + url); _slides = null; // nothing happens e.printStackTrace(); } } }); } //System.out.println("Loaded Slide Show for:" + url); } catch (Exception e) { System.out.println("Failed load of Slide Show:" + url); _slides = null; // nothing happens e.printStackTrace(); } } @Override public int getHeight() { return super.getHeight() - 1; } @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight() + 4); if (!_started && !_stoppedTransitions) { startAnimation(); } if (_transition != null) { _transition.paint(g); if (!_transition.isRunning()) { _transition = null; } } if (_transition == null && _currentImage != null) { g.drawImage(_currentImage, 0, 0, null); } } private void setup(List<Slide> slides, boolean randomStart) { _slides = filter(slides); _randomStart = randomStart; _currentSlideIndex = -1; setCursor(new Cursor(Cursor.HAND_CURSOR)); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { try { if (_currentImage == null) { return; } int actualSlideIndex; if (_currentSlideIndex == -1 && _slides != null && _slides.size() > 0) { actualSlideIndex = 0; } else { actualSlideIndex = _currentSlideIndex; } Slide slide = _slides.get(actualSlideIndex); if (slide.url != null) { GUIMediator.openURL(slide.url); } if (slide.torrent != null) { if (slide.torrent.toLowerCase().startsWith("http")) { GUIMediator.instance().openTorrentURI(slide.torrent, false); } else if (slide.torrent.toLowerCase().startsWith("magnet:?")) { GUIMediator.instance().openTorrentURI(slide.torrent, false); } } } catch (Exception ex) { ex.printStackTrace(); } } }); if (_controlsContainer != null && _useControls) { _controlsContainer.add(new SlideshowPanelControls(this), BorderLayout.PAGE_END); } } private void startAnimation() { if (_slides == null || _slides.size() == 0 || _stoppedTransitions) { return; } _started = true; _lastTimeSlideLoaded = 0; if (_slides.size() == 1) { try { ImageCache.instance().getImage(new URL(_slides.get(0).imageSrc), new OnLoadedListener() { public void onLoaded(URL url, BufferedImage image, boolean fromCache, boolean fail) { _currentImage = image; repaint(); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } else { _timer = new Timer(); _timer.schedule(new TimerTask() { @Override public void run() { tryMoveNext(false); } }, 0, 200); // Check every 200 milliseconds if we should trigger a transition } } private void tryMoveNext(boolean forceCurrentIndex) { if (_loadingNextImage) { return; } Slide slide = null; if (_currentSlideIndex == -1) { if (_randomStart) { _currentSlideIndex = new Random(System.currentTimeMillis()).nextInt(_slides.size()); } else { _currentSlideIndex = 0; } _loadingNextImage = true; try { ImageCache.instance().getImage(new URL(_slides.get(_currentSlideIndex).imageSrc), new OnLoadedListener() { public void onLoaded(URL url, BufferedImage image, boolean fromCache, boolean fail) { _currentImage = image; _loadingNextImage = false; if (_currentImage != null) { _lastImage = _currentImage; _lastTimeSlideLoaded = System.currentTimeMillis(); repaint(); } } }); } catch (MalformedURLException e) { e.printStackTrace(); } } else { slide = _slides.get(_currentSlideIndex); if (forceCurrentIndex) { //Switch Image without try { ImageCache.instance().getImage(new URL(slide.imageSrc), new OnLoadedListener() { public void onLoaded(URL url, BufferedImage image, boolean fromCache, boolean fail) { _currentImage = prepareImage(image); if (_transition != null) { _transition.stop(); } _transition = null; repaint(); } }); } catch (MalformedURLException e) { e.printStackTrace(); } return; } else if (slide.duration + _lastTimeSlideLoaded + _transitionTime < System.currentTimeMillis()) { _currentSlideIndex = (_currentSlideIndex + 1) % _slides.size(); slide = _slides.get(_currentSlideIndex); } else { slide = null; } } if (slide != null) { _loadingNextImage = true; try { ImageCache.instance().getImage(new URL(slide.imageSrc), new OnLoadedListener() { public void onLoaded(URL url, BufferedImage image, boolean fromCache, boolean fail) { _currentImage = prepareImage(image); if (_lastImage != null && _currentImage != null) { _transition = new FadeSlideTransition(SlideshowPanel.this, _lastImage, _currentImage); _transitionTime = _transition.getEstimatedDuration(); _transition.start(); } _loadingNextImage = false; if (_currentImage != null) { _lastImage = _currentImage; _lastTimeSlideLoaded = System.currentTimeMillis(); repaint(); } } }); } catch (MalformedURLException e) { e.printStackTrace(); } } } protected BufferedImage prepareImage(BufferedImage image) { if (image == null) { return null; } try { BufferedImage bImage = getMasterImage(800, 400); Graphics2D g = null; try { g = bImage.createGraphics(); int x = 0; int y = 0; //will try to center images that are smaller than the container. if (image.getHeight() < getHeight()) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); y = (getHeight() - image.getHeight()) / 2; } if (image.getWidth() < getWidth()) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); x = (getWidth() - image.getWidth()) / 2; } g.drawImage(image, x, y, null); } finally { if (g != null) { g.dispose(); } } return bImage; } catch (Exception e) { System.out.println("Error creating image for SlideShow " + "(" + getWidth() + ", " + getHeight() + ")"); e.printStackTrace(); return null; } } private List<Slide> filter(List<Slide> slides) { List<Slide> result = new ArrayList<Slide>(slides.size()); for (Slide slide : slides) { if (isMessageEligibleForMyLang(slide.language) && isMessageEligibleForMyOs(slide.os)) { result.add(slide); } } return result; } /* * Examples of when this returns true * given == lang in app * es_ve == es_ve * es == es_ve * * == es_ve */ private boolean isMessageEligibleForMyLang(String lang) { if (lang == null || lang.equals("*")) return true; String langinapp = ApplicationSettings.getLanguage().toLowerCase(); if (lang.length() == 2) return langinapp.toLowerCase().startsWith(lang.toLowerCase()); return lang.equalsIgnoreCase(langinapp); } private boolean isMessageEligibleForMyOs(String os) { if (os == null) return true; boolean im_mac_msg_for_me = os.equals("mac") && OSUtils.isMacOSX(); boolean im_windows_msg_for_me = os.equals("windows") && OSUtils.isWindows(); boolean im_linux_msg_for_me = os.equals("linux") && OSUtils.isLinux(); return im_mac_msg_for_me || im_windows_msg_for_me || im_linux_msg_for_me; } public boolean hasSlides() { return _slides != null && _slides.size() > 0; } private BufferedImage getMasterImage(int w, int h) { masterFlag = !masterFlag; if (masterFlag) { if (_masterImage1 == null) { _masterImage1 = null; _masterImage1 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } return _masterImage1; } else { if (_masterImage2 == null) { _masterImage2 = null; _masterImage2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } return _masterImage2; } } public void onTransitionStarted() { //notify listeners. if (_listeners == null || _listeners.size() == 0) { return; } for (SlideshowListener listener : _listeners) { listener.onSlideChanged(); } } public int getNumSlides() { if (_slides == null) { return -1; } return _slides.size(); } public int getCurrentSlideIndex() { return _currentSlideIndex; } /** * This method is for a user who wants to jump at a random slide. * It'll stop the timer. * * @param index */ public void switchToSlide(int index) { stopTransitions(); _currentSlideIndex = index; tryMoveNext(true); } public void stopTransitions() { _stoppedTransitions = true; _loadingNextImage = false; if (_timer != null) { _timer.cancel(); } _lastTimeSlideLoaded = 0; } public void addListener(SlideshowListener myDummyListener) { if (_listeners == null) { _listeners = new ArrayList<SlideshowPanel.SlideshowListener>(); } _listeners.add(myDummyListener); } public void removeListener(SlideshowListener myDummyListener) { if (_listeners == null) { return; } _listeners.remove(myDummyListener); } public void setupContainerAndControls(JPanel container, boolean useControls) { _controlsContainer = container; _useControls = useControls; } } <file_sep>package com.frostwire.alexandria; public final class LibraryUtils { private LibraryUtils() { } public static String luceneEncode(String s) { //+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ int length = s.length(); s = s.replace("AND", " ").replace("OR", " ").replace("NOT", " "); StringBuilder buff = new StringBuilder(2 * length); for (int i = 0; i < length; i++) { char c = s.charAt(i); switch (c) { case '+': buff.append("\\+"); break; case '-': buff.append("\\-"); break; case '&': buff.append("\\&"); break; // actually it's && case '|': buff.append("\\r"); break; // actually it's || case '!': buff.append("\\!"); break; case '(': buff.append("\\("); break; case ')': buff.append("\\)"); break; case '{': buff.append("\\{"); break; case '}': buff.append("\\}"); break; case '[': buff.append("\\["); break; case ']': buff.append("\\]"); break; case '^': buff.append("\\^"); break; case '\"': buff.append("\\\""); break; case '~': buff.append("\\~"); break; case '*': buff.append("\\*"); break; case '?': buff.append("\\?"); break; case ':': buff.append("\\:"); break; case '\\': buff.append("\\\\"); break; default: buff.append(c); break; } } return buff.toString().replaceAll("\\s+", " "); } public static String fuzzyLuceneQuery(String str) { String luceneStr = luceneEncode(str); String[] tokens = luceneStr.split(" "); if (tokens.length == 0) { return luceneStr; } if (tokens.length == 1) { return luceneStr + "~"; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length - 1; i++) { sb.append(tokens[i] + "~ AND "); } sb.append(tokens[tokens.length - 1] + "~"); return sb.toString().trim(); } public static String wildcardLuceneQuery(String str) { String luceneStr = luceneEncode(str); String[] tokens = luceneStr.split(" "); if (tokens.length == 0) { return luceneStr; } if (tokens.length == 1) { return luceneStr + "*"; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length - 1; i++) { sb.append(tokens[i] + "* AND "); } sb.append(tokens[tokens.length - 1] + "*"); return sb.toString().trim(); } } <file_sep>package com.limegroup.gnutella.gui.init; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JPanel; import com.limegroup.gnutella.gui.GUIMediator; import com.limegroup.gnutella.gui.GUIUtils; import com.limegroup.gnutella.gui.I18n; import com.limegroup.gnutella.gui.URLLabel; import com.limegroup.gnutella.gui.themes.SkinCustomUI; import com.limegroup.gnutella.gui.themes.ThemeMediator; /** * this class displays information welcoming the user to the * setup wizard. */ final class WelcomeWindow extends SetupWindow { /** * */ private static final long serialVersionUID = -5102133230630399469L; private static final String TEXT1 = I18n.tr("FrostWire is a Peer to Peer Application that enables you to share files of your choosing with other users connected to the BitTorrent network."); private static final String TEXT2 = I18n.tr("Installing and using the program does not constitute a license for obtaining or distributing unauthorized content."); /** * Creates the window and its components */ WelcomeWindow(SetupManager manager, boolean partial) { super( manager, I18n.tr("Welcome"), partial ? I18n.tr("Welcome to the FrostWire setup wizard. FrostWire has recently added new features that require your configuration. FrostWire will guide you through a series of steps to configure these new features.") : I18n.tr("Welcome to the FrostWire setup wizard. FrostWire will guide you through a series of steps to configure FrostWire for optimum performance.")); } public Icon getIcon() { return GUIMediator.getThemeImage("logo"); } @Override protected void createWindow() { super.createWindow(); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c; JComponent label1 = createPanel(TEXT1, TEXT2); c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = GridBagConstraints.REMAINDER; c.insets = new Insets(0, 0, 10, 0); panel.add(label1, c); setSetupComponent(panel); } private JComponent createPanel(String text1, String text2) { JPanel panel = new JPanel(); panel.putClientProperty(SkinCustomUI.CLIENT_PROPERTY_DARK_NOISE, true); panel.setBackground(GUIUtils.hexToColor("F7F7F7")); panel.setBorder(BorderFactory.createLineBorder(ThemeMediator.CURRENT_THEME.getCustomUI().getDarkBorder())); //panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(GUIUtils.hexToColor("C8C8C8"), 1), // BorderFactory.createLineBorder(GUIUtils.hexToColor("FBFBFB"), 3))); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); com.limegroup.gnutella.gui.MultiLineLabel label1 = new com.limegroup.gnutella.gui.MultiLineLabel(text1, 400); label1.setFont(label1.getFont().deriveFont(16f)); label1.setForeground(GUIUtils.hexToColor("333333")); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 1; c.insets = new Insets(10, 10, 10, 10); panel.add(label1, c); com.limegroup.gnutella.gui.MultiLineLabel label2 = new com.limegroup.gnutella.gui.MultiLineLabel(text2, 400); label2.setFont(label2.getFont().deriveFont(16f)); label2.setForeground(GUIUtils.hexToColor("333333")); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 1; c.insets = new Insets(10, 10, 10, 10); panel.add(label2, c); com.limegroup.gnutella.gui.MultiLineLabel label3 = new com.limegroup.gnutella.gui.MultiLineLabel(I18n.tr("FrostWire is free software, "), 400); label3.setFont(label3.getFont().deriveFont(16f)); label3.setForeground(GUIUtils.hexToColor("333333")); c.anchor = GridBagConstraints.LINE_START; c.gridwidth = 1; c.weightx = 0; c.insets = new Insets(10, 10, 10, 0); panel.add(label3, c); URLLabel findMore = new URLLabel("http://www.frostwire.com/scams", I18n.tr("Do not pay for FrostWire.")); findMore.setFont(findMore.getFont().deriveFont(16f)); findMore.setForeground(GUIUtils.hexToColor("333333")); c.anchor = GridBagConstraints.LINE_START; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 1.0; panel.add(findMore, c); return panel; } } <file_sep>package com.frostwire.alexandria.db; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.frostwire.alexandria.InternetRadioStation; import com.frostwire.alexandria.Library; import com.frostwire.alexandria.Playlist; import com.frostwire.alexandria.PlaylistItem; public class LibraryDB extends ObjectDB<Library> { public LibraryDB(LibraryDatabase db) { super(db); } public void fill(Library obj) { // this is a special case, since we will have only one library per database List<List<Object>> result = db.query("SELECT libraryId, name, version FROM Library"); if (result.size() > 0) { List<Object> row = result.get(0); fill(row, obj); } } public void fill(List<Object> row, Library obj) { int id = (Integer) row.get(0); String name = (String) row.get(1); int version = (Integer) row.get(2); obj.setId(id); obj.setName(name); obj.setVersion(version); } public void save(Library obj) { // nothing } public void delete(Library obj) { // nothing } public List<Playlist> getPlaylists(Library library) { List<List<Object>> result = db.query("SELECT playlistId, name, description FROM Playlists"); List<Playlist> playlists = new ArrayList<Playlist>(result.size()); for (List<Object> row : result) { Playlist playlist = new Playlist(library); playlist.getDB().fill(row, playlist); playlists.add(playlist); } return playlists; } public Playlist getPlaylist(Library library, String name) { List<List<Object>> result = db.query("SELECT playlistId, name, description FROM Playlists WHERE name = ?", name); Playlist playlist = null; if (result.size() > 0) { List<Object> row = result.get(0); playlist = new Playlist(library); playlist.getDB().fill(row, playlist); } return playlist; } public List<InternetRadioStation> getInternetRadioStations(Library library) { List<List<Object>> result = db.query("SELECT internetRadioStationId, name, description, url, bitrate, type, website, genre, pls, bookmarked FROM InternetRadioStations"); List<InternetRadioStation> internetRadioStations = new ArrayList<InternetRadioStation>(result.size()); for (List<Object> row : result) { InternetRadioStation internetRadioStation = new InternetRadioStation(library); internetRadioStation.getDB().fill(row, internetRadioStation); internetRadioStations.add(internetRadioStation); } return internetRadioStations; } public Playlist getStarredPlaylist(Library library) { String query = "SELECT playlistItemId, filePath, fileName, fileSize, fileExtension, trackTitle, trackDurationInSecs, trackArtist, trackAlbum, coverArtPath, trackBitrate, trackComment, trackGenre, trackNumber, trackYear, starred " + "FROM PlaylistItems WHERE starred = ?"; List<List<Object>> result = db.query(query, true); Playlist playlist = new Playlist(library, LibraryDatabase.STARRED_PLAYLIST_ID, "starred", "starred"); List<PlaylistItem> items = new ArrayList<PlaylistItem>(result.size()); Set<String> paths = new HashSet<String>(); for (List<Object> row : result) { PlaylistItem item = new PlaylistItem(playlist); item.getDB().fill(row, item); if (!paths.contains(item.getFilePath())) { items.add(item); paths.add(item.getFilePath()); } } playlist.getItems().addAll(items); return playlist; } public void updatePlaylistItemProperties(String filePath, String title, String artist, String album, String comment, String genre, String track, String year) { Object[] sqlAndValues = createPlaylistItemPropertiesUpdate(filePath, title, artist, album, comment, genre, track, year); db.update((String) sqlAndValues[0], (Object[]) sqlAndValues[1]); } private Object[] createPlaylistItemPropertiesUpdate(String filePath, String title, String artist, String album, String comment, String genre, String track, String year) { String sql = "UPDATE PlaylistItems SET trackTitle = LEFT(?, 500), trackArtist = LEFT(?, 500), trackAlbum = LEFT(?, 500), trackComment = LEFT(?, 500), trackGenre = LEFT(?, 20), trackNumber = LEFT(?, 6), trackYear = LEFT(?, 6) WHERE filePath = LEFT(?, 10000)"; Object[] values = new Object[] { title, artist, album, comment, genre, track, year, filePath }; return new Object[] { sql, values }; } public long getTotalRadioStations(Library library) { List<List<Object>> query = db.query("SELECT COUNT(*) FROM InternetRadioStations"); return query.size() > 0 ? (Long) query.get(0).get(0) : 0; } public void restoreDefaultRadioStations(Library library) { List<InternetRadioStation> internetRadioStations = getInternetRadioStations(library); InternetRadioStationsData data = new InternetRadioStationsData(); for (InternetRadioStation station : internetRadioStations) { data.add(station.getName(), station.getDescription(), station.getUrl(), station.getBitrate(), station.getType(), station.getWebsite(), station.getGenre(), station.getPls()); } db.update("DELETE FROM InternetRadioStations"); for (List<Object> row : data.getData()) { db.update("INSERT INTO InternetRadioStations (name, description, url, bitrate, type, website, genre, pls, bookmarked) VALUES (LEFT(?, 10000), LEFT(?, 10000), LEFT(?, 10000), LEFT(?, 100), LEFT(?, 100), LEFT(?, 10000), LEFT(?, 10000), LEFT(?, 100000), false)", row.toArray()); } } } <file_sep>/* * Created by <NAME> (@gubatron), <NAME> (aldenml) * Copyright (c) 2011, 2012, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frostwire.gui.library; import java.io.File; import java.util.Map; import org.limewire.util.FilenameUtils; import org.limewire.util.StringUtils; import com.frostwire.gui.mplayer.MPlayer; import com.frostwire.mp3.ID3v2; import com.frostwire.mp3.Mp3File; /** * * @author gubatron * @author aldenml * */ public class AudioMetaData { private String title; private float durationInSecs; private String artist; private String album; private String bitrate; private String comment; private String genre; private String track; private String year; public AudioMetaData(File file) { readUsingMPlayer(file); if (file.getName().endsWith("mp3")) { readUsingMP3Tags(file); } sanitizeData(file); } public String getTitle() { return title; } public float getDurationInSecs() { return durationInSecs; } public String getArtist() { return artist; } public String getAlbum() { return album; } public String getBitrate() { return bitrate; } public String getComment() { return comment; } public String getGenre() { return genre; } public String getTrack() { return track; } public String getYear() { return year; } private void readUsingMPlayer(File file) { MPlayer mplayer = new MPlayer(); try { Map<String, String> properties = mplayer.getProperties(file.getAbsolutePath()); title = properties.get("Title"); durationInSecs = parseDurationInSecs(properties.get("ID_LENGTH")); artist = properties.get("Artist"); album = properties.get("Album"); bitrate = parseBitrate(properties.get("ID_AUDIO_BITRATE")); comment = properties.get("Comment"); genre = properties.get("Genre"); track = properties.get("Track"); year = properties.get("Year"); } finally { mplayer.dispose(); } } private void readUsingMP3Tags(File file) { try { Mp3File mp3 = new Mp3File(file.getAbsolutePath()); if (mp3.hasId3v2Tag()) { ID3v2 tag = mp3.getId3v2Tag(); if (!StringUtils.isNullOrEmpty(tag.getTitle(), true)) { title = tag.getTitle(); } if (!StringUtils.isNullOrEmpty(tag.getArtist(), true)) { artist = tag.getArtist(); } if (!StringUtils.isNullOrEmpty(tag.getAlbum(), true)) { album = tag.getAlbum(); } if (!StringUtils.isNullOrEmpty(tag.getComment(), true) || comment.startsWith("0")) { comment = tag.getComment(); } if (!StringUtils.isNullOrEmpty(tag.getGenreDescription(), true) || genre.trim().equals("Unknown")) { genre = tag.getGenreDescription(); } if (!StringUtils.isNullOrEmpty(tag.getTrack(), true)) { track = tag.getTrack(); } if (!StringUtils.isNullOrEmpty(tag.getYear(), true)) { year = tag.getYear(); } durationInSecs = mp3.getLengthInSeconds(); } } catch (Exception e) { // ignore } } private void sanitizeData(File file) { if (StringUtils.isNullOrEmpty(title, true)) { title = FilenameUtils.getBaseName(file.getAbsolutePath()); } if (durationInSecs < 0) { durationInSecs = 0; } if (artist == null) { artist = ""; } if (album == null) { album = ""; } if (bitrate == null) { bitrate = ""; } if (comment == null) { comment = ""; } if (genre == null) { genre = ""; } if (track == null) { track = ""; } else { int index = -1; index = track.indexOf('/'); if (index != -1) { track = track.substring(0, index); } } if (year == null) { year = ""; } } private String parseBitrate(String bitrate) { if (bitrate == null) { return ""; } try { return (Integer.parseInt(bitrate) / 1000) + " kbps"; } catch (Exception e) { return bitrate; } } public float parseDurationInSecs(String durationInSecs) { try { return Float.parseFloat(durationInSecs); } catch (Exception e) { return 0; } } } <file_sep>/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.limegroup.gnutella.gui.menu; import javax.swing.JMenuBar; import javax.swing.JPopupMenu; import com.limegroup.gnutella.gui.GUIMediator; import com.limegroup.gnutella.gui.I18n; /** * This class acts as a mediator among all of the various items of the * application's menus. */ public final class MenuMediator { /** * We call this so that the menu won't be covered by the SWT Browser. */ static { JPopupMenu.setDefaultLightWeightPopupEnabled(false); } /** * Constant handle to the instance of this class for following * the singleton pattern. */ private static MenuMediator INSTANCE; /** * Constant handle to the <tt>JMenuBar</tt> instance that holds all * of the <tt>JMenu</tt> instances. */ private final JMenuBar MENU_BAR = new JMenuBar(); /** * Constant handle to the single <tt>FileMenu</tt> instance for * the application. */ private final FileMenu FILE_MENU = new FileMenu(); /** * Constant handle to the single <tt>ToolsMenu</tt> instance for * the application. */ private final Menu TOOLS_MENU = new ToolsMenu(); /** * Constant handle to the single <tt>HelpMenu</tt> instance for * the application. */ private final Menu HELP_MENU = new HelpMenu(); /** * Constant handle to the single <tt>ViewMenu</tt> instance for * the application. */ private final Menu VIEW_MENU = new ViewMenu("VIEW"); /** * Singleton accessor method for obtaining the <tt>MenuMediator</tt> * instance. * * @return the <tt>MenuMediator</tt> instance */ public static final MenuMediator instance() { if (INSTANCE == null) { INSTANCE = new MenuMediator(); } return INSTANCE; } /** * Private constructor that ensures that a <tt>MenuMediator</tt> * cannot be constructed from outside this class. It adds all of * the menus. */ private MenuMediator() { GUIMediator.setSplashScreenString(I18n.tr("Loading Menus...")); MENU_BAR.setFont(AbstractMenu.FONT); addMenu(FILE_MENU); addMenu(VIEW_MENU); addMenu(TOOLS_MENU); addMenu(HELP_MENU); } /** * Returns the <tt>JMenuBar</tt> for the application. * * @return the application's <tt>JMenuBar</tt> instance */ public JMenuBar getMenuBar() { return MENU_BAR; } /** * Adds a <tt>Menu</tt> to the next position on the menu bar. * * @param menu to the <tt>Menu</tt> instance that allows access to * its wrapped <tt>JMenu</tt> instance */ private void addMenu(Menu menu) { MENU_BAR.add(menu.getMenu()); } /** * Returns the height of the main menu bar. * * @return the height of the main menu bar */ public int getMenuBarHeight() { return MENU_BAR.getHeight(); } } <file_sep>/* * Created by <NAME> (@gubatron), <NAME> (aldenml) * Copyright (c) 2011, 2012, FrostWire(TM). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frostwire.gui.library; import org.limewire.util.StringUtils; class PlaylistItemProperty implements Comparable<PlaylistItemProperty> { private final String value; private final boolean playing; private final boolean exists; private final int columnIndex; public PlaylistItemProperty(String value, boolean playing, boolean exists, int columnIndex) { this.value = value; this.playing = playing; this.exists = exists; this.columnIndex = columnIndex; } public String getValue() { return value; } public boolean isPlaying() { return playing; } public boolean exists() { return exists; } public int compareTo(PlaylistItemProperty o) { if ((o == null || o.value == null) && value != null) { return 1; } else if (value == null && o!=null) { return -1; } else if (value == null && o==null) { return 0; } //bitrates come in strings, we only care about the numerical portion //since all of them are in KBPS. if (columnIndex == LibraryPlaylistsTableDataLine.BITRATE_IDX) { return compareByBitrate(o); } else if (columnIndex == LibraryPlaylistsTableDataLine.TRACK_IDX) { return compareByTrack(o); } return value.compareTo(o.value); } private int compareByBitrate(PlaylistItemProperty o) { if (StringUtils.isNullOrEmpty(value) && !StringUtils.isNullOrEmpty(o.value)) { return 1; } else if (!StringUtils.isNullOrEmpty(value) && StringUtils.isNullOrEmpty(o.value)) { return -1; } else if (StringUtils.isNullOrEmpty(value) && StringUtils.isNullOrEmpty(o.value)) { return 0; } try { return Integer.valueOf(value.toLowerCase().replace("kbps", "").trim()).compareTo(Integer.valueOf(o.value.toLowerCase().replace("kbps", "").trim())); } catch (Exception e) { return 0; } } private int compareByTrack(PlaylistItemProperty o) { if (StringUtils.isNullOrEmpty(value) && !StringUtils.isNullOrEmpty(o.value)) { return 1; } else if (!StringUtils.isNullOrEmpty(value) && StringUtils.isNullOrEmpty(o.value)) { return -1; } else if (StringUtils.isNullOrEmpty(value) && StringUtils.isNullOrEmpty(o.value)) { return 0; } try { return Integer.valueOf(value.toLowerCase().trim().replaceFirst("^0+(?!$)", "")).compareTo(Integer.valueOf(o.value.toLowerCase().trim().replaceFirst("^0+(?!$)", ""))); } catch (Exception e) { return 0; } } } <file_sep>package com.limegroup.gnutella.gui; import java.awt.GraphicsConfiguration; import java.awt.HeadlessException; import javax.swing.JDialog; public class FramedDialog extends LimeJFrame { /** * */ private static final long serialVersionUID = 171366776903869143L; private final JDialog dialog = new JDialog(this); public FramedDialog() throws HeadlessException { super(); initialize(); } public FramedDialog(GraphicsConfiguration arg0) { super(arg0); initialize(); } public FramedDialog(String arg0, GraphicsConfiguration arg1) { super(arg0, arg1); initialize(); } public FramedDialog(String arg0) throws HeadlessException { super(arg0); initialize(); } private void initialize() { setUndecorated(true); setSize(0, 0); } public void showDialog() { toFront(); setVisible(true); dialog.toFront(); dialog.setVisible(true); dispose(); } public JDialog getDialog() { return dialog; } }
722ac58da424189d533d28e16880149ef20c44ac
[ "Java" ]
10
Java
paradise666/frostwire-desktop
a4c240c9430af75cd23f06c6f504dce54d564d82
40fd93dda93a98d3307445bbf19222cc3bcbbde9
refs/heads/master
<repo_name>Sabbotage-cmd/JavaHomeworkJUnit1.2Postman<file_sep>/settings.gradle rootProject.name = 'Unit2.3' <file_sep>/README.md [![Build status](https://ci.appveyor.com/api/projects/status/jbjscj811muabd4n?svg=true)](https://ci.appveyor.com/project/Sabbotage-cmd/javahomeworkjunit1-2postman) <file_sep>/src/test/java/ru/netology/RestTest.java package ru.netology; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; public class RestTest { @Test public void shouldCheckDataValue() { given() .baseUri("https://postman-echo.com") .body("some data") .when() .post("/post") .then() .statusCode(200) .body("data", is("some data")); } @Test public void shouldCheckHostValue() { given() .baseUri("https://postman-echo.com") .body("some data") .when() .post("/post") .then() .statusCode(200) .body("headers.host", is("postman-echo.com")); } @Test public void shouldCheckJsonIsNull() { given() .baseUri("https://postman-echo.com") .body("some data") .when() .post("/post") .then() .statusCode(200) .body("json", is(nullValue())); } @Test public void shouldCheckFilesIsEmpty() { given() .baseUri("https://postman-echo.com") .body("some data") .when() .post("/post") .then() .statusCode(200) .body("files", is(anEmptyMap())); } }
bdc31cb07e7c26835847aa5c11817e29c63a8384
[ "Markdown", "Java", "Gradle" ]
3
Gradle
Sabbotage-cmd/JavaHomeworkJUnit1.2Postman
23ed8617f9d44854a6668793f812c9c8c2e5dfd1
a0a61f855f24576b65700c52434b3643152cff3c
refs/heads/master
<file_sep><?php namespace App\Repositories; use App\Repositories\ClientRepositoryInterface; use App\Models\Clients; use Illuminate\Http\Request; class ClientRepositoryEloquente implements ClientRepositoryInterface { private $model; public function __construct(Clients $clients) { $this->model = $clients; } public function getAll() { return $this->model->all(); } public function get($id) { return $this->model->find($id); } public function create(Request $request) { return $this->model->create($request->all()); } public function update($id, Request $request) { $client = $this->model->find($id); return (!empty($client->id)) ? $client->update($request->all()) : 0; } public function delete($id) { $client = $this->model->find($id); return (!empty($client) ? $client->delete() : null); } } <file_sep><?php namespace App\Services; use App\Exceptions\ValidationException; use App\Repositories\PastryRepositoryInterface; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Models\Validation\Pastry as ValidationPastry; class PastryService { private $repository; public function __construct(PastryRepositoryInterface $repository) { $this->repository = $repository; } public function getAll() { $pastries = $this->repository->getAll(); return (count($pastries) > 0) ? $pastries : []; } public function get($id) { $pastry = $this->repository->get($id); return (!empty($pastry->id)) ? $pastry : []; } public function store(Request $request) { $validator = Validator::make( $request->all(), ValidationPastry::RULES ); if ($validator->fails()) { throw new ValidationException("Error Processing Request", $validator->errors()); } return $this->repository->create($request); } public function update($id, Request $request) { $validator = Validator::make( $request->all(), ValidationPastry::RULES ); if ($validator->fails()) { throw new ValidationException("Error Processing Request", $validator->errors()); } return $this->repository->update($id, $request); } public function delete($id) { return $this->repository->delete($id); } } <file_sep><?php namespace App\Http\Controllers; use illuminate\http\Request; class OrdersController extends Controller { /** * Create a new controller instance. * @return void */ public function __construct() { // } public function get($client_id) { } public function store($client_id, Request $request) { } public function update($client_id, Request $request) { } public function delete($client_id) { } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Clients extends Model { use SoftDeletes; protected $table = 'clients'; protected $fillable = [ 'name', 'email', 'phone', 'birthday', 'address', 'complement', 'district', 'zipcode' ]; protected $casts = [ 'birthday' => 'Timestamp' ]; } <file_sep><?php namespace App\Models\Validation; class Order { const RULES = [ 'client_id' => 'required|exists:clients,id', 'pastry_id' => 'required|exists:pastries,id', 'quantity' => 'required|integer|gte:0' ]; } <file_sep># Pastelaria API RESTFul para o gerenciamento de pedidos de uma pastelaria utilizando o framework Laravel/Lúmen. Back-end Challenge - Doc88 ## Documentação Faça o dowload do arquivo zip ou adicione o repositório através do git git remote add origin https://github.com/alegneto/pastry-shop.git git push -u origin master Acesse o diretorio através de terminal e utilizando o composer, digite o seginte comando: composer install ## Banco de dados O projeto foi desenvolvido utilizando MySQL Criar database mysql > CREATE DATABASE pastry_shop Copiar o arquivo .env.exemple e renomear para .env Altere as informações de usuário e senha do bando de dados configurados em seu database No diretório da aplicação executar os seguintes comandos no terminal php artisan migrate php artisan db:seed ## Aplicação Para executar a aplicação, ainda dentro do terminal, executar o seguinte comando php -S localhost:8000 -t public ## API ## Licença [MIT license](https://opensource.org/licenses/MIT). <file_sep><?php namespace App\Services; use App\Exceptions\ValidationException; use App\Repositories\ClientRepositoryInterface; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Models\Validation\Client as ValidationClient; class ClientService { private $repository; public function __construct(ClientRepositoryInterface $repository) { $this->repository = $repository; } public function getAll() { $clients = $this->repository->getAll(); return (count($clients) > 0) ? $clients : []; } public function get($id) { $client = $this->repository->get($id); return (!empty($client->id)) ? $client : []; } public function store(Request $request) { $validator = Validator::make( $request->all(), ValidationClient::RULES ); if ($validator->fails()) { throw new ValidationException("Error Processing Request", $validator->errors()); } return $this->repository->create($request); } public function update($id, Request $request) { $validator = Validator::make( $request->all(), ValidationClient::RULES ); if ($validator->fails()) { throw new ValidationException("Error Processing Request", $validator->errors()); } return $this->repository->update($id, $request); } public function delete($id) { return $this->repository->delete($id); } } <file_sep><?php namespace App\Repositories; use App\Repositories\PastryRepositoryInterface; use App\Models\Pastries; use Illuminate\Http\Request; class PastryRepositoryEloquente implements PastryRepositoryInterface { private $model; public function __construct(Pastries $pastries) { $this->model = $pastries; } public function getAll() { return $this->model->all(); } public function get($id) { return $this->model->find($id); } public function create(Request $request) { return $this->model->create($request->all()); } public function update($id, Request $request) { $pastry = $this->model->find($id); return (!empty($pastry->id)) ? $pastry->update($request->all()) : 0; } public function delete($id) { $pastry = $this->model->find($id); return (!empty($pastry) ? $pastry->delete() : null); } } <file_sep><?php namespace App\Models\Validation; use Illuminate\Http\Request; class Client { const RULES = [ 'name' => 'required|max:120', 'email' => 'required|email|unique:clients,email', 'phone' => 'required|digits_between:10,11', 'birthday' => 'required|date_format: "Y-m-d"', 'address' => 'required|max:250', 'complement' => 'max:50', 'district' => 'required|max:100', 'zipcode' => 'required|digits:8' ]; } <file_sep><?php namespace App\Http\Controllers; use App\Exceptions\ValidationException; use App\Services\PastryService; use Illuminate\Http\Request; use Illuminate\Http\Response; class PastriesController extends Controller { private $service; /** * Create a new controller instance. * @return void */ public function __construct(PastryService $service) { $this->service = $service; } public function getAll() { try { return response()->json($this->service->getAll(), Response::HTTP_OK); } catch (\Exception $e) { return $this->error($e->getMessage()); } } public function get($id) { try { return response()->json($this->service->get($id), Response::HTTP_OK); } catch (\Exception $e) { return $this->error($e->getMessage()); } } public function store(Request $request) { try { return response()->json($this->service->store($request), Response::HTTP_CREATED); } catch (ValidationException $e) { return $this->error($e->getMessage(), Response::HTTP_BAD_REQUEST, $e->getDetails()); } catch (\Exception $e) { return $this->error($e->getMessage()); } } public function update($id, Request $request) { try { return response()->json($this->service->update($id, $request), Response::HTTP_OK); } catch (ValidationException $e) { return $this->error($e->getMessage(), Response::HTTP_BAD_REQUEST, $e->getDetails()); } catch (\Exception $e) { return $this->error($e->getMessage()); } } public function delete($id) { try { return response()->json($this->service->delete($id), Response::HTTP_OK); } catch (\Exception $e) { return $this->error($e->getMessage()); } } } <file_sep><?php namespace App\Models\Validation; class Pastry { const RULES = [ 'name' => 'required|max:100', 'price' => 'required|numeric', 'picture' => 'required|ends_with:png|max:50' ]; } <file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class PastriesSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('pastries')->insert([ 'name' => 'Queijo', 'price' => 5.50, 'picture' => 'pastel-queijo.png', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ]); DB::table('pastries')->insert([ 'name' => 'Carne', 'price' => 4.50, 'picture' => 'pastel-carne.png', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ]); DB::table('pastries')->insert([ 'name' => 'Pizza', 'price' => 5.50, 'picture' => 'pastel-pizza.png', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ]); DB::table('pastries')->insert([ 'name' => '<NAME>', 'price' => 6.50, 'picture' => 'pastel-frango-catupiry.png', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ]); DB::table('pastries')->insert([ 'name' => 'Camarão', 'price' => 7.50, 'picture' => 'pastel-camarao.png', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ]); DB::table('pastries')->insert([ 'name' => 'Palmito', 'price' => 6.00, 'picture' => 'pastel-palmito.png', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ]); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It is a breeze. Simply tell Lumen the URIs it should respond to | and give it the Closure to call when that URI is requested. | */ $router->get('/', function () use ($router) { return $router->app->version(); }); $router->get('/app/pastries', 'PastriesController@getAll'); $router->group(['prefix' => '/app/pastry'], function() use ($router) { $router->get('/{id}', "PastriesController@get"); $router->post('/', "PastriesController@store"); $router->put('/{id}', "PastriesController@update"); $router->delete('/{id}', "PastriesController@delete"); }); $router->get('/app/clients', 'ClientsController@getAll'); $router->group(['prefix' => '/app/client'], function() use ($router) { $router->get('/{id}', "ClientsController@get"); $router->post('/', "ClientsController@store"); $router->put('/{id}', "ClientsController@update"); $router->delete('/{id}', "ClientsController@delete"); }); $router->group(['prefix' => '/app/order'], function() use ($router) { $router->get('/{client_id}', 'OrdersController@get'); $router->post('/{client_id}', 'OrdersController@store'); $router->put('/{client_id}/{pastry_id}', 'OrdersController@update'); $router->delete('/{client_id}/{pastry_id}', 'OrdersController@delete'); }); $router->get('/app/checkout/{client_id}', 'CheckoutController@checkout');
1a2f1d7d922e5c3e45fc60af90a9069221085240
[ "Markdown", "PHP" ]
13
PHP
alegneto/pastry-shop
3b15762a438e244f11f784dbcf9b7b6e887e715d
4aefff463e9e10709e92e77fc98554ede44465b2
refs/heads/master
<repo_name>reneklacan/autohop<file_sep>/install.sh #!/bin/bash source=' h() { result=`autohop $@`; if [ $? -eq 0 ]; then cd $result; else echo $result; fi } ' echo $source >> ~/.zshrc
e9482ba677636fc89f57a700b911241822e25823
[ "Shell" ]
1
Shell
reneklacan/autohop
c239b31d370511fd98f2e480572d4b0ec1eeb6c5
4d178f4215efb1332c2aa16f3117f55e44bdae30
refs/heads/main
<repo_name>BW-Water-My-Plants2/front-end1<file_sep>/src/components/PlantContainer.js import React, { useEffect } from 'react' import { useHistory } from 'react-router-dom' import { connect } from 'react-redux' import { deletePlant, fetchData, startEdit } from '../actions/index' import PlantCard from "./PlantCard" const PlantContainer = ({ plants, fetchData, deletePlant, startEdit }) => { const { push } = useHistory(); useEffect(() => { fetchData() }, []) const editFunc = (plant) => { push(`/plant-form`) startEdit(plant) } const deleteFunc = (e) => { deletePlant(e.target.value) fetchData() } return ( <div> {plants && plants.map(plant => <PlantCard plant={plant} editFunc={editFunc} deletePlant={deleteFunc} /> )} </div> ) } const mapStateToProps = state => { return { plants: state.crud.plants } } export default connect(mapStateToProps, { deletePlant, fetchData, startEdit })(PlantContainer);<file_sep>/src/components/PlantCard.js import React from 'react' const PlantCard = ({ plant, editFunc, deleteFunc }) => { return ( <div className="Card" > <button onClick={() => editFunc(plant)}>Edit</button> <button onClick={deleteFunc}>X</button> <h3>{plant.plant_name}</h3> <p>{plant.plant_species}</p> </div> ) } export default PlantCard<file_sep>/src/actions/index.js import AxiosWithAuth from '../utils/AxiosWithAuth' import axios from 'axios' export const FETCHING_START = 'FETCHING_START' export const FETCHING_FAIL = 'FETCHING_FAIL' export const FETCHING_SUCCESS = 'FETCHING_SUCCESS' export const ADD_POST = 'ADD_POST' export const EDIT_POST = 'EDIT_POST' export const DELETE_POST = 'DELETE_POST' export const fetchData = () => dispatch => { dispatch({ type: FETCHING_START }) console.log('fetch in action') AxiosWithAuth() .get('/plants/') .then(res => dispatch({ type: FETCHING_SUCCESS, payload: res.data })) .catch(err => console.log(err), dispatch({ type: FETCHING_FAIL })) } export const addPlant = newPost => { // console.log('addPost in action',newPost) AxiosWithAuth() .post('/plants/', newPost) .then(res => console.log('post res in actions', res)) .catch(err => console.log('err in action add-', err)) return { type: ADD_POST, payload: newPost } } export const editPlant = (id, updated) => { console.log('editing in actions editPost:id and updated', id, updated) AxiosWithAuth() .put(`/plants/${id}`, updated) .then(res => console.log('post res in actions', res)) .catch(err => console.log('err in action add-', err)) return { type: EDIT_POST, payload: updated } } export const deletePlant = id => { // console.log('delete in action deletePost',id) AxiosWithAuth() .delete(`/plants/${id}`) .then(res => console.log('post res in actions', res)) .catch(err => console.log('err in action add-', err)) return { type: DELETE_POST, payload: id } } export const START_EDIT = "START_EDIT" export const startEdit = plant => { return { type: START_EDIT, payload: plant } } <file_sep>/src/App.js import React, { useState } from "react"; import NavigationBar from "./components/NavigationBar.js"; import { Route, Link, Switch } from "react-router-dom"; import PrivateRoute from './utils/PrivateRoute' import Signup from "./components/Signup.js"; import Login from "./components/Login.js"; import Dashboard from './components/PlantContainer' import PlantForm from './components/PlantForm' import "./app.css"; import "./index.css"; function App() { return ( <div className="App"> <NavigationBar /> <Switch> <Route path="/login"> <Login /> </Route> <Route path="/signup"> <Signup /> </Route> <PrivateRoute path="/dashboard"> <Dashboard /> </PrivateRoute> <PrivateRoute path="/plant-form"> <PlantForm /> </PrivateRoute> </Switch> </div> ); } export default App; <file_sep>/src/reducers/index.js import { combineReducers } from 'redux' import authReducer from './authReducer' import crudReducer from './crudReducer' export const reducer = combineReducers({ auth: authReducer, crud: crudReducer }) <file_sep>/src/reducers/crudReducer.js import { ADD_POST, DELETE_POST, EDIT_POST, FETCHING_START, FETCHING_SUCCESS, FETCHING_FAIL, START_EDIT } from "../actions"; const initialState = { plants: [], isFetching: false, fetchErr: "", editing: false, plant: { "plant_name": "", "plant_species": "", "water_schedule": "" } }; const reducer = (state = initialState, action) => { switch (action.type) { case FETCHING_START: return { ...state, isFetching: true, fetchingErr: '' }; case FETCHING_SUCCESS: console.log('fetchingSucces action.payload', action.payload) return { ...state, plants: action.payload, isFetching: false, fetchingErr: '' }; case FETCHING_FAIL: console.log("error") return { ...state, isFetching: false, fetchingErr: 'Fetching error' }; case ADD_POST: // console.log("ADDPost in reducer") // console.log("payload",action.payload) return { ...state, plants: [...state.plants, action.payload] }; case EDIT_POST: console.log("action.payload - EDIT_POST reducer", action.payload); console.log("state.plants", state.plants); return { ...state, editing: false, plant: { "plant_name": "", "plant_species": "", "water_schedule": "" } }; case DELETE_POST: // console.log('action.payload - DELETE_POST reducer', action.payload) // console.log('looking for state id', state.plants) return { ...state, plants: [...state.plants.filter((post) => post.id != action.payload)], }; case START_EDIT: return { ...state, editing: true, plant: action.payload } } return state; }; export default reducer
b7a20a33554e665f25d3c66daf689583db133866
[ "JavaScript" ]
6
JavaScript
BW-Water-My-Plants2/front-end1
2e4d188fcf33083a2df49b43f58f910c9b83d432
8e62516a26683f52313e23645951894985ee7814
refs/heads/master
<file_sep>const Manager = require("./lib/Manager"); const Engineer = require("./lib/Engineer"); const Intern = require("./lib/Intern"); const inquirer = require("inquirer"); const path = require("path"); const fs = require("fs"); const OUTPUT_DIR = path.resolve(__dirname, "output"); const outputPath = path.join(OUTPUT_DIR, "team.html"); const render = require("./lib/htmlRenderer"); const employeeArray = []; // Write code to use inquirer to gather information about the development team members, // and to create objects for each team member (using the correct classes as blueprints!) // prompting the user to gather information about the manager and team members (inquirer) // starting with the manager prompt managerPrompt(); function managerPrompt() { inquirer .prompt([ { type: "input", name: "managerName", message: "What's your Manager's name?", }, { type: "input", name: "managerId", message: "What's your Manager's ID number?", }, { type: "input", name: "managerEmail", message: "What's your Manager's email address?", }, { type: "input", name: "managerOfficeNumber", message: "What's your Manager's office number?", }, { type: "list", name: "teamMember", message: "Which team member(s) would you like to add?", choices: ["Engineer", "Intern"], }, ]) .then(function (response) { const newManager = new Manager( response.managerName, response.managerId, response.managerEmail, response.managerOfficeNumber ); employeeArray.push(newManager); // using conditionals to select the first team member if (response.teamMember === "Engineer") { console.log("selected an Engineer!"); engineerPrompt(); } else if (response.teamMember === "Intern") { console.log("Selected an Intern!"); internPrompt(); } }) .catch((error) => { if (error) throw error; }); } // this holds the engineer prompt function engineerPrompt() { inquirer .prompt([ { type: "input", name: "engineerName", message: "What's your Engineer's name?", }, { type: "input", name: "engineerId", message: "What's your Engineer's ID number?", }, { type: "input", name: "engineerEmail", message: "What's your Engineer's email address?", }, { type: "input", name: "engineerGithub", message: "What's your Engineer's GitHub username?", }, ]) .then(function (response) { console.log(response); const newEngineer = new Engineer( response.engineerName, response.engineerId, response.engineerEmail, response.engineerGithub ); employeeArray.push(newEngineer); stopPrompt(); }) .catch((error) => { if (error) throw error; }); } // this holds the intern prompt function internPrompt() { inquirer .prompt([ { type: "input", name: "internName", message: "What's your Intern's name?", }, { type: "input", name: "internId", message: "What's your Intern's ID number?", }, { type: "input", name: "internEmail", message: "What's your Intern's email address?", }, { type: "input", name: "internSchool", message: "What school does your Intern attend?", }, ]) .then(function (response) { console.log(response); const newIntern = new Intern( response.internName, response.internId, response.internEmail, response.internSchool ); employeeArray.push(newIntern); stopPrompt(); }) .catch((error) => { if (error) throw error; }); } // the is the add member function that asks the user after the second member selection function addMemberPrompt() { inquirer .prompt({ type: "list", name: "teamMember", message: "Which team member(s) would you like to add?", choices: ["Engineer", "Intern"], }) .then(function (response) { if (response.teamMember === "Engineer") { console.log("You picked another Engineer"); engineerPrompt(); } else if (response.teamMember === "Intern") { console.log("You picked another Intern"); internPrompt(); } }) .catch(function (err) { if (err) throw err; }); } // the stop function will ask the user if he or she wishes to continue building the team or is done // when true - user is taken to the add member prompt // when false - input is stored and html file is created through the render function function stopPrompt() { inquirer .prompt({ type: "confirm", name: "stop", message: "Would you like to add another team member?", }) .then(function (result) { console.log(result); if (result.stop === true) { addMemberPrompt(); } else { console.log("We're done here pal"); console.log(employeeArray); render(employeeArray); let returnedHTML = render(employeeArray); console.log(returnedHTML); fs.writeFile(outputPath, returnedHTML, function (err) { if (err) throw err; console.log("Your new file has been created!"); }); } }) .catch(function (err) { if (err) throw err; }); } // After the user has input all employees desired, call the `render` function (required // above) and pass in an array containing all employee objects; the `render` function will // generate and return a block of HTML including templated divs for each employee! // After you have your html, you're now ready to create an HTML file using the HTML // returned from the `render` function. Now write it to a file named `team.html` in the // `output` folder. You can use the variable `outputPath` above target this location. // Hint: you may need to check if the `output` folder exists and create it if it // does not. // HINT: each employee type (manager, engineer, or intern) has slightly different // information; write your code to ask different questions via inquirer depending on // employee type. // HINT: make sure to build out your classes first! Remember that your Manager, Engineer, // and Intern classes should all extend from a class named Employee; see the directions // for further information. Be sure to test out each class and verify it generates an // object with the correct structure and methods. This structure will be crucial in order // for the provided `render` function to work! ```
9c67c99d0f11bbaf87a5a37738aeaab31670374c
[ "JavaScript" ]
1
JavaScript
CodyBonsma/employee-template-engine
dd1c7d7d7522c6f83c1921fe30f7536f83d9ba1c
020af31a247c5d82df4133d3c360bebd2619515f
refs/heads/master
<file_sep>package com.jeecg.pro.equipment.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.jeecgframework.core.common.service.impl.CommonServiceImpl; import org.springframework.stereotype.Service; import com.jeecg.pro.equipment.entity.DeviceInvEntity; import com.jeecg.pro.equipment.entity.StockCheckEntity; import com.jeecg.pro.equipment.service.IStockCheckService; @Service("stockCheckServiceImpl") public class StockCheckServiceImpl extends CommonServiceImpl implements IStockCheckService { @Override public List<StockCheckEntity> createNewInfo(String storeId) { //根据storeId获取该仓库的设备库存信息 List<DeviceInvEntity> deviceInvs = this.commonDao.findByProperty(DeviceInvEntity.class, "store.id", storeId); if(deviceInvs != null && deviceInvs.size() >= 0) { List<StockCheckEntity> stockChecks = new ArrayList<StockCheckEntity>(); //获取已经盘点的最大盘点编号 String stockMaxNo = this.getMaxStockNo(); //获取盘点编号 String stockNo = this.getStockNo(); if(StringUtils.isEmpty(stockMaxNo)) { for(DeviceInvEntity deviceInv : deviceInvs) { StockCheckEntity stockCheck = new StockCheckEntity(); stockCheck.setId(UUID.randomUUID().toString()); stockCheck.setStockCheckNo(stockNo); stockCheck.setDeviceInv(deviceInv); stockChecks.add(stockCheck); } } else { List<StockCheckEntity> queryStocks = this.commonDao.findByProperty(StockCheckEntity.class, "stockCheckNo", stockMaxNo); Map<String, StockCheckEntity> stockMap = this.constructMap(queryStocks); for(DeviceInvEntity deviceInv : deviceInvs) { String deviceId = deviceInv.getId(); if(stockMap.containsKey(deviceId)) { StockCheckEntity stock = stockMap.get(deviceId); //必须要有这个临时对象不然的话,在原有查询出来的记录上修改,会直接改掉数据库,应该是个bug StockCheckEntity tmp = new StockCheckEntity(); tmp.setId(UUID.randomUUID().toString()); tmp.setDeviceInv(stock.getDeviceInv()); tmp.setStockCheckNo(stockNo); tmp.setOpenInvCount(stock.getCloseInvCount()); tmp.setCloseInvCount(null); tmp.setProfitCount(null); tmp.setLossPrice(null); tmp.setLossCount(null); tmp.setLossPrice(null); stockChecks.add(tmp); } else { StockCheckEntity stock = new StockCheckEntity(); stock.setId(UUID.randomUUID().toString()); stock.setDeviceInv(deviceInv); stock.setStockCheckNo(stockNo); stock.setOpenInvCount(0); stockChecks.add(stock); } } } return stockChecks; } return new ArrayList<StockCheckEntity>(); } private Map<String, StockCheckEntity> constructMap(List<StockCheckEntity> stocks) { Map<String, StockCheckEntity> result = new HashMap<String, StockCheckEntity>(); for(StockCheckEntity stock : stocks) { String devInvId = stock.getDeviceInv().getId(); result.put(devInvId, stock); } return result; } @Override public String getStockNo() { // TODO Auto-generated method stub String stockNo = ""; Map<String, Object> result = this.commonDao.findOneForJdbc("select max(stockCheckNo) as stockCheckNo from tbl_stockCheck", null); if(result.get("stockCheckNo") == null) { stockNo = "PDNO.0000001"; } else { stockNo = result.get("stockCheckNo").toString(); stockNo = stockNo.replaceAll("PDNO.", ""); long tmp = Long.parseLong(stockNo); tmp = tmp + 1; stockNo = "PDNO." + String.format("%07d", tmp); } return stockNo; } @Override public String getMaxStockNo() { String stockNo = ""; Map<String, Object> result = this.commonDao.findOneForJdbc("select max(stockCheckNo) as stockCheckNo from tbl_stockCheck", null); if(result.get("stockCheckNo") == null) { stockNo = ""; } else { stockNo = result.get("stockCheckNo").toString(); } return stockNo; } } <file_sep>package com.jeecg.pro.equipment.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.jeecgframework.core.common.entity.IdEntity; @Entity @Table(name="tbl_storage_doc") public class StorageDocEntity extends IdEntity { /** * 入库单号 */ private String storageDocNo; /** * 入库类型 */ private String storageType; /** * 仓库信息 */ private StoreEntity store; /** * 入库人 */ private String userName; /** * 审核人员 */ private String reviewer; /** * 入库状态 */ private String status; /** * 创建时间 */ private Date createDate; /** * 创建人 */ private String createOperator; @Column(name ="storageDocNo", nullable=false, length=15) public String getStorageDocNo() { return storageDocNo; } public void setStorageDocNo(String storageDocNo) { this.storageDocNo = storageDocNo; } @Column(name="storageType") public String getStorageType() { return storageType; } public void setStorageType(String storageType) { this.storageType = storageType; } @Column(name="userName") public String getUserName() { return userName; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="storeId") public StoreEntity getStore() { return store; } public void setStore(StoreEntity store) { this.store = store; } public void setUserName(String userName) { this.userName = userName; } @Column(name="reviewer") public String getReviewer() { return reviewer; } public void setReviewer(String reviewer) { this.reviewer = reviewer; } @Column(name="createOperator") public String getCreateOperator() { return createOperator; } public void setCreateOperator(String createOperator) { this.createOperator = createOperator; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Temporal(TemporalType.DATE) @Column(name="Date") public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } } <file_sep>package com.jeecg.pro.equipment.service; import org.jeecgframework.core.common.service.CommonService; public interface IDeviceService extends CommonService { /** * 获取设备编号 * @return */ public String getDeviceCode(); } <file_sep>package com.jeecg.pro.equipment.controller; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.tag.core.easyui.TagUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jeecg.pro.equipment.entity.DeviceEntity; import com.jeecg.pro.equipment.entity.ExitDocEntity; import com.jeecg.pro.equipment.service.IExitDocService; @Controller @RequestMapping("exitDoc") public class ExitDocController extends BaseController { @Resource(name="exitDocServiceImpl") private IExitDocService exitDocServiceImpl; @RequestMapping(params="list") public ModelAndView getList() { ModelAndView result = new ModelAndView("equipment/exitDoc/exitDocList"); result.getModel().put("exitDocNo", getNum()); return result; } @RequestMapping(params="datagrid") public void datagrid(DeviceEntity device, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { System.out.println("ddd"); // CriteriaQuery cq = new CriteriaQuery(DeviceEntity.class, dataGrid); // //查询条件组装器 // org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, device); // cq.add(); // this.exitDocServiceImpl.getDataGridReturn(cq, true); dataGrid.setResults(new ArrayList<>()); TagUtil.datagrid(response, dataGrid); } @RequestMapping(params="add") public ModelAndView add(HttpServletRequest req){ ModelAndView reuslt = new ModelAndView("equipment/exitDocDetail/exitDocDetailList"); return reuslt; } @RequestMapping(params="addorupdate") public ModelAndView addorupdate(ExitDocEntity exitDoc, HttpServletRequest req) { //获取入库单号 String exitDocNo = this.exitDocServiceImpl.getExitDocNo(); ModelAndView reuslt = new ModelAndView("equipment/exitDocDetail/exitDocDetailList"); reuslt.getModel().put("exitDocNo", exitDocNo); return reuslt; } @RequestMapping(params="deleteExitDoc") @ResponseBody public AjaxJson deleteExitDoc(ExitDocEntity exitDoc, HttpServletRequest req) { AjaxJson result = new AjaxJson(); // String exitDocId = exitDoc.getId(); // // List<ExitDocDetailEntity> exitDocDetails = this.exitDocServiceImpl.findByProperty(ExitDocDetailEntity.class, "exitDoc.id", exitDocId); // if(exitDocDetails != null && exitDocDetails.size() > 0) // { // for(ExitDocDetailEntity exitDocDetail : exitDocDetails) // { // String exitDocDetailId = exitDocDetail.getId(); // List<ExitDeviceEntity> exitDevices = this.exitDocServiceImpl.findByProperty(ExitDeviceEntity.class, "exitDocDetail.id", exitDocDetailId); // if(exitDevices != null && exitDevices.size() > 0) // { // this.exitDocServiceImpl.deleteAllEntitie(exitDevices); // } // } // // this.exitDocServiceImpl.deleteAllEntitie(exitDocDetails); // } // // this.exitDocServiceImpl.delete(exitDoc); return result; } @RequestMapping(params="deleteBatch") @ResponseBody public AjaxJson deleteBatch(String ids, HttpServletRequest req) { AjaxJson result = new AjaxJson(); // String exitDocIds[] = ids.split(","); // for(String exitDocId : exitDocIds) // { // ExitDocEntity exitDoc = new ExitDocEntity(); // exitDoc.setId(exitDocId); // // List<ExitDocDetailEntity> exitDocDetails = this.exitDocServiceImpl.findByProperty(ExitDocDetailEntity.class, "exitDoc.id", exitDocId); // if(exitDocDetails != null && exitDocDetails.size() > 0) // { // for(ExitDocDetailEntity exitDocDetail : exitDocDetails) // { // String exitDocDetailId = exitDocDetail.getId(); // List<ExitDeviceEntity> exitDevices = this.exitDocServiceImpl.findByProperty(ExitDeviceEntity.class, "exitDocDetail.id", exitDocDetailId); // if(exitDevices != null && exitDevices.size() > 0) // { // this.exitDocServiceImpl.deleteAllEntitie(exitDevices); // } // } // // this.exitDocServiceImpl.deleteAllEntitie(exitDocDetails); // } // // this.exitDocServiceImpl.delete(exitDoc); // } return result; } @RequestMapping(params="queryDetail") public ModelAndView queryDetail(ExitDocEntity exitDoc, HttpServletRequest req) { //获取入库单号 String exitDocId = exitDoc.getId(); ExitDocEntity result = this.exitDocServiceImpl.findUniqueByProperty(ExitDocEntity.class, "id", exitDocId); ModelAndView reuslt = new ModelAndView("equipment/exitDocDetail/exitDocDetailQuery"); reuslt.getModel().put("exitDoc", result); return reuslt; } @RequestMapping(params="updateDetail") public ModelAndView updateDetail(ExitDocEntity exitDoc, HttpServletRequest req) { //获取入库单号 String exitDocId = exitDoc.getId(); ExitDocEntity result = this.exitDocServiceImpl.findUniqueByProperty(ExitDocEntity.class, "id", exitDocId); ModelAndView reuslt = new ModelAndView("equipment/exitDocDetail/exitDocDetailUpdate"); reuslt.getModel().put("exitDoc", result); return reuslt; } /** * 获取编号 * @return */ public synchronized String getNum() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // TODO Auto-generated method stub int maxNo = exitDocServiceImpl.selectMaxNo(); Date date = new Date(); int k=maxNo+1; DecimalFormat df = new DecimalFormat("000"); String d = sdf.format(date); String n = df.format(k); StringBuffer sb = new StringBuffer(); sb.append("CK").append(d).append(n); return sb.toString(); } } <file_sep>package com.jeecg.pro.equipment.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.hibernate.criterion.Restrictions; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.tag.vo.datatable.SortDirection; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jeecg.pro.equipment.entity.StorageDetailEntity; import com.jeecg.pro.equipment.entity.StorageDocEntity; import com.jeecg.pro.equipment.service.IDeviceService; import com.jeecg.pro.equipment.service.IStorageDetailSerivce; @Controller @RequestMapping("/storageDetail") public class StorageDetailController extends BaseController { @Resource(name="storageDetailSerivceImpl") private IStorageDetailSerivce storageDetailSerivceImpl; @Resource(name="deviceServiceImpl") private IDeviceService deviceServiceImpl; @RequestMapping(params="list") public ModelAndView getList() { return new ModelAndView("equipment/storageDetail/storageDetailList"); } @RequestMapping(params="savaDetail") public AjaxJson savaDetail(HttpServletRequest request, HttpServletResponse response) { String docInfo = request.getParameter("docInfo"); String details = request.getParameter("details"); System.out.println(docInfo); System.out.println(details); return null; } @RequestMapping(params="datagrid") public void datagrid(StorageDetailEntity storageDetail, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { // String storageDocNo = request.getParameter("storageDocNo"); // List<StorageDocEntity> storages = this.storageDetailSerivceImpl.findByProperty(StorageDocEntity.class, "storageDocNo", storageDocNo); // if(storages != null && storages.size() > 0) // { // String storageId = storages.get(0).getId(); // CriteriaQuery cq = new CriteriaQuery(StorageDetailEntity.class, dataGrid); // cq.add(Restrictions.eq("storageDoc.id", storageId)); // //查询条件组装器 // org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, storageDetail); // cq.add(); // this.storageDetailSerivceImpl.getDataGridReturn(cq, true); // } // else // { // dataGrid.setResults(new ArrayList<Object>()); // } dataGrid.setResults(new ArrayList<>()); TagUtil.datagrid(response, dataGrid); } @RequestMapping(params="addorupdate") public ModelAndView addorupdate(StorageDetailEntity storageDetail, HttpServletRequest req) { //获取入库信息 // String storeId = req.getParameter("storeId"); // String storageDocNo = req.getParameter("storageDocNo"); // String storageDocType = req.getParameter("storageDocType"); // ModelAndView result = new ModelAndView("equipment/storageDetail/storageDetail"); // result.getModelMap().put("storeId", storeId); // result.getModelMap().put("storageDocNo", storageDocNo); // result.getModelMap().put("storageDocType", storageDocType); // if(!StringUtils.isEmpty(storageDetail.getId())) // { // storageDetail = this.storageDetailSerivceImpl.getEntity(StorageDetailEntity.class, storageDetail.getId()); // req.setAttribute("storageDetail", storageDetail); // } String data = req.getParameter("data"); ModelAndView result = new ModelAndView("equipment/storageDetail/storageDetail"); if(StringUtils.isEmpty(data)) { String deviceCode = deviceServiceImpl.getDeviceCode(); result.getModelMap().put("deviceCode", deviceCode); } else { result.getModelMap().put("data", data); } return result; } @RequestMapping(params="saveStorageDetail") @ResponseBody public AjaxJson saveStorageDetail(StorageDetailEntity storageDetail, HttpServletRequest req) { AjaxJson ajaxJson = new AjaxJson(); // String detailId = storageDetail.getId(); // //获取用户信息 // TSUser user = (TSUser) req.getSession().getAttribute("LOCAL_CLINET_USER"); // // //获取入库单信息 // String storeId = req.getParameter("storeId"); // String storageDocNo = req.getParameter("storageDocNo"); // String storageDocType = req.getParameter("storageDocType"); // // //部门 // TSDepart tsDepart = new TSDepart(); // tsDepart.setId(user.getCurrentDepart().getId()); // // //入库类型 // StorageDocTypeEntity type = new StorageDocTypeEntity(); // type.setId(String.valueOf(storageDocType.hashCode())); // // //仓库信息 // StoreEntity store = new StoreEntity(); // store.setId(storeId); // // //创建入库单对象 // StorageDocEntity storageDoc = new StorageDocEntity(); // storageDoc.setStorageDocNo(storageDocNo); // storageDoc.setTsDepart(tsDepart); // storageDoc.setStorageDocType(type); // storageDoc.setTsUser(user); // storageDoc.setReviewer(user); // storageDoc.setStore(store); // // //如果入库单信息存在则不需要插入入库单,否则需要插入入库单 // List<StorageDocEntity> queryStorageDocs = this.storageDetailSerivceImpl.findByProperty(StorageDocEntity.class, "storageDocNo", storageDocNo); // if(queryStorageDocs == null || queryStorageDocs.size() == 0) // { // this.storageDetailSerivceImpl.save(storageDoc); // queryStorageDocs = this.storageDetailSerivceImpl.findByProperty(StorageDocEntity.class, "storageDocNo", storageDocNo); // } // storageDetail.setStorageDoc(queryStorageDocs.get(0)); // if(StringUtils.isEmpty(detailId)) // { // this.storageDetailSerivceImpl.save(storageDetail); // } // else // { // this.storageDetailSerivceImpl.updateEntitie(storageDetail); // } // // //根据设备Id、供应商Id、价格判断tbl_deviceInv(设备库存表)是否存在记录,如果存在记录进行数量、总结累加,如果不存在进行插入 // String hql = "From DeviceInvEntity devInv where devInv.device.id = '"+storageDetail.getDevice().getId()+"' and devInv.supplier.id='"+storageDetail.getSupplier().getSupplierNo()+"' and devInv.price=" + storageDetail.getPrice(); // List<DeviceInvEntity> devoceInvs = this.storageDetailSerivceImpl.findByQueryString(hql); // if(devoceInvs != null && devoceInvs.size() > 0) // { // DeviceInvEntity devoceInv = devoceInvs.get(0); // devoceInv.setSumPrice(devoceInv.getSumPrice() + storageDetail.getSumPrice()); // devoceInv.setCount(devoceInv.getCount() + storageDetail.getCount()); // this.storageDetailSerivceImpl.saveOrUpdate(devoceInv); // } // else // { // DeviceInvEntity deviceInv = new DeviceInvEntity(); // // deviceInv.setDevice(storageDetail.getDevice()); // deviceInv.setSupplier(storageDetail.getSupplier()); // deviceInv.setCount(storageDetail.getCount()); // deviceInv.setPrice(storageDetail.getPrice()); // deviceInv.setSumPrice(storageDetail.getSumPrice()); // this.storageDetailSerivceImpl.save(deviceInv); // } return ajaxJson; } @RequestMapping(params="deleteStorageDetail") @ResponseBody public AjaxJson deleteStorageDetail(StorageDetailEntity storageDetail, HttpServletRequest req) { AjaxJson ajaxJson = new AjaxJson(); this.storageDetailSerivceImpl.delete(storageDetail); return ajaxJson; } @RequestMapping(params="deleteBatch") @ResponseBody public AjaxJson deleteBatch(String ids, HttpServletRequest req) { AjaxJson result = new AjaxJson(); List<String> detailIds = Arrays.asList(ids.split(",")); for(String detailId : detailIds) { StorageDetailEntity detail = this.storageDetailSerivceImpl.findUniqueByProperty(StorageDetailEntity.class, "id", detailId); this.storageDetailSerivceImpl.delete(detail); } return result; } @RequestMapping(params="datagridList") public void datagridList(StorageDetailEntity storageDetail, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(StorageDetailEntity.class, dataGrid); //查询条件组装器 cq.addOrder("storageDoc.storageDocNo", SortDirection.desc); org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, storageDetail); cq.add(); this.storageDetailSerivceImpl.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); } @RequestMapping(params="listAll") public ModelAndView getListAll() { return new ModelAndView("equipment/storageDetail/storageDetailAll"); } } <file_sep>package com.jeecg.pro.equipment.controller; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jeecg.pro.equipment.entity.MaintenanceEntity; import com.jeecg.pro.equipment.entity.MaintenanceEntity; import com.jeecg.pro.equipment.service.IMaintenanceService; /** * 维修厂商 * @author jack * */ @Controller @RequestMapping("/maintenance") public class MaintenanceController extends BaseController{ @Autowired private IMaintenanceService maintenanceService; @Autowired private SystemService systemService; @RequestMapping(params = "view") public ModelAndView getList() { return new ModelAndView("equipment/maintenance/maintenanceList"); } @RequestMapping(params="datagrid", produces="text/html;charset=UTF-8") public void datagrid(MaintenanceEntity maintenance, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(MaintenanceEntity.class, dataGrid); org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, maintenance); cq.add(); this.maintenanceService.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); } @RequestMapping(params="addOrEdit") public ModelAndView addOrEdit(MaintenanceEntity maintenance, HttpServletRequest req) { String id = maintenance.getId(); if(null!=id && StringUtil.isNotEmpty(id)) { maintenance = maintenanceService.getEntity(MaintenanceEntity.class, maintenance.getId()); req.setAttribute("maintenance", maintenance); } return new ModelAndView("equipment/maintenance/maintenance"); } @RequestMapping(params="saveOrUpdate") @ResponseBody public AjaxJson saveOrUpdate(MaintenanceEntity maintenance, HttpServletRequest req) { String message = null; String id = maintenance.getId(); AjaxJson ajaxJson = new AjaxJson(); if (!StringUtil.isNotEmpty(id)) { try { maintenance.setNum(getNum()); maintenanceService.save(maintenance); message = "保存成功!"; systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); message = "保存失败!"; systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); }}else{ try { maintenanceService.saveOrUpdate(maintenance); message = "编辑成功!"; systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); message = "编辑失败!"; systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } } ajaxJson.setMsg(message); return ajaxJson; } @RequestMapping(params="deleteAll") @ResponseBody public AjaxJson deleteAll(String ids, HttpServletRequest req) { AjaxJson j = new AjaxJson(); List<String> maintenanceIds = Arrays.asList(ids.split(",")); for (String id : maintenanceIds) { maintenanceService.deleteEntityById(MaintenanceEntity.class, id); } return j; } @RequestMapping(params="delete") @ResponseBody public AjaxJson delete(MaintenanceEntity maintenance, HttpServletRequest req) { String message = null; String id = req.getParameter("id"); try { maintenanceService.deleteEntityById(MaintenanceEntity.class, id); message="删除成功!"; } catch (Exception e) { // TODO: handle exception message="删除失败!"; e.printStackTrace(); } AjaxJson ajaxJson = new AjaxJson(); ajaxJson.setMsg(message); return ajaxJson; } /** * 获取编号 * @return */ public String getNum() { // TODO Auto-generated method stub String maxNo = maintenanceService.selectMaxNo(); if(StringUtils.isEmpty(maxNo)) { maxNo = "W0000001"; } else { String str = ""; maxNo = maxNo.replace("W", ""); Long tmp = Long.parseLong(maxNo); Long nextTmp = tmp + 1; int nextLength = String.valueOf(nextTmp).length(); int length = 7 - nextLength; if(length != 0 ) { for(int i = 0; i < length; i++) { str = str + "0"; } } maxNo = "W" + str + (tmp + 1); } return maxNo; } } <file_sep> public class demo { // String name ="领用出库"; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; demo other = (demo) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } <file_sep>package com.jeecg.pro.equipment.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.jeecgframework.core.common.entity.IdEntity; import org.jeecgframework.web.system.pojo.base.TSCategoryEntity; import org.jeecgframework.web.system.pojo.base.TSType; import com.app.equipment.entity.baseinfo.SupplierEntity; @Entity @Table(name="tbl_device") public class DeviceEntity extends IdEntity implements Serializable { /** * */ private static final long serialVersionUID = 8942504692032795545L; /** * 设备名称 */ private String name; /** * 设备类别 */ private TSCategoryEntity tsCategory; /** * 设备编码 */ private String code; /** * 设备编号 */ private String deviceNum; /** * 财务资产卡片编号(财务填写) */ private String assetNum; /** * 存放地点 */ private String store; /** * 设备规格 */ private String deviceSpec; /** * 生产厂家 */ private ManufacturerEntity manufacturer; /** * 供应商 */ private SupplierEntity supplier; /** * 维修厂商 */ private MaintenanceEntity maintenance; /** * 合同名称 */ private String contractName; /** * 技术参数 */ private String technicalParam; /** * 合同编号 */ private String contractNum; /** * 单位 */ private Units units; /** * 单价 */ private Double unitPrice; /** * 实物管理部门 */ private String objDepart; /** * 实物管理部门责任人 */ private String zrUser; /** * 使用保管部门 */ private String useDepart; /** * 使用保管部门责任人 */ private String useUser; /** * 验收人 */ private String ysUser; /** * 资产增加方式 */ private String zczjfs; /** * 启用日期 */ private Date qyDate; /** * 资产使用状况 */ private String tStype; /** * 出厂日期 */ private Date ccDate; /** * 购置日期 */ private Date buyDate; /** * 出厂编号 */ private String outNum; /** * 资金源头 */ private String capital; // /** // *用途分类 // */ // private TSType usetype; /** * 附属设备 */ private DeviceEntity parentDevice; /** * 设备状态 */ private String status; @Column(name="code") public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Column(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="deviceSpec") public String getDeviceSpec() { return deviceSpec; } public void setDeviceSpec(String deviceSpec) { this.deviceSpec = deviceSpec; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="unitId") public Units getUnits() { return units; } public void setUnits(Units units) { this.units = units; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="categoryId") public TSCategoryEntity getTsCategory() { return tsCategory; } public void setTsCategory(TSCategoryEntity tsCategory) { this.tsCategory = tsCategory; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="parentId") public DeviceEntity getParentDevice() { return parentDevice; } public void setParentDevice(DeviceEntity parentDevice) { this.parentDevice = parentDevice; } @Column(name="assetNum") public String getAssetNum() { return assetNum; } public void setAssetNum(String assetNum) { this.assetNum = assetNum; } @Column(name="store") public String getStore() { return store; } public void setStore(String store) { this.store = store; } @Column(name="contractName") public String getContractName() { return contractName; } public void setContractName(String contractName) { this.contractName = contractName; } @Column(name="technicalParam") public String getTechnicalParam() { return technicalParam; } public void setTechnicalParam(String technicalParam) { this.technicalParam = technicalParam; } @Column(name="contractNum") public String getContractNum() { return contractNum; } public void setContractNum(String contractNum) { this.contractNum = contractNum; } @Column(name="unitPrice") public Double getUnitPrice() { return unitPrice; } public void setUnitPrice(Double unitPrice) { this.unitPrice = unitPrice; } @Column(name="zczjfs") public String getZczjfs() { return zczjfs; } public void setZczjfs(String zczjfs) { this.zczjfs = zczjfs; } @Temporal(TemporalType.DATE) @Column(name="qyDate") public Date getQyDate() { return qyDate; } public void setQyDate(Date qyDate) { this.qyDate = qyDate; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="manufacturerId") public ManufacturerEntity getManufacturer() { return manufacturer; } public void setManufacturer(ManufacturerEntity manufacturer) { this.manufacturer = manufacturer; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="supplierId") public SupplierEntity getSupplier() { return supplier; } public void setSupplier(SupplierEntity supplier) { this.supplier = supplier; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="maintenanceId") public MaintenanceEntity getMaintenance() { return maintenance; } public void setMaintenance(MaintenanceEntity maintenance) { this.maintenance = maintenance; } @Column(name="objDepart") public String getObjDepart() { return objDepart; } public void setObjDepart(String objDepart) { this.objDepart = objDepart; } @Column(name="zrUser") public String getZrUser() { return zrUser; } public void setZrUser(String zrUser) { this.zrUser = zrUser; } @Column(name="useDepart") public String getUseDepart() { return useDepart; } public void setUseDepart(String useDepart) { this.useDepart = useDepart; } @Column(name="useUser") public String getUseUser() { return useUser; } public void setUseUser(String useUser) { this.useUser = useUser; } @Column(name="ysUser") public String getYsUser() { return ysUser; } public void setYsUser(String ysUser) { this.ysUser = ysUser; } @Column(name="tStypeId") public String gettStype() { return tStype; } public void settStype(String tStype) { this.tStype = tStype; } @Temporal(TemporalType.DATE) @Column(name="ccDate") public Date getCcDate() { return ccDate; } public void setCcDate(Date ccDate) { this.ccDate = ccDate; } @Temporal(TemporalType.DATE) @Column(name="buyDate") public Date getBuyDate() { return buyDate; } public void setBuyDate(Date buyDate) { this.buyDate = buyDate; } @Column(name="outNum") public String getOutNum() { return outNum; } public void setOutNum(String outNum) { this.outNum = outNum; } @Column(name="capital") public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "usetypeid") // public TSType getUsetype() { // return usetype; // } // // public void setUsetype(TSType usetype) { // this.usetype = usetype; // } @Column(name="deviceNum") public String getDeviceNum() { return deviceNum; } public void setDeviceNum(String deviceNum) { this.deviceNum = deviceNum; } @Column(name="status") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } <file_sep>package com.app.equipment.dao.impl.baseinfo; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.app.equipment.dao.baseinfo.ICustomerInfoDao; import com.app.equipment.entity.baseinfo.CustomerInfoEntity; import com.app.equipment.tools.StringTools; @Repository public class CustomerInfoDaoImpl implements ICustomerInfoDao { @Resource private JdbcTemplate jdbcTemplate; @Override public List<CustomerInfoEntity> selects(String wheresql) { // TODO Auto-generated method stub List<CustomerInfoEntity> customers = new ArrayList<CustomerInfoEntity>(); String sql = "select * from tbl_customer " + wheresql; List<Map<String, Object>> results = this.jdbcTemplate.queryForList(sql); if(results != null) { for(Map<String, Object> result : results) { CustomerInfoEntity customer = new CustomerInfoEntity(); customer.setId(result.get("customerNo").toString()); customer.setCustomerNo(result.get("customerNo").toString()); customer.setCustomerName(StringTools.obj2String(result.get("customerName"))); customer.setPhone(StringTools.obj2String(result.get("phone"))); customer.setTelphone(StringTools.obj2String(result.get("telphone"))); customer.setContactor(StringTools.obj2String(result.get("contactor"))); customer.setProduct(StringTools.obj2String(result.get("product"))); customer.setAddress(StringTools.obj2String(result.get("address"))); customer.setOptions(StringTools.obj2String(result.get("options"))); customer.setRemark(StringTools.obj2String(result.get("remark"))); customers.add(customer); } } return customers; } @Override public void deleteByCustomerNo(String customerNo) { // TODO Auto-generated method stub String sql = "delete from tbl_customer where customerNo = '" + customerNo + "'"; this.jdbcTemplate.execute(sql); } @Override public CustomerInfoEntity selectByCustomerNo(String customerNo) { // TODO Auto-generated method stub String sql = "select * from tbl_customer where customerNo= '" + customerNo +"'"; Map<String, Object> result = this.jdbcTemplate.queryForMap(sql); CustomerInfoEntity customer = new CustomerInfoEntity(); customer.setId(result.get("customerNo").toString()); customer.setCustomerNo(result.get("customerNo").toString()); customer.setCustomerName(StringTools.obj2String(result.get("customerName"))); customer.setPhone(StringTools.obj2String(result.get("phone"))); customer.setTelphone(StringTools.obj2String(result.get("telphone"))); customer.setContactor(StringTools.obj2String(result.get("contactor"))); customer.setProduct(StringTools.obj2String(result.get("product"))); customer.setAddress(StringTools.obj2String(result.get("address"))); customer.setOptions(StringTools.obj2String(result.get("options"))); customer.setRemark(StringTools.obj2String(result.get("remark"))); return customer; } @Override public void update(CustomerInfoEntity customer) { // TODO Auto-generated method stub String sql = "update " + "tbl_customer " + "set " + "customerName = ?," + "phone = ?," + "telphone = ?," + "contactor = ?," + "product = ?," + "address = ?," + "options = ?," + "remark = ? " + "where " + "customerNo = ?"; Object[] customerInfo = new Object[] { customer.getCustomerName(), customer.getPhone(), customer.getTelphone(), customer.getContactor(), customer.getProduct(), customer.getAddress(), customer.getOptions(), customer.getRemark(), customer.getCustomerNo() }; this.jdbcTemplate.update(sql, customerInfo); } @Override public void insert(CustomerInfoEntity customer) { // TODO Auto-generated method stub String sql = "insert into tbl_customer" + "(" + "customerNo," + "customerName," + "phone," + "telphone," + "contactor," + "product," + "address," + "options," + "remark" + ") " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?)"; Object[] customerInfo = new Object[] { customer.getCustomerNo(), customer.getCustomerName(), customer.getPhone(), customer.getTelphone(), customer.getContactor(), customer.getProduct(), customer.getAddress(), customer.getOptions(), customer.getRemark() }; this.jdbcTemplate.update(sql, customerInfo); } @Override public int selectCount(String wheresql) { // TODO Auto-generated method stub String sql = "select * from tbl_customer " + wheresql; List<Map<String, Object>> results = this.jdbcTemplate.queryForList(sql); if(results == null) { return 0; } return results.size(); } @Override public void deleteBatch(List<String> customerNos) { // TODO Auto-generated method stub String sql = "delete from tbl_customer where customerNo in ("; String customerStr = ""; for(String customerNo : customerNos) { customerStr = customerStr + ", '" + customerNo + "'"; } customerStr = customerStr.substring(1, customerStr.length()); sql = sql + customerStr + ");"; this.jdbcTemplate.execute(sql); } @Override public String selectMaxCustomerNo() { // TODO Auto-generated method stub String sql = "select max(customerNo) from tbl_customer"; String result = this.jdbcTemplate.queryForObject(sql, String.class); return result; } } <file_sep>package com.jeecg.pro.equipment.dao; import org.jeecgframework.minidao.annotation.MiniDao; import org.jeecgframework.minidao.annotation.Sql; @MiniDao public interface ExitDocDao { @Sql("SELECT Count(id) FROM tbl_exit_doc") int selectMaxNo(); } <file_sep>package com.jeecg.pro.equipment.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.jeecgframework.poi.excel.annotation.Excel; import org.jeecgframework.web.system.pojo.base.TSDepart; @Entity @Table(name="tbl_store") public class StoreEntity implements Serializable { /** * */ private static final long serialVersionUID = -7944417699205771532L; /** * 仓库编号 */ @Excel(name = "仓库编号") private String id; /** * 仓库名称 */ @Excel(name = "仓库名称") private String name; /** * 仓库位置 */ @Excel(name = "仓库位置") private String position; /** * 公司名称 */ @Excel(name = "公司名称") private String departName; /** * 公司 */ private TSDepart tsDepart; @Id @Column(name ="id",nullable=false,length=32) public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="position") public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="departId") public TSDepart getTsDepart() { return tsDepart; } public void setTsDepart(TSDepart tsDepart) { this.tsDepart = tsDepart; } @Transient public String getDepartName() { return departName; } public void setDepartName(String departName) { this.departName = departName; } } <file_sep>package com.jeecg.pro.equipment.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.criterion.Restrictions; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.p3.core.utils.common.StringUtils; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.pojo.base.TSDepart; import org.jeecgframework.web.system.pojo.base.TSUser; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.app.equipment.entity.baseinfo.SupplierEntity; import com.jeecg.pro.equipment.entity.DeviceInvEntity; import com.jeecg.pro.equipment.entity.ExitDocDetailEntity; import com.jeecg.pro.equipment.entity.ExitDocEntity; import com.jeecg.pro.equipment.entity.StoreEntity; import com.jeecg.pro.equipment.service.IExitDocDetailService; @Controller @RequestMapping("exitDocDetail") public class ExitDocDetailController extends BaseController { @Resource(name="exitDocDetailServiceImpl") private IExitDocDetailService exitDocDetailServiceImpl; @RequestMapping(params="list") public ModelAndView getList() { return new ModelAndView("equipment/exitDocDetail/exitDocDetailList"); } @RequestMapping(params="datagrid") public void datagrid(ExitDocDetailEntity exitDocDetail, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { String exitDocNo = request.getParameter("exitDocNo"); List<ExitDocEntity> exits = this.exitDocDetailServiceImpl.findByProperty(ExitDocEntity.class, "exitDocNo", exitDocNo); if(exits != null && exits.size() > 0) { String exitId = exits.get(0).getId(); CriteriaQuery cq = new CriteriaQuery(ExitDocDetailEntity.class, dataGrid); cq.add(Restrictions.eq("exitDoc.id", exitId)); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, exitDocDetail); cq.add(); this.exitDocDetailServiceImpl.getDataGridReturn(cq, true); } else { dataGrid.setResults(new ArrayList<Object>()); } TagUtil.datagrid(response, dataGrid); } @RequestMapping(params="addorupdate") public ModelAndView addorupdate(ExitDocDetailEntity exitDetail, HttpServletRequest req) { //获取入库信息 String storeId = req.getParameter("storeId"); String exitDocNo = req.getParameter("exitDocNo"); String exitDocType = req.getParameter("exitDocType"); ModelAndView result = new ModelAndView("equipment/exitDocDetail/exitDocDetail"); result.getModelMap().put("storeId", storeId); result.getModelMap().put("exitDocNo", exitDocNo); result.getModelMap().put("exitDocType", exitDocType); if(!StringUtils.isEmpty(exitDetail.getId())) { exitDetail = this.exitDocDetailServiceImpl.getEntity(ExitDocDetailEntity.class, exitDetail.getId()); req.setAttribute("exitDetail", exitDetail); } return result; } @RequestMapping(params="saveExitDetail") @ResponseBody public AjaxJson saveExitDetail(ExitDocDetailEntity exitDocDetail, HttpServletRequest request) { AjaxJson result = new AjaxJson(); // String storeId = request.getParameter("storeId"); // String exitDocNo = request.getParameter("exitDocNo"); // String exitDocType = request.getParameter("exitDocType"); // // //判断数据库中是否存在出库单记录如果不存在进行插入,存在则不进行动作 // ExitDocEntity exitDoc = new ExitDocEntity(); // exitDoc.setExitDocNo(exitDocNo); // List<ExitDocEntity> exitDocs = this.exitDocDetailServiceImpl.findByProperty(ExitDocEntity.class, "exitDocNo", exitDocNo); // if(exitDocs == null || exitDocs.size() == 0) // { // //出库部门 // TSDepart tsDepart = new TSDepart(); // tsDepart.setId(exitDocDetail.getTsDepart().getId()); // // //出库人 // TSUser tsUser = (TSUser) request.getSession().getAttribute("LOCAL_CLINET_USER"); // // //出库类型 // ExitDocType type = new ExitDocType(); // type.setId(String.valueOf(exitDocType.hashCode())); // type.setName(exitDocType); // // //仓库信息 // StoreEntity store = new StoreEntity(); // store.setId(storeId); // // exitDoc.setTsDepart(tsDepart); // exitDoc.setTsUser(tsUser); // exitDoc.setExitDocType(type); // exitDoc.setReviewer(tsUser); // exitDoc.setStore(store); // exitDoc.setCreateDate(new Date()); // // this.exitDocDetailServiceImpl.save(exitDoc); // } // else // { // exitDoc = exitDocs.get(0); // } // // //插入tbl_exitdocdetail(出库记录详细) // exitDocDetail.setExitDoc(exitDoc); // this.exitDocDetailServiceImpl.save(exitDocDetail); // // //插入出库设备选择供应商信息以及数目金额 // List<ExitDeviceEntity> exitDevices = new ArrayList<ExitDeviceEntity>(); // String selectSupplier = exitDocDetail.getSelectSupplier(); // String selectPrice = exitDocDetail.getSelectPrice(); // String selectCount = exitDocDetail.getSelectCount(); // String selectSumPrice = exitDocDetail.getSelectSumPrice(); // String selectDevInv = exitDocDetail.getSelectDevInv(); // if(!StringUtils.isEmpty(selectSupplier)) // { // String[] selectSuppliers = selectSupplier.split(","); // for(int i = 0; i < selectSuppliers.length; i++) // { // String supplierNo = selectSuppliers[i]; // if(!StringUtils.isEmpty(supplierNo)) // { // SupplierEntity supplier = new SupplierEntity(); // supplier.setSupplierNo(supplierNo); // // ExitDeviceEntity exitDevice = new ExitDeviceEntity(); // exitDevice.setSupplier(supplier); // exitDevice.setPrice(Float.parseFloat(selectPrice.split(",")[i])); // exitDevice.setCount(Integer.parseInt(selectCount.split(",")[i])); // exitDevice.setSumPrice(Float.parseFloat(selectSumPrice.split(",")[i])); // // exitDevice.setExitDocDetail(exitDocDetail); // exitDevices.add(exitDevice); // // //获取原有的库存信息 // String devInvId = selectDevInv.split(",")[i]; // DeviceInvEntity deviceInv = this.exitDocDetailServiceImpl.findUniqueByProperty(DeviceInvEntity.class, "id", devInvId); // deviceInv.setCount(deviceInv.getCount() - Integer.parseInt(selectCount.split(",")[i])); // deviceInv.setSumPrice(deviceInv.getSumPrice() - Float.parseFloat(selectSumPrice.split(",")[i])); // this.exitDocDetailServiceImpl.updateEntitie(deviceInv); // } // } // // this.exitDocDetailServiceImpl.batchSave(exitDevices); // } return result; } @RequestMapping(params="deleteExitDetail") @ResponseBody public AjaxJson deleteExitDetail(ExitDocDetailEntity exitDocDetail, HttpServletRequest request) { AjaxJson result = new AjaxJson(); // String exitDocDetailId = exitDocDetail.getId(); // // //先删除tbl_exitDevice表中的信息,根绝外键明细Id删除 // List<ExitDeviceEntity> exitDevices = this.exitDocDetailServiceImpl.findByProperty(ExitDeviceEntity.class, "exitDocDetail.id", exitDocDetailId); // this.exitDocDetailServiceImpl.deleteAllEntitie(exitDevices); // // //在删除tbl_exitDocDetail表中的信息 // this.exitDocDetailServiceImpl.deleteEntityById(ExitDocDetailEntity.class, exitDocDetailId); return result; } @RequestMapping(params="listAll") public ModelAndView getListAll() { return new ModelAndView("equipment/exitDocDetail/exitDocDetailAll"); } // @RequestMapping(params="datagridList") // public void datagridList(ExitDeviceEntity exitDevice, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) // { // CriteriaQuery cq = new CriteriaQuery(ExitDeviceEntity.class, dataGrid); // //查询条件组装器 // org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, exitDevice); // cq.add(); // this.exitDocDetailServiceImpl.getDataGridReturn(cq, true); // TagUtil.datagrid(response, dataGrid); // } } <file_sep>package com.jeecg.pro.equipment.controller; import java.util.Arrays; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.p3.core.utils.common.StringUtils; import org.jeecgframework.tag.core.easyui.TagUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jeecg.pro.equipment.entity.DeviceEntity; import com.jeecg.pro.equipment.service.IDeviceService; @Controller @RequestMapping("/device") public class DeviceController extends BaseController { @Resource(name="deviceServiceImpl") private IDeviceService deviceServiceImpl; @RequestMapping(params="list") public ModelAndView getList() { return new ModelAndView("equipment/device/deviceList"); } @RequestMapping(params="datagrid") public void dataGrid(DeviceEntity device, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(DeviceEntity.class, dataGrid); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, device); cq.add(); this.deviceServiceImpl.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); } @RequestMapping(params="addorupdate") public ModelAndView addorupdate(DeviceEntity device, HttpServletRequest req) { if(!StringUtils.isEmpty(device.getId())) { device = this.deviceServiceImpl.getEntity(DeviceEntity.class, device.getId()); req.setAttribute("device", device); } return new ModelAndView("equipment/device/device"); } @RequestMapping(params="saveDevice") @ResponseBody public AjaxJson saveDevice(DeviceEntity device, HttpServletRequest req) { AjaxJson ajaxJson = new AjaxJson(); String id = device.getId(); if(StringUtils.isEmpty(id)) { device.setCode(this.deviceServiceImpl.getDeviceCode()); this.deviceServiceImpl.save(device); } else { this.deviceServiceImpl.updateEntitie(device); } return ajaxJson; } @RequestMapping(params="deleteDevice") @ResponseBody public AjaxJson delete(DeviceEntity device, HttpServletRequest req) { AjaxJson result = new AjaxJson(); this.deviceServiceImpl.delete(device); return result; } @RequestMapping(params="deleteBatch") @ResponseBody public AjaxJson deleteBatch(String ids, HttpServletRequest req) { AjaxJson result = new AjaxJson(); List<String> deviceIds = Arrays.asList(ids.split(",")); for(String deviceId : deviceIds) { DeviceEntity device = this.deviceServiceImpl.findUniqueByProperty(DeviceEntity.class, "id", deviceId); this.deviceServiceImpl.delete(device); } return result; } @RequestMapping(params="deviceRead") public ModelAndView deviceRead() { return new ModelAndView("equipment/device/deviceRead"); } @RequestMapping(params="datagridRead") public void datagridRead(DeviceEntity device, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(DeviceEntity.class, dataGrid); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, device); cq.add(); this.deviceServiceImpl.getDataGridReturn(cq, false); TagUtil.datagrid(response, dataGrid); } }
d07540965c8d69015d514817bc6db1528432d584
[ "Java" ]
13
Java
kinky2015/DeviceManageSys
5690714b22849dd6bc9eb591128da95301432f53
764c208b3eaae59505a9ec85d8881e5b540fa624
refs/heads/master
<repo_name>CHSKingsmen/chs-tech-info<file_sep>/views/docs/offerings/apple-classroom.md ## Apple Classroom *adapted from [Apple's support page](https://support.apple.com/en-us/HT206151)* Classroom turns a teacher's iPad into a powerful teaching assistant, helping a teacher guide students through a lesson, see their progress, and keep them on track. With Classroom, teachers can easily launch the same app on every student device at the same time, or launch a different app for each group of students. Classroom helps teachers focus on teaching so students can focus on learning. Teachers can also lock students' iPads into an app, or lock the screens altogether, in order to keep students focused. Teachers are also able to see what is on their students' iPad screens, and use AirPlay to show the students screen to the rest of the class through the Apple TVs that every classroom is equipped with. <img src="https://2672686a4cf38e8c2458-2712e00ea34e3076747650c92426bbb5.ssl.cf1.rackcdn.com/2016-01-18-225944.jpeg" class="img-responsive center-block"/><file_sep>/views/docs/offerings/digital-textbooks.md ## Digital Textbooks Since every high school student receives an iPad we are able to provide required course text digitally. This page will describe some of the ways we do that. <br> #### iBooks iBooks is iOS's native digital book reader that comes on every iPad, iPhone, and Mac. It comes with a digital bookstore with over 2.5+ million books for sale. While much of the store sells traditional eBooks (like novels, for example), there is a significant selection of multi-touch enhanced books, especially textbooks. The science classes at CHS (Biology, Chemistry, Physics) all use these enhanced textbooks for their courses. Also, the English department uses iBooks as their preferred form of book distribution for the novels used in classes. Through the Volume Purchasing Program from Apple, CHS is able to purchase a mass amount of iBooks from Apple (often at a discounted price) and give redeemable codes to students so they can download them to their own devices. <br> #### Pearson eText *Adapted from their [promotional page](https://www.pearson.com/us/higher-education/products-services-teaching/course-content/pearson-etext-app/apple-ipad.html)* Pearson provides learning resources for K-12 and even for higher education. Many of our textbooks come through Pearson, including for Literature and Math. Also, our college level Physics, Math, and History textbooks come through Pearson. The Pearson eText app is the iPad companion to Pearson’s eText browser-based book reader. It allows students access their titles in a bookshelf on the iPad either online or via download. With the eText app, book content is displayed with the highest quality fidelity to the print and online versions of the textbook. The app provides students and instructors with many of the same features available to browser-based eText subscribers. The eText app provides full-text search capabilities, highlights, notes, bookmarks, support for multimedia content, glossaries, multitasking, ability to create study groups and many other features. <br> #### VitalSource BookShelf *Adapted from their [iTunes Store page](https://itunes.apple.com/us/app/bookshelf/id389359495?mt=8)* VitalSource BookShelf is a web and Android/iOS application for downloading and reading digital textbooks. This is used mainly for our History classes. The VitalSource Bookshelf® app for iOS to download and access VitalSource textbooks on your iPad, iPhone or iPod Touch. Students can access their books online or offline, search across their full library, and create notes and highlights to help them study. <br> #### McGraw-Hill McGraw-Hill Education is a learning science company that delivers personalized learning experiences that help students parents, educators and professionals drive results. We use their Glencoe Health curriculum for our 9th grade health course. McGraw-Hill offers the ConnectED platform to access course materials (like the textbook and other activities) online.<file_sep>/views/docs/offerings/office365.md ## Office 365 Office 365 is a subscription service offered by Microsoft to access the latest versions of its suite of productivity apps, including Word, PowerPoint, and Excel. These apps can be downloaded onto a PC or Mac, or can be accessed online . CHS subscribes to Office 365 for Education, which means everyone enrolled and employed at CHS has access to these services, as explained in more detail below. <br> #### Kingsmen email All students in Grades 6-12 are given a kingsmen.org email address, formatted "<EMAIL>". Students are able to log in with their provided email address and password at <PASSWORD> and receive all kinds of correspondence from teachers and fellow students. New student iPads are also set up with this email account linked to their "Mail" app. <br> #### Office applications Along with online versions of Office applications, all students in Grades 6-12 are able to download full versions of all the Office applications to up to 5 PCs and Macs, as well as to their iOS and Android devices. <center> <img src="/images/office365applications.png" width="600"> </center><file_sep>/views/docs/offerings/renweb.md ## RenWeb *adapted from their ["about us" page](https://www.renweb.com/about-us/)* RenWeb is the leader in school administration software for private K-12 schools. As well as being a time-saver for teachers and administrators in grading and reporting, RenWeb also has many features built for families. RenWeb’s core features offer a host of options for parents to keep up with their child’s progress in the classroom and at school. Parents can access attendance, homework, progress reports, and grades. Communication between families is made easier with a built-in directory, and permission slips and agreement forms are made simple with RenWeb's Web Forms.<file_sep>/views/docs/offerings/ipads.md ## iPads In 2013, CHS began a 1:1 iPad program for all high school students, and it continues to this day. <br> #### One iPad per student Every high school student will have the option to either lease an iPad from the school, or bring their own suitable iPad from home. Every device has at least 32 GB of storage to store all the books and apps a student might need. For those students who lease their iPad from us, we also provide a very protective [case](https://www.stmgoods.com/ipad-cases/ipad-air-cases/dux-for-ipad-air#92=16') in order to keep the device, and all the information on it, safe. In fact, it is the student's iPad, and thus their responsibility to keep it safe, we strong recommend that they do not allow others to use their iPad. Each iPad leased from CHS comes with full AppleCare + coverage. AppleCare+ for iPad extends repair coverage and telephone technical support to two years from the original lease date and adds coverage for up to two incidents of accidental damage due to handling. Each incident is subject to a $49 service fee, paid by the parents. <br> #### Apps While students in Grade 9 will not have the App Store available to add content, students in Grades 10-12 may have the app store available with parental permission. There are a plethora of education related [apps on the app store](href='https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewGenre?id=6017&mt=8&ls=1') that could potentially help the students in their studies. We also provide many [apps](/what-we-offer/ipad-software) to the students for use in their studies. Students who do not have the App Store may request (with parental permission) to have an app installed for educational purposes. If approved, there will be a designated time when the app store can be accessed and the app installed. <br> #### Monitoring CHS has full authority to collect and/or inspect a student's iPad at any time, or to alter, add, or delete installed software or hardware. We also provide 24/7 internet content filtering both on and off campus. Parents are encouraged to also monitor the content on their child's iPad, and are able to request a report detailing web activity at any time. Because the primary use of the iPad is for educational purposes, the teachers are able to control the use of the iPad at their discretion. They are able to use the [Apple Classroom](/what-we-offer/apple-classroom) app to offer fine-grained control of iPad use in the classroom, in order to keep students on task. <br> #### Cost The technology fee for the 2017-2018 school year is $50. If your student chooses to lease an iPad from the school, it will cost $190. Both of these costs are charged through SMART Tuition.<file_sep>/views/docs/offerings/managed-apple-ids.md ## Managed Apple IDs *Adapted from Apple's [support page](https://support.apple.com/en-us/HT205918)* Beginning with the class of 2021, we are taking advantage of a new educational offering from Apple called "Managed Apple IDs," which allow CHS to create and manage Apple IDs for our students. To maintain a focus on education, these services are disabled for Managed Apple IDs: - App Store purchasing - iTunes Store purchasing - HomeKit connected devices - Apple Pay - Find My iPhone - Find My Mac - Find My Friends - iCloud Mail - iCloud Keychain - FaceTime - iMessage However, with these Apple IDs, students are able to log into iCloud and iTunes U. CHS is also able to push out other [educational apps](/what-we-offer/ipad-software) to students' iPads.<file_sep>/views/docs/offerings/digital-assignment-submission.md ## Digital Assignment Submission CHS is on the cutting edge of digital education, so we use the latest tools to improve all aspects of schooling, especially the turning in of assignments. <br/> #### iTunes U <center><img src="https://images.apple.com/v/education/ipad/itunes-u/c/images/handoff_large_2x.jpg" width="500"></center> <br> iTunes U seamlessly organizes participating classes with homework hand=in, integrated feedback, document distribution, and private discussions. <br> #### Turnitin <center><img src="http://cei.ust.hk/files/turnitin/turnitin_05.jpg" width="500"></center> <br> Digitally turn in writing assignments, and get instant feedback on potential plagiarism. [Turnitin's Originality Checker](http://turnitin.com/en_us/what-we-offer/feedback-studio), and its database of over 730 million student papers and 60 billion web sites indexed, is used heavily by the English and History departments at CHS to ensure that all students' major papers and other assignments are truly their own. <file_sep>/controllers/offerings.js var renderOptions = { section: 'offerings' }; var express = require('express'); var router = express.Router(); router.get('/', function (req, res) { var opts = renderOptions; opts.title = 'What We Offer'; res.render('docs/offerings/home', opts); }); var offeringsHeadings = { ipads: { url: '/what-we-offer/ipads', relativeURL: "ipads", title: 'iPads' }, office365: { url: '/what-we-offer/office365', relativeURL: "office365", title: "Office 365", subheads: [ { title: "Kingsmen email", anchor: "#kingsmen-email" }, { title: "Office applications", anchor: '#office-applications' } ] }, renweb: { url: '/what-we-offer/renweb', relativeURL: 'renweb', title: 'RenWeb' }, digitalTextbooks: { url: '/what-we-offer/digital-textbooks', relativeURL: "digital-textbooks", title: "Digital Textbooks" }, digitalAssignmentSubmission: { url: '/what-we-offer/digital-assignment-submission', relativeURL: 'digital-assignment-submission', title: 'Digital Assignment Submission' }, ipadSoftware: { url: '/what-we-offer/ipad-software', relativeURL: 'ipad-software', title: 'iPad Software' }, appleClassroom: { url: '/what-we-offer/apple-classroom', relativeURL: 'apple-classroom', title: 'Apple Classroom' }, managedAppleIDs: { url: '/what-we-offer/managed-apple-ids', relativeURL: 'managed-apple-ids', title: 'Managed Apple IDs' }, naviance: { url: '/what-we-offer/naviance', relativeURL: 'naviance', title: 'Naviance' } }; for (const heading in offeringsHeadings) { const headingObj = offeringsHeadings[heading]; router.get('/' + headingObj.relativeURL, function (req, res) { var opts = renderOptions; opts.title = headingObj.title + ' - What We Offer'; opts.heading = heading; opts.subheads = headingObj.subheads; opts.allHeadings = offeringsHeadings; res.render('docs/offerings/' + headingObj.relativeURL, opts); }); } module.exports = router;<file_sep>/views/docs/offerings/naviance.md ## Naviance *adapted from their ["what we offer" page](https://www.naviance.com/solutions/parents-students)* Naviance by Hobsons is a comprehensive K-12 college and career readiness platform that enables self-discovery, career exploration, academic planning, and college preparation for millions of students across all ages and around the globe. School districts and schools like CHS purchase Naviance to help students explore their interests and strengths and develop a course of study that matches long-term goals with an actionable plan. Take surveys, find a career, and search for colleges with Naviance's feature-rich web application. Naviance also serves as a link for students to access [x2vol](https://www.x2vol.com/students.html), our online community service manager. Tracking hours is easy, and logging hours to meet CHS's service requirements is quick. Students can find service opportunities, too and write about their experience via Reflections. And x2vol matches service opportunities to the things students care about the most, so every hour matters even more.<file_sep>/views/docs/offerings/ipad-software.md ## iPad Software We provide free access to many iPad apps for use in school. </br> #### Notability <center> <img src="http://gingerlabs.com/images/iPad-note-mind-map-sketchnote.png" width="400"> </center> <br/> Originally $9.99, [Notability](https://itunes.apple.com/us/app/notability/id360593530?mt=8&ign-mpt=uo%3D4) is a fully-featured iOS note taking app. Students, teachers, and business professionals use Notability daily to take notes, sketch ideas, annotate PDFs, mark-up photos, and more. It is uniquely designed for each device to provide the best note taking experience at school, at home, and at work. And with iCloud, your notes are always up to date. Your notes can also be backed up to Dropbox or Google Drive. </br> #### myHomework <center> <img src="https://d1ec4mget7355z.cloudfront.net/myhw/imgs/ss-new-iPad@2x.jpg" width="400"> </center> <br/> myHomework is a digital planner for keeping track of homework and other assignments. As well, you can keep track of your classes and schedules with the built-in calendar and scheduling features. You can set reminders for assignments' due dates, and add a widget to the Today View detailing upcoming homework. With a free account, you can also sync all your information between devices. <br/> #### Educreations <center> <img src="https://www.educreations.com/static/focuslab/images/hero_ipad.e491ddba8d11.jpg" width="400"> </center> <br/> Using Educreations, students can create and show interesting audiovisual presentations. Teachers are also able to use this app to develop and share interesting video lessons with their students. </br> #### NearPod <center> <img src="http://4.bp.blogspot.com/-w1wHSEFBwyA/T7vNlnwoQ8I/AAAAAAAACqc/Gk-aRus_vyc/s1600/Nearpod-133136.png" width="550"> </center> <br/> NearPod provides the ability for teachers to create lessons that empower them to keep students on task, as well as inspiring students with interactive features such as quizzes, polls, slideshows, videos and more.
6390aa341819e1908e76ca213b743ca90943afdf
[ "Markdown", "JavaScript" ]
10
Markdown
CHSKingsmen/chs-tech-info
74b21122b1a68ad6c984a622ab99ee82de87e18c
068a19b6355e9f89686430b53f3ef39af05ad86f
refs/heads/master
<repo_name>sn31/word-count-django<file_sep>/templates/count.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <h1>Count page</h1> <a href="{% url 'home' %}">Redo</a> <h3>Original text:</h3> <p>{{ fulltext }}</p> <h3>Word Analysis:</h3> <h4>Total count: {{ total_count }}</h4> <h4>Word Frequency:</h4> {% for word, value in words%} <p>{{ word }} - {{ value }}</p> {% endfor %} </body> </html> <file_sep>/wordcount/views.py from django.http import HttpResponse from django.shortcuts import render def home(request): return render(request, "home.html") def count(request): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' fulltext = request.GET["fulltext"] for char in fulltext.lower(): if char in punctuations: fulltext = fulltext.replace(char, " ") count_dict = {} for word in fulltext.lower().strip().split(): if word.lower() in count_dict: count_dict[word] += 1 else: count_dict[word] = 1 word_frequency_sorted = sorted( count_dict.items(), key=lambda kv: kv[1], reverse=True) return render(request, "count.html", {"total_count": len(fulltext), "words": word_frequency_sorted, "fulltext": fulltext})
2f678312287117bb820aefeb17b25b821397fa82
[ "Python", "HTML" ]
2
HTML
sn31/word-count-django
744e9a90395831c021553fee3d3d481f8cfa9255
50392680cec957cb58e80742041c2f4cdd752cec
refs/heads/master
<repo_name>billy96322/Whymygo<file_sep>/src/main/java/zhang/salmon/whymygo/DoOrderTab.java package zhang.salmon.whymygo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.ArrayList; import java.util.zip.Inflater; /** * Created by Zhang on 2015/3/2. */ public class DoOrderTab extends ListFragment { private TabAdapter tabAdapter; ArrayList<ApkEntity> apk_list = new ArrayList<ApkEntity>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getData(); showListView(apk_list); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.lo_tab_doorder, container,false); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Log.d("DoOrderTab","Clicked!"); super.onListItemClick(l, v, position, id); } private void getData() { for (int i = 0; i < 10; i++) { ApkEntity entity = new ApkEntity(); entity.setName("麦当劳"); entity.setInfo("30元起送"); entity.setDes("免费配送"); apk_list.add(entity); } } private void showListView(ArrayList<ApkEntity> apk_list) { if (tabAdapter == null) { tabAdapter = new TabAdapter(getActivity(), apk_list); setListAdapter(tabAdapter); } else { tabAdapter.onDateChange(apk_list); } } } <file_sep>/src/main/java/zhang/salmon/whymygo/MainActivity.java package zhang.salmon.whymygo; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.ViewConfiguration; import android.view.Window; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class MainActivity extends FragmentActivity implements View.OnClickListener { private ViewPager mViewPager; private List<Fragment> mTabs = new ArrayList<Fragment>(); private FragmentPagerAdapter mAdapter; private List<TabChanger> mTabIndicators = new ArrayList<TabChanger>(); private int tabFlag=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setOverflowButtonAlways(); getActionBar().setDisplayShowHomeEnabled(true); getActionBar().setDisplayShowTitleEnabled(false); mViewPager = (ViewPager) findViewById(R.id.viewpager); initFragment(); initView(); } private void initView() { TabChanger one = (TabChanger) findViewById(R.id.id_indicator_one); mTabIndicators.add(one); TabChanger two = (TabChanger) findViewById(R.id.id_indicator_two); mTabIndicators.add(two); TabChanger three = (TabChanger) findViewById(R.id.id_indicator_three); mTabIndicators.add(three); one.setOnClickListener(this); two.setOnClickListener(this); three.setOnClickListener(this); one.setIconAlpha(1.0f); } private void initFragment() { DoOrderTab doOrderTab = new DoOrderTab(); OrderListTab orderListTab = new OrderListTab(); MeTab meTab = new MeTab(); mTabs.add(doOrderTab); mTabs.add(orderListTab); mTabs.add(meTab); mAdapter = new FragmentPagerAdapter( getSupportFragmentManager() ) { @Override public Fragment getItem(int position) { return mTabs.get(position); } @Override public int getCount() { return mTabs.size(); } }; mViewPager.setAdapter(mAdapter); //viewpager滑动事件监听器 mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Log.d("MainActivity","position: "+position+" positionOffset: "+positionOffset); mTabIndicators.get(position).setIconAlpha(1-positionOffset); if (position<mTabIndicators.size()-1) { mTabIndicators.get(position+1).setIconAlpha(positionOffset); } } @Override public void onPageSelected(int position) { resetTabsAlpha(); mTabIndicators.get(position).setIconAlpha(1.0f); // tabFlag = position; } @Override public void onPageScrollStateChanged(int state) { /* if (state == 2 || state == 0) { for (int i=0; i<mTabIndicators.size(); i++) { if (i != tabFlag) { mTabIndicators.get(i).setIconAlpha(0); } } }*/ } }); } //actionbar菜单 @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main,menu); return true; } //保持菜单在顶栏状态 private void setOverflowButtonAlways() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKey = ViewConfiguration.class .getDeclaredField("sHasPermanentMenuKey"); menuKey.setAccessible(true); menuKey.setBoolean(config, false); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onMenuOpened(int featureId, Menu menu) { if (featureId == Window.FEATURE_ACTION_BAR && menu != null) { if (menu.getClass().getSimpleName().equals("MenuBuilder")) { try { Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible",Boolean.TYPE); m.setAccessible(true); m.invoke(menu,true); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } return super.onMenuOpened(featureId, menu); } @Override public void onClick(View v) { resetTabsAlpha(); switch (v.getId()) { case R.id.id_indicator_one: mTabIndicators.get(0).setIconAlpha(1); mViewPager.setCurrentItem(0,false); break; case R.id.id_indicator_two: mTabIndicators.get(1).setIconAlpha(1); mViewPager.setCurrentItem(1,false); break; case R.id.id_indicator_three: mTabIndicators.get(2).setIconAlpha(1); mViewPager.setCurrentItem(2,false); break; } } private void resetTabsAlpha() { for (int i=0; i<mTabIndicators.size(); i++) { mTabIndicators.get(i).setIconAlpha(0); } } }
4ad27b8fd4a4cdbb60897f7a258fb0320aa1b47c
[ "Java" ]
2
Java
billy96322/Whymygo
dc153aa5ba181218c402e44accb391e33a7f85d9
a2f96c2584b5b2a4ad12e8abafe3da40aff408db
refs/heads/master
<repo_name>diego69775/TrabalhoSandro1<file_sep>/README.md # TrabalhoSandro1 Trabalho <NAME> <file_sep>/Segundo Arquivo PHP.php <? Arquivo PHP ?>
7d5c619d018aa4c6377a8e4d0f33206e44874f0f
[ "Markdown", "PHP" ]
2
Markdown
diego69775/TrabalhoSandro1
82807e9e5056476647d8af052854a4fe53e338c3
c2e3e53fc0d40278501a36fff34a3789442d067a
refs/heads/master
<file_sep>#ifndef BST_BST_H #define BST_BST_H #include <vector> #include "BSTNode.h" using std::vector; class BST { public: BST(); ~BST(); bool isEmpty() const; int getSize() const; // find retunrs the BSTNode* with a given target key BSTNode* find (int key); // make sure to cover different scenarios and use // private helper functions for recursive approaches // 1. empty tree // 2. a tree with only one node (root) // 3. insert/remove a leaf node // 4. insert/remove a branch node void insert(int key); void remove(int key); // contain checks if a BSTNode contains the target key bool contain(int key); // returns the height of a tree/subtree int getHeight() const ; // For every node in the tree, the difference between heights of its left // subtree and its right subtree is no more than 1, then it is considered // as a balanced tree. bool isBalanced() const; // public interface for traversals vector<int> preOrder(); vector<int> inOrder(); vector<int> inOrderNonRecursive(); vector<int> postOrder(); vector<int> postOrderNonRecursive(); vector<int> levelOrder(); private: BSTNode *root; int size; /** * helper function for insert * @param key the key to insert in the tree * @param current the root of the tree in which we are currently inserting the new key * @return the root of a tree that is just like current, but with the new key inserted */ BSTNode* insert_h(int key, BSTNode *newNode); /** * helper function used by find, update and contain * @param key the key we are looking for in the tree * @param current the root of the tree in which we are currently searching for the key * @return a pointer to the BSTNode that contains the key, nullptr if the key is not in the tree */ BSTNode* find_h(int key, BSTNode* current); /** * helper function for remove * @param key the key to be removed from the tree * @param current the root of the tree in which we are currently removing the key * @return a pointer to a BSTNode that is the root of a tree just like current, but with key removed * @throws runtime_error if key is not in the tree */ void remove_h(int key, BSTNode* current); /** * getMax finds the node containing the maximal key in the tree * @param current the root of the tree in which we are searching * @return a pointer to the BSTNode containing the maximal key * @throws runtime_error if current is an empty tree */ BSTNode* getMax(BSTNode* current); /* helper functions for the traversals */ int maxOfNodes_h(int lh, int rh) const; void levelOrder_h(BSTNode *curr, vector<int> &v); int getHeight_h(BSTNode * curr) const; bool leftInVec_h(BSTNode * curr,vector<int> valVector); bool rightInVec_h(BSTNode * curr,vector<int> valVector); void preOrder_h(BSTNode* current, vector<int>& v); void inOrder_h(BSTNode* current, vector<int>& v); void inOrderNonRecursive_h(BSTNode *curr, vector<int> &v); void postOrder_h(BSTNode* current, vector<int>& v); void destructTree(BSTNode* current); }; #endif //BST_BST_H <file_sep>#include "BST.h" #include "BSTNode.h" #include <vector> #include <queue> #include <stack> #include <stdexcept> #include <iostream> #include <algorithm> using namespace std; BST::BST() { this->root = nullptr; this->size = 0; } BST::~BST() { this->destructTree(this->root); } bool BST::isEmpty() const { return this->size == 0; } int BST::getSize() const { return this->size; } bool BST::isBalanced() const { BSTNode * leftHeight=this->root->left; BSTNode * rightHeight=this->root->right; int HL,HR; HL=getHeight_h(leftHeight); //gets the height of both trees to compare them to each other. HR=getHeight_h(rightHeight); return HL == HR || HR - HL == 1 || HR - HL == -1; } int BST::getHeight() const { BSTNode * curr= this->root; int totalHeight=getHeight_h(curr); int const finalHeight=totalHeight; return finalHeight; } int BST::getHeight_h(BSTNode * curr) const { //recursive function to get height of tree if(curr==nullptr){ return 0; } int ln = getHeight_h(curr->left); //for left int rn = getHeight_h(curr->right); //for right return 1 + maxOfNodes_h(ln,rn); //returns whichever height is greater plus one } int BST::maxOfNodes_h(int ln, int rn) const{ // compares two nodes on the tree to count height. if (ln > rn){ return ln; } else{ return rn; } } + //throw runtime_error("BST::insert, not yet implemented"); } BSTNode* BST::find(int key) { // BSTNode * maxPTR; //checking getMax in here cause function is private. // maxPTR=getMax(this->root); //cout << "This is the pointer for MAX and the key " << maxPTR << " and the key : "<< maxPTR->key; BSTNode* location = find_h(key, this->root); if (location == nullptr) { throw runtime_error("BST::find, key not present in BST"); } return location; } void BST::remove(int key){ BSTNode * curr = this->root; if(key==this->root->key){ //in case key is root terminates program cause there's no other purpose. } remove_h( key, curr); } void BST::remove_h(int key, BSTNode * curr) { queue<int> valQueue; bool found=false; if (curr != nullptr){ //stores values of tree into queue valQueue.push(curr->key); } queue<int> newQueue; while (!valQueue.empty()) { //stores values of tree into queue BSTNode *newCurr; newCurr = find(valQueue.front()); if (newCurr->left != nullptr) { valQueue.push(newCurr->left->key); } if (newCurr->right != nullptr) { valQueue.push(newCurr->right->key); } newQueue.push(valQueue.front()); if(key == newQueue.back()){ found=true; } valQueue.pop(); } this->root->left = nullptr; this->root->right = nullptr; for (int i = 0; i < size; i++){ if (newQueue.front() != key && newQueue.front() != this->root->key){ //deletes values from old queue and inserts them into a new ordered queue. insert(newQueue.front()); newQueue.pop(); size --; } else{ newQueue.pop(); } } if(!found){ __throw_runtime_error("Error, key not in list"); } size --; } bool BST::contain(int key) { BSTNode* location = find_h(key, this->root); return location != nullptr; } vector<int> BST::preOrder() { vector<int> vals; this->preOrder_h(this->root, vals); return vals; } vector<int> BST::inOrder() { vector<int> vals; this->inOrder_h(this->root, vals); return vals; } vector<int> BST::postOrder() { vector<int> vals; this->postOrder_h(this->root, vals); return vals; } // Helper functions BSTNode* BST::insert_h(int key, BSTNode *curr) { // TODO: complete insert_h size++; BSTNode * theHead = new BSTNode(key); return theHead; //throw runtime_error("BST::insert_h, not yet implemented"); } BSTNode* BST::find_h(int key, BSTNode *curr) { BSTNode * rootPTR=this->root; BSTNode * searcherCurr = curr; if(key==rootPTR->key){ return rootPTR; } while(true) { if (!isEmpty() && key > searcherCurr->key ) { //if I found the value I'm looking for if (searcherCurr->right->key == key){ return searcherCurr->right; } if (key > searcherCurr->key && searcherCurr->right != nullptr ) { //if val of what I'm looking for is higher move right searcherCurr = searcherCurr->right; } } if (!isEmpty() && key < searcherCurr->key){ if(searcherCurr->left->key == key){ //if I found the value I'm looking for return searcherCurr->left; } if (key < searcherCurr->key && searcherCurr->left != nullptr) { //if val of what I'm looking for is lower move left searcherCurr = searcherCurr->left; } } if(isEmpty() || (searcherCurr->left == nullptr && searcherCurr->right == nullptr)){ __throw_runtime_error("Not in tree"); //if not found } } } BSTNode* BST::getMax(BSTNode *curr) { BSTNode * theMax = curr; if(isEmpty()){ __throw_runtime_error("Tree empty"); } while(theMax->right != nullptr){ theMax=theMax->right; } return theMax; } void BST::preOrder_h(BSTNode *curr, vector<int> &v) { if (curr != nullptr) { v.push_back(curr->key); this->preOrder_h(curr->left, v); this->preOrder_h(curr->right, v); } } void BST::inOrder_h(BSTNode *curr, vector<int> &v) { if (curr != nullptr) { this->inOrder_h(curr->left, v); v.push_back(curr->key); this->inOrder_h(curr->right, v); } } void BST::postOrder_h(BSTNode *curr, vector<int> &v) { if (curr != nullptr) { this->postOrder_h(curr->left, v); this->postOrder_h(curr->right, v); v.push_back(curr->key); } } vector<int> BST::levelOrder(){ vector<int> vals; this->levelOrder_h(this->root, vals); return vals; } void BST::levelOrder_h(BSTNode *curr, vector<int> &v) { queue<int> Queue; if (curr != nullptr){ Queue.push(curr->key); ////populates queue with initial value } while (!Queue.empty()) { BSTNode *newCurr; newCurr = find(Queue.front()); if (newCurr->left != nullptr) { Queue.push(newCurr->left->key); //populates queue from top down } if (newCurr->right != nullptr) { Queue.push(newCurr->right->key); //populates queue from top down } v.push_back(Queue.front()); Queue.pop(); } } vector<int> BST::inOrderNonRecursive(){ vector<int> vals; this->inOrderNonRecursive_h(this->root, vals); return vals; } void BST::inOrderNonRecursive_h(BSTNode *curr, vector<int> &v) { queue<int> Queue; //makes Queue if (curr != nullptr){ Queue.push(curr->key); } queue<int> newQueue; //makes second queue to copy int MAX; bool maxDefined = false; //makes min and max to later use as reference. int MIN; bool minDefined = false; while (!Queue.empty()) { //populates queue BSTNode *newCurr; newCurr = find(Queue.front()); if (newCurr->left != nullptr) { Queue.push(newCurr->left->key); if (!minDefined){ MIN = newCurr->left->key; minDefined = true; //gets min } if (newCurr->left->key < MIN){ MIN = newCurr->left->key; //compares min } } if (newCurr->right != nullptr) { Queue.push(newCurr->right->key); if (!maxDefined){ MAX = newCurr->right->key; //gets max maxDefined = true; } if (newCurr->right->key > MAX){ MAX = newCurr->right->key; //compares max } } newQueue.push(Queue.front()); //populates second queue Queue.pop(); } int Array[size]; for (int i = 0; i < size; i++){ Array[i] = newQueue.front(); newQueue.pop(); } int Avg = sizeof(Array)/ sizeof(Array[0]); sort(Array, Array + Avg); //sorts array for order. for (int i = 0; i < size; i++){ v.push_back(Array[i]); } } bool BST::leftInVec_h(BSTNode * curr, vector<int> valVector){ //checks if the value below curr on the left is already in the array. if(curr==nullptr){ return false; } int vSize; vSize = valVector.size(); for(int j=0; j<vSize;j++){ if(curr->key == valVector[j]){ //finds if key in vector already return true; } } return false; } bool BST::rightInVec_h(BSTNode * curr, vector<int> valVector){ //checks if the value below curr on the right is already in the array. if(curr==nullptr){ return false; } int vSize; vSize = valVector.size(); for(int j=0; j<vSize;j++){ if(curr->key == valVector[j]){ //finds if key in vector already return true; } } return false; } vector<int> BST::postOrderNonRecursive(){ //if curr left and right are nullptr or if values of children are in array add the number. After a number is added traverse rest of tree. If you've seen a key go to other option. vector<int> valVector; valVector.push_back(0); BSTNode * curr=this->root; bool done=false; while (!done){ if(valVector.size() == size ){ //to stop the loop once it is reordered. done=true; } if(((!leftInVec_h(curr->left,valVector) && !rightInVec_h(curr->right,valVector)) && (curr->left != nullptr && curr->right != nullptr))){ //at the start, both the left and right node are not in the vector, so I just make it go left to start the process. curr=curr->left; } if((curr->left == nullptr && curr->right == nullptr) || (leftInVec_h(curr->left,valVector) && curr->right==nullptr) || (rightInVec_h(curr->right,valVector) && curr->left==nullptr) || (rightInVec_h(curr->right,valVector) && leftInVec_h(curr->left,valVector))){ //Excepts all possible cases of when a node could be accepted into the array valVector.push_back(curr->key); curr=this->root; } if((leftInVec_h(curr->left,valVector) || curr->left==nullptr) && curr->right != nullptr && !rightInVec_h(curr->right,valVector)){ //if the left is in the vector or there is no left node, progress to the right. curr=curr->right; } if((rightInVec_h(curr->right,valVector) || curr->right == nullptr) && !leftInVec_h(curr->left,valVector) && curr->left != nullptr){ //if the right is in the vector or there is no right node, progress to the left. curr=curr->left; } } valVector.erase(valVector.begin()); return valVector; } void BST::destructTree(BSTNode *curr) { if (curr != nullptr) { destructTree(curr->left); destructTree(curr->right); delete curr; } }<file_sep>#include <iostream> #include "BST.h" /* Name: (<NAME>) * Date: (12/6/19) * Section: (1) * Assignment: (8) * Due Date: (12/6/19) * About this project: (This project creates a binary tree and performs various functions associated with manipulating the tree. Worked with Jack Otis as some of the functions were easier to do together) * Comments: (Code compiles and runs without errors) * (deleting the root will throw a runtime error.) * Honor Pledge: I have abided by the Wheaton Honor Code and all work below * was performed by (<NAME>). */ using namespace std; /* void insert(int key) [x] * BSTNode* find(int key)[x] * void remove(int key)[x] * BSTNode* getMax(BSTNode* curr)[x] * int getHeight()[x] * bool isBalanced()[x] * vector<int> inOrderNonRecursive()[x] * vector<int> postOrderNonRecursive() [x] * vector<int> levelOrder()[x] */ void print(vector<int> v) { cout << "vec: "; for (int i = 0; i < v.size(); i++) { cout << v[i] << ", "; } cout << endl; } int main() { BST tree; BSTNode * ans; tree.insert(10); tree.insert(5); tree.insert(15); tree.insert(2); tree.insert(12); tree.insert(11); tree.insert(14); /*tree.insert(15); * tree.insert(16); * tree.insert(17); * tree.insert(18); * tree.insert(19); * tree.insert(20); * // to make tree unbalanced * */ cout << "Done with inserts"; //tree.remove(10); //removes a number in tree //tree.remove(230); removes a number not in tree //ans= tree.find(2); // works for finding an element // cout << " \n Checking find " << ans << "<--- is Pointer " << ans->key << "<---- is Key"; // cout << "getting height "; // cout << tree.getHeight(); //works for getting height // cout << " got height "; // cout << tree.isBalanced() << "Tree is balanced?";// works when tree is balanced and unbalanced vector<int> v1 = tree.preOrder(); cout << " \n This is pre \n"; print(v1); vector<int> v2 = tree.inOrder(); cout << " \n This is in order \n"; print(v2); vector<int> v3 = tree.postOrder(); cout << " \n This is post \n"; print(v3); cout << " printing tree.levelOrder \n "; vector<int> v4 = tree.levelOrder(); print(v4); cout << " printing inOrderNonRecursive \n "; vector<int> v5 = tree.inOrderNonRecursive(); print(v5); cout << " printing postOrderNonRecursive \n "; vector<int> v6 = tree.postOrderNonRecursive(); print (v6); /* try to run all the traversals on your tree * the preOrder should give you: [10,5,2,15,12,11,14] * the inOrder should give you: [2,5,10,11,12,14,15] * the postOrder should give you: [2,5,11,14,12,15,10] if curr left and right are nullptr or if values of children are in array add the number. After a number is added traverse rest of tree. If you've seen a key go to other option. * the levelOrder should give you: [10,5,15,2,12,11,14] **/ return 0; }<file_sep>#ifndef BST_BSTNODE_H #define BST_BSTNODE_H class BSTNode { public: int key; // can be called value or data too BSTNode *left; // left child of the current TreeNode BSTNode *right; // right child of the current TreeNode BSTNode (int val, BSTNode *left=nullptr, BSTNode *right=nullptr){ this->key = val; this->left = left; this->right = right; } }; #endif //BST_BSTNODE_H
e7fb4ab1617b7b7a203eee93bd97ff133c3ef961
[ "C++" ]
4
C++
MightyTidy/Mighty-Uploads
d8a16d824b90b204bc385e85e39f7f78bb9e6d54
5bc18e89017b4ee831b2973c0765e9b6535bc880
refs/heads/master
<repo_name>Rzelmiszel/CarShop<file_sep>/tofiks_michal.sql -- phpMyAdmin SQL Dump -- version 3.5.8.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 23, 2015 at 07:08 PM -- Server version: 5.1.72 -- PHP Version: 5.3.28 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Database: `tofiks_michal` -- -- -------------------------------------------------------- -- -- Table structure for table `basket` -- CREATE TABLE IF NOT EXISTS `basket` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` varchar(255) NOT NULL, `item_ids` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; -- -- Dumping data for table `basket` -- INSERT INTO `basket` (`id`, `user_id`, `item_ids`) VALUES (1, '1', '1 '); -- -------------------------------------------------------- -- -- Table structure for table `items` -- CREATE TABLE IF NOT EXISTS `items` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `year` varchar(255) NOT NULL, `horsepower` varchar(255) NOT NULL, `price` varchar(255) NOT NULL, `img_src` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ; -- -- Dumping data for table `items` -- INSERT INTO `items` (`id`, `name`, `year`, `horsepower`, `price`, `img_src`) VALUES (4, 'VW Passat Kombi 1.9 TDI', '1999', '105', '12900', 'images/1.jpg'), (8, 'Seat Leon 1.6 + LPG ', '2002', '105', '11500', 'images/2.jpg'), (9, 'Audi A3 1.8', '1998', '125', '11000', 'images/3.jpg'), (10, 'Audi A4 2.8 TDI', '2005', '200', '17900', 'images/4.jpg'), (11, 'VW Golf 1.6', '1998', '105', '7000', 'images/5.jpg'), (12, 'VW Golf GTI R20 ', '2010', '330', '76000', 'images/6.jpg'), (13, 'VW Passat 1.6', '2012', '105', '37900', 'images/7.jpg'), (14, 'Seat Ibiza 1.9 TDI ', '2006', '130', '20900', 'images/8.jpg'), (15, 'Seat Toledo 1.8 + LPG', '2003', '125', '13000', 'images/9.jpg'), (16, 'Ford Focus 1.6', '1999', '101', '6500', 'images/10.jpg'), (17, 'Ford C-Max 1.8 TDCI', '2008', '118', '38000', 'images/11.jpg'), (18, 'Opel Astra Elegance 1.6 + LPG ', '2003', '101', '7500', 'images/12.jpg'), (19, 'Audi RS6 5.0 TFSI V10', '2008', '580', '127500', 'images/13.jpg'), (20, 'Renault Megane 1.6 + LPG', '2004', '115', '11800', 'images/14.jpg'), (21, 'Renault Megane 1.4 ', '1998', '75', '6000', 'images/15.jpg'), (22, 'Seat Leon Cupra 2.4 V6', '2008', '224', '34000', 'images/16.jpg'), (23, 'BMW E90 2.0 TDI', '2006', '143', '24500', 'images/17.jpg'), (24, 'Ford Fiesta 1.4 Zetec-S ', '1997', '90', '3500', 'images/18.jpg'), (25, 'Ford Fiesta 1.25 Zetec-S + LPG ', '2007', '80', '13500', 'images/19.jpg'), (26, 'Volvo V40 1.6 Diesel', '2013', '120', '37000', 'images/20.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `name` varchar(100) DEFAULT NULL, `email` varchar(70) DEFAULT NULL, PRIMARY KEY (`uid`), UNIQUE KEY `username` (`username`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`uid`, `username`, `password`, `name`, `email`) VALUES (1, 'admin', '<PASSWORD>', '<NAME>', '<EMAIL>'); /*!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 */; <file_sep>/basket.php <?php @include_once('functions.php'); class Basket{ public function showBasket(){ $dbObj = new DB_Class(); $db = $dbObj->connect(); $uid = $_SESSION['uid']; $result = $db->query('SELECT item_ids FROM basket WHERE user_id='.$uid.' '); $result = $result->fetch(PDO::FETCH_ASSOC); $items = explode(' ', $result['item_ids']); $result2 = $db->query('SELECT * FROM items'); $result3 = array(); $i =0; foreach ($result2 as $key) { if(strstr($result['item_ids'], $key['id'])){ $result3[$i++] = $key; } } return $result3; } } ?> <file_sep>/header.php <!DOCTYPE html> <html lang="pl"> <head> <meta charset="utf-8"> <title>NiemiecPłakałJakSprzedawał.pl</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="wrapper"> <div class="header"> <div class="logo"> <img src="images/logo.jpg"><h1> <a href="index.php">NiemiecPłakałJakSprzedawał.pl</a> </h1> </div> </div> <div class="container"> <div class="menu"> <?php if(isset($_SESSION['uid'])) { ?> <div class="user-text"> Hi <span><?php $user->get_fullname($_SESSION['uid']); ?>!</span> [ <a href="?q=logout">Logout</a> ] </div> <div class="user-menu"> <ul> <li><a href="basket_view.php">Your Cart</a></li> </ul> </div> <?php } ?> </div> <div class="content"> <file_sep>/index.php <?php session_start(); include_once 'functions.php'; include_once 'items.php'; $user = new User(); $uid = $_SESSION['uid']; if (!$user->get_session()) { header("location:login.php"); } if (isset($_GET['q']) && ($_GET['q'] == 'logout')) { $user->user_logout(); header("location:login.php"); } $items = new Items(); $allItems = $items->showItems(); if(isset($_GET['iid'])) { $items->addToBasket(); } if(isset($_POST['submit'])) { if($temp = $items->filterItems()) { $allItems = $temp; } } ?> <?php include "header.php"; ?> <div class="section-header"> <h1> Car offers </h1> </div> <div class="filter"> <form id="Form2" method="POST" action="" name="login"> <div class="form-group"> Prize from <input type="text" name="priceA" /> to <input type="text" name="priceB" /> </div> <div class="form-group"> Year from <input type="text" name="yearA" /> to <input type="text" name="yearB" /> </div> <div class="form-group"> Horsepower from <input type="text" name="horseA" /> to <input type="text" name="horseB" /> </div> <div class="form-group"> <input type="submit" name="submit" class="btn" value="Filter"/> </div> </form> </div> <?php foreach($allItems as $k) {?> <div class="item-box"> <div class="item-image"> <img src="<?=$k['img_src'];?>"> </div> <div class="item-desc"> <ul> <li> <span> name: </span> <?=$k['name'];?> </li> <li> <span> year: </span> <?=$k['year'];?> </li> <li> <span> horsepower[KM]: </span> <?=$k['horsepower'];?> </li> <li> <span> price[PLN]: </span> <?=$k['price'];?> </li> </ul> <?php if($items->isInBasket($k['id'])) { ?> <p class="addToBuy"> Added to Cart</p> <?php } else {?> <a href="?q=addToBuy&iid=<?=$k['id'];?>" class="addToBuy"> >Add to Cart<</a> <?php } ?> </div> </div> <?php } ?> <?php include "footer.php"; ?> <file_sep>/functions.php <?php class DB_Class { public function connect() { try { return $db = new PDO('mysql:host=localhost;dbname=samochody', 'root', ''); } catch (PDOException $e) { print "Błąd połączenia z bazą!: " . $e->getMessage() . "<br/>"; die(); } } } ?> <file_sep>/basket_view.php <?php session_start(); include_once 'functions.php'; include_once 'items.php'; include_once 'basket.php'; $user = new User(); $basket = new Basket(); $items = new Items(); $uid = $_SESSION['uid']; if (!$user->get_session()) { header("location:login.php"); } if (isset($_GET['q']) && ($_GET['q'] == 'logout')) { $user->user_logout(); header("location:login.php"); } if (isset($_GET['q']) && ($_GET['q'] == 'deleteItem') && isset($_GET['iid'])) { $items->removeFromBasket($_GET['iid']); } $allItems = $basket->showBasket(); ?> <?php include "header.php"; ?> <div class="section-back"> <a href="index.php"> < Home </a> </div> <div class="section-header"> <h1> Koszyk </h1> </div> <?php if($allItems) foreach($allItems as $k) {?> <div class="item-box"> <div class="item-image"> <img src="<?=$k['img_src'];?>"> </div> <div class="item-desc"> <ul> <li> <span> name: </span> <?=$k['name'];?> </li> <li> <span> year: </span> <?=$k['year'];?> </li> <li> <span> horsepower[KM]: </span> <?=$k['horsepower'];?> </li> <li> <span> price[PLN]: </span> <?=$k['price'];?> </li> </ul> <a href="?q=deleteItem&iid=<?=$k['id'];?>" class="addToBuy"> >Remove from Cart<</a> </div> </div> <?php } else{ echo "Koszyk pusty"; } ?> <?php include "footer.php"; ?> <file_sep>/login.php <?php session_start(); include_once 'functions.php'; $user = new User(); if ($user->get_session()) { header("location:index.php"); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $login = $user->check_login($_POST['emailusername'], $_POST['password']); if ($login) { // Login Success header("location:login.php"); } else { // Login Failed $msg= 'Username / password wrong'; } } ?> <?php include "header.php"; ?> <div class="section-header"> <h1> Sign In </h1> </div> <form id="Form1" method="POST" action="" name="login"> <div class="form-group"> <span>Login</span> <input type="text" name="emailusername"/> </div> <div class="form-group"> <span>Password</span> <input type="<PASSWORD>" name="<PASSWORD>"/> </div> <div class="form-group"> <input type="submit" class="btn" value="Login"/> </div> </form> <?php include "footer.php"; ?> <file_sep>/items.php <?php class Items{ public function showItems(){ $dbObj = new DB_Class(); $db = $dbObj->connect(); $result = $db->query("SELECT * FROM items"); return $result; } public function addToBasket(){ $dbObj = new DB_Class(); $db = $dbObj->connect(); $result = $db->query("SELECT item_ids FROM basket"); $result = $result->fetch(PDO::FETCH_ASSOC); $temp = $result['item_ids']; if(!strstr($temp, $_GET['iid']) ) $temp.=$_GET['iid']." "; $result2 = $db->query("UPDATE basket SET item_ids = '$temp'"); } public function isInBasket($iid){ $dbObj = new DB_Class(); $db = $dbObj->connect(); $result = $db->query("SELECT item_ids FROM basket"); $result = $result->fetch(PDO::FETCH_ASSOC); if(strstr($result['item_ids'], $iid) ) return true; else return false; } public function removeFromBasket($iid){ $dbObj = new DB_Class(); $db = $dbObj->connect(); $result = $db->query("SELECT item_ids FROM basket"); $result = $result->fetch(PDO::FETCH_ASSOC); $temp = $result['item_ids']; $temp = str_replace($_GET['iid'].' ', '', $temp); $result2 = $db->query("UPDATE basket SET item_ids = '$temp'"); } public function filterItems(){ $dbObj = new DB_Class(); $db = $dbObj->connect(); $query='SELECT * FROM items WHERE '; if(!empty($_POST['priceA']) || $_POST['priceA'] == '0'){ if(empty($_POST['priceB'])){ $query.='price > '.$_POST["priceA"].' AND '; } else{ $query.='price BETWEEN '.$_POST["priceA"].' AND '.$_POST["priceB"].' AND '; } } else{ if(empty($_POST['priceB'])) $query.='price > 0 AND '; else $query.='price < '.$_POST["priceB"].' AND '; } if(!empty($_POST['yearA']) || $_POST['yearA'] == '0'){ if(empty($_POST['yearB'])){ $query.='year > '.$_POST["yearA"].' AND '; } else{ $query.='year BETWEEN '.$_POST["yearA"].' AND '.$_POST["yearB"].' AND '; } } else{ if(empty($_POST['yearB'])) $query.='year > 0 AND '; else $query.='year < '.$_POST["yearB"].' AND '; } if(!empty($_POST['horseA']) || $_POST['horseA'] == '0'){ if(empty($_POST['horseB'])){ $query.='horsepower > '.$_POST["horseA"].' '; } else{ $query.='horsepower BETWEEN '.$_POST["horseA"].' AND '.$_POST["horseB"].' '; } } else{ if(empty($_POST['horseB'])) $query.='horsepower > 0 '; else $query.='horsepower < '.$_POST["horseB"].' '; } $result = $db->query($query); return $result; } } ?>
9fc3a58bcdf5a566c43ee93b23ff7d76366b33b0
[ "SQL", "PHP" ]
8
SQL
Rzelmiszel/CarShop
b6f72d52a990d3b9236446fe6df6afce5048c2e1
b1e1f387965a456aeb948de23c37bd6bbb9d4eff
refs/heads/master
<repo_name>georgevlada/crono<file_sep>/README.md [![uikit banner](https://georgevlada.github.io/crono/images/preview.png)](https://georgevlada.github.io/crono/) # Crono - Mini Web app Chronometer for small and in-house sport competitions. - Functionalities: - Set and edit start time - Remove row/entry - View duplicates - Add observations for every row/entry - CSV export <file_sep>/data/scripts/base/custom/mod_sidebar.js /* ======================================================================== * Photon Admin: mod_sidebar.js v1.0.0 * * ======================================================================== * Copyright 2011-2016 eMAG, Inc. * Licensed under MIT * ======================================================================== */ function initScrollbarForSidebar() { $('#sidebar .sidebar-outer').customScrollbar({ skin: 'default-skin', hScroll: false, updateOnWindowResize: true }); } function updateScrollbar() { $('#sidebar .sidebar-outer').customScrollbar('resize', true); } function newScrollbarHeight($sidebarInner, $menuItem) { var rowHeight = $('.sidebar-inner > .menu-item:first-of-type').outerHeight(); return Math.max( ((rowHeight * ($sidebarInner.find(' > .menu-item').index($menuItem) + 1)) + $menuItem.find('.sidebar-submenu').outerHeight()), $sidebarInner.height() ); } function updateSidebarHeight() { var $sidebarInner = $('#sidebar .sidebar-inner'); $sidebarInner.css('height', ''); var $sidebarInner = $('#sidebar .sidebar-inner'); var $firstActiveMenuItem = $('#sidebar .menu-item.active').eq(0); var newHeight = newScrollbarHeight($sidebarInner, $firstActiveMenuItem); $sidebarInner.height(newHeight); } function updateSidebarHeightByMenuItem($menuItem) { var $sidebarInner = $('#sidebar .sidebar-inner'); if ($menuItem.parent().hasClass('sidebar-inner')) { $sidebarInner.css('height', ''); if ($menuItem.hasClass('active')) { var newHeight = newScrollbarHeight($sidebarInner, $menuItem); $sidebarInner.height(newHeight); } } else { if ($menuItem.hasClass('active')) { $sidebarInner.height($sidebarInner.height() + $menuItem.find('.sidebar-submenu').outerHeight()); } else { $sidebarInner.height($sidebarInner.height() - $menuItem.find('.sidebar-submenu').outerHeight()); } } } function staticNavigation(path) { path = (typeof path === 'undefined') ? window.location.pathname + window.location.hash : path; $('#sidebar .menu-item').removeClass('active'); $('#sidebar .menu-item > a').each(function () { var href = $(this).attr('href'); if (href == '#') { href = $(this).attr('data-href'); } if (path === href) { $(this).parents('.menu-item-has-children').addClass('active'); $(this).closest('.menu-item').addClass('active'); } }); $(window).resize(); } function initSidebarEvents() { /** * Jquery objects for sidebar * @type {*|HTMLElement} */ var $toggleNavBtn = $('#toggle-nav-btn'); var $sidebar = $('#sidebar'); var $toggleSidebarBtn = $('#toggle-sidebar-btn'); var $document = $(document); /** * CSS Classes that trigger the submenu collapse * @type {string} */ var menuItemHasChildrenCssClass = '.menu-item-has-children'; const SCREEN_XS_MAX = 767; /** * Sidebar elements * @event click */ $sidebar.on('click', '.menu-item a', function (e) { if ($(this).attr('href') == '#') { e.preventDefault(); } var element = $($(this).parents('.menu-item')[0]); $sidebar.find('.menu-item').not('.menu-item-has-children').removeClass('active'); if (element.hasClass('active')) { element.removeClass('active'); element.find(menuItemHasChildrenCssClass).removeClass('active'); } else { element.parent().find(menuItemHasChildrenCssClass).removeClass('active'); element.addClass('active'); } }); /** * Collapse sidebar using the dedicated button from the bottom (Only on desktop/tablet) * @event click */ $sidebar.on('click', '#toggle-sidebar-size-btn', function (e) { e.preventDefault(); var $sidebarInner = $('#sidebar .sidebar-inner'); $(this).find('.menu-icon').toggleClass('fa-arrow-right fa-arrow-left'); if($sidebar.hasClass('sidebar-min')) { $sidebar.removeClass('sidebar-min'); $(window).trigger('maximize.photon.sidebar'); setCookie('sidebarStatus', 'open'); $sidebarInner.css('height', ''); } else { $sidebar.addClass('sidebar-min'); $(window).trigger('minimize.photon.sidebar'); setCookie('sidebarStatus', 'close'); updateSidebarHeight(); } updateScrollbar(); $(window).resize(); realignNotifications(); }); /** * Open/Close sidebar by using the "#toggle-sidebar-btn" button from the main navigation (Only on mobile) * @event click */ $document.on('click', '#toggle-sidebar-btn', function (e) { e.preventDefault(); $(this).toggleClass('btn-primary'); if($sidebar.hasClass('open')) { $sidebar.removeClass('open'); $(window).trigger('close.photon.sidebar'); } else { $sidebar.addClass('open'); $(window).trigger('open.photon.sidebar'); } if($toggleNavBtn.hasClass('btn-primary')) { $toggleNavBtn.toggleClass('btn-primary'); $toggleNavBtn.find('i.fa').toggleClass('fa-chevron-down fa-chevron-up'); } $('#main-nav').collapse('hide'); }); /** * Close sidebar on mobile when click out of sidebar * @event click */ $document.on('click', function (e) { if (!$(e.target).closest('#sidebar, #toggle-sidebar-btn').length) { $sidebar.removeClass('open'); if($toggleSidebarBtn.hasClass('btn-primary')){ $toggleSidebarBtn.removeClass('btn-primary'); } } }); /** Function to toggle the navbar minimization */ $(document).on('click', '#toggle-nav-btn', function (e) { e.preventDefault(); $(this).toggleClass('btn-primary'); $(this).find('i.fa').toggleClass('fa-chevron-down fa-chevron-up'); }); $(document).on('click', '.menu-item > a, .menu-item > .menu-item-data > a', function (e) { if ($('#sidebar').hasClass('sidebar-min')) { var $menuItem = $(this).parents('.menu-item').eq(0); updateSidebarHeightByMenuItem($menuItem); } updateScrollbar(); }); $document.on('ready', function () { var sidebarStatus = getCookie('sidebarStatus'); if (sidebarStatus == '') { setCookie('sidebarStatus', 'open'); } else { if (sidebarStatus == 'close' && window.innerWidth > SCREEN_XS_MAX) { $sidebar.addClass('sidebar-min'); $sidebar.find('#toggle-sidebar-size-btn .menu-icon').removeClass('fa-arrow-left').addClass('fa-arrow-right'); } } }); $(window).on('resize', function () { var sidebarStatus = getCookie('sidebarStatus'); var $sidebarInner = $('#sidebar .sidebar-inner'); if (sidebarStatus == 'close' && window.innerWidth > SCREEN_XS_MAX) { $sidebar.addClass('sidebar-min'); $sidebar.find('#toggle-sidebar-size-btn .menu-icon').removeClass('fa-arrow-left').addClass('fa-arrow-right'); updateSidebarHeight(); } else { $sidebar.removeClass('sidebar-min'); $sidebar.find('#toggle-sidebar-size-btn .menu-icon').removeClass('fa-arrow-right').addClass('fa-arrow-left'); $sidebarInner.css('height', ''); } }) } +function ($) { initScrollbarForSidebar(); initSidebarEvents(); }(jQuery);
a5b8ec2ce1b6c272ed7d379f558b0a27157f3688
[ "Markdown", "JavaScript" ]
2
Markdown
georgevlada/crono
fca930205baf8cccde8e032e18c7e4cbe858eca9
b418757f9398abc1f4afc279446a195dc88234c2
refs/heads/main
<repo_name>soymizra/agenciadigital<file_sep>/dist/js/main.js (function(){ var prevScrollpos = window.pageYOffset; window.onscroll = function() { var currentScrollPos = window.pageYOffset; if (prevScrollpos > currentScrollPos) { document.getElementById("nav").style.top = "0"; console.log('arriba'); } else { document.getElementById("nav").style.top = "-128px"; } prevScrollpos = currentScrollPos; } function test(){ console.log('Hola'); } })(); // menu hamburger function menuHamburger(x){ x.classList.toggle("change"); document.querySelector('nav').classList.toggle('opacity-0'); }<file_sep>/tailwind.config.js module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { extend: { colors:{ dark: "#001233", dark2: '#001845', primary: '#0466C8', success: '#42E2B8', danger: '#214E34', secondary: '#FFFAFF', warning: '#EEE0CB' } }, }, variants: { extend: {}, }, plugins: [], }
5ff6153bdc51833f8e17537b774af8e052798b7c
[ "JavaScript" ]
2
JavaScript
soymizra/agenciadigital
9e81aa0a24a98d96609733168b95d2bfe033d9de
a36c42b5c20a60e58851efaf369ed620b8216802
refs/heads/master
<repo_name>thloykot/SpringShop<file_sep>/src/main/java/com/thl/spring/model/Sneakers.java package com.thl.spring.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; @Data @Entity @Table @AllArgsConstructor @NoArgsConstructor public class Sneakers implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String firm; private String model; private int size; private int price; } <file_sep>/src/main/java/com/thl/spring/service/SneakersService.java package com.thl.spring.service; import com.thl.spring.model.Sneakers; import java.util.List; import java.util.Optional; public interface SneakersService { int save(Sneakers sneakers); Optional<Sneakers> findById(int id); List<Sneakers> findByFirm(String firm); boolean delete(int id); } <file_sep>/src/main/java/com/thl/spring/redis/model/UserCounter.java package com.thl.spring.redis.model; import lombok.AllArgsConstructor; import lombok.Getter; import java.io.Serializable; @AllArgsConstructor @Getter public class UserCounter implements Serializable { private final int counter; private final long date; } <file_sep>/Dockerfile FROM openjdk:14-alpine ADD target/Spring-shop.jar Spring-shop.jar ENTRYPOINT ["java","-jar","Spring-shop.jar" ] EXPOSE 8080<file_sep>/src/main/java/com/thl/spring/dao/criteriaqueries/IdOnly.java package com.thl.spring.dao.criteriaqueries; public interface IdOnly { int getId(); } <file_sep>/src/main/java/com/thl/spring/redis/dao/UserCounterDao.java package com.thl.spring.redis.dao; import com.thl.spring.redis.model.UserCounter; import java.util.Optional; public interface UserCounterDao { void save(String username, UserCounter userCounter); Optional<UserCounter> findByUsername(String username); } <file_sep>/src/main/java/com/thl/spring/service/impl/LoginUserService.java package com.thl.spring.service.impl; import com.thl.spring.model.UserEntity; import com.thl.spring.service.UserService; import lombok.AllArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @AllArgsConstructor @Service public class LoginUserService implements UserDetailsService { private final UserService userService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userService.findByUsername(username).map(UserEntity::toUser). orElseThrow(() -> new UsernameNotFoundException("User not found")); } }<file_sep>/src/main/java/com/thl/spring/redis/SessionFilter.java package com.thl.spring.redis; import com.thl.spring.redis.model.UserCounter; import com.thl.spring.redis.service.UserCounterService; import com.thl.spring.service.UserService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Base64; import java.util.Optional; @Slf4j @Component @AllArgsConstructor public class SessionFilter extends OncePerRequestFilter { private static final int LIMIT = 50; private final UserCounterService userCounterService; private final UserService userService; private final BCryptPasswordEncoder bCryptPasswordEncoder; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String authorizationHeader = request.getHeader("authorization"); if (authorizationHeader != null) { authenticate(authorizationHeader); } filterChain.doFilter(request, response); } private void authenticate(String authorizationHeader) { String decodedAuth = new String(Base64.getDecoder().decode(authorizationHeader.replaceAll("Basic ", ""))); String[] userDetails = decodedAuth.split(":"); if (userDetails.length == 2) { userService.findByUsername(userDetails[0]).ifPresent(userEntity -> { if (bCryptPasswordEncoder.matches(userDetails[1], userEntity.getPassword()) && isUserCounterNotExceeded(userDetails[0])) { User user = userEntity.toUser(); Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); } }); } } private boolean isUserCounterNotExceeded(String username) { Optional<UserCounter> redisUserCounterOptional = userCounterService.find(username); if (redisUserCounterOptional.isEmpty() || isTimePassed(Instant .ofEpochMilli(redisUserCounterOptional.get().getDate()))) { userCounterService.set(username, 1); } else { int userCounter = redisUserCounterOptional.get().getCounter(); if (userCounter < LIMIT) { userCounter++; userCounterService.set(username, userCounter); } else { return false; } } return true; } public boolean isTimePassed(Instant userTime) { return ZonedDateTime.ofInstant(userTime, ZoneOffset.UTC).isAfter(ZonedDateTime.now(ZoneOffset.UTC).plusHours(24)); } } <file_sep>/src/main/java/com/thl/spring/redis/service/UserCounterService.java package com.thl.spring.redis.service; import com.thl.spring.redis.model.UserCounter; import java.util.Optional; public interface UserCounterService { void save(String username, UserCounter userCounter); Optional<UserCounter> find(String username); void set(String username, int counter); } <file_sep>/src/main/java/com/thl/spring/redis/dao/impl/UserCounterDaoImpl.java package com.thl.spring.redis.dao.impl; import com.thl.spring.redis.dao.UserCounterDao; import com.thl.spring.redis.model.UserCounter; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public class UserCounterDaoImpl implements UserCounterDao { private final HashOperations<String, String, UserCounter> hashOperations; private final static String USER = "USER"; public UserCounterDaoImpl(RedisTemplate<String, UserCounter> redisTemplate) { hashOperations = redisTemplate.opsForHash(); } public void save(String username, UserCounter userCounter) { hashOperations.put(USER, username, userCounter); } public Optional<UserCounter> findByUsername(String username) { return Optional.ofNullable(hashOperations.get(USER, username)); } }
12617c7ed6735346ff594da13810cd8382947108
[ "Java", "Dockerfile" ]
10
Java
thloykot/SpringShop
48800542f548820c33b0e36e55962904e0df38f6
75926a6f7bcb2f6f0a72abd2644c09b1211119a8
refs/heads/master
<repo_name>buiduclong0511/covid-tracker<file_sep>/src/Components/index.js export * from "./SelectField"; export * from "./DateField";<file_sep>/src/App.jsx import { Button } from "@material-ui/core"; import axios from "axios"; import Highcharts from 'highcharts' import HighchartsReact from 'highcharts-react-official' import { useState, useEffect } from "react"; import styled from "styled-components"; import { DateField, SelectField } from "./Components"; export const App = () => { const [countries, setCountries] = useState([]); const [selectedCountry, setSelectedCountry] = useState(null); const [dateRange, setDateRange] = useState({ from: null, to: null }); const [isFetching, setIsFetching] = useState(false); const [total, setTotal] = useState(null); const [report, setReport] = useState([]); const [options, setOptions] = useState({ title: { text: '' }, xAxis: { categories: [] }, series: [] }); const [isShowChart, setIsShowChart] = useState(false); // effect handler const fetchCountries = async () => { try { const res = await axios.get("https://api.covid19api.com/countries"); setCountries(res.data); } catch (err) { console.log(err.response); } }; // console.log(dateRange); const fetchReport = async () => { try { setIsFetching(true); const dateFrom = dateRange.from ? new Date(new Date(dateRange.from).setDate(new Date(dateRange.from).getDate() - 1)).toISOString() : new Date().toISOString(); const dateTo = dateRange.to ? new Date(dateRange.to).toISOString() : new Date().toISOString(); const res = await axios.get(` https://api.covid19api.com/country/${selectedCountry.Slug}?from=${dateFrom}&to=${dateTo} `); setReport(res.data); if (!res.data.length) { setTotal(null); } const chartTitle = selectedCountry.Country; const _dateRange = res.data.map(data => new Date(data.Date).toDateString()); const deaths = res.data.map(data => data.Deaths); const recovereds = res.data.map(data => data.Recovered); const confirmeds = res.data.map(data => data.Confirmed); // const setOptions({ title: { text: chartTitle }, xAxis: { title: { text: 'Ngày' }, categories: _dateRange }, yAxis: { title: { text: 'Số ca' } }, series: [ { name: "Số ca nhiễm", data: confirmeds, color: "#f00" }, { name: "Số ca tử vong", data: deaths, color: "#000" }, { name: "Số ca phục hổi", data: recovereds, color: "#0f0" }, ] }); setIsShowChart(true); } catch (err) { console.log(err.response); } finally { setIsFetching(false); } }; const fetchReportNow = async () => { try { // const dateFrom = new Date(new Date().setDate(new Date().getDate() - 2)).toISOString(); // const dateTo = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString(); const res = await axios.get(` https://api.covid19api.com/total/country/${selectedCountry.Slug} `); if (res.data.length) { setTotal({ deaths: res.data[res.data.length - 1].Deaths, confirmeds: res.data[res.data.length - 1].Confirmed, recovereds: res.data[res.data.length - 1].Recovered }); } } catch (err) { console.log(err); } }; // effect handler // effect useEffect(() => { fetchCountries(); }, []); useEffect(() => { if (selectedCountry) { fetchReport(); fetchReportNow(); } else { setTotal(null); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [dateRange, selectedCountry]); // effect // handle function const handleChange = (e, value) => { setSelectedCountry(value); }; const handleChangeDateFrom = (date) => { setDateRange({ ...dateRange, from: date }); }; const handleChangeDateTo = (date) => { setDateRange({ ...dateRange, to: date }); }; // handle function return ( <Container className="App"> <div className="choseOptions"> <div className="flexItem country"> <SelectField options={countries} selectedValue={selectedCountry} label="Chọn quốc gia" onChange={handleChange} /> </div> <div className="flexItem date"> <DateField label="From" value={dateRange.from} onChange={handleChangeDateFrom} maxDate={dateRange.to ? new Date(dateRange.to) : null} /> <Button variant="contained" color="primary" className="reset" onClick={() => setDateRange({ ...dateRange, from: null })}>Reset date from</Button> </div> <div className="flexItem date"> <DateField label="To" value={dateRange.to} onChange={handleChangeDateTo} /> <Button variant="contained" color="primary" className="reset" onClick={() => setDateRange({ ...dateRange, to: null })}>Reset date to</Button> </div> </div> {total ? ( <div className="total"> <p>Tổng số ca nhiễm: {total.confirmeds.toLocaleString()}</p> <p>Tổng số ca tử vong: {total.deaths.toLocaleString()}</p> </div> ) : ( <div className="total"> <p>Tổng số ca nhiễm:</p> <p>Tổng số ca tử vong:</p> </div> )} {isShowChart && selectedCountry ? report.length ? ( <div className="chart"> <HighchartsReact highcharts={Highcharts} options={options} /> <span className="api"> Api document: <a href="https://documenter.getpostman.com/view/10808728/SzS8rjbc" target="_blank">https://documenter.getpostman.com/view/10808728/SzS8rjbc</a> </span> </div> ) : ( <p className="noReport" style={{ display: isFetching ? "none" : "" }}>Không có thống kê của {selectedCountry.Country}</p> ) : ( <div className="chart"> <HighchartsReact highcharts={Highcharts} options={{ title: { text: 'Biểu đồ' }, xAxis: { title: { text: 'Ngày' }, categories: [] }, yAxis: { title: { text: 'Số ca' } }, series: [ { name: "Số ca nhiễm", data: [], color: "#f00" }, { name: "Số ca tử vong", data: [], color: "#000" }, { name: "Số ca phục hổi", data: [], color: "#0f0" }, ] }} /> <span className="api"> Api document: <a href="https://documenter.getpostman.com/view/10808728/SzS8rjbc" target="_blank">https://documenter.getpostman.com/view/10808728/SzS8rjbc</a> </span> </div> )} </Container> ); }; const Container = styled.div` .choseOptions { display: flex; @media (max-width: 540px) { flex-direction: column; } } .flexItem { flex: 1; padding: 0 20px; } .date { /* padding-top: 15px; */ } .chart { padding: 30px 40px; @media (max-width: 540px) { padding: 30px; } @media (max-width: 376px) { padding: 20px; } } .total { padding-left: 20px; } .noReport { padding-left: 10px; } .api { display: inline-block; max-width: 100%; overflow-x: hidden; text-overflow: ellipsis; } `;<file_sep>/src/Components/SelectField.jsx import { TextField } from "@material-ui/core"; import Autocomplete from "@material-ui/lab/Autocomplete"; export const SelectField = ({ options = [], selectedValue = null, label = "", onChange = () => {} }) => { return ( <Autocomplete options={options} getOptionLabel={(option) => option.Country} fullWidth onChange={onChange} value={selectedValue} renderInput={(params) => <TextField {...params} label={label} margin="normal" variant="standard" />} /> ); };<file_sep>/src/Components/DateField.jsx import styled from "styled-components"; import 'date-fns'; import React from 'react'; import Grid from '@material-ui/core/Grid'; import DateFnsUtils from '@date-io/date-fns'; import { MuiPickersUtilsProvider, KeyboardDatePicker, } from '@material-ui/pickers'; export const DateField = ({ label = "", value = null, maxDate = null, onChange = () => {} }) => { return ( <StyledDateField> <MuiPickersUtilsProvider utils={DateFnsUtils}> <Grid container justifyContent="space-around"> <KeyboardDatePicker disableToolbar variant="inline" format="MM/dd/yyyy" margin="normal" id="date-picker-inline" label={label} value={value} onChange={onChange} KeyboardButtonProps={{ 'aria-label': 'change date', }} autoOk maxDate={maxDate ? maxDate : new Date(new Date().setDate(new Date().getDate() - 1))} maxDateMessage="Ngày không hợp lệ" fullWidth /> </Grid> </MuiPickersUtilsProvider> </StyledDateField> ); }; const StyledDateField = styled.div` `;
9f31c231b877d2d816668d7250158dca07a06f09
[ "JavaScript" ]
4
JavaScript
buiduclong0511/covid-tracker
e7d06960428e58466a558c964b118cd04dc235ee
761158604fd44f2b4bb882f658685fdd79af2365
refs/heads/master
<repo_name>aristyogresearch/2019-nCoV<file_sep>/hsir/__init__.py from .law import * from .empirical import * from .sir import * from .sirq import * __all__ = ['Law', 'Bin', 'Poi', 'Gau' 'Region', 'Epidemic', 'Sample', 'SIR', 'InferSIR', 'SIRQ', 'InferSIRQ'] <file_sep>/README.md # 2019-nCoV 2019年-2020年新型冠状病毒肺炎(COVID-19) #### 2019-12-08 The first known case of an infected patient in Wuhan, a stall operator from the Huanan Seafood Market. #### 2019-12-31 27 cases of **pneumonia** #### 2020-01-01 Huanan seafood market closed #### 2020-01-03 44 cases of **virus** pneumonia #### 2020-01-05 59 cases of **virus** pneumonia #### 2020-01-11 41 cases of **COVID-19** pneumonia #### 2020-01-16 41 cases (including two deaths) have been confirmed in Wuhan City with three confirmed cases in travellers detected in Thailand (2 cases) and Japan (1 case). #### 2020-01-23 At 2AM, authorities in Wuhan suddenly issued the order to close off the city. From 10AM that same day, all public buses, subways, ferries, long-distance buse and other transport services would be suspended; the airport and train stations would be shuttered #### 2020-01-24 Up to noon, a total of 14 cities in Hubei provincee would be brought into the quarantine zone. 35 million people are concerned. #### 2020-02-04 Huoshen Montain Hospital accepted the first patient #### 2020-02-05 Wuhan FireEye labortory FangCang Hospital
b885399104c22b752944c8be17220c1a6c03d36d
[ "Markdown", "Python" ]
2
Python
aristyogresearch/2019-nCoV
3317f030d88e048b780795d3ee822ec5e2d9a88e
5569d54d62772220a7aa3a4f75d0653a7b4327b8
refs/heads/master
<file_sep>package com.ashik619.prokriyademo.adapters; import android.util.Log; import android.view.View; import com.ashik619.prokriyademo.MainActivity; import com.ashik619.prokriyademo.Models.User; import com.ashik619.prokriyademo.R; import com.ashik619.prokriyademo.custum_view.CustomTextView; import com.firebase.ui.database.FirebaseListAdapter; import com.google.firebase.database.DatabaseReference; /** * Created by ashik619 on 07-06-2017. */ public class UsersAdapter extends FirebaseListAdapter<User> { MainActivity activity; public UsersAdapter(MainActivity activity, Class<User> modelClass, int modelLayout, DatabaseReference ref) { super(activity, modelClass, modelLayout, ref); this.activity = activity; } @Override protected void populateView(View v, User model, int position) { CustomTextView nameText = (CustomTextView) v.findViewById(R.id.nameText); //Log.e("user",model.getName()); nameText.setText(model.getName()); } } <file_sep># prokriya2_demo # Used firebase database for realtime chat <file_sep>package com.ashik619.prokriyademo.Models; /** * Created by ashik619 on 07-06-2017. */ public class Message { public String text; public String timestamp; public Message(){ } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } } <file_sep>package com.ashik619.prokriyademo; import android.app.Application; import com.ashik619.prokriyademo.helper.PrefHandler; import com.google.firebase.database.FirebaseDatabase; /** * Created by ashik619 on 08-06-2017. */ public class ProkriyaApplication extends Application { public static PrefHandler localStorageHandler; public static PrefHandler getLocalPrefInstance() { return localStorageHandler; } @Override public void onCreate() { super.onCreate(); if (localStorageHandler == null) { localStorageHandler = new PrefHandler(getApplicationContext()); } FirebaseDatabase.getInstance().setPersistenceEnabled(true); } }
b15c97f6e6985933132f7ef766b685d7c7d4ff39
[ "Markdown", "Java" ]
4
Java
ashik619/prokriya2_demo
6fb9ba0c65c67206753d1c378fc4365444bc7040
f17d5ed4c6c00a6d624fc44fcf096d914ee7f844
refs/heads/master
<repo_name>slark1995/work-orders-app<file_sep>/README.md In the project directory, you can run: `yarn add package.json` <br /> `yarn start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. what does the app do: * Displays all the work orders ( display the worker information that corresponds with each order) * An input field that can filter work orders by order name * A switch or toggle that lets you sort all the work orders by deadline (earliest first, or latest first - default should be earliest first) The first API returns all the work orders in the database. Each work order has: * id (String) - a unique id of the order * name (String) - the name of the order * description (String) - a short description about the order * deadline (integer) - the deadline for the order in epoch time (seconds) * workerId (integer) - the worker id that is responsible for this worker order The second API returns information about a worker given their id. Each worker has: * id (integer) - a unique id of the worker * name (String) - the name of the worker * email (String) - the email of the worker * companyName (String) - the company of the worker * image (String) - an image for the worker ``` Request: Route: ​XXX Method: ​GET Response: Body: { "orders"​: [{ ​"id"​: ​"480cb439",​ "name"​: ​"Worker Order Name",​ "description"​: ​"This is a description for the work order...",​ "deadline"​: ​1558249206,​ "workerId"​: ​4 }, ... ] } Status:200 #​ epoch time in seconds ``` ``` Request: Route: XXX Method: ​GET Parameters: ​worker_id​: A url parameter that corresponds to the worker id Response: Body: { "worker"​: { ​"id"​:4​, "name"​: ​"<NAME>",​ "email"​: "​ <EMAIL>"​, "companyName"​: ​"Wordify"​, "image": "http://dummyimage.com/250x250.jpg/ff4444/ffffff" } } Status:200 ``` <file_sep>/src/containers/WorkerOrdersContainer.jsx import React from "react"; import WorkOrder from "../components/WorkOrder.jsx"; import { fetchWorkerOrders, fetchWorker } from "../lib/Api.js"; import "./WorkerOrdersContainer.css" class WorkerOrdersContainer extends React.Component { constructor() { super(); this.state = { workerOrders: [], workers: {}, queryStr: "" }; this.onSearch = this.onSearch.bind(this); } onSearch(e) { this.setState({ queryStr: e.target.value }); } fetchData() { // fetch all work orders fetchWorkerOrders().then(data => { const workerOrders = data.orders; // fetch worker for each work order workerOrders.forEach(workerOrder => { const { workerId } = workerOrder; // fetch single worker fetchWorker(workerId).then(workerData => { const worker = workerData.worker; const workers = this.state.workers; // update worker dictionary using fetched worker workers[worker.id] = worker; this.setState({ workers }); // one line solution // this.setState({ workers: {...this.state.workers, [worker.id]: worker }}); }); }); this.setState({ workerOrders }); }); } componentDidMount() { this.fetchData(); } render() { const { workerOrders, workers } = this.state; const orders = workerOrders.filter(workOrder => workOrder.name.includes(this.state.queryStr)) // .sort() .map(workOrder => ( <WorkOrder key={workOrder.id} workOrder={workOrder} worker={workers[workOrder.workerId]} /> )); // console.log(workerOrders, workers) return ( <div className = "page"> search by order name:<input value={this.state.queryStr} onChange={this.onSearch}/> <div className = "cards"> {orders} </div> </div> ); } } export default WorkerOrdersContainer; <file_sep>/src/components/WorkOrder.jsx import React from "react"; import './WorkOrder.css' class WorkOrder extends React.Component { render() { const { workOrder, worker } = this.props; const time = new Date(workOrder.deadline * 1000); return ( <div className = "card"> <div className="order-name"> <h2>{workOrder.name}</h2> </div> <div>{workOrder.description}</div> <div className = "picture"> {worker ? <img src={worker.image} alt="" /> : ""}<br /> </div> {worker ? worker.name : ""} <br /> {worker ? worker.companyName : ""} <br /> {worker ? worker.email : ""} <br /> deadline: {time.toUTCString()} </div> ); } } export default WorkOrder;
3bbe0e3ca9b3c78fc7b610e23d43dc5885b881ea
[ "Markdown", "JavaScript" ]
3
Markdown
slark1995/work-orders-app
1f05edaa5b46bc7c9aaa4ca4500cf644e5596146
ac51ebf7fabae5e59ecc7c08ffcbe6066098afdd
refs/heads/master
<repo_name>szepeviktor/seb2<file_sep>/server/websocket/res/table.js window.onload = init; var prot = "", sock_url = "", msg = null, ws = null, sebTable = null, sebTableHead = null, sebTableBody = null, ws = null, params = {}, ipFilter = {}, checkIp = null, handler = { "addData":addData, "addSeb":addSeb, "removeSeb":removeSeb, "socketError":socketError }; function init() { msg = document.getElementById("message"); log("init"); params = getParams(); ipFilter["local"] = /^(127\.0\.0\.1$)|(\:\:1)$/; ipFilter["intern"] = /^192\.168\.0\.\d+$/; defaulFilter = (defaultFilter) ? defaultFilter : (params.filter) ? params.filter : null; log("defaultFilter: " + defaultFilter); if (defaultFilter && ipFilter[defaultFilter]) { //can be defined in html page checkIp = ipFilter[defaultFilter]; } if (params.filter && ipFilter[params.filter]) { defaultFilter = params.filter; checkIp = ipFilter[defaultFilter]; } if (checkIp != null) { var val = btnShutDownAll.getAttribute("value") + ": " + defaultFilter; btnShutDownAll.setAttribute("value", val); } //log("regex: "+ipFilter["local"].test("127.0.0.0")); sebTable = document.getElementById("sebTable"); sebTableHead = document.getElementById("sebTableHead"); sebTableBody = document.getElementById("sebTableBody"); prot = (window.location.protocol === "https:") ? "wss:" : "ws:"; // for ssl sock_url = prot + "//" + window.location.host; ws = new WebSocket(sock_url); ws.onopen = on_open; ws.onclose = on_close; ws.onmessage = on_message; ws.onerror = on_error; } function on_open() { log("on_open"); } function on_close() { log("on_close"); } function on_message(e) { log("on_message: " + e.data); var obj = JSON.parse(e.data); var h = handler[obj.handler]; if (typeof h === 'function') { h.apply(undefined, [obj.opts]); } } function on_error(e) { log("on_error: " + e); } function log(str) { console.log(str); if (msg.textContent) { msg.textContent = str; return; } if (msg.innerText) { msg.innerText = str; return; } msg.innerHTML = str; } /* handler */ function addData(sebs) { // pushed from monitor server log("addData: " + JSON.stringify(sebs)); for (var key in sebs) { addRow(sebs[key]); } } function addSeb(seb) { log("addSeb: " + JSON.stringify(seb)); addRow(seb); } function removeSeb(seb) { log("removeSeb: " + JSON.stringify(seb)); removeRow(seb); } function socketError(opts) { log(opts.error); ws.close(); } function getParams() { if (!window.location.search) { return({}); // return empty object } var parms = {}; var temp; var items = window.location.search.slice(1).split("&"); // remove leading ? and split for (var i = 0; i < items.length; i++) { temp = items[i].split("="); if (temp[0]) { if (temp.length < 2) { temp.push(""); } parms[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]); } } return(parms); } /* GUI */ function resetTable() { } function setFilter() { } function addRow(seb) { log("addRow: " + JSON.stringify(seb)); if (checkIp != null && !checkIp.test(seb.ip)) { log("filtered: " + seb.ip); return; }; var row = sebTableBody.insertRow(0); row.setAttribute("id","row_"+seb.id); var idCell = row.insertCell(0); idCell.className = "td-id"; var ipCell = row.insertCell(1); ipCell.className = "td-ip"; var rbCell = row.insertCell(2); rbCell.className = "td-reboot"; var sdCell = row.insertCell(3); sdCell.className = "td-shutdown"; idCell.innerHTML = seb.id; ipCell.innerHTML = seb.ip; rbCell.innerHTML = "<input type=\"button\" value=\"reboot\" class=\"btn-reboot\" onclick=\"reboot(\'" + seb.id + "\');\" />"; sdCell.innerHTML = "<input type=\"button\" value=\"shutdown\" class=\"btn-shutdown\" onclick=\"shutdown(\'" + seb.id + "\');\" />"; } function removeRow(seb) { log("removeRow: " + JSON.stringify(seb)); var row = document.getElementById("row_"+seb.id); if (row) { row.parentNode.removeChild(row); } } function shutdown(id) { log("shutdown: " + id); var ret = confirm("Shutdown " + id + "?"); if (ret) { ws.send(JSON.stringify({"handler":"shutdown","opts":{"id":id}})); } } function shutdownAll() { log("shutdownAll"); var idNodes = sebTableBody.querySelectorAll('.td-id'); var ids = []; for (var i=0;i<idNodes.length;i++) { ids.push(idNodes[i].textContent); } var ret = confirm("Shutdown all " + defaultFilter + "?"); if (ret) { ws.send(JSON.stringify({"handler":"shutdownAll","opts":{"ids":ids}})); } //var rows sebTableBody.getElementBy } function reboot(id) { log("reboot: " + id); var ret = confirm("Reboot " + id + "?"); if (ret) { ws.send(JSON.stringify({"handler":"reboot","opts":{"id":id}})); } } function rebootAll() { log("rebootAll"); var idNodes = sebTableBody.querySelectorAll('.td-id'); var ids = []; for (var i=0;i<idNodes.length;i++) { ids.push(idNodes[i].textContent); } var ret = confirm("Reboot all " + defaultFilter + "?"); if (ret) { ws.send(JSON.stringify({"handler":"rebootAll","opts":{"ids":ids}})); } //var rows sebTableBody.getElementBy } //http://caniuse.com/#feat=queryselector <file_sep>/firefox/linux/firefox64.sh #!/bin/bash ./64/firefox -profile firefoxProfile64
d93ba6aa7caeb46e6d0548831704ea88b1c44bee
[ "JavaScript", "Shell" ]
2
JavaScript
szepeviktor/seb2
15f6d4b3bf610ef32cd249f58a1980aa41fee0fc
ac3316f97c7e8d9e1aae52ffcc9eac667cbc25f6
refs/heads/master
<file_sep>package jp.ac.ritsumei.cs.ubi.gucci.LocalizePaths.tree; import jp.ac.ritsumei.cs.ubi.gucci.LocalizePaths.entry.Entry; import java.sql.Timestamp; import java.util.ArrayList; import java.util.TreeMap; /** * Created by gucci on 2015/08/05. */ public class APTreeMaker { private int count; private ArrayList<Component> rootsList; APTreeSercher apTreeSercher; ArrayList<Component> composites; public APTreeMaker(){ this.count = 0; this.rootsList = new ArrayList<Component>(); this.apTreeSercher = new APTreeSercher(); this.composites= new ArrayList<Component>(); } public ArrayList<Component> makeTrees(TreeMap<Timestamp, ArrayList<Entry>> timestampToEntries) { boolean isfirst = true; System.out.println("count : "+ (++count)); for(Timestamp t : timestampToEntries.keySet()){ System.out.print(t + " : "); for(Entry e : timestampToEntries.get(t)) { composites.add(new Composite(e)); } if(isfirst){ rootsList = composites; isfirst = false; }else{ apTreeSercher.addLeaf(rootsList, composites); } composites = new ArrayList<Component>(); } return rootsList; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.FeaturePoint; import jp.ac.ritsumei.cs.ubi.zukky.BRM.hubenyVelocity.HubenyVelocityCalculator; import jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa.Gps; /** * 同一滞在地のGPSをクラスタリングするクラス * @author zukky * */ public class Clustering { private final static Long STAYING_TIME_THRESHOLD = (long) 0; private final static int INITIAL_DISTANCE = 10000; private final double ACC_SECOND_PER_METER = 0.039435287; private final double ACC_DEGREE_PER_METER = ACC_SECOND_PER_METER / 3600; /** * GPSクラスのリストをFeaturePointクラスのリストに変換するメソッド * @param gpsList * @return FeaturePointList */ public List<FeaturePoint> convertGpsListToFeaturePointList(List<Gps> gpsList){ List<FeaturePoint> FeaturePointList = new ArrayList<FeaturePoint>(); for(int i=0; i<gpsList.size(); i++){ Gps gps = gpsList.get(i); FeaturePoint featurePoint = new FeaturePoint(gps); FeaturePointList.add(featurePoint); } return FeaturePointList; } /** * 重心法を用いてGPSをクラスタリングするメソッド(隣り合った点のみをクラスタリングする) * @param culsterGpsList クラスタリングしたいGPSのリスト * @param thresholdDistance クラスタリングする距離の閾値 * @return cehckpointList (クラスタリングしたGPS = チェックポイント)のリスト */ public List<FeaturePoint> clusterNearGpsByCentroidMethod(List<FeaturePoint> FeaturePointList, int thresholdDistance){ double hubenyDistance = INITIAL_DISTANCE; double centroidLat = 0; double centroidLng = 0; boolean arrivalPoint = true; Timestamp arrivalTime = null; Timestamp departureTime = null; long stayingTime = 0; int count = 0; int j=0; if(FeaturePointList.size() != 0){ for(int i=0; (i+1)<FeaturePointList.size(); i=j){ count = i; if(arrivalPoint){ stayingTime = 0; arrivalPoint = false; } hubenyDistance = HubenyVelocityCalculator.calcDistHubeny( FeaturePointList.get(i).getLat(), FeaturePointList.get(i).getLng(), FeaturePointList.get(i+1).getLat(), FeaturePointList.get(i+1).getLng()); if(hubenyDistance < thresholdDistance){ //新しく作成したクラスタに重心をとった緯度経度を入れる centroidLat = (FeaturePointList.get(i).getLat() + FeaturePointList.get(i+1).getLat()) / 2; centroidLng = (FeaturePointList.get(i).getLng() + FeaturePointList.get(i+1).getLng()) / 2; FeaturePointList.get(i).setLat(centroidLat); FeaturePointList.get(i).setLng(centroidLng); FeaturePoint tmp = judgeMaxMinLatLngData_clusterNearGps(FeaturePointList.get(i), FeaturePointList.get(i+1)); FeaturePointList.get(i).setMinLat(tmp.getMinLat() - getAccDgreeFromAcc(tmp.getAcc())); FeaturePointList.get(i).setMaxLat(tmp.getMaxLat() + getAccDgreeFromAcc(tmp.getAcc())); FeaturePointList.get(i).setMinLng(tmp.getMinLng() - getAccDgreeFromAcc(tmp.getAcc())); FeaturePointList.get(i).setMaxLng(tmp.getMaxLng() + getAccDgreeFromAcc(tmp.getAcc())); Timestamp startTime = FeaturePointList.get(i).getArrivalTime(); Timestamp endTime = FeaturePointList.get(i+1).getDepartureTime(); FeaturePointList.get(i).setArrivalTime(startTime); FeaturePointList.get(i).setDepartureTime(endTime); stayingTime = (endTime.getTime() - startTime.getTime())/1000; stayingTime = stayingTime + FeaturePointList.get(i).getStayingTime(); departureTime = FeaturePointList.get(i+1).getTime(); FeaturePointList.get(i).setStayingTime(stayingTime); FeaturePointList.remove(i+1); j=i; }else{ if(stayingTime == 0){ FeaturePointList.get(i).setDepartureTime(FeaturePointList.get(i).getArrivalTime()); }else{ FeaturePointList.get(i).setDepartureTime(departureTime); } arrivalPoint = true; j++; } } if(FeaturePointList.get(count).getDepartureTime() == null){ FeaturePointList.get(count).setDepartureTime(departureTime); arrivalPoint = true; } } return FeaturePointList; } /** * 作成したFeaturepointを最短距離のクラスターにクラスタリングする(ただし、thresholdDistance以下の場合のみクラスタリング) * TODO: クラスタリングの実装は要見直しの必要あり!! * @param clusterList クラスターリスト * @param featurePointList 新たに作成したFeaturePointList * @param thresholdDistance クラスタリングするか否かを決める閾値 * @return */ public void nearestNeighborClustering(List<FeaturePoint> clusterList, List<FeaturePoint> featurePointList, double thresholdDistance){ final int INITIAL_VALUE = 10000; double centroidLat = 0; double centroidLng = 0; double minDistance = thresholdDistance; int clusterListSize = clusterList.size(); int minDistancePointNumber = INITIAL_VALUE; double hubenyDistance; for(int i=0; i<featurePointList.size(); i++){ minDistance = thresholdDistance; for(int j=0; j<clusterListSize; j++){ hubenyDistance = HubenyVelocityCalculator.calcDistHubeny( clusterList.get(j).getLat(), clusterList.get(j).getLng(), featurePointList.get(i).getLat(), featurePointList.get(i).getLng()); if(hubenyDistance < minDistance && clusterList.get(j).getTranshipmentType() == featurePointList.get(i).getTranshipmentType()){ minDistancePointNumber = j; minDistance = hubenyDistance; } } if(minDistance < thresholdDistance){ centroidLat = (clusterList.get(minDistancePointNumber).getLat() + featurePointList.get(i).getLat()) / 2; centroidLng = (clusterList.get(minDistancePointNumber).getLng() + featurePointList.get(i).getLng()) / 2; clusterList.get(minDistancePointNumber).setLat(centroidLat); clusterList.get(minDistancePointNumber).setLng(centroidLng); FeaturePoint tmp = judgeMaxMinLatLngData_ClusterFeaturePoint(clusterList.get(minDistancePointNumber), featurePointList.get(i)); clusterList.get(minDistancePointNumber).setMinLat(tmp.getMinLat()); clusterList.get(minDistancePointNumber).setMaxLat(tmp.getMaxLat()); clusterList.get(minDistancePointNumber).setMinLng(tmp.getMinLng()); clusterList.get(minDistancePointNumber).setMaxLng(tmp.getMaxLng()); clusterList.get(minDistancePointNumber).setTime(featurePointList.get(i).getTime()); clusterList.get(minDistancePointNumber).addTimeList(featurePointList.get(i).getTime()); //クラスタリングする前のデータもクラスタリング後のデータに更新 featurePointList.set(i, clusterList.get(minDistancePointNumber)); }else{ clusterList.add(featurePointList.get(i)); } } } /** * 重心法を用いてGPSデータをクラスタリングするメソッド * @param gpsList クラスタリングしたいGPSのリスト * @return cehckpointList (クラスタリングしたGPS = チェックポイント)のリスト */ public List<FeaturePoint> clusteringCentroidMethod(List<FeaturePoint> FeaturePointList, int thresholdDistance){ double minDistance = INITIAL_DISTANCE; double hubenyDistance = INITIAL_DISTANCE; int minIndex1 = 0; int minIndex2 = 0; double centroidLat = 0; double centroidLng = 0; /* 2点間の距離が一定以下になるまでクラスタリングを続ける */ do{ //最も近い2点をクラスタとしてまとめる if(minDistance != INITIAL_DISTANCE){ centroidLat = (FeaturePointList.get(minIndex1).getLat() + FeaturePointList.get(minIndex2).getLat()) / 2; centroidLng = (FeaturePointList.get(minIndex1).getLng() + FeaturePointList.get(minIndex2).getLng()) / 2; FeaturePointList.get(minIndex1).setLat(centroidLat); FeaturePointList.get(minIndex1).setLng(centroidLng); FeaturePoint tmp = judgeMaxMinLatLngData_ClusterFeaturePoint(FeaturePointList.get(minIndex1), FeaturePointList.get(minIndex2)); FeaturePointList.get(minIndex1).setMinLat(tmp.getMinLat()); FeaturePointList.get(minIndex1).setMaxLat(tmp.getMaxLat()); FeaturePointList.get(minIndex1).setMinLng(tmp.getMinLng()); FeaturePointList.get(minIndex1).setMaxLng(tmp.getMaxLng()); FeaturePointList.get(minIndex1).setTime(FeaturePointList.get(minIndex2).getTime()); FeaturePointList.get(minIndex1).addTimeList(FeaturePointList.get(minIndex2).getTime()); //統合したクラスタの元のクラスタを削除 FeaturePointList.remove(minIndex2); } minDistance = INITIAL_DISTANCE; System.out.println("ok"); for(int i=0; i<FeaturePointList.size()-1; i++){ for(int j=i+1; j<FeaturePointList.size(); j++){ hubenyDistance = HubenyVelocityCalculator.calcDistHubeny( FeaturePointList.get(i).getLat(), FeaturePointList.get(i).getLng(), FeaturePointList.get(j).getLat(), FeaturePointList.get(j).getLng()); if(hubenyDistance < minDistance && FeaturePointList.get(i).getType() == FeaturePointList.get(j).getType()){ minDistance = hubenyDistance; minIndex1 = i; minIndex2 = j; } } } }while(minDistance < thresholdDistance); return FeaturePointList; } private FeaturePoint judgeMaxMinLatLngData_clusterNearGps(FeaturePoint checkPoint, FeaturePoint newGps){ FeaturePoint resultPoint = new FeaturePoint(); if(newGps.getLat() < checkPoint.getMinLat() || checkPoint.getMinLat() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMinLat(newGps.getLat()); resultPoint.setAcc(newGps.getAcc()); }else{ resultPoint.setMinLat(checkPoint.getMinLat()); resultPoint.setAcc(checkPoint.getAcc()); }if(checkPoint.getMaxLat() < newGps.getLat() || checkPoint.getMaxLat() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMaxLat(newGps.getLat()); resultPoint.setAcc(newGps.getAcc()); }else{ resultPoint.setMaxLat(checkPoint.getMaxLat()); resultPoint.setAcc(checkPoint.getAcc()); } if(newGps.getLng() < checkPoint.getMinLng() || checkPoint.getMinLng() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMinLng(newGps.getLng()); resultPoint.setAcc(newGps.getAcc()); }else{ resultPoint.setMinLng(checkPoint.getMinLng()); resultPoint.setAcc(checkPoint.getAcc()); }if(checkPoint.getMaxLng() < newGps.getLng() || checkPoint.getMaxLng() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMaxLng(newGps.getLng()); resultPoint.setAcc(newGps.getAcc()); }else{ resultPoint.setMaxLng(checkPoint.getMaxLng()); resultPoint.setAcc(checkPoint.getAcc()); } return resultPoint; } private FeaturePoint judgeMaxMinLatLngData_ClusterFeaturePoint(FeaturePoint checkPoint, FeaturePoint newFeaturePoint){ FeaturePoint resultPoint = new FeaturePoint(); if(newFeaturePoint.getMinLat() < checkPoint.getMinLat() || checkPoint.getMinLat() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMinLat(newFeaturePoint.getMinLat()); }else{ resultPoint.setMinLat(checkPoint.getMinLat()); }if(checkPoint.getMaxLat() < newFeaturePoint.getMaxLat() || checkPoint.getMaxLat() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMaxLat(newFeaturePoint.getMaxLat()); }else{ resultPoint.setMaxLat(checkPoint.getMaxLat()); } if(newFeaturePoint.getMinLng() < checkPoint.getMinLng() || checkPoint.getMinLng() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMinLng(newFeaturePoint.getMinLng()); }else{ resultPoint.setMinLng(checkPoint.getMinLng()); }if(checkPoint.getMaxLng() < newFeaturePoint.getMaxLng() || checkPoint.getMaxLng() == FeaturePoint.INITIAL_DEGREE){ resultPoint.setMaxLng(newFeaturePoint.getMaxLng()); }else{ resultPoint.setMaxLng(checkPoint.getMaxLng()); } return resultPoint; } /** * gpsのaccuracyを緯度経度の大きさに変換するメソッド * (注)経度35度付近のデータを決め打ちして計算しているので日本以外では微妙 * @param acc * @return */ private double getAccDgreeFromAcc(float acc){ double accDegree = 0; if(acc <= 8){ accDegree = acc * ACC_DEGREE_PER_METER; }else{ accDegree = 8 * ACC_DEGREE_PER_METER; } return accDegree; } } ///** // * 2つのチェックポイントのリストの中で、同一のチェックポイントをまとめるメソッド // * TODO: クラスタリングの実装は要見直しの必要あり!! // * @param beforeCluster // * @param nextCluster // * @return // */ //public List<FeaturePoint> clusterFeaturePoint(List<FeaturePoint> beforeClusterList, List<FeaturePoint> nextClusterList, double threshold, int routeNumber){ // // List<FeaturePoint> FeaturePointList = new ArrayList<FeaturePoint>(); // // for(FeaturePoint point: beforeClusterList) FeaturePointList.add(point); // for(FeaturePoint point: nextClusterList) FeaturePointList.add(point); // // double centroidLat = 0; // double centroidLng = 0; // // double hubenyDistance; // boolean TERMINATED = false; // // while(!TERMINATED){ // TERMINATED = true; // for(int i=0; i<FeaturePointList.size(); i++){ // for(int j=i+1; j<FeaturePointList.size(); j++){ // // hubenyDistance = HubenyVelocityCalculator.calcDistHubeny( // FeaturePointList.get(i).getLat(), FeaturePointList.get(i).getLng(), // FeaturePointList.get(j).getLat(), FeaturePointList.get(j).getLng()); // // if(hubenyDistance < threshold){ // centroidLat = (FeaturePointList.get(i).getLat() + FeaturePointList.get(j).getLat()) / 2; // centroidLng = (FeaturePointList.get(i).getLng() + FeaturePointList.get(j).getLng()) / 2; // // FeaturePoint newFeaturePoint = new FeaturePoint(); // newFeaturePoint.setLat(centroidLat); // newFeaturePoint.setLng(centroidLng); // // FeaturePoint tmp = judgeMaxMinLatLngData_ClusterFeaturePoint(FeaturePointList.get(i), FeaturePointList.get(j)); // // // newFeaturePoint.setMinLat(tmp.getMinLat() - getAccDgreeFromAcc(tmp.getAcc())); // newFeaturePoint.setMaxLat(tmp.getMaxLat() + getAccDgreeFromAcc(tmp.getAcc())); // newFeaturePoint.setMinLng(tmp.getMinLng() - getAccDgreeFromAcc(tmp.getAcc())); // newFeaturePoint.setMaxLng(tmp.getMaxLng() + getAccDgreeFromAcc(tmp.getAcc())); // // newFeaturePoint.setDetailedType(FeaturePointList.get(i).getDetailedType()); // // newFeaturePoint.setStayingTimeList(FeaturePointList.get(i).getStayingTimeList()); // // // FeaturePointList.add(newFeaturePoint); // FeaturePointList.remove(i); // FeaturePointList.remove(j-1); // TERMINATED = false; // // } // } // } // } // // return FeaturePointList; // //} // /** // * 重心法を用いてGPSデータをクラスタリングするメソッド // * @param gpsList クラスタリングしたいGPSのリスト // * @return cehckpointList (クラスタリングしたGPS = チェックポイント)のリスト // */ // public List<FeaturePoint> FeaturePointByCentroidMethod(List<FeaturePoint> FeaturePointList, int thresholdDistance){ // // double minDistance = INITIAL_DISTANCE; // double hubenyDistance = INITIAL_DISTANCE; // int minIndex1 = 0; // int minIndex2 = 0; // double centroidLat = 0; // double centroidLng = 0; // // /* 2点間の距離が一定以下になるまでクラスタリングを続ける */ // do{ // //最も近い2点をクラスタとしてまとめる // if(minDistance != INITIAL_DISTANCE){ // // FeaturePoint cluster = new FeaturePoint(); // // //新しく作成したクラスタに重心をとった緯度経度を入れる // centroidLat = (FeaturePointList.get(minIndex1).getLat() + FeaturePointList.get(minIndex2).getLat()) / 2; // centroidLng = (FeaturePointList.get(minIndex1).getLng() + FeaturePointList.get(minIndex2).getLng()) / 2; // // cluster.setLat(centroidLat); // cluster.setLng(centroidLng); // // //クラスタに含まれているGPSListのインデックスを統合する // List<Integer> indexList1 = FeaturePointList.get(minIndex1).getIndexList(); // List<Integer> indexList2 = FeaturePointList.get(minIndex2).getIndexList(); // // //indexリストを昇順に挿入 // for(int i: indexList1){ // if(cluster.getIndexList().size() == 0){ // cluster.addIndexList(i); // }else{ // for(int j=0; j<cluster.getIndexList().size(); j++){ // // if(i < cluster.getIndexList().get(j)){ // cluster.addIndexList(j, i); // break; // } // if(j == cluster.getIndexList().size() -1){ // cluster.addIndexList(i); // break; // } // } // } // } // // for(int i: indexList2){ // if(cluster.getIndexList().size() == 0){ // cluster.addIndexList(i); // } // for(int j=0; j<cluster.getIndexList().size(); j++){ // if(i < cluster.getIndexList().get(j)){ // cluster.addIndexList(j, i); // break; // } // if(j == cluster.getIndexList().size() -1){ // cluster.addIndexList(i); // break; // } // } // } // // //統合したクラスタの元のクラスタを削除 // FeaturePointList.remove(minIndex1); // FeaturePointList.remove(minIndex2 - 1); // FeaturePointList.add(cluster); // } // // minDistance = INITIAL_DISTANCE; // // for(int i=0; i<FeaturePointList.size()-1; i++){ // for(int j=i+1; j<FeaturePointList.size(); j++){ // hubenyDistance = HubenyVelocityCalculator.calcDistHubeny( // FeaturePointList.get(i).getLat(), // FeaturePointList.get(i).getLng(), // FeaturePointList.get(j).getLat(), // FeaturePointList.get(j).getLng()); // // if(hubenyDistance < minDistance){ // minDistance = hubenyDistance; // minIndex1 = i; // minIndex2 = j; // } // } // } // //System.out.println("minDistance :" + minDistance); // }while(minDistance < thresholdDistance); // // return FeaturePointList; // } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.movingStatisticsDB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.FeaturePoint; public class DropInSiteGetter { /** * 統計情報データベースから立ち寄りポイントのデータを取得するメソッド * @param id 立ち寄りポイントのID * @return dropInSite 取得した立ち寄りポイントのデータ */ public FeaturePoint getDropInSite(int id){ FeaturePoint dropInSite = new FeaturePoint(); PreparedStatement ps; DBHelper connector = new DBHelper(); Connection con; try { con = connector.connectDatabase(); ps = con.prepareStatement("SELECT * from clusteredDropInSite where id = ?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); while(rs.next()){ dropInSite.setLat(rs.getDouble("lat")); dropInSite.setLng(rs.getDouble("lng")); dropInSite.setMaxLat(rs.getDouble("maxLat")); dropInSite.setMinLat(rs.getDouble("minLat")); dropInSite.setMaxLng(rs.getDouble("maxLng")); dropInSite.setMinLng(rs.getDouble("minLng")); } }catch (SQLException e) { System.out.println("Failed to connect DB"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return dropInSite; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.transport; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.Clustering; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.FeaturePoint; import jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa.Gps; import jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa.KubiwaHelper; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; /** * 移動区間を決めうちで取得するクラス * (たくちゃんの研究が完成するまでの仮クラス) * TODO 1つ目の移動区間が格納されてないっぽい * @author zukky * */ public class TransportPeriodGetting { KubiwaHelper kubiwaHelper = new KubiwaHelper(); List<Gps> startGpsList = new ArrayList<Gps>(); List<Gps> endGpsList = new ArrayList<Gps>(); public static void main(String[] args) { } /** * * @param sTime * @param eTime * @return */ public Timestamp[][] getTransportFromstartToend(Timestamp sTime, Timestamp eTime, FeaturePoint startPoint, FeaturePoint endPoint, int devId){ double startLatLow = startPoint.getMinLat(); double startLatHigh = startPoint.getMaxLat(); double startLngLow = startPoint.getMinLng(); double startLngHigh = startPoint.getMaxLng(); //移動終了地点の矩形 double endLatLow = endPoint.getMinLat(); double endLatHigh = endPoint.getMaxLat(); double endLngLow = endPoint.getMinLng(); double endLngHigh = endPoint.getMaxLng(); startGpsList = kubiwaHelper.getGpsPlace(devId, sTime, eTime, startLatLow, startLatHigh, startLngLow, startLngHigh); endGpsList = kubiwaHelper.getGpsPlace(devId, sTime, eTime, endLatLow, endLatHigh, endLngLow, endLngHigh); List<FeaturePoint> featurePointStartList = getFeaturePointList(startGpsList); List<FeaturePoint> featurePointEndList = getFeaturePointList(endGpsList); Timestamp[][] timeArray = new Timestamp[featurePointStartList.size()+1][2]; int i=0; for(FeaturePoint startGps: featurePointStartList){ for(FeaturePoint endGps: featurePointEndList){ long startTime = startGps.getTime().getTime(); long endTime = endGps.getTime().getTime(); long secTime = (endTime - startTime) /1000; if(0 < secTime && secTime < 7200){ timeArray[i][0] = startGps.getTime(); timeArray[i][1] = endGps.getTime(); i++; } } } return timeArray; } // private void divideGpsGetter(Timestamp begin, Timestamp end, FeaturePoint startPoint, FeaturePoint endPoint, int devId){ // // //移動開始地点の矩形 // double startLatLow = startPoint.getMinLat(); // double startLatHigh = startPoint.getMaxLat(); // double startLngLow = startPoint.getMinLng(); // double startLngHigh = startPoint.getMaxLng(); // // //移動終了地点の矩形 // double endLatLow = endPoint.getMinLat(); // double endLatHigh = endPoint.getMaxLat(); // double endLngLow = endPoint.getMinLng(); // double endLngHigh = endPoint.getMaxLng(); // // // int startMonth = begin.getMonth(); // int startYear = begin.getYear(); // int endMonth = end.getMonth(); // int endYear = end.getYear(); // // int differMonth = (endYear - startYear) * 12 + (endMonth - startMonth); // // for(int i=startMonth; i<=(differMonth + startMonth); i++){ // // int differYear = (i+1) / 12; // int sMonth = i % 12; // if(sMonth == 0) sMonth = 12; // int eMonth = (i+1) % 12; // if(eMonth == 0) eMonth = 12; // // Timestamp startTime = new Timestamp(startYear+differYear, sMonth, 2, 0, 0, 0, 0); // Timestamp endTime = new Timestamp(startYear+differYear, eMonth, 1, 23, 59, 59, 59); // // if(i==startMonth){ // startTime = begin; // } // if(i==endMonth){ // endTime = end; // } // // System.out.println("startTime, endTime:" + startTime + " , " +endTime); // // List<Gps> sList = kubiwaHelper.getGpsPlace(devId, startTime, endTime, startLatLow, startLatHigh, startLngLow, startLngHigh); // List<Gps> eList = kubiwaHelper.getGpsPlace(devId, startTime, endTime, endLatLow, endLatHigh, endLngLow, endLngHigh); // // for(Gps gps: sList) startGpsList.add(gps); // for(Gps gps: eList) endGpsList.add(gps); // } // } private List<FeaturePoint> getFeaturePointList(List<Gps> gpsList){ List<FeaturePoint> resultFpList = new ArrayList<FeaturePoint>(); FeaturePoint tmpFpPoint; Clustering clustering = new Clustering(); long TresholdTime = 3600; //10時間 long time = 0; int startIndex = 0; int endIndex = 0; boolean newCluster = true; for(int i=0; i+1 <gpsList.size(); i++){ if(newCluster){ startIndex = i; newCluster = false; } time = ((gpsList.get(i+1).getTime().getTime() - gpsList.get(i).getTime().getTime()) /1000); if(TresholdTime < time){ endIndex = i; List<FeaturePoint> tmpList = new ArrayList<FeaturePoint>(); if(startIndex == endIndex){ tmpList.add(new FeaturePoint(gpsList.get(startIndex))); }else{ for(int j=startIndex; j<endIndex; j++){ tmpList.add(new FeaturePoint(gpsList.get(j))); } tmpList = clustering.clusterNearGpsByCentroidMethod(tmpList, 30000); } tmpFpPoint = tmpList.get(tmpList.size()-1); resultFpList.add(tmpFpPoint); newCluster = true; } if(i+1 == gpsList.size()-1){ List<FeaturePoint> tmpList = new ArrayList<FeaturePoint>(); tmpList.add(new FeaturePoint(gpsList.get(startIndex))); tmpFpPoint = tmpList.get(0); resultFpList.add(tmpFpPoint); newCluster = true; } } return resultFpList; } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker.gps; import jp.ac.ritsumei.cs.ubi.geo.LatLng; public class GPSRectangle { private double minLat; private double minLng; private double maxLat; private double maxLng; public GPSRectangle(double minLat,double minLng,double maxLat,double maxLng){ this.setMinLat(minLat); this.setMinLng(minLng); this.setMaxLat(maxLat); this.setMaxLng(maxLng); } public boolean isContaion(LatLng point){ if((minLat<=point.getLat())&&(point.getLat()<=maxLat)&& (minLng<=point.getLng())&&(point.getLng()<=maxLng)) return true; else return false; } public double getMinLat() { return minLat; } public void setMinLat(double minLat) { this.minLat = minLat; } public double getMinLng() { return minLng; } public void setMinLng(double minLng) { this.minLng = minLng; } public double getMaxLat() { return maxLat; } public void setMaxLat(double maxLat) { this.maxLat = maxLat; } public double getMaxLng() { return maxLng; } public void setMaxLng(double maxLng) { this.maxLng = maxLng; } } <file_sep>/* * Copyright (C) 2008-2012 Ritsumeikan University Nishio Laboratory All Rights Reserved. */ package jp.ac.ritsumei.cs.ubi.kubiwa.pressure.mining; import java.util.ArrayList; import java.util.List; import jp.ac.ritsumei.cs.ubi.library.pressure.PressureObject; import jp.ac.ritsumei.cs.ubi.library.pressure.UpdownListener; /** * This class detect a updown and call LeaveListeners. * @author kome */ public class UpdownDetectorTmp { private final int TYPICAL_VALUE_QUEUE_CAPACITY = 3; // This is a secondValueQueue capacity. private final static float HPA_THRESHOLD = 0.005f; private final static float COUNT_THRESHOLD = 3; private final static float RETURN_TIME_THRESHOLD = 2 * 1000; private final static float LOWPASS_ALPHA = 0.1f; private final static long ONE_SECOND_IN_MILLISECONDS = 1 * 1000; private List<UpdownListener> updownListeners = null; // These listeners are called when this class detect a updown. private ArrayList<Float> rawValueQueue = null; // This is a queue of the most recent pressure. private List<PressureObject> typicalValueQueue= null; // This is a queue of the most recent smoothed pressure. private List<PressureObject> smoothedValueQueue= null; // This is a queue of the most recent smoothed pressure. /*** for updown ***/ private float peakDelta = 0; private float sumDelta = 0; private float tmpSumDelta = 0; /*** for updown detect ***/ private long firstDataTime = -1; private long updownStartTime = -1; private long pastOverTime = -1; private int overCount = 0; private boolean updownFlg = false; private int pastStatus = 0; /** * This is a constructor. */ public UpdownDetectorTmp() { updownListeners = new ArrayList<UpdownListener>(); rawValueQueue = new ArrayList<Float>(); typicalValueQueue = new ArrayList<PressureObject>(); smoothedValueQueue = new ArrayList<PressureObject>(); } /** * Registers a UpdownListener for the Updown Event. * @param updownlistener A UpdownListener object. */ public void addListener(UpdownListener updownlistener){ updownListeners.add(updownlistener); } /** * detect a Updown Event and nortify */ public void detectUpdownAndNortify(long time, long t, float hpa) { if(firstDataTime == -1) { firstDataTime = time; } // System.out.println("[SIZE:" + rawValueQueue.size() + "]Raw Data: " + new Timestamp(time) + ", " + hpa); /*** 以前のデータと比較して、秒が変わっていたら検知処理を開始 ***/ if(time - firstDataTime >= ONE_SECOND_IN_MILLISECONDS) { typicalValueQueue.add(new PressureObject(firstDataTime, calcAverageOfRawValueQueue())); // 平均で秒の代表値を算出 // System.out.println("[SIZE:" + typicalValueQueue.size() + "]Typical Data: " + new Timestamp(firstDataTime) + ", " + calcAverageOfRawValueQueue()); /*** 平滑用キューが埋まっていれば平滑処理を開始 ***/ if(typicalValueQueue.size() >= TYPICAL_VALUE_QUEUE_CAPACITY) { float typicalValue = calcAverageOfTypicalValueQueue(); // 直近の代表値3データにおける平均を計算 float smoothedValue = 0; if(smoothedValueQueue.isEmpty()) { /*** 初めてのローパスフィルタなら平均をそのまま利用 ***/ smoothedValue = typicalValue; smoothedValueQueue.add(new PressureObject(typicalValueQueue.get(TYPICAL_VALUE_QUEUE_CAPACITY-1).getTime(), typicalValue)); } else { /*** 前回のローパスフィルタの結果があるなら利用して平滑処理計算 ***/ smoothedValue = lowpassFiltering(typicalValue); smoothedValueQueue.add(new PressureObject(typicalValueQueue.get(TYPICAL_VALUE_QUEUE_CAPACITY-1).getTime(), smoothedValue)); } typicalValueQueue.remove(0); // System.out.println("[SIZE:" + smoothedValueQueue.size() + "]Smoothed Data: " + new Timestamp(firstDataTime) + ", " + smoothedValue); } /*** updown検知処理 ***/ if(smoothedValueQueue.size() >= 2) { detectUpdown(); smoothedValueQueue.remove(0); } rawValueQueue.clear(); //秒の代表値における処理が終われば、次の秒の処理に向けてキューを初期化 firstDataTime = time; //現在フォーカスしている秒を再設定 } rawValueQueue.add(hpa); } /** * detect a Updown Event */ private void detectUpdown() { float delta = smoothedValueQueue.get(smoothedValueQueue.size()-1).getHpa() - smoothedValueQueue.get(smoothedValueQueue.size()-2).getHpa(); long diffTime = -1; /*** 今回の閾値越え検知がupdownにおける初めての検知でなければ、前回に閾値を越えた時間との差分を計算 ***/ if(pastOverTime != -1) { diffTime = smoothedValueQueue.get(smoothedValueQueue.size()-1).getTime() - pastOverTime; // 最終閾値検知と現時刻との差分を計算(特徴点終了判定に利用) } /* * 以下のどちらかに合致すればupdownの終了処理を行う。 * 「前回の閾値越え検知時刻と現在時刻の差分が閾値を超えており」、かつ、「閾値を下回っていた場合」 * 「今回のupdownにおけるピーク値と正負が逆」で、かつ「閾値を超えた場合」 */ if(updownStartTime != -1 && ((diffTime >= RETURN_TIME_THRESHOLD && Math.abs(delta) < HPA_THRESHOLD) || ((peakDelta >= 0) != (delta >= 0) && Math.abs(delta) >= HPA_THRESHOLD))) { /*** updown検知が開始していたら、UpdownStopedイベントを発行 ***/ if(updownFlg) { for(UpdownListener updownListener : updownListeners){ updownListener.onUpdownStoped(pastOverTime+ONE_SECOND_IN_MILLISECONDS, sumDelta, peakDelta); pastStatus = 0; } // 次回特徴点のための初期化 peakDelta = 0; sumDelta = 0; tmpSumDelta = 0; updownFlg = false; } pastOverTime = -1; // 前回のピーク値検出時間を初期化 diffTime = -1; // 前回のピーク値検出時間と現時点との時刻を初期化 updownStartTime = -1; // 特徴点の開始時刻を初期化 overCount = 0; // 閾値越え連続検知回数を初期化 } /*** 前回の気圧値との差分が閾値を超えていたらUpdown検知処理開始 ***/ if(Math.abs(delta) >= HPA_THRESHOLD) { /*** 閾値越え検知が今回の検知イベント中で初めてなら、初期化を行う ***/ if(updownStartTime == -1) { updownStartTime = smoothedValueQueue.get(smoothedValueQueue.size()-1).getTime(); // updown開始時刻を最新のデータ時刻に設定 overCount = 0; // 連続で閾値を越えた回数を初期化 sumDelta = 0; // updownイベント中の気圧変化を初期化 } // 現時点における特徴点の最大(最小)ピーク値を保存 if(delta >= 0) { peakDelta = Math.max(peakDelta, delta); } else { peakDelta = Math.min(peakDelta, delta); } sumDelta = sumDelta + delta; // 特徴点抽出全期間における気圧変化を記録 if(tmpSumDelta != 0) { sumDelta = sumDelta + tmpSumDelta; tmpSumDelta = 0; } overCount++; // 連続で閾値を越えた回数を記録 pastOverTime = smoothedValueQueue.get(smoothedValueQueue.size()-1).getTime(); // 現時点における最終閾値越え検知時刻を更新 /* 連続閾値越え検知回数が閾値を超えていたら、updownイベントを発行 */ if(overCount >= COUNT_THRESHOLD) { updownFlg = true; for(UpdownListener updownListener : updownListeners){ if(peakDelta >= 0 && pastStatus != 2) { updownListener.onDowned(updownStartTime); pastStatus = 2; } else if(peakDelta < 0 && pastStatus != 1) { updownListener.onUpped(updownStartTime); pastStatus = 1; } } } } else { if(updownStartTime != -1) { tmpSumDelta = tmpSumDelta + delta; } overCount = 0; // 閾値を越えなかった場合は、連続閾値越え検知カウンタをリセット } } /** * Returns if this Collection contains no elements. This implementation tests, whether size returns 0. * @return if there is no listeners, return true. */ public boolean isEmpty(){ return updownListeners.isEmpty(); } /** * ローパスフィルタをかけるメソッド. * @param t SensorEvent.timestamp * @param hpa SensorEvent.values[0] */ private float lowpassFiltering(float hpa) { return smoothedValueQueue.get(smoothedValueQueue.size()-1).getHpa()*(1-LOWPASS_ALPHA) + hpa*LOWPASS_ALPHA; } /** * calculate average of rawValueQueue * @return average of queue */ private float calcAverageOfRawValueQueue() { float avgHpa = 0; for(Float hpa: rawValueQueue){ avgHpa += hpa; } return avgHpa/rawValueQueue.size(); } /** * calculate average of secondValueQueue * @return average of queue */ private float calcAverageOfTypicalValueQueue() { float avgHpa = 0; for(PressureObject pressure: typicalValueQueue){ avgHpa += pressure.getHpa(); } return avgHpa/typicalValueQueue.size(); } }<file_sep>rootProject.name = 'AutomatedManagementSystem' <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa; import jp.ac.ritsumei.cs.ubi.library.accelerometer.AccelerometerObject; /** * 加速度に関する情報を保持するクラス * @author zukky * */ public class Acceleration extends AccelerometerObject{ private boolean step; private long time; public long getTime() { return time; } public void setTime(long time) { this.time = time; } public boolean isStep() { return step; } public void setStep(boolean step) { this.step = step; } public Acceleration(long time, long t, float x, float y, float z) { super(time,t, x, y, z); // TODO Auto-generated constructor stub } public Acceleration(Acceleration acc){ super(acc.getTime(), acc.getT(), acc.getX(), acc.getY(), acc.getZ()); this.time = acc.getTime(); } public Acceleration(){ super(0, 0, 0, 0, 0); } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker.db; //TODO �����[�X���ɂ͂����̏����������� /** * Blackhole�ւ̐ڑ��ɕK�v�Ȋe�����ێ����Ă����N���X * @author takuchan */ public class ConstantBlackhole { final static String USER="kubiwauser"; final static String PASS="<PASSWORD>"; //final static String URL="jdbc:mysql://exp-www.ubi.cs.ritsumei.ac.jp:3306/blackhole"; //�|�[�g�t�H���[�f�B���O final static String URL="jdbc:mysql://exp-www.ubi.cs.ritsumei.ac.jp:3306/blackhole"; final static String PORT_FWD_URL="jdbc:mysql://localhost:9000/blackhole"; } <file_sep>package jp.ac.ritsumei.cs.ubi.kubiwa.pressure.mining; import jp.ac.ritsumei.cs.ubi.library.pressure.PressureObject; import java.util.Comparator; public class PressureValueComparator implements Comparator<PressureObject> { @Override public int compare(PressureObject a, PressureObject b) { float aHpa = a.getHpa(); float bHpa = b.getHpa(); //Hpaを用いて昇順でソート if (aHpa > bHpa) { return 1; } else if (aHpa == bHpa) { return 0; } else { return -1; } } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.json; import java.util.ArrayList; import java.util.List; public class Json_Movement { private List<Json_Transportation> jTransportationList = new ArrayList<Json_Transportation>(); public List<Json_Transportation> getjTransportationList() { return jTransportationList; } public void setjTransportationList(List<Json_Transportation> jTransportationList) { this.jTransportationList = jTransportationList; } public void addjTransportationList(Json_Transportation jTransportation) { this.jTransportationList.add(jTransportation); } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.manager; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.calculation.Similarity; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.calculation.WeightedEuclideanDistance; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.entries.WifiSignature; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.cluster.Cluster; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.cluster.ClusterMode; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.config.ThreshConfig; import java.util.Set; /** * Created by gucci on 2015/06/15. */ public class MatchClusterFinder { FindResult findResult = new FindResult(); ThreshConfig threshConfig = new ThreshConfig(); public FindResult find(WifiSignature newWifiSignature, Set<Cluster> clusters, SystemPhase phase){ Similarity similarity = new WeightedEuclideanDistance(); double distance = 0; double nearestDist = 1000; for(Cluster cluster : clusters) { distance = similarity.between(newWifiSignature, cluster.getWifiSignature());//特徴量と標本 if (distance < nearestDist) { findResult.setMatchCluster(cluster); nearestDist = distance; } } switch (phase) { case LOCALIZE: if (nearestDist >= threshConfig.getGenerateClusterThresh()) { findResult.setNow_state(ClusterMode.CREATE); } else if (nearestDist <= threshConfig.getUpdateClusterThresh()) { findResult.setNow_state(ClusterMode.UPDATE); } else { findResult.setNow_state(ClusterMode.DO_NOTHING); } return findResult; case MANAGEMENT: if (nearestDist > threshConfig.getUpdateClusterThresh()) { findResult.setNow_state(ClusterMode.CREATE); } else{ findResult.setNow_state(ClusterMode.UPDATE); } return findResult; } return null; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa.Gps; /** * 乗換えポイント、チェックポイント候補などをまとめて管理するクラス * @author zukky */ public class FeaturePoint extends Gps { public static final double INITIAL_DEGREE = 10000000; public static final int priHigh = 3; public static final int priNormal = 2; public static final int priLow = 1; public enum Type{ TRANSHIPMENT_POINT, CHECKPOINT_CANDIDATE, DROP_IN_SITE } public enum DetailedType{ BUS_STOP, STATION, CYCLE_PARKING, TRAFFIC_LIGHT, UNKNOWN, } public enum TranshipmentPointType{ WALK_TO_VEHICLE, VEHICLE_TO_WALK; } private boolean isIndoor = false; //private List<Type> TypeList = new ArrayList<Type>(); private Type type; private DetailedType detailedType; private TranshipmentPointType transhipmentType; private int id = 0; private double lat; private double lng; private double maxLat = INITIAL_DEGREE; private double minLat = INITIAL_DEGREE; private double maxLng = INITIAL_DEGREE; private double minLng = INITIAL_DEGREE; private long stayingTime = 0; private long averageStayingTime = 0; private long sumStayingTime = 0; private float probability; private int numberPassages = 0; private int numberStop = 0; private List<Timestamp> timeList = new ArrayList<Timestamp>(); private int priority = priNormal; public float getProbability() { return probability; } public void setProbability(float probability) { this.probability = probability; } private List<Long> stayingTimeList = new ArrayList<Long>(); //private Map<Integer, Long> stayingTimeMap = new HashMap<Integer, Long>(); //arrivalTime と departureTime もMap型に private Timestamp arrivalTime; private Timestamp departureTime; // private List<String> idList = new ArrayList<>(); public FeaturePoint(Gps gps) { this.setAcc(gps.getAcc()); this.setDevId(gps.getDevId()); this.setLat(gps.getLat()); this.setLng(gps.getLng()); this.setlTime(gps.getlTime()); this.setSpeed(gps.getSpeed()); this.setTime(gps.getTime()); this.setArrivalTime(gps.getTime()); this.setDepartureTime(gps.getTime()); // TODO Auto-generated constructor stub } public FeaturePoint(FeaturePoint featurePoint){ this.setId(featurePoint.getId()); this.setAcc(featurePoint.getAcc()); this.setDevId(featurePoint.getDevId()); this.setLat(featurePoint.getLat()); this.setLng(featurePoint.getLng()); this.setlTime(featurePoint.getlTime()); this.setSpeed(featurePoint.getSpeed()); this.setTime(featurePoint.getTime()); this.setArrivalTime(getTime()); this.setDepartureTime(getTime()); this.setStayingTime(featurePoint.getStayingTime()); this.setSumStayingTime(featurePoint.getSumStayingTime()); this.setAverageStayingTime(featurePoint.getSumStayingTime()); this.setProbability(featurePoint.getProbability()); this.setNumberPassages(featurePoint.getNumberPassages()); this.setNumberStop(featurePoint.getNumberStop()); } public FeaturePoint(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public double getMaxLat() { return maxLat; } public void setMaxLat(double maxLat) { this.maxLat = maxLat; } public double getMinLat() { return minLat; } public void setMinLat(double minLat) { this.minLat = minLat; } public double getMaxLng() { return maxLng; } public void setMaxLng(double maxLng) { this.maxLng = maxLng; } public double getMinLng() { return minLng; } public void setMinLng(double minLng) { this.minLng = minLng; } public Timestamp getArrivalTime() { return arrivalTime; } public void setArrivalTime(Timestamp arrivalTime) { this.arrivalTime = arrivalTime; } public Timestamp getDepartureTime() { return departureTime; } public void setDepartureTime(Timestamp departureTime) { this.departureTime = departureTime; } public DetailedType getDetailedType() { return detailedType; } public void setDetailedType(DetailedType detailedType) { this.detailedType = detailedType; } public void addTimeList(Timestamp time){ this.timeList.add(time); } public List<Timestamp> getTimeList(){ return this.timeList; } /** * 矩形を囲むための最大値と最小値をセットするメソッド * @param lat1 * @param lng1 * @param lat2 * @param lng2 */ public void setMinMaxLatLng(double lat1, double lng1, double lat2, double lng2){ if(lat1 <= lat2){ minLat = lat1; maxLat = lat2; }else{ minLat = lat2; maxLat = lat1; } if(lng1 <= lng2){ minLng = lng1; maxLng = lng2; }else{ minLng = lng2; maxLng = lng1; } } /** * 矩形を囲むための最大値と最小値をセットするメソッド * @param lat1 * @param lng1 * @param lat2 * @param lng2 */ public void setMinMaxLatLng(Gps gps1, Gps gps2){ if(gps1.getLat() <= gps2.getLat()){ minLat = gps1.getLat(); maxLat = gps2.getLat(); }else{ minLat = gps2.getLat(); maxLat = gps1.getLat(); } if(gps1.getLng() <= gps2.getLng()){ minLng = gps1.getLng(); maxLng = gps2.getLng(); }else{ minLng = gps2.getLng(); maxLng = gps1.getLng(); } } // public Map<Integer, Long> getStayingTimeMap() { // return stayingTimeMap; // } // // public void setStayingTimeMap(Map<Integer, Long> stayingTimeMap) { // this.stayingTimeMap = stayingTimeMap; // } // public void putStayingTimeMap(int routeId, long stayingTime){ // this.stayingTimeMap.put(routeId, stayingTime); // } // public List<String> getIdList() { // return idList; // } // // public void setIdList(List<String> IdList) { // this.idList = IdList; // } // public void addIdList(String id){ // this.idList.add(id); // } public long getStayingTime() { return stayingTime; } public void setStayingTime(long stayingTime) { this.stayingTime = stayingTime; } public List<Long> getStayingTimeList() { return stayingTimeList; } public void setStayingTimeList(List<Long> stayingTimeList) { this.stayingTimeList = stayingTimeList; } public void addStayingTime(long stayingTime){ this.stayingTimeList.add(stayingTime); } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public long getAverageStayingTime() { return averageStayingTime; } public void setAverageStayingTime(long averageStayingTime) { this.averageStayingTime = averageStayingTime; } public long getSumStayingTime() { return sumStayingTime; } public void setSumStayingTime(long sumStayingTime) { this.sumStayingTime = sumStayingTime; } public int getNumberPassages() { return numberPassages; } public void setNumberPassages(int numberPassages) { this.numberPassages = numberPassages; } public int getNumberStop() { return numberStop; } public void setNumberStop(int numberStop) { this.numberStop = numberStop; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public TranshipmentPointType getTranshipmentType() { return transhipmentType; } public void setTranshipmentType(TranshipmentPointType transhipmentType) { this.transhipmentType = transhipmentType; } public boolean isIndoor() { return isIndoor; } public void setIndoor(boolean isIndoor) { this.isIndoor = isIndoor; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa; import java.io.Serializable; import java.sql.Timestamp; public class Gps implements Serializable{ private static final long serialVersionUID = 1L; private Timestamp time; private int devId; private double lat; private double lng; private float acc; private float speed; private Timestamp lTime; public Gps(double lat, double lng){ this.setLat(lat); this.setLng(lng); } public Gps(){ } public Timestamp getTime() { return time; } public void setTime(Timestamp time) { this.time = time; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public float getAcc() { return acc; } public void setAcc(float acc) { this.acc = acc; } public float getSpeed() { return speed; } public void setSpeed(float speed) { this.speed = speed; } public int getDevId() { return devId; } public void setDevId(int devId) { this.devId = devId; } public Timestamp getlTime() { return lTime; } public void setlTime(Timestamp lTime) { this.lTime = lTime; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.movingStatisticsDB; public class MovementDbUtil { final static String USER="kubiwauser"; final static String PASS="<PASSWORD>"; //final static String URL="jdbc:mysql://cloud.ubi.cs.ritsumei.ac.jp/movingStatistic_db"; // final static String URL="jdbc:mysql://localhost:3307/movingStatistic_db"; } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.ClusteredDropInSite; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.DropInSite; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.DropInSiteTransition; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.DropInSiteTransitionCount; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.transition.TransitionGenerator; import java.util.List; /** * �������|�C���g�̊e������R���\�[����ɏo�͂���ׂ̃N���X * @author takuchan */ public class DropInSiteInformer { TransitionGenerator transitionGenerator = new TransitionGenerator(); public void displayGeneralInformationOfDropInSite(List<DropInSite> dropInSiteList,List<ClusteredDropInSite> clusteredDropInSiteList){ System.out.println("[DropInSiteInformer display general information...]"); for(DropInSite dropInSite:dropInSiteList){ // System.out.println("\nID:" + dropInSite.getId() + ", CLUSTER ID:" + dropInSite.getClusterId() // + ", START:" + dropInSite.getStartTime() + ", END:" + dropInSite.getEndTime()); // System.out.println("Drop in time:" + dropInSite.getDropInTime()/60000); // System.out.println("MaxLatLng:(" + (get(clusteredDropInSiteList,dropInSite.getClusterId())).getMaxLat() + "," + // (get(clusteredDropInSiteList,dropInSite.getClusterId())).getMaxLng() + // "), MinLatLng:(" + (get(clusteredDropInSiteList,dropInSite.getClusterId())).getMinLat() + "," + // (get(clusteredDropInSiteList,dropInSite.getClusterId())).getMinLng() + ")"); } } public void displayDropInSiteTransition(List<DropInSite> dropInSiteList,List<ClusteredDropInSite> clusteredDropInSiteList){ String startID,endID; System.out.println("[DropInSiteInformer displaying transition...]"); List<DropInSiteTransition> dropInSiteTransitionList = transitionGenerator.generateDropInSiteTransitionList(dropInSiteList); for(DropInSiteTransition dropInSiteTransition:dropInSiteTransitionList){ //�m�C�Y���ۂ��̏���t������ if(get(clusteredDropInSiteList, dropInSiteTransition.getStartId()).isNoise()) startID = dropInSiteTransition.getStartId() + "(noise)"; else startID = dropInSiteTransition.getStartId(); if(get(clusteredDropInSiteList, dropInSiteTransition.getEndId()).isNoise()) endID = dropInSiteTransition.getEndId() + "(noise)"; else endID = dropInSiteTransition.getEndId(); System.out.println("\nSTART ID:" + startID + ",END ID:" + endID); System.out.println("START TIME:" + dropInSiteTransition.getStartTime() + ",END TIME:" + dropInSiteTransition.getEndTime()); } } public void displayTransitionCount(List<DropInSite> dropInSiteList,List<ClusteredDropInSite> clusteredDropInSiteList){ String startID,endID; System.out.println("[DropInSiteInformer displaying transition count ...]"); List<DropInSiteTransitionCount> transitionCountList = transitionGenerator.generateDropInSiteTransitionCountList(dropInSiteList); for(DropInSiteTransitionCount transitionCount:transitionCountList){ //�m�C�Y���ۂ��̏���s�‚��� if(get(clusteredDropInSiteList, transitionCount.getStartId()).isNoise()) startID = transitionCount.getStartId() + "(noise)"; else startID = transitionCount.getStartId(); if(get(clusteredDropInSiteList, transitionCount.getEndId()).isNoise()) endID = transitionCount.getEndId() + "(noise)"; else endID = transitionCount.getEndId(); System.out.println("\nSTART ID:" + startID + ",END ID:" + endID + ",COUNT:" + transitionCount.getCount()); } } /** * �{���Ȃ�ClusteredDropInSiteList�Ƃ������N���X�������,�����������Ă����ׂ��Ȃ̂��낤�����,���f���ʓ|�Ȃ̂ł����Ƀ��\�b�h���. * TODO ���ƂŒ��� * @param id * @return */ private ClusteredDropInSite get(List<ClusteredDropInSite> clusteredDropInSiteList,String id){ for(ClusteredDropInSite clusteredDropInSite:clusteredDropInSiteList){ if(clusteredDropInSite.getId().equals(id)) return clusteredDropInSite; } return null; } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker.gps; import java.sql.Timestamp; import java.util.ArrayList; import jp.ac.ritsumei.cs.ubi.geo.LatLng; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.gps.*; public class GPSDataList extends ArrayList<jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.gps.GPSData>{ //����GPSDataList�������ɑ؍݂��Ă�����ԂɎ擾���ꂽ���̂��ǂ��� private boolean isIndoorSite=false; private Timestamp lastFoundTime; private LatLng firstLostPoint; private LatLng lastFoundPoint; private int stepCount; public boolean isIndoorSite() { return isIndoorSite; } public void setIndoorSite(boolean isIndoorDropInSite) { this.isIndoorSite = isIndoorDropInSite; } public Timestamp getLastFoundTime() { return lastFoundTime; } public void setLastFoundTime(Timestamp lastFoundTime) { this.lastFoundTime = lastFoundTime; } public int getStepCount() { return stepCount; } public void setStepCount(int stepCount) { this.stepCount = stepCount; } public LatLng getLastFoundPoint() { return lastFoundPoint; } public void setLastFoundPoint(LatLng lastFoundPoint) { this.lastFoundPoint = lastFoundPoint; } public LatLng getFirstLostPoint() { return firstLostPoint; } public void setFirstLostPoint(LatLng firstLostPoint) { this.firstLostPoint = firstLostPoint; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.inputOutput; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.List; import java.util.Map; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.FeaturePoint; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.FeaturePoint.TranshipmentPointType; import jp.ac.ritsumei.cs.ubi.zukky.BRM.hubenyVelocity.HubenyVelocity; import jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa.Gps; /** * 指定したデータをCSVファイルに書き込むクラス * @author zukky * */ public class CsvWriter { /** * TODO: ジェネリクスとか勉強して下記の関数を書き直す */ public void writeRouteDataTest(List<List> routeDataList, String filePath){ try { for(int i=0; i<routeDataList.size(); i++){ List<FeaturePoint> routeData = routeDataList.get(i); PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath + "_" + i + ".csv"))); System.out.println("csvRouteDataList: " + routeData.size()); for(FeaturePoint fp: routeData){ printWriter.println(fp.getMinLat() + "," + fp.getMinLng() + "," + fp.getMaxLat() + "," + fp.getMaxLng() + "," + "blue"); } printWriter.close(); } } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } /** * ちゃんたく用にlat,lngのペアのみをCSVファイルに書き込む * @param gpsList * @param filePath */ public void writeLatLngData(List<Gps> gpsList, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(Gps gps: gpsList){ printWriter.println(gps.getLat() + "," + gps.getLng()); } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } public void writeTestRectangleData(Gps gps1, Gps gps2, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); printWriter.println(gps1.getLat() + "," + gps1.getLng() + "," + gps2.getLat() + "," + gps2.getLng() + "," + "blue"); printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } /** * ちゃんたく用にlat,lngのペアのみをCSVファイルに書き込む * @param checkpointList * @param filePath */ public void writeLatLngCheckpointData(List<FeaturePoint> FeaturePointList, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(FeaturePoint featurePoint: FeaturePointList){ printWriter.println(featurePoint.getLat() + "," + featurePoint.getLng()); } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } /** * ちゃんたく用にlat,lngのペアのみをCSVファイルに書き込む * @param checkpointList * @param filePath */ public void writeRectangleData(List<FeaturePoint> featurePointList, String filePath, String color){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(FeaturePoint checkpoint: featurePointList){ double minLat = checkpoint.getMinLat(); double maxLat = checkpoint.getMaxLat(); double minLng = checkpoint.getMinLng(); double maxLng = checkpoint.getMaxLng(); if(!checkpoint.isIndoor()){ //printWriter.println(maxLat + "," + maxLng + "," + minLat + "," + minLng + "," + color); if(checkpoint.getTranshipmentType() == TranshipmentPointType.VEHICLE_TO_WALK){ printWriter.println(maxLat + "," + maxLng + "," + minLat + "," + minLng + "," + "green"); }else{ printWriter.println(maxLat + "," + maxLng + "," + minLat + "," + minLng + "," + "blue"); } } } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } public void writeRectangleData(FeaturePoint featurePoint, String filePath, String color){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); double minLat = featurePoint.getMinLat(); double maxLat = featurePoint.getMaxLat(); double minLng = featurePoint.getMinLng(); double maxLng = featurePoint.getMaxLng(); printWriter.println(minLat + "," + minLng + "," + maxLat + "," + maxLng + "," + color); printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } public void writeRectangleData(List<String> resultList, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(String result: resultList){ printWriter.println(result); } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + "_ファイル書き込みエラーです"); } } public void writeTime(Map<Timestamp, Timestamp> timeMap, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(Timestamp key: timeMap.keySet()){ long sec = (timeMap.get(key).getTime() - key.getTime()) / 1000; printWriter.println("startTime, endTime, sec:" + key +","+ timeMap.get(key) +","+ sec); } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } public void writeRequiredTimeTest(Timestamp[][] time, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); int arrayLength = 0; for(int i=0; time[i][0] != null; i++){ arrayLength++; } long[] timeArrayAscend = new long[arrayLength]; System.out.println("time.length: " + time.length); for(int i=0; time[i][0] != null; i++){ System.out.println("time[i][1].getTime " + time[i][1].getTime()); timeArrayAscend[i] = (time[i][1].getTime() - time[i][0].getTime()); System.out.println("i :" + i); } java.util.Arrays.sort(timeArrayAscend); long count = 0; long sumTime = 0; for(int i=0; i<timeArrayAscend.length; i++){ printWriter.println("【" + i + "】所要時間: " + (timeArrayAscend[i] / 1000)); sumTime = sumTime + (timeArrayAscend[i] / 1000); count++; } long averageTime = (sumTime / count); printWriter.println("averageTime " + averageTime); printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } public void writeHubenyVelocity(List<Double> hubenyVelocityList, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(double hubenyVelocity: hubenyVelocityList){ printWriter.println(hubenyVelocity); } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } public void writeHubenyVelocity2(List<HubenyVelocity> hubenyVelocityList, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(HubenyVelocity hubenyVelocity: hubenyVelocityList){ printWriter.println(hubenyVelocity.getStartTime() + "," + hubenyVelocity.getVelocity()); } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } /** * ヒュベニ速度を欠損区間の速度を0にして算出するメソッド * @param hubenyVelocityList * @param filePath */ public void writeHubenyVelocityDeficit(List<HubenyVelocity> hubenyVelocityList, String filePath){ try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); for(HubenyVelocity hubenyVelocity: hubenyVelocityList){ printWriter.println(hubenyVelocity.getStartTime() + "," + hubenyVelocity.getVelocity()); if(1000 < (hubenyVelocity.getEndTime().getTime() - hubenyVelocity.getStartTime().getTime())){ long time = hubenyVelocity.getStartTime().getTime(); while(1000 < (hubenyVelocity.getEndTime().getTime() - time)){ time = time + 1000; printWriter.println(new Timestamp(time) + "," + 0); } } } printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } public void writeTransportation(String transportation, String filePath){ try { PrintWriter printWriter = new PrintWriter(new FileWriter(filePath , true)); printWriter.println(transportation); printWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + e); } } } <file_sep>package jp.ac.ritsumei.cs.ubi.kubiwa.pressure.mining; import jp.ac.ritsumei.cs.ubi.library.pressure.UpdownListener; import jp.ac.ritsumei.cs.ubi.zukky.BRM.pressure.Pressure; import jp.ac.ritsumei.cs.ubi.zukky.BRM.pressure.PressureValue; import java.util.List; //import com.sun.xml.internal.ws.api.config.management.policy.ManagedServiceAssertion.ImplementationRecord; /** * 気圧センサのデータを与えて、up-downの情報を取得するクラス * @author zukky * */ public class UpDownFinder { public static UpdownRecorder getUpDown(List<Pressure> pressureList, final UpdownRecorder updownRecorder){ UpdownDetector updownDetector = new UpdownDetector(); UpdownListener updownListener = implementUpdownListener(updownRecorder); updownDetector.addListener(updownListener); for(Pressure pressure: pressureList){ for(PressureValue pressureValue: pressure.getValue()){ updownDetector.detectUpdownAndNortify(pressure.getTime().getTime(), pressureValue.getT(), new Float(pressureValue.getHpa())); } } return updownRecorder; } /** * * @return */ private static UpdownListener implementUpdownListener(final UpdownRecorder updownRecorder){ UpdownListener updownListener = new UpdownListener() { @Override public void onUpped(long t) { // TODO Auto-generated method stub //System.out.println("up"); updownRecorder.addUpCount(); } @Override public void onUpdownStoped(long t, float sum, float peak) { // TODO Auto-generated method stub //System.out.println("down"); updownRecorder.addDownCount(); } @Override public void onDowned(long t) { // TODO Auto-generated method stub } }; return updownListener; } } <file_sep>/** * Copyright (C) 2008-2012 Nishio Laboratory All Rights Reserved */ package jp.ac.ritsumei.cs.ubi.walker; import java.util.ArrayList; import java.util.List; /** * This class listens for step events and tells when the walker is standstill or * walking. * * @author Ubiquitous Computing and Networking Laboratory */ public class WalkerStateDetector implements StepListener { /** * The maximum possible number of milliseconds between steps while walking. */ private double PITCH_MAX; final List<WalkerStateListener> listeners = new ArrayList<WalkerStateListener>(1); final List<WalkerState> cluster = new ArrayList<WalkerState>(1); /** * The time in milliseconds of the first step of the last walk. */ long firstStep = -1; /** * The time in milliseconds of the last step. */ long lastStep = -1; /** * The number of steps after {@link #firstStep}. */ int steps = 0; long firstLog; boolean isLastLog = false; boolean isFirstState = true; /** * Adds the specified {@code WalkerStateListener} to receive notifications * when the walker's state has changed. * * @param l the listener to add * @throws NullPointerException if {@code l} is {@code null} */ void addWalkerStateListener(WalkerStateListener l) { if (l == null) { throw new NullPointerException(); } listeners.add(l); } protected void setTimeThresh(int sec){ this.PITCH_MAX = sec * 1000; } public List<WalkerState> getCluster(){ return cluster; } public void firstLog(long time) { this.firstLog = time; } public void lastLog(){ this.isLastLog = true; } int i = 0; public void onStep(long time) { steps++; i++; //System.out.println("counter:"+i); if(isFirstState){ // System.out.println("aaaaaaa"); // System.out.println("start:"+firstLog+ " end:"+time); fireWalkerStateChanged(new WalkerState( WalkerState.Type.STANDSTILL, firstLog, time, 0)); firstStep = time; isFirstState = false; lastStep = time; } if(isLastLog){ //System.out.println("sstart:"+lastStep+ " end:"+time); fireWalkerStateChanged(new WalkerState( WalkerState.Type.WALKING, firstStep, lastStep, steps)); fireWalkerStateChanged(new WalkerState( WalkerState.Type.STANDSTILL, lastStep, time, 0)); } if (lastStep > 0 && PITCH_MAX < time - lastStep && !isLastLog) { //System.out.println("ssstart:"+lastStep+ " end:"+time); //if (firstStep > 0) { fireWalkerStateChanged(new WalkerState( WalkerState.Type.WALKING, firstStep, lastStep, steps)); //} fireWalkerStateChanged(new WalkerState( WalkerState.Type.STANDSTILL, lastStep, time, 0)); steps = 0; firstStep = time; } //steps++; lastStep = time; //System.out.println("lastStep:"+lastStep); } protected void fireWalkerStateChanged(WalkerState state) { cluster.add(state); for (WalkerStateListener l : listeners) { l.onWalkerStateChanged(state); } } } <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>jp.ac.ritsumei.cs.ubi.cluster</groupId> <artifactId>SampleCluster</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <plugins> </plugins> </build> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.20</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.1.5.Final</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>net.arnx</groupId> <artifactId>jsonic</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.kohsuke</groupId> <artifactId>graphviz-api</artifactId> <version>1.1</version> </dependency> </dependencies> </project><file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa; public class Device { private int devId; private int userid; private int devTypeId; private String devName; private String picture; private String color; private int active; private String bthName; private String bthAddr; public int getDevId() { return devId; } public void setDevId(int devId) { this.devId = devId; } public int getUserid() { return userid; } public void setUserid(int userId) { this.userid = userId; } public int getDevTypeId() { return devTypeId; } public void setDevTypeId(int deviceTypeId) { this.devTypeId = deviceTypeId; } public String getDevName() { return devName; } public void setDevName(String devName) { this.devName = devName; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getActive() { return active; } public void setActive(int active) { this.active = active; } public String getBthName() { return bthName; } public void setBthName(String bthName) { this.bthName = bthName; } public String getBthAddr() { return bthAddr; } public void setBthAddr(String bthAddr) { this.bthAddr = bthAddr; } } <file_sep>kubiwa.mysql.url = jdbc:mysql://exp-www-local.ubi.cs.ritsumei.ac.jp/blackhole?useUnicode=true&characterEncoding=utf8 kubiwa.mysql.urlPortFwd = jdbc:mysql://localhost:9000/blackhole?useUnicode=true&characterEncoding=utf8 kubiwa.mysql.passwd = <PASSWORD> kubiwa.mysql.user = kubiwauser kubiwa.mysql.table = LocationLog<file_sep>/** * Copyright (C) 2008-2012 Nishio Laboratory All Rights Reserved */ package jp.ac.ritsumei.cs.ubi.walker; /** * Interface for objects to listen for step events. */ interface StepListener { /** * Invoked when a step is detected. * * @param time the time in milliseconds */ public void onStep(long time); public void firstLog(long time); public void lastLog(); } <file_sep>/** * Copyright (C) 2008-2012 Nishio Laboratory All Rights Reserved */ package jp.ac.ritsumei.cs.ubi.walker; import java.util.ArrayList; import java.util.List; /** * Detects steps and notifies {@link StepListener}s. * <p> * The codes are taken from <a href="http://code.google.com/p/pedometer/"> * {@code name.bagi.levente.pedometer.StepDetector}</a> with slight * modifications. * * @see <a href="http://code.google.com/p/pedometer/">Pedometer - Android app</a> */ class StepDetecter implements SensorEventListener { static final float STANDARD_GRAVITY = 9.80665f; static final float Y_OFFSET = 240.0f; static final float SCALE = -(Y_OFFSET * (1.0f / (STANDARD_GRAVITY * 2))); final List<StepListener> mStepListeners = new ArrayList<StepListener>(1); /* * very high 10 * high 20 * medium 30 * low 40 * very low 50 */ int mLimit; //41 nexus s int lastDirection = 0; int lastMatch = 0; float lastV = 0; float lastDiff = 0; float[] lastExtremes = new float[] { 0, 0 }; public StepDetecter(int thresh){ this.mLimit = thresh; } public void addStepListener(StepListener l) { mStepListeners.add(l); } float x = 0,y=0,z=0; float alpha = 0.015f;//0.015 public void onSensorChanged(SensorEvent event) { if(event.isFirstLog){ for (StepListener stepListener : mStepListeners) { stepListener.firstLog(event.time); } } if(event.isLastLog){ for (StepListener stepListener : mStepListeners) { stepListener.lastLog(); stepListener.onStep(event.time); } return; } //x = alpha * event.x + (1.0f - alpha) * x; //y = alpha * event.y + (1.0f - alpha) * y; //z = alpha * event.z + (1.0f - alpha) * z; float v = Y_OFFSET + SCALE * (event.x + event.y + event.z) / 3.0f; int direction = Float.compare(v, lastV); if (direction * lastDirection < 0) { // Direction changed int extType = (direction > 0 ? 0 : 1); // minimum or maximum? lastExtremes[extType] = lastV; float diff = Math.abs(lastExtremes[extType] - lastExtremes[1 - extType]); if (diff > mLimit) { boolean isAlmostAsLargeAsPrevious = (diff > (lastDiff * 2 / 3)); boolean isPreviousLargeEnough = (lastDiff > (diff / 3)); boolean isNotContra = (lastMatch != 1 - extType); if (isAlmostAsLargeAsPrevious && isPreviousLargeEnough && isNotContra) { for (StepListener stepListener : mStepListeners) { stepListener.onStep(event.time); } lastMatch = extType; } else { lastMatch = -1; } } lastDiff = diff; } lastDirection = direction; lastV = v; } }<file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite; import java.sql.Timestamp; public class DropInSiteTransition { private String startId; private String endId; private Timestamp startTime; private Timestamp endTime; public DropInSiteTransition(String startId,String endId,Timestamp startTime,Timestamp endTime) { this.setStartId(startId); this.setEndId(endId); this.setStartTime(startTime); this.setEndTime(endTime); } public String getStartId() { return startId; } public void setStartId(String startId) { this.startId = startId; } public String getEndId() { return endId; } public void setEndId(String endId) { this.endId = endId; } public Timestamp getStartTime() { return startTime; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public Timestamp getEndTime() { return endTime; } public void setEndTime(Timestamp endTime) { this.endTime = endTime; } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.LocalizePaths.statistic; import jp.ac.ritsumei.cs.ubi.gucci.LocalizePaths.entry.Entry; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * Created by gucci on 2015/08/12. */ public class APStatisticTool { private Map<String, APSquare> bssidToAPSquare; Timestamp startTimestamp = new Timestamp(0); Timestamp endTimestamp = new Timestamp(0); double maxRssi = 0; double minRssi = 0; long timeDifference = 0; long width = 0; double height = 0; public Map<String, APSquare> squareAreaStatisticProcess( TreeMap<String, ArrayList<Entry>> bssidToEntries){ bssidToAPSquare = new HashMap<String, APSquare>(); for(String s : bssidToEntries.keySet()){ APSquare apSquare = new APSquare(); width = 0; for(Entry e : bssidToEntries.get(s)){ timeDifference = e.getTimestamp().getTime() - endTimestamp.getTime(); if(300<timeDifference) { startTimestamp = e.getTimestamp(); endTimestamp = e.getTimestamp(); maxRssi = e.getRssi(); minRssi= e.getRssi(); }else{ endTimestamp = e.getTimestamp(); if (maxRssi < e.getRssi()) maxRssi = e.getRssi(); else if (e.getRssi() < minRssi) minRssi = e.getRssi(); if(width < (endTimestamp.getTime() - startTimestamp.getTime())) { width = endTimestamp.getTime() - startTimestamp.getTime(); apSquare.setStartTimestamp(startTimestamp); apSquare.setEndTimestamp(endTimestamp); apSquare.setMaxRssi(maxRssi); apSquare.setMinRssi(minRssi); } } } bssidToAPSquare.put(s,apSquare); } System.out.println("[[check all bssid]]"); for(String s: bssidToAPSquare.keySet()){ width = bssidToAPSquare.get(s).getEndTimestamp().getTime() - bssidToAPSquare.get(s).getStartTimestamp().getTime(); height = bssidToAPSquare.get(s).getMaxRssi() - bssidToAPSquare.get(s).getMinRssi(); System.out.println(s +" : "+ bssidToAPSquare.get(s).getStartTimestamp() +" : "+ width+" : "+height +" : "+ (width*height)); } return bssidToAPSquare; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.pressure; import java.sql.Timestamp; import java.util.List; public class Pressure { private Timestamp time; private List<PressureValue> value; public Pressure(){} public Pressure(Timestamp time, List<PressureValue> value) { super(); this.time = time; this.value = value; } /** * @return the time */ public Timestamp getTime() { return time; } /** * @param time the time to set */ public void setTime(Timestamp time) { this.time = time; } /** * @return the value */ public List<PressureValue> getValue() { return value; } /** * @param value the value to set */ public void setValue(List<PressureValue> value) { this.value = value; } @Override public String toString() { return "Pressure [time=" + time + ", value=" + value + "]"; } }<file_sep>/** * Copyright (C) 2008-2012 Nishio Laboratory All Rights Reserved */ package jp.ac.ritsumei.cs.ubi.walker; /** * This class represents a sample of accelerometer values. * * @author Ubiquitous Computing and Networking Laboratory */ class SensorEvent { /** * Acceleration on the x-axis in SI units (m/s^2). */ float x; /** * Acceleration on the y-axis in SI units (m/s^2). */ float y; /** * Acceleration on the z-axis in SI units (m/s^2). */ float z; /** * Time stamp in milliseconds. */ long time; /** * Time stamp in nanoseconds. */ long nanos; /** * Time stamp in second. */ float second; boolean isFirstLog = false; boolean isLastLog = false; SensorEvent(float x, float y, float z, long time, long nanos) { super(); this.x = x; this.y = y; this.z = z; this.time = time; this.nanos = nanos; this.second = time / 1000; } SensorEvent(float second, float x, float y, float z) { super(); this.x = x; this.y = y; this.z = z; this.time = (long) (second * 1000); this.nanos = (long) (second * 1000000000); this.second = second; } SensorEvent(float x, float y, float z, long time, long nanos, boolean isLastLog) { super(); this.x = x; this.y = y; this.z = z; this.time = time; this.nanos = nanos; this.second = time / 1000; this.isLastLog = isLastLog; } SensorEvent(boolean isFirstLog, float x, float y, float z, long time, long nanos) { super(); this.x = x; this.y = y; this.z = z; this.time = time; this.nanos = nanos; this.second = time / 1000; this.isFirstLog = isFirstLog; } @Override public String toString() { return "[" + x + ", " + y + ", " + z + "]"; } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.statistic; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.cluster.Cluster; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.statistic.AccumulatedTimeComparator; import java.util.Set; import java.util.TreeSet; /** * Created by gucci on 2015/06/24. */ public class StatisticalProcessor { public TreeSet sortClusters(Set<Cluster> clusters){ TreeSet<Cluster> sortedClusters = new TreeSet<Cluster>(new AccumulatedTimeComparator()); for(Cluster c : clusters){ sortedClusters.add(c); } return sortedClusters; } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker.dropInSite; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class DropInSiteTransitionCountList extends ArrayList<DropInSiteTransitionCount> implements Serializable{ public DropInSiteTransitionCountList(List<DropInSiteTransitionCount> DropInSiteTransitionCountList){ this.addAll(DropInSiteTransitionCountList); } public List<DropInSiteTransitionCount> getAllClusteredDropInSiteList(){ return this; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.path; import java.util.List; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.FeaturePoint; import jp.ac.ritsumei.cs.ubi.zukky.BRM.transport.Transportation.TransportationType; /** * 乗り換えポイント間の移動情報を保持するクラス * @author zukky * */ public class PathSegment { private int pathID; private int segmentID; private int routeID; private TransportationType type; private FeaturePoint tsStartPoint; private FeaturePoint tsEndPoint; private List<FeaturePoint> checkPointcandidateList; public FeaturePoint getTsStartPoint() { return tsStartPoint; } public void setTsStartPoint(FeaturePoint tsStartPoint) { this.tsStartPoint = tsStartPoint; } public FeaturePoint getTsEndPoint() { return tsEndPoint; } public void setTsEndPoint(FeaturePoint tsEndPoint) { this.tsEndPoint = tsEndPoint; } public TransportationType getType() { return type; } public void setType(TransportationType type) { this.type = type; } public int getPathID() { return pathID; } public void setPathID(int pathID) { this.pathID = pathID; } public int getSegmentID() { return segmentID; } public void setSegmentID(int segmentID) { this.segmentID = segmentID; } public List<FeaturePoint> getCheckPointCandidateList() { return checkPointcandidateList; } public void setCheckPointCandidateList(List<FeaturePoint> checkPointCandidateList) { this.checkPointcandidateList = checkPointCandidateList; } public void add(FeaturePoint checkPointCandidate){ this.checkPointcandidateList.add(checkPointCandidate); } public int getRouteID() { return routeID; } public void setRouteID(int routeID) { this.routeID = routeID; } } <file_sep>/* * Copyright (C) 2008-2012 Ritsumeikan University Nishio Laboratory All Rights Reserved. */ package jp.ac.ritsumei.cs.ubi.kubiwa.pressure.mining; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jp.ac.ritsumei.cs.ubi.library.pressure.PressureObject; import jp.ac.ritsumei.cs.ubi.library.pressure.UpdownListener; /** * This class detect a updown and call LeaveListeners. * @author kome */ public class UpdownDetector { private List<UpdownListener> updownListeners = null; // These listeners are called when this class detect a updown. // private final static float HPA_DETECT_THRESHOLD = 0.0035f; // for 6data/sec // private final static float HPA_DELTA_DETECT_THRESHOLD = 0.018f; // for 1data/sec private final static float HPA_DELTA_DETECT_THRESHOLD = 0.03f; // for 1data/sec private final static float COUNT_THRESHOLD = 3; private final static float LOWPASS_ALPHA = 0.1f; private final static int SEARCH_DATA_WINDOW_SIZE = 15; // means search Updown occur point with 15s (for 1data/sec) private final static int SEARCH_DATA_AVERAGE_WINDOW_SIZE = 25; // means SEARCH DATA generated by 4s avg. (This value is MUST "ODD" number) private ArrayList<PressureObject> rawValueQueue = null; // This is a queue of the most recent pressure. private List<PressureObject> smoothedValueQueueX1= null; // This is a queue of the most recent smoothed(EMAx1) pressure. private List<PressureObject> smoothedValueQueueX2= null; // This is a queue of the most recent smoothed(EMAx2) pressure. private List<PressureObject> smoothedValueQueueX3= null; // This is a queue of the most recent smoothed(EMAx3) pressure. private List<PressureObject> smoothedValueQueueX4= null; // This is a queue of the most recent smoothed(EMAx4) pressure. private List<PressureObject> valueQueueForDetect= null; // This is a queue of the most recent smoothed(for Detect Start) pressure. private List<PressureObject> valueQueueForSearch= null; // This is a queue of the most recent smoothed(for Search Start/End) pressure. private List<PressureObject> tmpQueueForDetect= null; private List<PressureObject> tmpQueueForSearch= null; private List<PressureObject> tmpAvgQueueForSearch= null; private final static int WHETHER_CORRECT_SLOPE_WINDOW_SIZE = 45; // 線形近似を算出するために使うデータ数 (for 1data/sec) private final static int NOISE_CORRECT_AVERAGE_WINDOW_SIZE = 5; // ノイズ補正を行うために利用するデータ数 private List<PressureObject> pressureQueueForErrorCorrect = null; // 線形近似&ノイズ補正を算出するために使うデータ private List<PressureObject> deltaQueueForErrorCorrect = null; // 線形近似を算出するために使うデータ /*** for updown ***/ private PressureObject updownStartObj = null; private PressureObject updownEndObj = null; private PressureObject fixedUpdownStartObj = null; private PressureObject fixedUpdownEndObj = null; private float peakDelta = 0; /*** for updown detect ***/ private int overCount = 0; public int currentStatus = 0; private PressureObject peakObj = null; private boolean isSequentialOver = false; private boolean isDecisionStay = false; private boolean isCorrectWork = false; int counter = 0; /** * This is a constructor. */ public UpdownDetector() { updownListeners = new ArrayList<UpdownListener>(); rawValueQueue = new ArrayList<PressureObject>(); smoothedValueQueueX1 = new ArrayList<PressureObject>(); smoothedValueQueueX2 = new ArrayList<PressureObject>(); smoothedValueQueueX3 = new ArrayList<PressureObject>(); smoothedValueQueueX4 = new ArrayList<PressureObject>(); valueQueueForDetect = new ArrayList<PressureObject>(); valueQueueForSearch = new ArrayList<PressureObject>(); tmpQueueForDetect = new ArrayList<PressureObject>(); tmpQueueForSearch = new ArrayList<PressureObject>(); tmpAvgQueueForSearch = new ArrayList<PressureObject>(); pressureQueueForErrorCorrect = new ArrayList<PressureObject>(); deltaQueueForErrorCorrect = new ArrayList<PressureObject>(); } /** * Registers a UpdownListener for the Updown Event. * @param updownlistener A UpdownListener object. */ public void addListener(UpdownListener updownlistener){ updownListeners.add(updownlistener); } /** * detect a Updown Event and nortify */ public void detectUpdownAndNortify(long time, long t, float hpa) { rawValueQueue.add(new PressureObject(time, hpa)); prepareSmoothedData(); //観測されたrawデータから、Avg(変化開始終了探索用)とLP(階層移動検知用)のデータを生成 /*** updown検知処理 ***/ if(currentStatus == PressureObject.STATE_STAY) { detectUpdown(); } if(currentStatus != PressureObject.STATE_STAY) { detectStay(); } /*** 変化検知用キューは最新データのみ保持(直近との差分のみを使用) ***/ if(valueQueueForDetect.size() >= 2) { valueQueueForDetect.remove(0); } /*** 変化地点探索用キューは10秒間保持 ***/ if(currentStatus == PressureObject.STATE_STAY && valueQueueForSearch.size() >= SEARCH_DATA_WINDOW_SIZE) { valueQueueForSearch.remove(0); } if(pressureQueueForErrorCorrect.size() >= 150) { pressureQueueForErrorCorrect.remove(0); } if(deltaQueueForErrorCorrect.size() >= 150) { // System.out.println("delta remove[" + 0 + "] : " + new Timestamp(deltaQueueForErrorCorrect.get(0).getTime())); deltaQueueForErrorCorrect.remove(0); } } /** * detect a Updown Event */ private void detectUpdown() { if(valueQueueForDetect.size() >= 2) { float delta = valueQueueForDetect.get(valueQueueForDetect.size()-1).getHpa() - valueQueueForDetect.get(valueQueueForDetect.size()-2).getHpa(); // // System.out.println(new Timestamp(valueQueueForDetect.get(valueQueueForDetect.size()-1).getTime()) + ", hpa:" + valueQueueForDetect.get(valueQueueForDetect.size()-1).getHpa() + ", delta:" + delta); /*** 前回の気圧値との差分が閾値を超えていたらカウンタを更新 ***/ if(Math.abs(delta) >= HPA_DELTA_DETECT_THRESHOLD) { if(delta >= 0) peakDelta = Math.max(peakDelta, delta); // 現時点における特徴点の最大ピーク値を保存 else peakDelta = Math.min(peakDelta, delta); // 現時点における特徴点の最小ピーク値を保存 overCount++; // 連続で閾値を越えた回数を記録 } else { isSequentialOver = false; peakDelta = 0; overCount = 0; // 閾値を越えなかった場合は、カウンタをリセット } /* 連続閾値越え検知回数が閾値を超えていたら、updown検知処理を開始 */ if(overCount >= COUNT_THRESHOLD && !isSequentialOver) { // // System.out.println("[UPDOWN EVENT OCCURED]"); /* 変化開始地点を探索 */ searchStartPoint(peakDelta); fixedUpdownStartObj = correctStartPoint(); for(UpdownListener updownListener : updownListeners){ if(isCorrectWork) { // 補正が動作した場合 if(peakDelta < 0 && currentStatus != PressureObject.STATE_UP && fixedUpdownStartObj != null) { updownListener.onUpped(fixedUpdownStartObj.getTime()); currentStatus = PressureObject.STATE_UP; isSequentialOver = true; } else if(peakDelta >= 0 && currentStatus != PressureObject.STATE_DOWN && fixedUpdownStartObj != null) { updownListener.onDowned(fixedUpdownStartObj.getTime()); currentStatus = PressureObject.STATE_DOWN; isSequentialOver = true; } } else { // 補正が動作しなかった場合 if(peakDelta < 0 && currentStatus != PressureObject.STATE_UP && updownStartObj != null) { updownListener.onUpped(updownStartObj.getTime()); currentStatus = PressureObject.STATE_UP; isSequentialOver = true; } else if(peakDelta >= 0 && currentStatus != PressureObject.STATE_DOWN && updownStartObj != null) { updownListener.onDowned(updownStartObj.getTime()); currentStatus = PressureObject.STATE_DOWN; isSequentialOver = true; } } } } } } private void detectStay() { if(valueQueueForDetect.size() >= 2) { float delta = valueQueueForDetect.get(valueQueueForDetect.size()-1).getHpa() - valueQueueForDetect.get(valueQueueForDetect.size()-2).getHpa(); /*** 現在の階層移動における気圧変化ピーク値を更新 (一度閾値を下回った場合は対象外として更新しない) ***/ if(Math.abs(delta) >= HPA_DELTA_DETECT_THRESHOLD && isSequentialOver) { // // System.out.println("[STILL OVER THRESHOLD]" + delta); if(delta >= 0) peakDelta = Math.max(peakDelta, delta); else peakDelta = Math.min(peakDelta, delta); } else if(Math.abs(delta) < HPA_DELTA_DETECT_THRESHOLD) { // // System.out.println("[UNDER THRESHOLD]" + delta); isSequentialOver = false; } // まず終了地点を探す if(updownEndObj == null) { searchEndPoint(peakDelta); if(updownEndObj != null) { // // System.out.println("END POINT DETECT AT : " + new Timestamp(updownEndObj.getTime())); } } if (updownEndObj != null) { // updown終了地点を見つけたら if(isCorrectWork) { // updown開始時点で補正が働いていたら、終了時点も同様に補正を実行 // ノイズ補正のためにデータを収集する // NOISE_CORRECT_AVERAGE_WINDOW_SIZE分のデータが集まるか、閾値が一旦下回ってからもう一度越えた(次のupdownが始まる)とき if((!isSequentialOver && Math.abs(delta) >= HPA_DELTA_DETECT_THRESHOLD) || valueQueueForDetect.get(valueQueueForDetect.size()-1).getTime() - updownEndObj.getTime() >= (NOISE_CORRECT_AVERAGE_WINDOW_SIZE+1) * 1000) { // // System.out.println("DIFF TIME : " + (valueQueueForDetect.get(valueQueueForDetect.size()-1).getTime() - updownEndObj.getTime())); // // System.out.println("DECISION STAY : " + true + " at " + new Timestamp(valueQueueForDetect.get(valueQueueForDetect.size()-1).getTime())); isDecisionStay = true; } if(currentStatus != 0 && isDecisionStay) { for(UpdownListener updownListener : updownListeners){ // // System.out.println(new Timestamp(updownStartObj.getTime()) + "," + updownStartObj.getHpa()); // // System.out.println(new Timestamp(updownEndObj.getTime()) + "," + updownEndObj.getHpa()); fixedUpdownEndObj = correctEndPoint(); // System.out.println("[BEFORE CORRECT]start(" + new Timestamp(updownStartObj.getTime()) + ")" + updownStartObj.getHpa() + ", end(" + new Timestamp(updownEndObj.getTime()) + ")=" + updownEndObj.getHpa() + ", diff=" + (updownEndObj.getHpa() - updownStartObj.getHpa())); // System.out.println("[AFTER CORRECT]start(" + new Timestamp(fixedUpdownStartObj.getTime()) + ")" + fixedUpdownStartObj.getHpa() + ", end(" + new Timestamp(fixedUpdownEndObj.getTime()) + ")=" + fixedUpdownEndObj.getHpa() + ", diff=" + (fixedUpdownEndObj.getHpa() - fixedUpdownStartObj.getHpa())); updownListener.onUpdownStoped(fixedUpdownEndObj.getTime(), fixedUpdownEndObj.getHpa() - fixedUpdownStartObj.getHpa(), peakDelta); // 「停滞時のデータが足りないときは直近の停滞時のデータを使いたい場合」は次の処理をコメントアウト、ここから for(int i=deltaQueueForErrorCorrect.size()-1; i>=0; i--) { if(deltaQueueForErrorCorrect.get(i).getTime() < updownEndObj.getTime()) { deltaQueueForErrorCorrect.remove(i); } } // ここまで updownStartObj = null; updownEndObj = null; fixedUpdownStartObj = null; fixedUpdownEndObj = null; peakDelta = 0; currentStatus = PressureObject.STATE_STAY; isDecisionStay = false; isCorrectWork = false; } } } else { // updown開始時点で補正が働いていなかったら、そのままオリジナルを使って決定 if(currentStatus != 0) { for(UpdownListener updownListener : updownListeners){ // // System.out.println(new Timestamp(updownStartObj.getTime()) + "," + updownStartObj.getHpa()); // // System.out.println(new Timestamp(updownEndObj.getTime()) + "," + updownEndObj.getHpa()); // System.out.println("[DO NOT WORK CORRECT]start(" + new Timestamp(updownStartObj.getTime()) + ")+" + updownStartObj.getHpa() + ", end(" + new Timestamp(updownEndObj.getTime()) + ")=" + updownEndObj.getHpa() + ", diff=" + (updownEndObj.getHpa() - updownStartObj.getHpa())); updownListener.onUpdownStoped(updownEndObj.getTime(), updownEndObj.getHpa() - updownStartObj.getHpa(), peakDelta); // 「停滞時のデータが足りないときは直近の停滞時のデータを使いたい場合」は次の処理をコメントアウト、ここから for(int i=deltaQueueForErrorCorrect.size()-1; i>0; i--) { if(deltaQueueForErrorCorrect.get(i).getTime() <= updownEndObj.getTime()) { deltaQueueForErrorCorrect.remove(i); } } // ここまで updownStartObj = null; updownEndObj = null; fixedUpdownStartObj = null; fixedUpdownEndObj = null; peakDelta = 0; currentStatus = PressureObject.STATE_STAY; isDecisionStay = false; isCorrectWork = false; } } } } } } private void searchStartPoint(float overDelta) { /*** 探索の基準となる、探索用キューの過去における変化の最大値を探索 ***/ searchPeakPoint(overDelta); /*** 基準(変化最大値)から過去に向かって、変化の変わり目を探索 ***/ for(int i=valueQueueForSearch.size()-1; i>0; i--) { // // System.out.println("[Compare Peak Time(" + new Timestamp(peakObj.getTime()) + ")]current : " + new Timestamp(valueQueueForSearch.get(i).getTime())); if(valueQueueForSearch.get(i).getTime() <= peakObj.getTime()) { float currentDelta = valueQueueForSearch.get(i).getHpa() - valueQueueForSearch.get(i-1).getHpa(); // // System.out.println("[Search Start Change Sign]current : " + currentDelta); if((overDelta >= 0) != (currentDelta >= 0)) { // // System.out.println("[UPDOWN DETECT RESULT]: " + new Timestamp(valueQueueForSearch.get(i).getTime())); updownStartObj = valueQueueForSearch.get(i); return; } } } if(updownStartObj == null) { updownStartObj = valueQueueForSearch.get(0); // // System.out.println("[UPDOWN DETECT RESULT]Cannot find change sign, use 1st data: " + new Timestamp(valueQueueForSearch.get(0).getTime())); } } private void searchEndPoint(float overDelta) { int endIndex = -1; /*** 変化最大値から未来に向かって、変化の変わり目を探索 ***/ for(int i=1; i<=valueQueueForSearch.size()-1; i++) { // // System.out.println("[Compare Peak Time(" + new Timestamp(peakObj.getTime()) + ")]current : " + new Timestamp(valueQueueForSearch.get(i).getTime())); if(valueQueueForSearch.get(i).getTime() >= peakObj.getTime()) { float currentDelta = valueQueueForSearch.get(i).getHpa() - valueQueueForSearch.get(i-1).getHpa(); endIndex = i; // // System.out.println("[Search End Change Sign]current : " + currentDelta); if((overDelta >= 0) != (currentDelta >= 0)) { // // System.out.println("[STAY DETECT RESULT]: " + new Timestamp(valueQueueForSearch.get(i).getTime())); updownEndObj = valueQueueForSearch.get(i); break; } } } for(int i=0; i<endIndex-1; i++) { valueQueueForSearch.remove(0); } } private void searchPeakPoint(float overDelta) { float peakDelta = 0; /*** 探索用キューの過去における変化の最大値を探索 ***/ for(int i=1; i<=valueQueueForSearch.size()-1; i++) { float currentDelta = valueQueueForSearch.get(i).getHpa() - valueQueueForSearch.get(i-1).getHpa(); // // System.out.println("[Search Peak]CurrentTime:" + new Timestamp(valueQueueForSearch.get(i).getTime()) + ", CurrentDelta:" + currentDelta); if(Math.abs(currentDelta) >= Math.abs(peakDelta) && (currentDelta>=0) == (overDelta>=0)) { // 今回のdeltaが過去最高deltaを上回り、かつ符号が同じならば peakObj = valueQueueForSearch.get(i); peakDelta = currentDelta; } } // // System.out.println("[PEAK DETECT RESULT]PeakTime:" + new Timestamp(peakObj.getTime()) + ", PeakDelta:" + peakDelta); } /** * Returns if this Collection contains no elements. This implementation tests, whether size returns 0. * @return if there is no listeners, return true. */ public boolean isEmpty(){ return updownListeners.isEmpty(); } /* * ローパスフィルタをかける */ private void lowpassFiltering(List<PressureObject> srcList, List<PressureObject> dstList) { PressureObject srcLatest = srcList.get(srcList.size()-1); if(dstList.isEmpty()) { dstList.add(new PressureObject(srcLatest.getTime(), srcLatest.getHpa())); } else { PressureObject dstLatest = dstList.get(dstList.size()-1); dstList.add(new PressureObject(srcLatest.getTime(), dstLatest.getHpa()*(1-LOWPASS_ALPHA) + srcLatest.getHpa()*LOWPASS_ALPHA)); } } /* * 秒毎の代表値(中央値使用)を選出する */ private static PressureObject selectTypicalValueWithMedian(List<PressureObject> pressureList) { List<PressureObject> sortedValueList = new ArrayList<PressureObject>(); sortedValueList.addAll(pressureList); Collections.sort(sortedValueList, new PressureValueComparator()); if(sortedValueList.size() % 2 == 0) { return new PressureObject(sortedValueList.get(sortedValueList.size()/2).getTime(), (sortedValueList.get((sortedValueList.size()/2)-1).getHpa() + sortedValueList.get(sortedValueList.size()/2).getHpa())/2); } else { return new PressureObject(sortedValueList.get(sortedValueList.size()/2).getTime(), sortedValueList.get(sortedValueList.size()/2).getHpa()); } } /* * イベント検知に必要な平滑データの用意を行う */ private float prepareSmoothedData() { lowpassFiltering(rawValueQueue, smoothedValueQueueX1); lowpassFiltering(smoothedValueQueueX1, smoothedValueQueueX2); lowpassFiltering(smoothedValueQueueX2, smoothedValueQueueX3); lowpassFiltering(smoothedValueQueueX3, smoothedValueQueueX4); // if(!smoothedValueQueueX4.isEmpty()) { // // System.out.println(counter++ + "," + smoothedValueQueueX4.get(smoothedValueQueueX4.size()-1).getHpa()); // } /*** updown検知用データ(/sec->lowpass*4)を格納 ***/ if(tmpQueueForDetect.size()>=2) { if(smoothedValueQueueX4.get(smoothedValueQueueX4.size()-1).getTime() - tmpQueueForDetect.get(0).getTime() >= 1000) { valueQueueForDetect.add(selectTypicalValueWithMedian(tmpQueueForDetect)); tmpQueueForDetect.clear(); // // System.out.println(new Timestamp(valueQueueForDetect.get(valueQueueForDetect.size()-1).getTime()) + "," + valueQueueForDetect.get(valueQueueForDetect.size()-1).getHpa()); } } tmpQueueForDetect.add(smoothedValueQueueX4.get(smoothedValueQueueX4.size()-1)); /*** updown開始時点探索用データ(avg/sec)を格納 ***/ tmpQueueForSearch.add(rawValueQueue.get(rawValueQueue.size()-1)); if(tmpQueueForSearch.size() == SEARCH_DATA_AVERAGE_WINDOW_SIZE) { if(tmpAvgQueueForSearch.size() >= 2) { // 現在tmpAvgQueueForSearchに入っている時刻と、次に入ってくるtmpQueueForSearch.size()/2の時刻を比較し、 // 時刻が変わるなら、現在の時刻の代表値をtmpAvgQueueForSearchの中央値で選出 if(tmpQueueForSearch.get(tmpQueueForSearch.size()/2).getTime() - tmpAvgQueueForSearch.get(0).getTime() >= 1000) { valueQueueForSearch.add(selectTypicalValueWithMedian(tmpAvgQueueForSearch)); // 誤差補正用 pressureQueueForErrorCorrect.add(selectTypicalValueWithMedian(tmpAvgQueueForSearch)); // // System.out.println("pressure add : " + pressureQueueForErrorCorrect.get(pressureQueueForErrorCorrect.size()-1).getHpa() + ", " + new Timestamp(pressureQueueForErrorCorrect.get(pressureQueueForErrorCorrect.size()-1).getTime())); if(pressureQueueForErrorCorrect.size() >= 2) { deltaQueueForErrorCorrect.add(new PressureObject(pressureQueueForErrorCorrect.get(pressureQueueForErrorCorrect.size()-1).getTime(), pressureQueueForErrorCorrect.get(pressureQueueForErrorCorrect.size()-1).getHpa() - pressureQueueForErrorCorrect.get(pressureQueueForErrorCorrect.size()-2).getHpa())); // // System.out.println("delta add[" + (deltaQueueForErrorCorrect.size()-1) + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(deltaQueueForErrorCorrect.size()-1).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(deltaQueueForErrorCorrect.size()-1).getTime())); } tmpAvgQueueForSearch.clear(); // // System.out.println(new Timestamp(valueQueueForSearch.get(valueQueueForSearch.size()-1).getTime()) + "," + valueQueueForSearch.get(valueQueueForSearch.size()-1).getHpa()); } } // 前後SEARCH_DATA_AVERAGE_WINDOW_SIZE分のデータで平均 tmpAvgQueueForSearch.add(new PressureObject(tmpQueueForSearch.get(tmpQueueForSearch.size()/2).getTime(), calcAverageOfPressurObjecteList(tmpQueueForSearch))); // if(!tmpAvgQueueForSearch.isEmpty()) { // // System.out.println(counter++ + "," + tmpAvgQueueForSearch.get(tmpAvgQueueForSearch.size()-1).getHpa()); // } tmpQueueForSearch.remove(0); } /*** 必要のない中間データを掃除 ***/ if(rawValueQueue.size() >= 2) rawValueQueue.remove(0); if(smoothedValueQueueX1.size() >= 2) smoothedValueQueueX1.remove(0); if(smoothedValueQueueX2.size() >= 2) smoothedValueQueueX2.remove(0); if(smoothedValueQueueX3.size() >= 2) smoothedValueQueueX3.remove(0); if(smoothedValueQueueX4.size() >= 2) smoothedValueQueueX4.remove(0); return 0; } /* * 受け取ったPressureObjectリストの値の平均値を算出する */ private float calcAverageOfPressurObjecteList(List<PressureObject> list) { float avgHpa = 0; for(PressureObject val : list){ avgHpa += val.getHpa(); } return avgHpa/list.size(); } /* * updown開始時点が確定した祭に、updown以前のデータを用いて天候補正・ノイズ補正を行い、補正を元に時刻の補正も行う * また、この祭にisCorrectWorkの値に、補正が動作したかどうかの値を保持する。 */ private PressureObject correctStartPoint() { int startIndexForDelta = 0; /*** updown開始点のインデックスを保持 ***/ // // System.out.println("deltaQueueForErrorCorrect.size() = " + deltaQueueForErrorCorrect.size()); for(int i=deltaQueueForErrorCorrect.size()-1; i>=0; i--) { PressureObject p = deltaQueueForErrorCorrect.get(i); if(updownStartObj.getTime() == p.getTime()) { startIndexForDelta = i; // // System.out.println("start detect(delta)[" + i + "] : " + startIndexForDelta + "(" + p.getTime() + ")"); break; } } /*** 階層移動開始点以前に十分なデータが存在しない場合には補正を中止 ***/ if(startIndexForDelta < WHETHER_CORRECT_SLOPE_WINDOW_SIZE-1) { // System.out.println("[CORRECT UPDOWN ERROR]Can not calc slope : at correct START point"); isCorrectWork = false; return null; } /*** updown開始点からWHETHER_CORRECT_SLOPE_WINDOW_SIZE分のデータを用いて線形近似の傾きを算出 ***/ List<PressureObject> deltaListForCorrect = new ArrayList<PressureObject>(); double sumHpa = 0; // // System.out.println("START : " + startIndexForDelta + ", FROM : " + (startIndexForDelta-WHETHER_CORRECT_SLOPE_WINDOW_SIZE+1)); for(int i=startIndexForDelta-WHETHER_CORRECT_SLOPE_WINDOW_SIZE+1; i<=startIndexForDelta; i++) { // // System.out.println("add correct[" + i + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(i).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime())); sumHpa += deltaQueueForErrorCorrect.get(i).getHpa(); deltaListForCorrect.add(new PressureObject(deltaQueueForErrorCorrect.get(i).getTime(), (float)sumHpa)); // // System.out.println("" + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + ", " + sumHpa); // // System.out.println("for whether correct[" + i + "] : " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + ", " + sumHpa); } double slope = calcSlope(deltaListForCorrect); // System.out.println("[CORRECT UPDOWN ERROR]Slope(with " + WHETHER_CORRECT_SLOPE_WINDOW_SIZE + "s data) : " + new DecimalFormat("0.0000000000").format(slope)); /*** updown開始終了点のインデックスを保持 ***/ int startIndexForPressure = 0; for(int i=pressureQueueForErrorCorrect.size()-1; i>=0; i--) { PressureObject p = pressureQueueForErrorCorrect.get(i); if(p.getTime() == updownStartObj.getTime()) { startIndexForPressure = i; // // System.out.println("START INDEX(PRESSURE) : " + i + "(" + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + ")"); break; } } /*** 算出した傾きから、気圧値を補正 ***/ List<PressureObject> correctedPressure = new ArrayList<PressureObject>(); int xDiff = 1 - NOISE_CORRECT_AVERAGE_WINDOW_SIZE; for(int i=startIndexForPressure-NOISE_CORRECT_AVERAGE_WINDOW_SIZE+1; i<=pressureQueueForErrorCorrect.size()-1; i++) { // updown開始時点からNOISE_CORRECT_AVERAGE_WINDOW_SIZEデータ前から、現時点までの気圧値全てを補正 double correctedHpa = pressureQueueForErrorCorrect.get(i).getHpa() - (xDiff * slope); // // System.out.println(pressureQueueForErrorCorrect.get(i).getHpa() + " - (" + xDiff +" * " + slope + ") = " + correctedHpa); // // System.out.println("WHEATHER ERROR REMOVED : " + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + " " + correctedHpa); correctedPressure.add(new PressureObject(pressureQueueForErrorCorrect.get(i).getTime(), (float)correctedHpa)); xDiff++; } /*** updown開始点直近NOISE_CORRECT_AVERAGE_WINDOW_SIZE分のデータでノイズを除去した値を算出 ***/ double correctedStartHpa = 0; double sum = 0; for (int i=0; i<NOISE_CORRECT_AVERAGE_WINDOW_SIZE; i++) { sum += correctedPressure.get(i).getHpa(); } correctedStartHpa = sum/NOISE_CORRECT_AVERAGE_WINDOW_SIZE; /*** 天候補正・ノイズ補正を行った結果の気圧値から、時間を補正 ***/ long correctedStartTime = 0; if(peakDelta < 0) { // currentStatus == PressureObject.STATE_UP) correctedStartTime = updownStartObj.getTime(); if(updownStartObj.getHpa() - correctedStartHpa >= 0) { // 補正前の方が補正後よりも大きかったら(ノイズが階層移動を助長する方に重なっていたら)、未来の方向にこの値に近づく点を探しに行く for(int i=NOISE_CORRECT_AVERAGE_WINDOW_SIZE-1; i<correctedPressure.size()-1; i++) { // // System.out.println("i=" + i + "(" + new Timestamp(correctedPressure.get(i).getTime()) + ") current=" + correctedPressure.get(i).getHpa() + ", diff=" + (correctedPressure.get(i).getHpa() - correctedStartHpa)); double diff = correctedPressure.get(i).getHpa() - correctedStartHpa; if(diff < 0) { // 平均値と交差したら、この点を階層移動開始時間として補正 correctedStartTime = correctedPressure.get(i).getTime(); // System.out.println("[CORRECT UPDOWN ERROR]Correct UP START time (with avg val(" + NOISE_CORRECT_AVERAGE_WINDOW_SIZE +"s data):" + correctedStartHpa + ")\n\t: " + new Timestamp(updownStartObj.getTime()) + "(" + updownStartObj.getHpa() + ") -> " + new Timestamp(correctedStartTime) + "(" + correctedPressure.get(i).getHpa() + ")"); break; } } } else { // それ以外なら元々の時刻を使用 // System.out.println("[CORRECT UPDOWN ERROR]Do not correct DOWN START time (with avg val:" + correctedStartHpa + ") : " + updownStartObj.getHpa()); correctedStartTime = updownStartObj.getTime(); } } else if(peakDelta >= 0) { // currentStatus == PressureObject.STATE_DOWN correctedStartTime = updownStartObj.getTime(); if(updownStartObj.getHpa() - correctedStartHpa < 0) { // 補正前の方が補正後よりも小さかったら(ノイズが階層移動を助長する方に重なっていたら)、未来の方向にこの値に近づく点を探しに行く for(int i=NOISE_CORRECT_AVERAGE_WINDOW_SIZE-1; i<correctedPressure.size()-1; i++) { // // System.out.println("i=" + i + "(" + new Timestamp(correctedPressure.get(i).getTime()) + ") current=" + correctedPressure.get(i).getHpa() + ", diff=" + (correctedPressure.get(i).getHpa() - correctedStartHpa)); double diff = correctedPressure.get(i).getHpa() - correctedStartHpa; if(diff >= 0) { // 平均値と交差したら、この点を階層移動開始時間として補正 correctedStartTime = correctedPressure.get(i).getTime(); // System.out.println("[CORRECT UPDOWN ERROR]Correct DOWN START time (with avg val(" + NOISE_CORRECT_AVERAGE_WINDOW_SIZE +"s data):" + correctedStartHpa + ")\n\t: " + new Timestamp(updownStartObj.getTime()) + "(" + updownStartObj.getHpa() + ") -> " + new Timestamp(correctedStartTime) + "(" + correctedPressure.get(i).getHpa() + ")"); break; } } } else { // それ以外なら元々の時刻を使用 // System.out.println("[CORRECT UPDOWN ERROR]Do not correct DOWN START time (with avg val:" + correctedStartHpa + ") : " + updownStartObj.getHpa()); correctedStartTime = updownStartObj.getTime(); } } isCorrectWork = true; return new PressureObject(correctedStartTime, (float)correctedStartHpa); } private PressureObject correctEndPoint() { // // System.out.println("Into correctError()"); int startIndexForDelta = 0; /*** 停滞時以外のデータを削除し、updown開始点のインデックスを保持 ***/ // // System.out.println("deltaQueueForErrorCorrect.size() = " + deltaQueueForErrorCorrect.size()); for(int i=deltaQueueForErrorCorrect.size()-1; i>=0; i--) { PressureObject p = deltaQueueForErrorCorrect.get(i); if(updownStartObj.getTime() < p.getTime() && p.getTime() < updownEndObj.getTime()) { // // System.out.println("delta remove[" + i + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(i).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + " (" + new Timestamp(updownStartObj.getTime()) + " - " + new Timestamp(updownEndObj.getTime()) + ")"); deltaQueueForErrorCorrect.remove(i); } else { // // System.out.println("delta current[" + i + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(i).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + " (" + new Timestamp(updownStartObj.getTime()) + " - " + new Timestamp(updownEndObj.getTime()) + ")"); } if(updownStartObj.getTime() == p.getTime()) { startIndexForDelta = i; // // System.out.println("start detect[" + i + "] : " + startIndexForDelta + "(" + p.getTime() + ")"); break; } } /*** 階層移動開始点以前に十分なデータが存在しない場合には補正を中止 ***/ if(startIndexForDelta < WHETHER_CORRECT_SLOPE_WINDOW_SIZE-1) { // System.out.println("[CORRECT UPDOWN ERROR]Can not calc slope : at correct END point"); return updownEndObj; } /*** updown開始点からWHETHER_CORRECT_SLOPE_WINDOW_SIZE分のデータを用いて線形近似の傾きを算出 ***/ List<PressureObject> deltaListForCorrect = new ArrayList<PressureObject>(); double sumHpa = 0; // // System.out.println("START : " + startIndexForDelta + ", FROM : " + (startIndexForDelta-WHETHER_CORRECT_SLOPE_WINDOW_SIZE+1)); for(int i=startIndexForDelta-WHETHER_CORRECT_SLOPE_WINDOW_SIZE+1; i<=startIndexForDelta; i++) { // // System.out.println("add correct[" + i + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(i).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime())); sumHpa += deltaQueueForErrorCorrect.get(i).getHpa(); deltaListForCorrect.add(new PressureObject(deltaQueueForErrorCorrect.get(i).getTime(), (float)sumHpa)); // // System.out.println("" + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + ", " + sumHpa); // // System.out.println("for whether correct[" + i + "] : " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + ", " + sumHpa); } double slope = calcSlope(deltaListForCorrect); // System.out.println("[CORRECT UPDOWN ERROR]Slope(with " + WHETHER_CORRECT_SLOPE_WINDOW_SIZE + "s data) : " + new DecimalFormat("0.0000000000").format(slope)); /*** updown開始終了点のインデックスを保持 ***/ int startIndexForPressure = 0; int endIndexForPressure = 0; for(int i=pressureQueueForErrorCorrect.size()-1; i>=0; i--) { PressureObject p = pressureQueueForErrorCorrect.get(i); if(p.getTime() == updownEndObj.getTime()) { endIndexForPressure = i; // // System.out.println("END INDEX : " + i + "(" + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + ")"); } if(p.getTime() == updownStartObj.getTime()) { startIndexForPressure = i; // // System.out.println("START INDEX : " + i + "(" + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + ")"); break; } } /*** 算出した傾きから、気圧値を補正 ***/ List<PressureObject> correctedPressure = new ArrayList<PressureObject>(); int xDiff = 1 - NOISE_CORRECT_AVERAGE_WINDOW_SIZE; for(int i=startIndexForPressure-NOISE_CORRECT_AVERAGE_WINDOW_SIZE+1; i<=endIndexForPressure+NOISE_CORRECT_AVERAGE_WINDOW_SIZE-1; i++) { if(i >= pressureQueueForErrorCorrect.size()) { // 十分にデータ量が確保できていない場合には現時点までのデータで補正 // // System.out.println("BREAK"); break; } double correctedHpa = pressureQueueForErrorCorrect.get(i).getHpa() - (xDiff * slope); // // System.out.println(pressureQueueForErrorCorrect.get(i).getHpa() + " - (" + xDiff +" * " + slope + ") = " + correctedHpa); // // System.out.println("WHEATHER ERROR REMOVED : " + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + " " + correctedHpa); correctedPressure.add(new PressureObject(pressureQueueForErrorCorrect.get(i).getTime(), (float)correctedHpa)); xDiff++; } /*** updown終了点直後NOISE_CORRECT_AVERAGE_WINDOW_SIZE分のデータでノイズを除去した値を算出 ***/ double correctedEndHpa = 0; double sum = 0; int count = 0; // // System.out.println("END : " + (correctedPressure.size()-1) + ", TO : " + (correctedPressure.size()-1-NOISE_CORRECT_AVERAGE_WINDOW_SIZE)); for (int i=correctedPressure.size()-1; i>correctedPressure.size()-1-NOISE_CORRECT_AVERAGE_WINDOW_SIZE; i--) { if(correctedPressure.get(i).getTime() < updownEndObj.getTime()) { break; } // // System.out.println("CURRENT : " + i + ", " + new Timestamp(correctedPressure.get(i).getTime())); sum += correctedPressure.get(i).getHpa(); count++; } correctedEndHpa = sum/count; // // System.out.println(sum + " / " + count + " = " + correctedEndHpa); /*** 最終停滞時以前のデータは削除 ***/ for(int i=pressureQueueForErrorCorrect.size()-1; i<=0; i--) { PressureObject p = pressureQueueForErrorCorrect.get(i); if(p.getTime() < updownEndObj.getTime()) { pressureQueueForErrorCorrect.remove(i); } } /*** 天候補正・ノイズ補正を行った結果の気圧値から、時間を補正 ***/ long correctedEndTime = 0; if(currentStatus == PressureObject.STATE_UP) { correctedEndTime = updownEndObj.getTime(); if(updownEndObj.getHpa() - correctedEndHpa < 0) { // 補正前の方が補正後よりも小さかったら(ノイズが階層移動を助長する方に重なっていたら)、過去の方向にこの値に近づく点を探しに行く for(int i=correctedPressure.size()-NOISE_CORRECT_AVERAGE_WINDOW_SIZE-1; i>=0; i--) { // // System.out.println("i=" + i + "(" + new Timestamp(correctedPressure.get(i).getTime()) + ") current=" + correctedPressure.get(i).getHpa() + ", diff=" + (correctedPressure.get(i).getHpa() - correctedEndHpa)); double diff = correctedPressure.get(i).getHpa() - correctedEndHpa; if(diff >= 0) { // 平均値と交差したら、この点を階層移動開始時間として補正 correctedEndTime = correctedPressure.get(i).getTime(); // System.out.println("[CORRECT UPDOWN ERROR]Correct UP END time (with avg val(" + NOISE_CORRECT_AVERAGE_WINDOW_SIZE +"s data):" + correctedEndHpa + ")\n\t: " + new Timestamp(updownEndObj.getTime()) + "(" + updownEndObj.getHpa() + ") -> " + new Timestamp(correctedEndTime) + "(" + correctedPressure.get(i).getHpa() + ")"); break; } } } else { // それ以外なら元々の時刻を使用 // System.out.println("[CORRECT UPDOWN ERROR]Do not correct UP END time (with avg val:" + correctedEndHpa + ") : " + updownEndObj.getHpa()); correctedEndTime = updownEndObj.getTime(); } } else if(currentStatus == PressureObject.STATE_DOWN) { correctedEndTime = updownEndObj.getTime(); if(updownEndObj.getHpa() - correctedEndHpa >= 0) { // 補正前の方が補正後よりも大きかったら(ノイズが階層移動を助長する方に重なっていたら)、過去の方向にこの値に近づく点を探しに行く for(int i=correctedPressure.size()-NOISE_CORRECT_AVERAGE_WINDOW_SIZE-1; i>=0; i--) { // System.out.println("i=" + i + "(" + new Timestamp(correctedPressure.get(i).getTime()) + ") current=" + correctedPressure.get(i).getHpa() + ", diff=" + (correctedPressure.get(i).getHpa() - correctedEndHpa)); double diff = correctedPressure.get(i).getHpa() - correctedEndHpa; if(diff < 0) { // 平均値と交差したら、この点を階層移動開始時間として補正 // System.out.println("[CORRECT UPDOWN ERROR]Correct DOWN END time (with avg val(" + NOISE_CORRECT_AVERAGE_WINDOW_SIZE +"s data):" + correctedEndHpa + ")\n\t: " + new Timestamp(updownEndObj.getTime()) + "(" + updownEndObj.getHpa() + ") -> " + new Timestamp(correctedEndTime) + "(" + correctedPressure.get(i).getHpa() + ")"); correctedEndTime = correctedPressure.get(i).getTime(); break; } } } else { // それ以外なら元々の時刻を使用 // System.out.println("[CORRECT UPDOWN ERROR]Do not correct DOWN END time (with avg val:" + correctedEndHpa + ") : " + updownEndObj.getHpa()); correctedEndTime = updownEndObj.getTime(); } } isCorrectWork = true; return new PressureObject(correctedEndTime, (float)correctedEndHpa); } // private List<PressureObject> correctError() { //// // System.out.println("Into correctError()"); // int startIndexForDelta = 0; // // /*** 停滞時以外のデータを削除し、updown開始点のインデックスを保持 ***/ //// // System.out.println("deltaQueueForErrorCorrect.size() = " + deltaQueueForErrorCorrect.size()); // for(int i=deltaQueueForErrorCorrect.size()-1; i>=0; i--) { // PressureObject p = deltaQueueForErrorCorrect.get(i); // if(updownStartObj.getTime() < p.getTime() && p.getTime() < updownEndObj.getTime()) { //// // System.out.println("delta remove[" + i + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(i).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + " (" + new Timestamp(updownStartObj.getTime()) + " - " + new Timestamp(updownEndObj.getTime()) + ")"); // deltaQueueForErrorCorrect.remove(i); // } else { //// // System.out.println("delta current[" + i + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(i).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + " (" + new Timestamp(updownStartObj.getTime()) + " - " + new Timestamp(updownEndObj.getTime()) + ")"); // } // if(updownStartObj.getTime() == p.getTime()) { // startIndexForDelta = i; // // System.out.println("start detect[" + i + "] : " + startIndexForDelta + "(" + p.getTime() + ")"); // break; // } // } // // /*** 階層移動開始点以前に十分なデータが存在しない場合には補正を中止 ***/ // if(startIndexForDelta < WHETHER_CORRECT_SLOPE_WINDOW_SIZE-1) { // return new ArrayList<PressureObject>(); // } // // /*** updown開始点からWHETHER_CORRECT_SLOPE_WINDOW_SIZE分のデータを用いて線形近似の傾きを算出 ***/ // List<PressureObject> deltaListForCorrect = new ArrayList<PressureObject>(); // double sumHpa = 0; //// // System.out.println("START : " + startIndexForDelta + ", FROM : " + (startIndexForDelta-WHETHER_CORRECT_SLOPE_WINDOW_SIZE+1)); // for(int i=startIndexForDelta-WHETHER_CORRECT_SLOPE_WINDOW_SIZE+1; i<=startIndexForDelta; i++) { //// // System.out.println("add correct[" + i + "] : " + new DecimalFormat("0.0000000000").format(deltaQueueForErrorCorrect.get(i).getHpa()) + ", " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime())); // sumHpa += deltaQueueForErrorCorrect.get(i).getHpa(); // deltaListForCorrect.add(new PressureObject(deltaQueueForErrorCorrect.get(i).getTime(), (float)sumHpa)); //// // System.out.println("" + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + ", " + sumHpa); //// // System.out.println("for whether correct[" + i + "] : " + new Timestamp(deltaQueueForErrorCorrect.get(i).getTime()) + ", " + sumHpa); // } // double slope = calcSlope(deltaListForCorrect); // // System.out.println("Slope : " + new DecimalFormat("0.0000000000").format(slope)); // // /*** updown開始終了点のインデックスを保持 ***/ // int startIndexForPressure = 0; // int endIndexForPressure = 0; // for(int i=pressureQueueForErrorCorrect.size()-1; i>=0; i--) { // PressureObject p = pressureQueueForErrorCorrect.get(i); // if(p.getTime() == updownEndObj.getTime()) { // endIndexForPressure = i; //// // System.out.println("END INDEX : " + i + "(" + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + ")"); // } // if(p.getTime() == updownStartObj.getTime()) { // startIndexForPressure = i; //// // System.out.println("START INDEX : " + i + "(" + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + ")"); // break; // } // } // // /*** 算出した傾きから、気圧値を補正 ***/ // List<PressureObject> correctedPressure = new ArrayList<PressureObject>(); // int xDiff = 1 - NOISE_CORRECT_AVERAGE_WINDOW_SIZE; // for(int i=startIndexForPressure-NOISE_CORRECT_AVERAGE_WINDOW_SIZE+1; i<=endIndexForPressure+NOISE_CORRECT_AVERAGE_WINDOW_SIZE-1; i++) { // if(i >= pressureQueueForErrorCorrect.size()) { // 十分にデータ量が確保できていない場合には現時点までのデータで補正 //// // System.out.println("BREAK"); // break; // } // double correctedHpa = pressureQueueForErrorCorrect.get(i).getHpa() - (xDiff * slope); //// // System.out.println(pressureQueueForErrorCorrect.get(i).getHpa() + " - (" + xDiff +" * " + slope + ") = " + correctedHpa); //// // System.out.println("WHEATHER ERROR REMOVED : " + new Timestamp(pressureQueueForErrorCorrect.get(i).getTime()) + " " + correctedHpa); // correctedPressure.add(new PressureObject(pressureQueueForErrorCorrect.get(i).getTime(), (float)correctedHpa)); // xDiff++; // } // // /*** updown開始点直近NOISE_CORRECT_AVERAGE_WINDOW_SIZE分のデータでノイズを除去した値を算出 ***/ // double correctedStartHpa = 0; // double sum = 0; // for (int i=0; i<NOISE_CORRECT_AVERAGE_WINDOW_SIZE; i++) { // sum += correctedPressure.get(i).getHpa(); // } // correctedStartHpa = sum/NOISE_CORRECT_AVERAGE_WINDOW_SIZE; // // /*** updown終了点直後NOISE_CORRECT_AVERAGE_WINDOW_SIZE分のデータでノイズを除去した値を算出 ***/ // double correctedEndHpa = 0; // sum = 0; // int count = 0; //// // System.out.println("END : " + (correctedPressure.size()-1) + ", TO : " + (correctedPressure.size()-1-NOISE_CORRECT_AVERAGE_WINDOW_SIZE)); // for (int i=correctedPressure.size()-1; i>correctedPressure.size()-1-NOISE_CORRECT_AVERAGE_WINDOW_SIZE; i--) { // if(correctedPressure.get(i).getTime() < updownEndObj.getTime()) { // break; // } //// // System.out.println("CURRENT : " + i + ", " + new Timestamp(correctedPressure.get(i).getTime())); // sum += correctedPressure.get(i).getHpa(); // count++; // } // correctedEndHpa = sum/count; //// // System.out.println(sum + " / " + count + " = " + correctedEndHpa); // // /*** 最終停滞時以前のデータは削除 ***/ // for(int i=pressureQueueForErrorCorrect.size()-1; i<=0; i--) { // PressureObject p = pressureQueueForErrorCorrect.get(i); // if(p.getTime() < updownEndObj.getTime()) { // pressureQueueForErrorCorrect.remove(i); // } // } // // List<PressureObject> result = new ArrayList<PressureObject>(); //// // System.out.println(correctedStartHpa + "," + correctedEndHpa); // result.add(new PressureObject(updownStartObj.getTime(), (float)correctedStartHpa)); // result.add(new PressureObject(updownEndObj.getTime(), (float)correctedEndHpa)); // // return result; // } /* * 最小二乗法により線形近似の傾きを算出 * http://gihyo.jp/dev/serial/01/java-calculation/0061?page=2 */ private double calcSlope(List<PressureObject> deltaList) { double x, y, x_sum=0, y_sum=0, xx_sum=0, xy_sum=0; for(int i=0;i<deltaList.size();i++){ // // System.out.println(new DecimalFormat("0.0000000000").format(deltaList.get(i).getHpa())); x = i; y = deltaList.get(i).getHpa(); x_sum += x; y_sum += y; xx_sum += x*x; xy_sum += x*y; }// of for i return (double) (deltaList.size()*xy_sum-x_sum*y_sum) / (double) (deltaList.size()*xx_sum-x_sum*x_sum); } } //TODO: 計算をできるだけdoubleで行い、最終的なアウトプットもdoubleで行う //TODO: 天候補正時に直前停滞時のデータが足りなかった場合の方法の調査 <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.json; import java.util.ArrayList; import java.util.List; public class Json_Mode { private int jModeId; private String mode; private List<Json_Route> routeList = new ArrayList<Json_Route>(); public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } public List<Json_Route> getRouteList() { return routeList; } public void setRouteList(List<Json_Route> routeList) { this.routeList = routeList; } public void addRoute(Json_Route jRoute){ this.routeList.add(jRoute); } public int getjModeId() { return jModeId; } public void setjModeId(int jModeId) { this.jModeId = jModeId; } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.cluster; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.entries.WifiSignature; import java.util.Map; import java.util.TreeMap; /** * Created by gucci on 2015/04/07. */ public class Cluster { private static int idCount = 0; private int id; private WifiSignature wifiSignature; private long accumulatedTime;/* データの時間 */ private TreeMap<Long, WifiSignature> timestampToWifiSignatureMap; public Cluster(){ this.id = 0; this.wifiSignature = null; accumulatedTime = 0; timestampToWifiSignatureMap = new TreeMap<Long, WifiSignature>(); } public Cluster(WifiSignature newWifisignature){ idCount++; this.id = idCount; this.wifiSignature = new WifiSignature(); timestampToWifiSignatureMap = new TreeMap<Long, WifiSignature>(); addWifiSignature(newWifisignature); } public void addWifiSignature(WifiSignature newWifisignature){ if( newWifisignature == null ) throw new NullPointerException("It may not be null"); timestampToWifiSignatureMap.put(newWifisignature.getStartTime(), newWifisignature); accumulatedTime += newWifisignature.getEndTime() - newWifisignature.getStartTime(); Map<String, WifiSignature.Entry> newEntries = newWifisignature.getEntries(); for (String bssid : newEntries.keySet()) { String essid = newEntries.get(bssid).getEssid(); double rssi = newEntries.get(bssid).getRssi(); int freq = newEntries.get(bssid).getFrequency(); if (this.wifiSignature.getEntries().containsKey(bssid)) { this.wifiSignature.getEntries().get(bssid).update(freq, rssi * freq); } else { this.wifiSignature.getEntries().put(bssid, new WifiSignature.Entry(bssid, essid, rssi * freq, freq)); } } } public void removeWifiSignature(WifiSignature removeWifiSignature){ timestampToWifiSignatureMap.remove(removeWifiSignature.getStartTime()); accumulatedTime -= removeWifiSignature.getEndTime() - removeWifiSignature.getStartTime(); Map<String, WifiSignature.Entry> removeEntries = removeWifiSignature.getEntries(); for (String bssid : removeEntries.keySet()) { double rssi = removeEntries.get(bssid).getRssi(); int freq = removeEntries.get(bssid).getFrequency(); if (this.wifiSignature.getEntries().containsKey(bssid)) { this.wifiSignature.getEntries().get(bssid).remove(freq, rssi * freq); if(this.wifiSignature.getEntries().get(bssid).getFrequency() <= 0){ this.wifiSignature.getEntries().remove(bssid); } } } } /** * Obtains the unique identifier of this cluster. * * @return the unique identifier of this cluster */ public int getId() { return id; } public WifiSignature getWifiSignature() { return wifiSignature; } public long getAccumulatedTime() { return accumulatedTime; } public TreeMap<Long, WifiSignature> getTimestampToWifiSignatureMap() { return timestampToWifiSignatureMap; } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker.gps; import java.sql.Timestamp; import jp.ac.ritsumei.cs.ubi.geo.LatLng; public class GPSData { private Timestamp time; private int devId; private double lat; private double lng; private float acc; private float speed; private Timestamp providerTime; public GPSData(Timestamp time,int devid,double lat,double lng,float acc,float speed,Timestamp providerTime){ this.time = time; this.devId = devid; this.lat = lat; this.lng = lng; this.acc = acc; this.speed = speed; this.providerTime = providerTime; } public LatLng getLatLng(){ return new LatLng(lat,lng); } public Timestamp getTime() { return time; } public void setTime(Timestamp time) { this.time = time; } public int getDevId() { return devId; } public void setDevId(int devId) { this.devId = devId; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public float getAcc() { return acc; } public void setAcc(float acc) { this.acc = acc; } public float getSpeed() { return speed; } public void setSpeed(float speed) { this.speed = speed; } public Timestamp getProviderTime() { return providerTime; } public void setProviderTime(Timestamp lTime) { this.providerTime = lTime; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.json; import java.util.ArrayList; import java.util.List; import jp.ac.ritsumei.cs.ubi.zukky.BRM.transport.Transportation; public class Json_Transportation{ private List<Json_Mode> modeList = new ArrayList<Json_Mode>(); private List<Transportation> transportationList = new ArrayList<Transportation>(); private String transportationListString; public List<Json_Mode> getModeList() { return modeList; } public void setModeList(List<Json_Mode> modeList) { this.modeList = modeList; } public void addModeList(Json_Mode mode){ this.modeList.add(mode); } public List<Transportation> getTransportationList() { return transportationList; } public void setTransportationList(List<Transportation> transportationList) { this.transportationList = transportationList; } public String getTransportationListString() { return transportationListString; } public void setTransportationListString(List<Transportation> transportationList) { this.transportationListString = toString(transportationList); } private String toString(List<Transportation> transportationList){ String resultString = ""; for(Transportation transportation: transportationList){ resultString = resultString + transportation.getType().toString(); } return resultString; } // public String getjTransportationId() { // return jTransportationId; // } // // public void setjTransportationId(String jTransportationId) { // this.jTransportationId = jTransportationId; // } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.LocalizePaths.statistic; import java.sql.Timestamp; /** * Created by gucci on 2015/08/12. */ public class APSquare { private Timestamp startTimestamp; private Timestamp endTimestamp; private double maxRssi; private double minRssi; APSquare(){ this.startTimestamp = new Timestamp(0); this.endTimestamp = new Timestamp(0); maxRssi = -100; minRssi = 0; } public Timestamp getStartTimestamp() { return startTimestamp; } public void setStartTimestamp(Timestamp startTimestamp) { this.startTimestamp = startTimestamp; } public Timestamp getEndTimestamp() { return endTimestamp; } public void setEndTimestamp(Timestamp endTimestamp) { this.endTimestamp = endTimestamp; } public double getMaxRssi() { return maxRssi; } public void setMaxRssi(double maxRssi) { this.maxRssi = maxRssi; } public double getMinRssi() { return minRssi; } public void setMinRssi(double minRssi) { this.minRssi = minRssi; } } <file_sep>package jp.ac.ritsumei.cs.ubi.ubilabsensorlibrary; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class SqlConnector { private Properties dataBasePropaty; protected Connection connection; public SqlConnector(String propatyName) throws IOException{ this.dataBasePropaty = new Properties(); dataBasePropaty.load( new FileInputStream(propatyName) ); } public void createConnection() throws ClassNotFoundException, SQLException{ this.connection = getConnection(); } private Connection getConnection() throws ClassNotFoundException, SQLException{ String dataBaseUrl = dataBasePropaty.getProperty("kubiwa.mysql.url"); String dataBaseUser = dataBasePropaty.getProperty("kubiwa.mysql.user"); String dataBasePassword = dataBasePropaty.getProperty("kubiwa.mysql.passwd"); Class.forName("com.mysql.jdbc.Driver"); return (Connection) DriverManager.getConnection(dataBaseUrl, dataBaseUser, dataBasePassword); } public String getDBName(){ return dataBasePropaty.getProperty("kubiwa.mysql.table"); } public void close() throws SQLException { if(connection != null){ connection.close(); } } public boolean isClosed() throws SQLException{ if(connection == null){ return true; } return connection.isClosed(); } }<file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.csv; import jp.ac.ritsumei.cs.ubi.geo.LatLng; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.db.DataGetter; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.ClusteredDropInSite; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.DropInSite; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.DropInSiteTransition; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.gps.GPSData; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.gps.GPSDataList; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; /** * CHANTAKU�p��CSV�������o���N���X * @author takuchan */ public class CSVWriter { //�o�͐�̎w�� private String outputPath = "/Users/takuchan/Desktop/Results/"; /** * �ړ��E��؂�2��Ԃɋ�ʂ��ꂽ�e��Ԃ̈ʒu���Ɋւ��āA�S�Ă̋�ԏ���1�t�@�C���ɏo�͂��郁�\�b�h * @param list�@�ړ��E��؂�2��Ԃɋ�ʂ��ꂽ�e��Ԃ̈ʒu���̃��X�g(GPSDataList)�̃��X�g */ public void writeDividedGPSDataLists(List<GPSDataList> list){ System.out.println("[CSVWriter] write all dividedGPSDataList for one file..."); List<GPSDataList> dividedGPSDataLists = list; String color = "blue"; try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputPath+"devidedGPS.csv"))); for(GPSDataList gpsDataListTemp:dividedGPSDataLists){ if(gpsDataListTemp.isIndoorSite()) color="red"; else color="blue"; for(GPSData gpsDataTemp:gpsDataListTemp){ //�Ōゾ���‚��‚܍��킹���K�v if(gpsDataListTemp.indexOf(gpsDataTemp)+1==gpsDataListTemp.size()){ if(color.matches("blue")) color = "red"; else color = "blue"; } printWriter.println(gpsDataTemp.getTime() + "," + gpsDataTemp.getLat() + "," + gpsDataTemp.getLng() + "," + color); } } printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } /** * �ړ��E��؂�2��Ԃɋ�ʂ��ꂽ�e��Ԃ̈ʒu���Ɋւ��āA���ꂼ��̋�Ԗ��Ƀt�@�C���𐶐��E�o�͂��郁�\�b�h * @param list �ړ��E��؂�2��Ԃɋ�ʂ��ꂽ�e��Ԃ̈ʒu���̃��X�g(GPSDataList)�̃��X�g */ public void writeEachDividedGPSDataLists(List<GPSDataList> list){ System.out.println("[CSVWriter]---------------write all dividedGPSDataList for each file---------------"); List<GPSDataList> dividedGPSDataLists = list; GPSDataList gpsDataListTemp; GPSData gpsDataTemp; Iterator<GPSDataList> listIte = dividedGPSDataLists.iterator(); String color = "blue"; int count=1; try { while(listIte.hasNext()){ gpsDataListTemp = listIte.next(); Iterator<GPSData> dataIte = gpsDataListTemp.iterator(); PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputPath + "segment" + count + ".csv"))); while(dataIte.hasNext()){ gpsDataTemp = dataIte.next(); System.out.println(gpsDataTemp.getTime() + "," + gpsDataTemp.getLat() + "," + gpsDataTemp.getLng() + "," + color); printWriter.println(gpsDataTemp.getTime() + "," + gpsDataTemp.getLat() + "," + gpsDataTemp.getLng() + "," + color); } printWriter.close(); count++; } } catch (IOException e) { e.printStackTrace(); } } /** * ���������������|�C���g(DropInSite)�S�Ă�1�‚̃t�@�C���ɏo�͂��郁�\�b�h * @param dropInSiteList */ public void writeDropInSite(List<DropInSite> dropInSiteList){ System.out.println("[CSVWriter] writing all drop in sites..."); String color = "red"; int count = 0; int writeCount = 0; try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputPath + "dropInSiteTest.csv"))); for(DropInSite dropInSite : dropInSiteList){ //�m�C�Y�ɂ���Đ�����傫�ȗ������|�C���g����������ꍇ�͂����̃R�����g�A�E�g������ // if(new LatLng(dropInSite.getMaxLat(),dropInSite.getMaxLng()).distance(new LatLng(dropInSite.getMinLat(),dropInSite.getMinLng()))<300){ if((0<=dropInSite.getDropInTime())&&(dropInSite.getDropInTime()<600000)) //0�b�ȏ�10������ color = "green"; else if((600000<=dropInSite.getDropInTime())&&(dropInSite.getDropInTime()<3600000)) //10���ȏ�1���Ԗ��� color = "blue"; else //1���Ԉȏ� color = "red"; //printWriter.println(dropInSite.getMaxLat() + "," + dropInSite.getMaxLng() + "," + dropInSite.getMinLat() + "," + dropInSite.getMinLng() + "," + color // + "," + "start:" + dropInSite.getStartTime() + " end:" + dropInSite.getEndTime()); writeCount++; // } count++; } System.out.println("count of generate drop in site:" + count + "\ncount of write out drop in site:" + writeCount); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public void writeClusteredDropInSite(List<ClusteredDropInSite> clusteredDropInSiteList){ System.out.println("[CSVWriter writing all clustered DropInSite...]"); String color = "red"; try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputPath + "clusteredDropInSite.csv"))); PrintWriter printWriter2 = new PrintWriter(new BufferedWriter(new FileWriter(outputPath + "clusteredDropInSiteCentroid.csv"))); for(ClusteredDropInSite clusteredDropInSite:clusteredDropInSiteList){ if(clusteredDropInSite.size()==1){ color = "green"; }else if(1<clusteredDropInSite.size()&&clusteredDropInSite.size()<=5){ color = "blue"; }else if(5<clusteredDropInSite.size()){ color = "red"; }else{ color = "black"; } printWriter.println(clusteredDropInSite.getMaxLat() + "," + clusteredDropInSite.getMaxLng() + "," + clusteredDropInSite.getMinLat() + "," + clusteredDropInSite.getMinLng() + "," + color + ",id:" + clusteredDropInSite.getId() + "<br>Centroid lat:" + clusteredDropInSite.getCentroid().getLat() + " lng:" + clusteredDropInSite.getCentroid().getLng() + " size:" + clusteredDropInSite.size() + " aveTime:" + clusteredDropInSite.getAverageDropInTime()+ " maxTime" + clusteredDropInSite.getMaxDropInTime() + " minTime" + clusteredDropInSite.getMinDropInTime()); printWriter2.println(clusteredDropInSite.getCentroid().getLat() + "," + clusteredDropInSite.getCentroid().getLng()); } System.out.println("count of clustered drop in site:" + clusteredDropInSiteList.size()); printWriter.close(); printWriter2.close(); } catch (IOException e) { e.printStackTrace(); } } //TODO�@�ʃN���X�ɕ����� /** * �������ꂽ�e��Ԃ��ꂼ��Ɋւ��Ă̑��x�����R���\�[����ɕ\�����郁�\�b�h * �m�F�p(�ʏ�̈ړ����Ɏ擾�����ʒu���ƁA�m�C�Y�̍��ٔ���) * @param dividedGPSDataList �ړ��E��؂�2��Ԃɋ�ʂ��ꂽ�e��Ԃ̈ʒu���̃��X�g(GPSDataList)�̃��X�g */ public void displaySpeedData(List<GPSDataList> dividedGPSDataList){ System.out.println("[CSVWrite] displaying each segment's speed infomation..."); GPSData preData = null; double currentSpeed = 0; double preSpeed = -1; //ave,max,min double count=0; double ave=0; double max=0; double min=1000; //counter int count0to5 = 0; int count5to10 = 0; int count10to20 = 0; int count20toInfinite = 0; for(GPSDataList gpsDataList:dividedGPSDataList){ //�ړ����̏��݂̂�ΏۂƂ���. if(!gpsDataList.isIndoorSite()){ for(GPSData gpsData:gpsDataList){ if(gpsDataList.indexOf(gpsData)!=0){ currentSpeed = getSmoothingSpeed(preData, gpsData, preSpeed); //ave,max,min count++; ave += currentSpeed; if(currentSpeed>max) max = currentSpeed; if(currentSpeed<min) min = currentSpeed; //counter if(currentSpeed<5) count0to5++; else if((5<=currentSpeed)&&(currentSpeed<10)) count5to10++; else if((10<=currentSpeed)&&(currentSpeed<20)) count10to20++; else if(20<=currentSpeed) count20toInfinite++; else System.out.println("odd speed"); } preData = gpsData; preSpeed = currentSpeed; } System.out.println("\nstart:" + gpsDataList.get(0).getTime() + ",end:" + gpsDataList.get(gpsDataList.size()-1).getTime()); System.out.println("ave:" + ave/count + ",max:" + max + ",min" + min); System.out.println("0-5:" + count0to5 + ",5-10:" + count5to10 + ",10-20" + count10to20 + ",20-:" + count20toInfinite); } //TODO ���� preSpeed = -1; count = 0; ave = 0; max = 0; min = 1000; count0to5 = 0; count5to10 = 0; count10to20 = 0; count20toInfinite = 0; } //TODO �������ĐF�X�\����������΂�����. } /** * GPSData2�‚���,2�_�Ԃ̋������Z�o. * @param preData * @param currentData * @return */ private double getSpeed(GPSData preData,GPSData currentData){ long duration; double distance; double speed; LatLng currentPoint; LatLng prePoint; duration = (currentData.getTime().getTime()-preData.getTime().getTime())/1000; currentPoint = new LatLng(currentData.getLat(),currentData.getLng()); prePoint = new LatLng(preData.getLat(),preData.getLng()); distance = currentPoint.distance(prePoint); speed = (distance/duration) * 3.6; if(Double.isInfinite(speed)||Double.isNaN(speed)){ speed=0; } return speed; } private static double SMOOTHING_RATE=0.8; /** * 2�n�_�̈ܓx�o�x�Ǝ���,����ɒ��O�̑��x���g�� * @param preData * @param currentData * @param preSpeed * @return */ private double getSmoothingSpeed(GPSData preData,GPSData currentData,double preSpeed){ double currentSpeed = getSpeed(preData, currentData); if(preSpeed==-1){ //-1���n���ꂽ�Ƃ��͂��̂܂܂̃q���x�j���x��Ԃ� return currentSpeed; }else{ //�X���[�W���O���� return (preSpeed * SMOOTHING_RATE) + (currentSpeed * (1.0-SMOOTHING_RATE)); } } /** * "�ړ����Ă���"�Ɣ��肳�ꂽ��Ԃ̊e�ʒu����,1�‘O�̋�ԂŒ�؂��Ă��������Ƃ̋������Z�o���郁�\�b�h. * ���e�ړ���Ԗ��Ƀt�@�C�������������̂Œ��� * �P�Ɋm�F�p * @param dividedGPSDataList �ړ��E��؂̂ǂ��炩�ɕ�����ꂽGPSDataList�̃��X�g */ public void writeDistance(List<GPSDataList> dividedGPSDataList){ System.out.println("[CSVWriter] writing distances..."); int count = 0; LatLng preIndoorFirstLostPoint; try { for(GPSDataList gpsDataList : dividedGPSDataList){ if(!gpsDataList.isIndoorSite()&&count!=0){ PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputPath + "distance_" + count + ".csv"))); preIndoorFirstLostPoint = dividedGPSDataList.get(count-1).getFirstLostPoint(); for(GPSData gpsData : gpsDataList){ printWriter.println(preIndoorFirstLostPoint.distance(gpsData.getLatLng())); } printWriter.close(); } count++; } } catch (IOException e) { e.printStackTrace(); } } /** * �J�ڂɂ�����e�o�H���o�͂���ׂ̃��\�b�h * @param dropInSiteTransitionList */ public void writeRoute(List<DropInSiteTransition> dropInSiteTransitionList){ System.out.println("[CSVWriter] writing routes..."); DataGetter dataGetter = new DataGetter(); List<String> routeTemp; int count = 0; for(DropInSiteTransition dropInSiteTransition:dropInSiteTransitionList){ routeTemp = dataGetter.getRoute(dropInSiteTransition.getStartTime(), dropInSiteTransition.getEndTime()); try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputPath + "Routes/route" + count + ".csv"))); for(String s:routeTemp){ printWriter.println(s); } printWriter.close(); } catch (IOException e) { e.printStackTrace(); } count++; } } /** * �e��؋�Ԃ̐擪��lost���o�͂��郁�\�b�h * @param devidedGPSDataLists */ public void writeFirstLostPoint(List<GPSDataList> devidedGPSDataLists){ System.out.println("[CSVWriter writing First lost point...]"); LatLng firstLostPointTemp; try { PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(outputPath + "FirstLostPoint.csv"))); for(GPSDataList gpsDataList:devidedGPSDataLists){ if(gpsDataList.isIndoorSite()){ firstLostPointTemp = gpsDataList.getFirstLostPoint(); printWriter.println(firstLostPointTemp.getLat() + "," + firstLostPointTemp.getLng()); } } printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.manager; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.entries.WifiSignature; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.cluster.Cluster; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.cluster.ClusterMode; import java.util.Set; /** * Created by gucci on 2015/06/15. */ public class Localizer { Set<Cluster> clusters = null;//測位用のclusters MatchClusterFinder matchClusterFinder = new MatchClusterFinder(); FindResult findResult = new FindResult(); public void localize(WifiSignature newWifiSignature){ if(clusters.isEmpty()){ System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(); System.out.println("Localize Unknown Place!"); System.out.println(); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); }else{ findResult = matchClusterFinder.find(newWifiSignature, clusters, SystemPhase.LOCALIZE); if (findResult.getNow_state() == ClusterMode.CREATE) { System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(); System.out.println("Localize Unknown Place!"); System.out.println(); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } else if (findResult.getNow_state() == ClusterMode.UPDATE) { System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(); System.out.println("Localize here !!!!!!!!!!! : " + findResult.getMatchCluster().getId()); System.out.println(); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } else { System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(); System.out.println("Localize Unknown Place!"); System.out.println(); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } } } public void setClusters(Set<Cluster> clusters) { this.clusters = clusters; } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Created by gucci on 2015/03/24. */ public class DBHelper { private static final String host = "exp-www.ubi.cs.ritsumei.ac.jp:3306", user = "kubiwauser", password = "<PASSWORD>", dbname = "blackhole"; // ポートフォワーディングしてる場合 //private static final String host = "localhost:9000", user = "kubiwauser", password = "<PASSWORD>", dbname = "blackhole"; private static final String[] dbinfo = { "jdbc:mysql://" + host + "/" + dbname, user, password,}; private Connection con = null; public Connection connect() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); this.con = DriverManager.getConnection(dbinfo[0], dbinfo[1], dbinfo[2]); } catch (Exception e) { System.out.println("DBConnection Error !!!"); } return this.con; } public void disconnect(){ try { if(con != null){ con.close(); } } catch (SQLException e) { e.printStackTrace(); } } }<file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.HeartRailsExpress; /** * HeartRails Expressから取得した最寄り駅情報を格納するクラス * @author zukky * */ public class NearStation { private String name; private String prev; private String next; private double lat; private double lng; private int distance; private int postal; private String prefecture; private String line; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrev() { return prev; } public void setPrev(String prev) { this.prev = prev; } public String getNext() { return next; } public void setNext(String next) { this.next = next; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public int getPostal() { return postal; } public void setPostal(int postal) { this.postal = postal; } public String getPrefecture() { return prefecture; } public void setPrefecture(String prefecture) { this.prefecture = prefecture; } public String getLine() { return line; } public void setLine(String line) { this.line = line; } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.util; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.config.DataConfig; import jp.ac.ritsumei.cs.ubi.zukky.BRM.transport.JudgementStepZone; import jp.ac.ritsumei.cs.ubi.zukky.BRM.transport.Transportation; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; /** * Created by gucci on 2015/03/24. */ public class StayTermDetector { /** * 使用するデータの設定を保持するクラス */ DataConfig dataConfig = new DataConfig(); /** * データを分割して処理をしやすく */ // private static final long SLICE_TIME = 21600; //6h private static final long SLICE_TIME = 10800; //3h /** * 歩数検知のための閾値 */ private static final long CONNECT_THRESH = 0; //2秒 歩行区切る private static final long REMOVE_THRESH = 0; //10秒 一定期間以下の歩行を削除 /** * 最低停留期間 */ private static final int STAY_DURATION = 20; public ArrayList<Long[]> detectStayTerm(){ ArrayList<Long[]> stayTermList = new ArrayList<Long[]>(); Long[] startToEndArray = null; int devId = dataConfig.getDevId(); long startTime = dataConfig.getStartTime(); long endTime = dataConfig.getEndTime(); Timestamp startTimeStamp = new Timestamp(startTime*1000); Timestamp endTimeStamp = new Timestamp(endTime*1000); JudgementStepZone judgementStepZone = new JudgementStepZone(); for(long tEndTime=startTime+SLICE_TIME; tEndTime <= endTime; tEndTime+=SLICE_TIME){ List<Transportation> listOfStepZone = judgementStepZone.judgeStepZone(startTimeStamp, endTimeStamp, devId, CONNECT_THRESH, REMOVE_THRESH); for(int walkStausNum = 0; walkStausNum < listOfStepZone.size(); walkStausNum++) { Transportation transportState = listOfStepZone.get(walkStausNum); /** 停留期間のみ抽出 **/ if (transportState.getType().toString().equals("UNKNOWN")) { long stayStartTime = transportState.getStartTime().getTime() / 1000; long stayEndTime = transportState.getEndTime().getTime() / 1000; if ((stayEndTime - stayStartTime) < STAY_DURATION) continue; System.out.println("STAY [" + walkStausNum + "] : " + transportState.getStartTime().toString() + " ~ " + transportState.getEndTime().toString()); startToEndArray = new Long[2]; startToEndArray[0] = stayStartTime; startToEndArray[1] = stayEndTime; stayTermList.add(startToEndArray); } } } return stayTermList; } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker.dropInSite; import java.util.ArrayList; import java.util.List; import jp.ac.ritsumei.cs.ubi.geo.LatLng; public class ClusteredDropInSite extends ArrayList<DropInSite>{ //TODO もっと正確に.緯度経度も分ける private static double SECONDS_PAR_METER = 0.0324; //1m辺りの秒数(参考:http://okwave.jp/qa/q5540938.html) private static double NOISE_THRESHOLD = 300; //ノイズと見なすための距離閾値 //TODO center,dispersionなどはメソッドとして用意しておけば良いかな private String id; //ユニークなid private ArrayList<String> containDropInSiteIdList = new ArrayList<String>();//Clusterの含むDropInSiteのidのリスト private double maxLat; //右上の点 private double maxLng; private double minLat; //左下の点 private double minLng; private LatLng centroid; //重心 boolean isIndoor; //建物への出入りを含むかどうか boolean isNoise = false; double dispersion; //分散 double radius; //半径(標準偏差) /** * DropInSiteをClusteredDropInSiteに変換するとき利用するコンストラクタ * @param dropInSite * @param flag 各dropInSiteの矩形生成時に推定foundを利用するかどうか */ public ClusteredDropInSite(DropInSite dropInSite){ this.add(dropInSite); //要素の追加 this.id = Long.toString(dropInSite.getBeginTime().getTime()/1000); //先頭のUNIXTIME(long)をIDとして採用する if(isNoiseDropInSite(dropInSite)) isNoise = true; this.maxLat = dropInSite.getMaxLat(); //各値の代入 this.maxLng = dropInSite.getMaxLng(); this.minLat = dropInSite.getMinLat(); this.minLng = dropInSite.getMinLng(); this.centroid = new LatLng((maxLat+minLat)/2,(maxLng+minLng)/2); //重心計算 //矩形を分散から生成 calculateDispersionFromCentroid(); this.containDropInSiteIdList.add(dropInSite.getId()); //idの登録 } /** * 2つの異なるClusterDropInSiteから新しいクラスタを生成するメソッド * (重心法専用?必要があれば分離すること) * @param clusterA * @param clusterB */ public ClusteredDropInSite(ClusteredDropInSite clusterA,ClusteredDropInSite clusterB){ this.addAll(clusterA); //A,Bの含むDropInSiteを追加 this.addAll(clusterB); if(new Long(clusterA.getId()).longValue()<new Long(clusterB.getId()).longValue())//小さい方のUNIXTIMEをIDとして付与 this.id = clusterA.getId(); else this.id = clusterB.getId(); this.maxLat = Math.max(clusterA.getMaxLat(), clusterB.getMaxLat()); //max,minの更新 this.maxLng = Math.max(clusterA.getMaxLng(), clusterB.getMaxLng()); this.minLat = Math.min(clusterA.getMinLat(), clusterB.getMinLat()); this.minLng = Math.min(clusterA.getMinLng(), clusterB.getMinLng()); this.centroid = calculateCentroid(clusterA, clusterB); //重心の再計算 calculateDispersionFromCentroid(); this.containDropInSiteIdList.addAll(clusterA.getContainDropInSiteIdList()); //結合したidListの登録 this.containDropInSiteIdList.addAll(clusterB.getContainDropInSiteIdList()); } /** * 2クラスタの重心を算出すメソッド * @param clusterA * @param clusterB * @return */ private LatLng calculateCentroid(ClusteredDropInSite clusterA,ClusteredDropInSite clusterB){ double centroidLat,centroidLng; double weightA = (double)clusterA.size() / ((double)clusterA.size()+(double)clusterB.size()); double weightB = (double)clusterB.size() / ((double)clusterA.size()+(double)clusterB.size()); centroidLat = (clusterA.getCentroid().getLat() * weightA) + (clusterB.getCentroid().getLat() * weightB); centroidLng = (clusterA.getCentroid().getLng() * weightA) + (clusterB.getCentroid().getLng() * weightB); return new LatLng(centroidLat,centroidLng); } /** * 重心からの距離の分散値を求めるメソッド * TODO 分散を求める対象を変更 * @return */ private double calculateDispersionFromCentroid(){ double dispersionFromCentroid = 0; //ネーミングセンス疑うわ... double squareOfDifferenceFromLost = 0; //あああああああああ double squareOfDifferenceFromNew = 0; double standardDivision = 0; //標準偏差(度) LatLng lostPoint,newPoint; long count=0; for(DropInSite dropInSite:this){ lostPoint = dropInSite.getLostPoint(); newPoint = dropInSite.getNewPoint(); squareOfDifferenceFromLost = Math.pow(this.centroid.distance(lostPoint),2); squareOfDifferenceFromNew = Math.pow(this.centroid.distance(newPoint),2); dispersionFromCentroid += squareOfDifferenceFromLost; dispersionFromCentroid += squareOfDifferenceFromNew; count++; } dispersionFromCentroid /= (count*2)-1; //不偏分散を算出 radius = Math.sqrt(dispersionFromCentroid); //標準偏差を格納 standardDivision = Math.sqrt(dispersionFromCentroid) * SECONDS_PAR_METER / 3600; //標準偏差(m) × 秒/m / 3600で標準偏差(度)を算出 this.maxLat = centroid.getLat() + standardDivision; this.maxLng = centroid.getLng() + standardDivision; this.minLat = centroid.getLat() - standardDivision; this.minLng = centroid.getLng() - standardDivision; return dispersionFromCentroid; } /** * クラスタに含まれる立ち寄りポイントに関して、立ち寄った時間の平均値(分)を算出するメソッド * @return */ public long getAverageDropInTime(){ long totalDropInTime = 0; for(DropInSite dropInSite:this){ totalDropInTime += dropInSite.getDropInTime(); } totalDropInTime = totalDropInTime/this.size(); totalDropInTime = totalDropInTime/1000; //s totalDropInTime = totalDropInTime/60; //m return totalDropInTime; } /** * クラスタに含まれる立寄ポイントに関して、立ち寄った最長時間(分)を取得 * @return */ public long getMaxDropInTime(){ long maxDropInTime = 0; for(DropInSite dropInSite:this){ if(maxDropInTime<dropInSite.getDropInTime()) maxDropInTime = dropInSite.getDropInTime(); } maxDropInTime = maxDropInTime/1000; //s maxDropInTime = maxDropInTime/60; //m return maxDropInTime; } /** * クラスタに含まれる立寄ポイントに関して、立ち寄った最短時間(分)を取得 * @return */ public long getMinDropInTime(){ long minDropInTime = 10000000; for(DropInSite dropInSite:this){ if(minDropInTime>dropInSite.getDropInTime()) minDropInTime = dropInSite.getDropInTime(); } minDropInTime = minDropInTime/1000; //s minDropInTime = minDropInTime/60; //m return minDropInTime; } /** * クラスタリングされた重心の座標を返すメソッド * @return */ public LatLng getCentroid() { return centroid; } public void setCentroid(LatLng centroid) { this.centroid = centroid; } public double getMaxLat() { return maxLat; } public void setMaxLat(double maxLat) { this.maxLat = maxLat; } public double getMaxLng() { return maxLng; } public void setMaxLng(double maxLng) { this.maxLng = maxLng; } public double getMinLat() { return minLat; } public void setMinLat(double minLat) { this.minLat = minLat; } public double getMinLng() { return minLng; } public void setMinLng(double minLng) { this.minLng = minLng; } public List<String> getContainDropInSiteIdList(){ return containDropInSiteIdList; } public String getId(){ return id; } public boolean isNoise(){ return isNoise; } public double getRadius(){ return this.radius; } /** * ノイズになってしまっているDropInSiteを判定するメソッド */ private static boolean isNoiseDropInSite(DropInSite dropInSite){ double distance = new LatLng(dropInSite.getMaxLat(),dropInSite.getMaxLng()).distance(new LatLng(dropInSite.getMinLat(),dropInSite.getMinLng())); if(distance > 300) return true; else return false; } }<file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa; public class KubiwaUser { private int id; private String uname; private String password; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String name) { this.uname = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public KubiwaUser(){ super(); } public KubiwaUser(int id){ this.id=id; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa; import java.sql.Timestamp; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; /** * Kubiwa DBを操作するHelperクラス * どう動いているかはkubiwa.cfg.xml, KubiwaUser.hbm.xmlあたりを見れば分かるはず * @see http://www.techscore.com/tech/Java/Others/Hibernate/index/ * @author SoichiroHorimi */ public class KubiwaHelper{ private Session getSession() { @SuppressWarnings("deprecation") SessionFactory sessionFactory = new Configuration().configure("jp/ac/ritsumei/cs/ubi/zukky/BRM/util/kubiwa.cfg.xml").buildSessionFactory(); Session s = sessionFactory.openSession(); return s; } /** * 指定した期間のGPSの値をDBから取得する関数 * @param devId * @param sTime 取得したいGPSの期間の開始時刻 * @param eTime 取得したいGPSの期間の終了時刻 * @return 取得したいGPSのリスト */ //おそらくListをキャストしてないことによる警告が出てる @SuppressWarnings("unchecked") public List<Gps> getGps(int devId, Timestamp sTime, Timestamp eTime){ Criteria c=getSession().createCriteria(Gps.class); //検索条件を設定.MySQLで"WHERE userid=..."と指定するみたいなイメージ c.add(Restrictions.eq("devId", devId)); c.add(Restrictions.between("time", sTime, eTime)); c.addOrder(Order.asc("time")); //useridに紐づいたデバイスID一覧を返す return c.list(); } @SuppressWarnings("unchecked") public List<Gps> getGpsPlace(int devId, Timestamp sTime, Timestamp eTime, double latLow, double latHigh, double lngLow, double lngHigh){ Criteria c=getSession().createCriteria(Gps.class); //検索条件を設定.MySQLで"WHERE userid=..."と指定するみたいなイメージ c.add(Restrictions.eq("devId", devId)); c.add(Restrictions.between("time", sTime, eTime)); c.add(Restrictions.between("lat", latLow, latHigh)); c.add(Restrictions.between("lng", lngLow, lngHigh)); c.addOrder(Order.asc("time")); return c.list(); } /** * * @param id * @return */ @SuppressWarnings("unchecked") public List<Device> getDevicesTest(){ Criteria c=getSession().createCriteria(Device.class); //検索条件を設定.MySQLで"WHERE userid=..."と指定するみたいなイメージ c.add(Restrictions.eq("devName", "vino")); c.add(Restrictions.between("devId", 0, 10)); //useridに紐づいたデバイスID一覧を返す return c.list(); } /** * 指定したKubiwaIDに紐づいたデバイス一覧を取得する * @param id * @return */ @SuppressWarnings("unchecked") public List<Device> getDevicesByUserId(int id){ Criteria c=getSession().createCriteria(Device.class); //検索条件を設定.MySQLで"WHERE userid=..."と指定するみたいなイメージ c.add(Restrictions.eq("userid", id)); //useridに紐づいたデバイスID一覧を返す return c.list(); } /** * 指定した名前のユーザを返す * @param name * @return */ public KubiwaUser getUserByName(String name) { KubiwaUser result=null; Session s=getSession(); Criteria c=s.createCriteria(KubiwaUser.class); c.add(Restrictions.eq("uname", name)); try{ //条件にマッチした結果を返す.nameに一致する結果は一つだけ result=(KubiwaUser) c.uniqueResult(); }catch(HibernateException e){ e.printStackTrace(); }finally{ s.close(); } return result; } /** * クラスの使い方サンプル * @param args */ public static void main(String[] args){ // String name="vino"; KubiwaHelper helper=new KubiwaHelper(); List<Device> devices = helper.getDevicesTest(); for(Device d: devices){ System.out.println(d); } // KubiwaUser u=helper.getUserByName(name); // if(u==null){ // System.out.println("kubiwauser "+name+" not found."); // } // else{ // List<Device> devices=helper.getDevicesByUserId(u.getId()); // for(Device d : devices){ // System.out.println("devid="+d.getDevId()); // } // } } }<file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.gps.GPSData; /** * Blackhole�f�[�^�x�[�X����f�[�^���擾���邽�߂̃N���X * @author takuchan */ public class DataGetter { public List<GPSData> getGPSDataList(){ List<GPSData> gpsDataList = new ArrayList<GPSData>(); Timestamp currentTime = new Timestamp(0); PreparedStatement ps; DBConnector connector = new DBConnector(); Connection con; try { con = connector.connectDatabase(); ps = con.prepareStatement("SELECT * FROM LocationLog WHERE provider='gps' AND devid=? AND time BETWEEN from_unixtime( ? ) AND from_unixtime( ? ) ORDER BY " + "time" ); ps.setInt(1, Target.devid); ps.setString(2, Long.toString(Target.start)); ps.setString(3, Long.toString(Target.end)); ResultSet rs = ps.executeQuery(); while(rs.next()){ if(!rs.getTimestamp("time").equals(currentTime)){ gpsDataList.add(new GPSData(rs.getTimestamp("time"), rs.getInt("devid"), rs.getDouble("lat"), rs.getDouble("lng"), rs.getFloat("acc"), rs.getFloat("speed"), rs.getTimestamp("provider_time"))); currentTime = rs.getTimestamp("time"); } } //������close()���܂��傤 rs.close(); ps.close(); con.close(); } catch (SQLException e) { System.out.println("Failed to connect DB"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return gpsDataList; } public List<Timestamp> getStep(){ List<Timestamp> stepList = new ArrayList<Timestamp>(); PreparedStatement ps; DBConnector connector = new DBConnector(); Connection con; try { con = connector.connectDatabase(); ps = con.prepareStatement("SELECT * FROM step WHERE devid=? AND time BETWEEN from_unixtime( ? ) AND from_unixtime( ? )"); ps.setInt(1, Target.devid); //ps.setInt(1,114); //TODO �P���ɑ�p���邾���łȂ�,��������K�v�L�� ps.setString(2, Long.toString(Target.start)); ps.setString(3, Long.toString(Target.end)); ResultSet rs = ps.executeQuery(); while(rs.next()){ stepList.add(rs.getTimestamp("time")); } //������close()���܂��傤 rs.close(); ps.close(); con.close(); } catch (SQLException e) { System.out.println("Failed to connect DB"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return stepList; } /** * �ȈՌo�H�����o�����\�b�h * @param startTime * @param endTime * @return */ public List<String> getRoute(Timestamp startTime,Timestamp endTime){ List<String> routeList = new ArrayList<String>(); String routeTemp = null; PreparedStatement ps; DBConnector connector = new DBConnector(); Connection con; try { con = connector.connectDatabase(); con = connector.connectDatabase(); ps = con.prepareStatement("SELECT time,lat,lng FROM LocationLog WHERE provider='gps' AND devid=? AND time BETWEEN ? AND ?"); ps.setInt(1, Target.devid); //ps.setInt(1,114); //TODO �P���ɑ�p���邾���łȂ�,��������K�v�L�� ps.setTimestamp(2, startTime); ps.setTimestamp(3, endTime); ResultSet rs = ps.executeQuery(); while(rs.next()){ routeTemp = rs.getTimestamp("time") + "," + rs.getDouble("lat") + "," + rs.getDouble("lng") + ",blue"; routeList.add(routeTemp); } //������close()���܂��傤 rs.close(); ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return routeList; } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.manager; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.entries.EntriesGenerator; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.util.DBHelper; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.StringTokenizer; /** * Created by gucci on 2015/03/24. * * 与えられたデータの中で * 標本を管理するクラス * */ public class MainManager { public static void main(String[] arg){ /** * DBにアクセスする際のConnectionを取得 */ DBHelper db = new DBHelper(); System.out.println("========== start AutomatedManagementSystem =========="); // /** 停留期間の検出 **/ // StayTermDetector stayTermDetector = new StayTermDetector(); // ArrayList<Long[]> stayTermList = stayTermDetector.detectStayTerm(); // // // /** 特徴量の生成 **/ // EntriesGenerator entriesGenerator = new EntriesGenerator(db); // int count = 0; // for(Long[] stay: stayTermList){ // count++; // System.out.println("[STAY Number:"+count+"]"); // entriesGenerator.genarate(stay[0], stay[1]); // } // // /** ファイル出力 **/ //---------- For Debug -------- try { File csv = new File("/Users/gucci/Desktop/StartEndTimeSet_Jan.csv"); // CSVデータファイル //File csv = new File("/Users/gucci/Desktop/Short_StartEndTimeSet_Jan.csv"); // CSVデータファイル BufferedReader bwT = new BufferedReader(new FileReader(csv)); String line; StringTokenizer token; long sTime = 0; long eTime = 0; EntriesGenerator entriesGenerator = new EntriesGenerator(db); while ((line = bwT.readLine()) != null) { token = new StringTokenizer(line, ","); sTime = 0; eTime = 0; int c = 0; while (token.hasMoreTokens()) { c++; if (c == 1) sTime = Long.parseLong(token.nextToken()); else eTime = Long.parseLong(token.nextToken()); } //停留の開始、終了時間が出てくるので、その時間のデータベースにアクセスして、timestampと基地局セットを紐付け entriesGenerator.genarate(sTime,eTime); // Timestamp tmpStartTimeStamp = new Timestamp(sTime * 1000); // Timestamp tmpEndTimeStamp = new Timestamp(eTime * 1000); } }catch(Exception e){ } //---------- For Debug -------- System.out.println("========== end AutomatedManagementSystem =========="); db.disconnect(); } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.movingStatisticsDB; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBHelper { private Connection con; public Connection connectDatabase() throws SQLException, ClassNotFoundException{ //if connection hasn't close, return it if(con!=null){ if(!con.isClosed()){ return con; } } Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(MovementDbUtil.URL, MovementDbUtil.USER,MovementDbUtil.PASS); return con; } } <file_sep>package jp.ac.ritsumei.cs.ubi.ubilabsensorlibrary; import java.io.IOException; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Calendar; import java.util.List; import org.json.JSONException; import jp.ac.ritsumei.cs.ubi.library.accelerometer.AccelerometerObject; /** * this is sample class for UbilabSensorLibrary.jar * @author sacchin * */ public class StepCounterMain { public static void main(String[] args){ int devid = 133; Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); start.set(2013, 9, 25, 16, 00, 00); end.set(2013, 9, 25, 16, 15, 00); try { List<AccelerometerObject> logs = selectAccelerometer(start, end, devid); StepCounter sc = new StepCounter(logs); //int count = sc.countStep(); List<Long> times = sc.getStepTimes(); for(long time: times){ System.out.println("time :" + new Timestamp(time)); } //System.out.println("steps " + count); } catch (SQLException e) { e.printStackTrace(); } } private static String format(Calendar c){ if(c == null){ return "error"; } int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); return year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second; } /** * 加速度をselectするメソッド. * @param sql selectするsql文 * @return AccelerometerObjectのリスト. * @throws java.sql.SQLException */ private static List<AccelerometerObject> selectAccelerometer(Calendar start, Calendar end, int devid) throws SQLException { String sql = "select * from accelerometer where devid = " + devid + " and time between '" + format(start) + "' and '" + format(end) + "' order by time asc"; System.out.println(sql); BlackholeConnector connector = null; try { connector = new BlackholeConnector("kubiwa.properties"); connector.createConnection(); return connector.selectAccelerometer(sql); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } catch (SQLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } catch (JSONException e) { e.printStackTrace(); return null; }finally{ if(connector != null && !connector.isClosed()){ connector.close(); } } } }<file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.json; import java.util.ArrayList; import java.util.List; import jp.ac.ritsumei.cs.ubi.zukky.BRM.featurePoint.FeaturePoint; import jp.ac.ritsumei.cs.ubi.zukky.BRM.path.PathSegment; public class Json_Route { private int jRouteId; private FeaturePoint tsStartPoint; private FeaturePoint tsEndPoint; private List<FeaturePoint> checkPointCandidateList = new ArrayList<FeaturePoint>(); public Json_Route(PathSegment pathSegment){ this.tsStartPoint = pathSegment.getTsStartPoint(); this.tsEndPoint = pathSegment.getTsEndPoint(); this.checkPointCandidateList = pathSegment.getCheckPointCandidateList(); } public Json_Route(){ } public FeaturePoint getTsStartPoint() { return tsStartPoint; } public void setTsStartPoint(FeaturePoint tsStartPoint) { this.tsStartPoint = tsStartPoint; } public FeaturePoint getTsEndPoint() { return tsEndPoint; } public void setTsEndPoint(FeaturePoint tsEndPoint) { this.tsEndPoint = tsEndPoint; } public List<FeaturePoint> getCheckPointCandidateList() { return checkPointCandidateList; } public void setCheckPointCandidateList(List<FeaturePoint> checkPointCandidateList) { this.checkPointCandidateList = checkPointCandidateList; } public void addCheckPointCandidateList(FeaturePoint checkPointCandidate){ this.checkPointCandidateList.add(checkPointCandidate); } public int getjRouteId() { return jRouteId; } public void setjRouteId(int jRouteId) { this.jRouteId = jRouteId; } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.movingStatisticsDB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; /** * テーブルmovingBetweenDropInSitesにアクセスするクラス * @author zukky * */ public class MovingBetweenDropInSitesGetter { /** * 指定したmovingIdに合致する移動を取得するメソッド * @param movingId * @return times 移動の開始時間,終了時間<startTime, endTime>を要素とするMapを返す */ public MovingTimes getMovementTimes(int movingId){ MovingTimes movingTimes = new MovingTimes(); PreparedStatement ps; DBHelper connector = new DBHelper(); Connection con; try { con = connector.connectDatabase(); ps = con.prepareStatement("SELECT * from MovingBetweenDropInSites where movingId = ? order by startTime asc"); ps.setInt(1, movingId); ResultSet rs = ps.executeQuery(); while(rs.next()){ movingTimes.addStartTimeList(rs.getTimestamp("startTime")); movingTimes.putTimeMap(rs.getTimestamp("startTime"), rs.getTimestamp("endTime")); } }catch (SQLException e) { System.out.println("Failed to connect DB"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return movingTimes; } public MovingTimes getMovementTimes(int movingId, Timestamp sTime, Timestamp eTime){ MovingTimes movingTimes = new MovingTimes(); PreparedStatement ps; DBHelper connector = new DBHelper(); Connection con; try { con = connector.connectDatabase(); ps = con.prepareStatement("SELECT * from MovingBetweenDropInSites where movingId = ? and startTime between ? and ? order by startTime asc"); ps.setInt(1, movingId); ps.setTimestamp(2, sTime); ps.setTimestamp(3, eTime); ResultSet rs = ps.executeQuery(); while(rs.next()){ movingTimes.addStartTimeList(rs.getTimestamp("startTime")); movingTimes.putTimeMap(rs.getTimestamp("startTime"), rs.getTimestamp("endTime")); } }catch (SQLException e) { System.out.println("Failed to connect DB"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return movingTimes; } } <file_sep>import java.sql.Timestamp; /** * Created by gucci on 2015/08/12. */ public class test { public static void main(String[] arg) { Timestamp checkTimestamp = new Timestamp(0); Timestamp startTimestamp = new Timestamp(System.currentTimeMillis() - 3000); Timestamp endTimestamp = new Timestamp(System.currentTimeMillis()); System.out.println(checkTimestamp.equals(new Timestamp(0))); System.out.println(startTimestamp); System.out.println(endTimestamp); System.out.println(endTimestamp.getTime() - checkTimestamp.getTime()); } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.util; public class MovingUtil{ public enum VelocityType { DOPPLER, HUBENY } //private static final double SMOOTHING_RATE = 0.05; private static final double SMOOTHING_RATE = 0.1; private static final double SMOOTHING_RATE_CHECKPOINT = 0.12; private static final long WALKING_CONNECTION_THRESHOLD = 2000; //WALKING_CONNECTION_THRESHOLDミリ秒で歩行区間が連続していた場合、同一歩行区間とする private static final long REMOVE_STAYING_TIME_THRESHOLD = 5000; //REMOVE_STAYING_TIME_THRESHOLDミリ秒より小さいの滞在区間を削除する private static final long REMOVE_WALKING_TIME_THREHSHOLD = 15000; //REMOVE_WALKING_TIME_THREHSHOLDミリ秒より小さい歩行区間を削除する private static final long INDOOR_DISTANCE_THRESHOLD = 200; //移動区間がINDOOR_THRESHOLDメートル以下ならば、同一建物とみなす private static final double VEHICLE_DISTANCE_TRESHOLD = 1000; //移動区間がVEHICLE_DISTANCE_TRESHOLD以上ならば、乗り物による移動とみなす private static final long VEHICLE_UP_DOWN_THRESHOLD = 5; //気圧センサによるUP_DONW検知がVEHICLE_UP_DOWN_THRESHOLD以上ならば、乗り物による移動とみなす private static final float ESCARATOR_MIN_UP_PER_SECOND = 0.02f; //エスカレータはだいたい1秒間に0.25M上昇する(下方修正して0.2)それをPressure換算 private static final float ESCARATOR_MAX_UP_PER_SECOND = 0.03f; //エスカレータはだいたい1秒間に0.25M上昇する(上方修正して0.3)それをPressure換算 private static final float PRESSURE_DIFFER_BETWEEN_FLOORS = 0.3f; //1階分の気圧差はだいたい0.3hpa(1階を3mとして計算) private static final float PRESSURE_DIFFER_OVER_HUMAN = 0.2f; //人間が端末を拾い上げても2m以上は上昇しない public static float getEscaratorMinUpPerSecond() { return ESCARATOR_MIN_UP_PER_SECOND; } public static float getEscaratorMaxUpPerSecond() { return ESCARATOR_MAX_UP_PER_SECOND; } public static double getSmoothingRate() { return SMOOTHING_RATE; } public static double getSmoothingRateCheckpoint() { return SMOOTHING_RATE_CHECKPOINT; } public static long getWalkingConnectionThreshold() { return WALKING_CONNECTION_THRESHOLD; } public static long getRemoveStayingTimeThreshold() { return REMOVE_STAYING_TIME_THRESHOLD; } public static long getRemoveWalkingTimeThrehshold() { return REMOVE_WALKING_TIME_THREHSHOLD; } public static long getIndoorDistanceThreshold() { return INDOOR_DISTANCE_THRESHOLD; } public static double getVehicleDistanceTreshold() { return VEHICLE_DISTANCE_TRESHOLD; } public static long getVehicleUpDownThreshold() { return VEHICLE_UP_DOWN_THRESHOLD; } public static float getPressureDifferBetweenFloors() { return PRESSURE_DIFFER_BETWEEN_FLOORS; } public static float getPressureDifferOverHuman() { return PRESSURE_DIFFER_OVER_HUMAN; } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnector { private Connection con; public Connection connectDatabase() throws SQLException, ClassNotFoundException{ //if connection hasn't close, return it if(con!=null){ if(!con.isClosed()){ return con; } } Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(ConstantBlackhole.URL,ConstantBlackhole.USER,ConstantBlackhole.PASS); return con; } } <file_sep>/** * using service by "HeartRails Express" */ package jp.ac.ritsumei.cs.ubi.zukky.BRM.HeartRailsExpress; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * * HeartRails ExpressのAPIを利用して駅情報を取得するメソッド * @author zukky * */ public class AccessHeartRailsApi { public static void main(String[] args){ AccessHeartRailsApi ahra = new AccessHeartRailsApi(); NearStation nearStation = ahra.getNearStationdata(35.092383,136.054688); } public NearStation getNearStationdata(double lat, double lng){ NearStation nearStation = new NearStation(); try { URL url = new URL("http://express.heartrails.com/api/json?method=getStations&x=" + lng + "&y=" + lat); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); if(connection.getResponseCode() == 200){ //受け取ったデータを書き込み BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream responseArray = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int length; while((length = inputStream.read(buf)) != -1) { if(length > 0) { responseArray.write(buf, 0, length); } } //受け取ったJSONデータをパース JSONObject jsonObj = new JSONObject(new String(responseArray.toByteArray())); jsonObj = jsonObj.getJSONObject("response"); JSONArray jsonArray = jsonObj.getJSONArray("station"); //とりあえず一番初めのステーション(最寄り駅)だけを取得 jsonObj = jsonArray.getJSONObject(0); nearStation.setName(jsonObj.getString("name")); nearStation.setPrev(jsonObj.getString("prev")); nearStation.setNext(jsonObj.getString("next")); nearStation.setLat(jsonObj.getDouble("y")); nearStation.setLng(jsonObj.getDouble("x")); String[] str = jsonObj.getString("distance").split("m"); nearStation.setDistance(Integer.valueOf(str[0])); nearStation.setPostal(jsonObj.getInt("postal")); nearStation.setPrefecture(jsonObj.getString("prefecture")); nearStation.setLine(jsonObj.getString("line")); }else{ System.out.println("error code: " + connection.getResponseCode()); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return nearStation; } } <file_sep>package jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.statistic; import jp.ac.ritsumei.cs.ubi.gucci.AutomatedManagementSystem.cluster.Cluster; import java.util.Comparator; /** * Created by gucci on 2015/06/24. */ public class AccumulatedTimeComparator implements Comparator{ @Override public int compare(Object arg0, Object arg1){ Cluster one = (Cluster) arg0; Cluster another = (Cluster) arg1; Long oneAccumulatedTime = one.getAccumulatedTime(); Long anotherAccumulatedTime = another.getAccumulatedTime(); if(oneAccumulatedTime < anotherAccumulatedTime) return 1; else if(oneAccumulatedTime > anotherAccumulatedTime) return -1; else return 0; } } <file_sep>apply plugin: 'java' sourceCompatibility = 1.5 version = '1.0' repositories { mavenCentral() // maven { // url "http://sub-www.ubi.cs.ritsumei.ac.jp/archiva/repository/internal/" // credentials { // username laboratoryMavenUser // password <PASSWORD> // } // } // maven { // url "http://sub-www.ubi.cs.ritsumei.ac.jp/archiva/repository/snapshots/" // credentials { // username laboratoryMavenUser // password <PASSWORD> // } // } } dependencies { testCompile group: 'junit', name: 'junit', version: '4.11' compile 'net.arnx:jsonic:1.2.9' compile 'org.hibernate:hibernate-core:4.3.8.Final' compile 'com.google.code.gson:gson:1.7.2' /** * パスが上手く通らなくて利用できなかったので、jarを直接ライブラリとしてimport */ // compile 'jp.ac.ritsumei.cs.ubi:ubilab-sensor-library:1.0.0' // compile 'jp.ac.ritsumei.cs.ubi:ubilab-utils:0.3.3' /** * パスが上手く通らなくて利用できなかったので("com.mysql.jdbc.Driver")、 * jarを直接ライブラリとしてimport */ //compile 'mysql:mysql-connector-java:5.1.34' }<file_sep>package jp.ac.ritsumei.cs.ubi.kubiwa.pressure.mining; /** * 気圧センサのupdownについて記録するクラス * @author zukky * */ public class UpdownRecorder { private int upCount = 0; private int downCount = 0; private int onUpDownStopCount = 0; public int getUpCount() { return upCount; } public void setUpCount(int upCount) { this.upCount = upCount; } public int getDownCount() { return downCount; } public void setDownCount(int downCount) { this.downCount = downCount; } public void addUpCount(){ this.upCount++; } public void addDownCount(){ this.downCount++; } public int getOnUpDownStopCount() { return onUpDownStopCount; } public void setOnUpDownStopCount(int onUpDownStopCount) { this.onUpDownStopCount = onUpDownStopCount; } public void addOnUpDownStopCount(){ this.onUpDownStopCount++; } } <file_sep>/** * Copyright (C) 2008-2012 Nishio Laboratory All Rights Reserved */ package jp.ac.ritsumei.cs.ubi.walker; import java.util.ArrayDeque; import java.util.LinkedList; import java.util.Queue; /** * This class detects the elevator DESCENDIG or ASCENDING. * * @author dany */ class ElevatorWalkerStateDetector extends WalkerStateDetector implements SensorEventListener { //desire DEV2 //desire colearning static final double UP_MAX = 10.4; //11.0 //10.8 10.25 10.65 11.18 static final double UP_MIN = 9.6; //10.40 //10.45 10.0 10.35 10.33 static final double DOWN_MAX = 9.6; //9.8 //9.76 9.5 10.0 10.03 static final double DOWN_MIN = 8.8; //9.42 //9.42 9.2 9.75 9.18 static final double MINIMA_TIME_THRESH = 1.5 * 1000000000; //default 1.5 static final double MAXIMA_TIME_THRESH = 16.0 * 1000000000; static final double GRAVITY = 9.58;//9.58 //10.18(desire) static final double V_ABS_THRESH_MIN = 0.15; //0.15 static final double V_ABS_THRESH_MAX = 1.0; static double lastAbs = 0; static double lastUpAbs = 9.58;//10.18(desire) static double lastDownAbs = 9.58;//10.18(desire) static final double ALLOW_DIFF_THRESH = 0.3; static int flag =0; static int flag2 =0; static int last; private long startTime; float alpha = 0.015f; //0.015 final Queue<SensorEvent> buf = new ArrayDeque<SensorEvent>(); final Queue<Double> q = new LinkedList<Double>(); public void onSensorChanged(SensorEvent event) { buf.offer(event); } public ElevatorWalkerStateDetector(int sec) { super.setTimeThresh(sec); } @Override protected void fireWalkerStateChanged(WalkerState state) { //System.out.println("beforessssstttttttt"); if (state.getType() == WalkerState.Type.STANDSTILL) { // long r = state.endTime-state.startTime; //System.out.println("state.endTime-state.startTime "+r); if(state.endTime-state.startTime < 600000){ state = detectElevator(state); } buf.clear(); } super.fireWalkerStateChanged(state); } long calcTimeWidth(long startTime, long endTime){ long timeWidth = endTime - startTime; return timeWidth; } Double CalcDispersion(Queue<Double> q){ double sum = 0; double size = q.size(); double ave; double sumDiff = 0; for(Double d : q){ sum += d; } //System.out.println("sum: "+sum); ave = sum / size; //System.out.println("ave: "+ave); for(Double d : q){ sumDiff += (Math.abs(ave - d)) * (Math.abs(ave - d)); } //System.out.println("sumDiff: "+sumDiff); return sumDiff / size; } WalkerState detectElevator(WalkerState state) { float x = 0, y = 0, z = 0; double lastV = 0; //lastVMaxima = 0, //lastVMinima = 0; double lastNanos = 0, lastNanosMaxima = 0, lastNanosMinima = 0; int lastDirection = 0; boolean up = false, down = false; for (SensorEvent event; (event = buf.poll()) != null;) { if (event.time < state.startTime) { continue; } // Low-pass filters x = alpha * event.x + (1.0f - alpha) * x; y = alpha * event.y + (1.0f - alpha) * y; z = alpha * event.z + (1.0f - alpha) * z; double v = Math.sqrt(x * x + y * y + z * z); //System.out.println(v); if(q.size()==100){ q.poll(); } // int a = 0; q.offer(v); //System.out.println(v); int direction = Double.compare(v, lastV); if(direction == 0){ direction = lastDirection; } if (direction * lastDirection < 0) { // Direction changed if (direction < 0) { // Local maxima lastNanosMaxima = lastNanos; // boolean isInRange = (MINIMA_TIME_THRESH < lastNanosMaxima - lastNanosMinima ? // (lastNanosMaxima - lastNanosMinima < MAXIMA_TIME_THRESH ? true : false) : false); if (MINIMA_TIME_THRESH < lastNanosMaxima - lastNanosMinima) { //lastVMaxima = v; if (UP_MIN <= v && v <= UP_MAX) { // double div = CalcDispersion(q); //System.out.println("dddddd"); if (down) { double diff = Math.abs(lastDownAbs - Math.abs(GRAVITY - v)); if(diff < ALLOW_DIFF_THRESH){ state.setType(WalkerState.Type.DESCENDING); ElevatorState evState = new ElevatorState( ElevatorState.Type.DESCENDING, startTime, event.time, calcTimeWidth(startTime, event.time)); state.evState.add(evState); //System.out.println("10.2"); } flag=1; up = false; down = false; } else{ up = true; lastUpAbs = Math.abs(v - GRAVITY); //System.out.println("10"); flag2=1; } startTime = event.time; } } } else { // Local minima lastNanosMinima = lastNanos; if (MINIMA_TIME_THRESH < lastNanosMinima - lastNanosMaxima) { //lastVMinima = v; if (DOWN_MIN <= v && v <= DOWN_MAX) { //System.out.println("aaaaa"); if (up) { double diff = Math.abs(lastUpAbs - Math.abs(GRAVITY - v)); if(diff < ALLOW_DIFF_THRESH){ state.setType(WalkerState.Type.ASCENDING); //fireWalkerStateChanged(new WalkerState( // WalkerState.Type.ASCENDING, startTime, event.time, 0)); ElevatorState evState = new ElevatorState( ElevatorState.Type.ASCENDING, startTime, event.time, calcTimeWidth(startTime, event.time)); System.out.println("CalcDispersion(q): "+CalcDispersion(q)); state.evState.add(evState); //System.out.println("10.2"); flag = 1; up = false; down = false; } } else{ down = true; lastDownAbs = Math.abs(v - GRAVITY); //System.out.println("10"); flag2=1; } startTime = event.time; } } } } if(flag==0 && flag2==0){ //System.out.println("0"); } if(flag==1){ flag=0; } if(flag2==1){ flag2=0; } lastV = v; lastDirection = direction; lastNanos = event.nanos; } for(ElevatorState es : state.evState){ state.moveFloor += es.moveFloor; } return state; } } <file_sep>package jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSiteMaker; import java.util.ArrayList; import java.util.List; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.ClusteredDropInSite; import jp.ac.ritsumei.cs.ubi.takuchan.dropInSiteMaker.dropInSite.DropInSite; /** * �N���X�^�����O�Ƃ�����l * @author takuchan * */ public class DropInSiteCoordinator { private static double DISTANCE_THRESHOLD = 100; //����臒l /** * �d�S�@���g����DropInSite���N���X�^�����O���郁�\�b�h * @return �N���X�^�����O�ς�DropInSite(ClusteredDropInSite�̃��X�g) */ public List<ClusteredDropInSite> clusteringDropInSiteByCentroidMethod(List<DropInSite> dropInSiteList){ int indexTemp; //�C���f�b�N�X�ꎞ�i�[�p int indexA=-1,indexB=-1; //�ŒZ�������\������2�N���X�^�̃C���f�b�N�X�̊i�[�p double distanceTemp,minDistance; ClusteredDropInSite clusteredDropInSiteTemp; //DropInSiteList��S��ClusteredDropInSite�Ɉ�U�ϊ� List<ClusteredDropInSite> clusteredDropInSiteList = convertDropInSiteToClusteredDropInSite(dropInSiteList); do{ minDistance = DISTANCE_THRESHOLD; //�N���X�^�̏d�S�Ԃ̍ŒZ������,������`������N���X�^�̑g�𔭌����� for(ClusteredDropInSite clusteredDropInSite:clusteredDropInSiteList){ indexTemp = clusteredDropInSiteList.indexOf(clusteredDropInSite); //�O��for���ʼn񂵂Ă�List�̍��̃C���f�b�N�X for(int count = indexTemp+1;count<clusteredDropInSiteList.size()-1;count++){ //count�͒���for���ʼn񂵂Ă�List�̍��̃C���f�b�N�X clusteredDropInSiteTemp = clusteredDropInSiteList.get(count); distanceTemp = clusteredDropInSite.getCentroid().distance(clusteredDropInSiteTemp.getCentroid());//2�N���X�^�����Z�o if((distanceTemp<minDistance)&&!clusteredDropInSite.isNoise()&&!clusteredDropInSiteTemp.isNoise()){//�ǂ��炩���m�C�Y�Ȃ�X�V�����Ȃ� //minDistance,indexA,indexB�̍X�V minDistance = distanceTemp; indexA = indexTemp; indexB = count; } } } //minDistance���X�V����Ă���΃N���X�^�����O���s�� if(minDistance<DISTANCE_THRESHOLD){ //indexA,indexB���g���ĐV�����N���X�^�𐶐�&���X�g�ɒlj� clusteredDropInSiteTemp = new ClusteredDropInSite(clusteredDropInSiteList.get(indexA), clusteredDropInSiteList.get(indexB)); clusteredDropInSiteList.add(clusteredDropInSiteTemp); //���p�����Q�v�f�����X�g����폜 clusteredDropInSiteList.remove(indexA); clusteredDropInSiteList.remove(indexB-1); //A��������������1�ƒY���Ă���͂��Ȃ̂�-1 } }while(minDistance<DISTANCE_THRESHOLD); //�N���X�^�Ԃ̍ŒZ������臒l�𒴂���,���邢�͏���l(臒l)����ύX����Ȃ��Ȃ�܂ő����� return clusteredDropInSiteList; } /** * �n���ꂽ���X�g����DropInSite��S��ClusteredDropInSite�ɕύX���郁�\�b�h * @param dropInSiteList * @return */ private List<ClusteredDropInSite> convertDropInSiteToClusteredDropInSite(List<DropInSite> dropInSiteList){ List<ClusteredDropInSite> clusteredDropInSiteList = new ArrayList<ClusteredDropInSite>(); for(DropInSite dropInSite:dropInSiteList){ clusteredDropInSiteList.add(new ClusteredDropInSite(dropInSite)); } return clusteredDropInSiteList; } /** * ���X�������ꂽ�������|�C���g�̃��X�g��,�N���X�^�����O�ς݂̗������|�C���g�̃��X�g���g��, * �O�҂̊e�������|�C���g�ɑ΂���,�U�蕪����ꂽ�N���X�^��id��t�^���郁�\�b�h * TODO �킩��ɂ����̂ŗ]�T���ł���������������� * */ public void grantClusterId(List<DropInSite> dropInSiteList, List<ClusteredDropInSite> clusteredDropInSiteList){ List<String> idListTemp; //�N���X�^�̊܂ފe�������|�C���g��id�̃��X�g�i�[�p for(DropInSite dropInSite:dropInSiteList){ //�S�Ă̗������|�C���g�ɑ΂��ăN���X�^��id��t�^���� for(ClusteredDropInSite clusteredDropInSite:clusteredDropInSiteList){ //�m�F�͑S�N���X�^�ɑ΂��čs�� idListTemp = clusteredDropInSite.getContainDropInSiteIdList(); //���X�g�̊i�[ if(idListTemp.contains(dropInSite.getId())){ //���������ڂ��Ă��闧�����|�C���g�����X�g�Ɋ܂܂��� dropInSite.setClusterId(clusteredDropInSite.getId()); //�N���X�^id��t�^ break; } } } } } <file_sep>package jp.ac.ritsumei.cs.ubi.zukky.BRM.hubenyVelocity; import java.util.ArrayList; import java.util.List; import jp.ac.ritsumei.cs.ubi.zukky.BRM.kubiwa.Gps; import jp.ac.ritsumei.cs.ubi.zukky.BRM.util.MovingUtil; /* 著作権表示の書き方については,要確認の必要あり */ /* Portions are: * Copyright © 2007-2012 やまだらけ * */ /** * ヒュベニ速度を計算するクラス * @author zukky * */ public class HubenyVelocityCalculator { public static final double BESSEL_A = 6377397.155; public static final double BESSEL_E2 = 0.00667436061028297; public static final double BESSEL_MNUM = 6334832.10663254; public static final double GRS80_A = 6378137.000; public static final double GRS80_E2 = 0.00669438002301188; public static final double GRS80_MNUM = 6335439.32708317; public static final double WGS84_A = 6378137.000; public static final double WGS84_E2 = 0.00669437999019758; public static final double WGS84_MNUM = 6335439.32729246; public static final int BESSEL = 0; public static final int GRS80 = 1; public static final int WGS84 = 2; public static double deg2rad(double deg){ return deg * Math.PI / 180.0; } public static double calcDistHubeny(double lat1, double lng1, double lat2, double lng2, double a, double e2, double mnum){ double my = deg2rad((lat1 + lat2) / 2.0); double dy = deg2rad(lat1 - lat2); double dx = deg2rad(lng1 - lng2); double sin = Math.sin(my); double w = Math.sqrt(1.0 - e2 * sin * sin); double m = mnum / (w * w * w); double n = a / w; double dym = dy * m; double dxncos = dx * n * Math.cos(my); return Math.sqrt(dym * dym + dxncos * dxncos); } public static double calcDistHubeny(double lat1, double lng1, double lat2, double lng2){ return modifyOverFlow(calcDistHubeny(lat1, lng1, lat2, lng2, GRS80_A, GRS80_E2, GRS80_MNUM)); } // public static double calcDistHubery(double lat1, double lng1, // double lat2, double lng2, int type){ // switch(type){ // case BESSEL: // return calcDistHubeny(lat1, lng1, lat2, lng2, // BESSEL_A, BESSEL_E2, BESSEL_MNUM); // case WGS84: // return calcDistHubeny(lat1, lng1, lat2, lng2, // WGS84_A, WGS84_E2, WGS84_MNUM); // default: // return calcDistHubeny(lat1, lng1, lat2, lng2, // GRS80_A, GRS80_E2, GRS80_MNUM); // } // } public double calculateHubenyVelocity(Gps gps1, Gps gps2){ double lat1 = gps1.getLat(); double lng1 = gps1.getLng(); double lat2 = gps2.getLat(); double lng2 = gps2.getLng(); //ヒュベニの公式を用いてヒュベニ距離を算出 double distance = calcDistHubeny(lat1, lng1, lat2, lng2); /* 2点間の移動時間をミリ秒で算出 */ // System.out.println("gps2.getTime() " + gps2.getTime()); // System.out.println("gps1.getTime() " + gps1.getTime()); Long diffMilliSec = gps2.getTime().getTime() - gps1.getTime().getTime(); /* ミリ秒を秒に変換 */ Long diffSec = diffMilliSec / 1000L; double hubeneyVelocity = 0.0; if(distance != 0.0){ hubeneyVelocity = distance / diffSec; } //時速に変換 hubeneyVelocity = hubeneyVelocity * 3.6; return hubeneyVelocity; } /*** * ヒュべ二距離の桁数がオーバーフローしたときに * @param distance * @return */ private static double modifyOverFlow(double distance){ String distanceString = String.valueOf(distance); String[] split = distanceString.split("E"); return Double.valueOf(split[0]); } /** * ヒュベニ速度を計算し、取得するメソッド * @param gpsList * @param smoothingRate * @return resultHubenyVelocityList 引数にとったgpsListに対応するヒュベニ速度のリスト */ public List<HubenyVelocity> getHubenyVelocityList(List<Gps> gpsList){ List<HubenyVelocity> resultHubenyVelocityList = new ArrayList<HubenyVelocity>(); Gps previousGpsData = new Gps(); Gps nextGpsData = new Gps(); double velocity = 0.0; double velocityBefore = 0.0; HubenyVelocityCalculator velocityCalculator = new HubenyVelocityCalculator(); for(int i=0; i<gpsList.size(); i++){ HubenyVelocity hubenyVelocity = new HubenyVelocity(); nextGpsData = gpsList.get(i); if(i != 0){ velocity = velocityCalculator.calculateHubenyVelocity(previousGpsData, nextGpsData); if(1 < i){ velocity = smoothingHubenyVelocity(velocityBefore, velocity); velocityBefore = velocity; } hubenyVelocity.setStartTime(previousGpsData.getTime()); hubenyVelocity.setEndTime(nextGpsData.getTime()); float acc = Math.max(previousGpsData.getAcc(), nextGpsData.getAcc()); hubenyVelocity.setAcc(acc); hubenyVelocity.setVelocity(velocity); resultHubenyVelocityList.add(hubenyVelocity); } previousGpsData = nextGpsData; } return resultHubenyVelocityList; } /** * ヒュベニ速度が一定以下のポイントを抽出するメソッド * @param gpsList 解析したいGPSデータのリスト * @param HubenyVelocityThreshold 抽出したい速度の閾値 * @return resultGpsList ヒュベニ速度が一定以下のGPSデータのリスト */ public List<Gps> getGpsListFilteringHubeny(List<Gps> gpsList, double hubenyVelocityThreshold, double smoothingRate){ List<Gps> resultGpsList = new ArrayList<Gps>(); int newestIndex = 0; Gps previousGpsData = new Gps(); Gps nextGpsData = new Gps(); double hubenyVelocity = 0.0; double hubenyVelocityBefore = 0.0; HubenyVelocityCalculator velocityCalculator = new HubenyVelocityCalculator(); for(int i=0; i<gpsList.size(); i++){ nextGpsData = gpsList.get(i); if(i != 0){ hubenyVelocity = velocityCalculator.calculateHubenyVelocity(previousGpsData, nextGpsData); if(1 < i){ hubenyVelocity = smoothingHubenyVelocity(hubenyVelocityBefore, hubenyVelocity); //System.out.println("hubenyVelocity " + hubenyVelocity); hubenyVelocityBefore = hubenyVelocity; } if(hubenyVelocity < hubenyVelocityThreshold){ newestIndex = resultGpsList.size() -1; //取得したデータの重複を避ける if(newestIndex <= 0){ resultGpsList.add(previousGpsData); resultGpsList.add(nextGpsData); }else if(!resultGpsList.get(newestIndex).getTime().equals(previousGpsData.getTime())){ resultGpsList.add(previousGpsData); resultGpsList.add(nextGpsData); }else{ resultGpsList.add(nextGpsData); } } } previousGpsData = nextGpsData; } return resultGpsList; } /** * ヒュベニ速度をスムージングするメソッド * @param HubeneyVelocityBefore * @param HubeneyVelocityNext * @param smoothingRate * @return */ private double smoothingHubenyVelocity(double HubeneyVelocityBefore, double HubeneyVelocityNext){ double HubeneyVelocity = (1.0 - MovingUtil.getSmoothingRate()) * HubeneyVelocityBefore + HubeneyVelocityNext * MovingUtil.getSmoothingRate(); return HubeneyVelocity; } }
d44aa8a22d386d62cb282689d2d5800ee4100721
[ "Java", "Maven POM", "INI", "Gradle" ]
63
Java
gucci-megane/AMS
f43208dbee21959e781d6faea93fcaa7bb3c423c
1f27519cbcef532820d66dd2bde34edd8123fc50
refs/heads/master
<file_sep># Learning Redux This is a small project I have made with two goals: * Learn Redux * Create an React App without the create-react-app CLI.<file_sep>import {combineReducers} from 'redux'; import {ADD_TO_QUEUE, SET_LAST_NUMBER} from './actions.js'; function queue(state = [], action) { if (action.type !== ADD_TO_QUEUE) return state; return [ ...state, action.payload, ]; } function lastNumber(state = null, action) { if (action.type !== SET_LAST_NUMBER) return state; return action.payload; } const learningApp = combineReducers({ queue, lastNumber, }); export default learningApp; <file_sep>import {connect} from 'react-redux'; import {ServiceSelector} from '../screens/serviceSelector'; import {addToQueue, setLastNumber} from '../store/actions.js'; const mapStateToProps = (state) => { return { queue: state.queue, lastNumber: state.lastNumber, } } const mapDispatchToProps = (dispatch) => { return { onClickOnService: (service) => { setTimeout(() => { const number = service[0] + Math.floor(Math.random() * 100); dispatch(addToQueue(number)); dispatch(setLastNumber(number)); setTimeout(() => dispatch(setLastNumber(null)), 5000); }, 500); } } } const Queue = connect( mapStateToProps, mapDispatchToProps )(ServiceSelector); export default Queue; <file_sep>import React from 'react'; import {QueueConfirmation} from '../../components/queueConfirmation/'; import styles from './index.module.css'; export function ServiceSelector(props) { function onClickOnService(service) { props.onClickOnService(service); } return ( <div className="serviceSelector"> <ul> <li> <button onClick={() => onClickOnService('General')} > General Public </button> </li> <li> <button onClick={() => onClickOnService('Priorities')} > Priorities (Senior Citizens, Persons with Disabilities, Pregnant Women) </button> </li> </ul> { props.lastNumber && ( <div> <QueueConfirmation queueNumber={props.lastNumber}/> </div> ) } <div className={styles.teste}> {props.queue.join(', ')} </div> </div> ); } <file_sep>import React from 'react'; export function QueueConfirmation(props) { return ( <div> <h1>Sua senha é {props.queueNumber}</h1> </div> ); } <file_sep>/* * Action Types */ export const ADD_TO_QUEUE = 'ADD_TO_QUEUE'; export const SET_LAST_NUMBER = 'SET_LAST_NUMBER'; /* * Action Creators */ export function addToQueue(queueNumber) { return { type: ADD_TO_QUEUE, payload: queueNumber } } export function setLastNumber(number) { return { type: SET_LAST_NUMBER, payload: number, } }
4146b8badbf8cefce70e2d522028e77a80749af0
[ "Markdown", "JavaScript" ]
6
Markdown
celsopalmeiraneto/learning-redux
b3561a84ffca5267827eb317356eab4d50f94515
4093a492c8b095bb6a693e7350e8d2c76476db44
refs/heads/master
<repo_name>Juanmogal/SQL<file_sep>/Ejemplos restricciones.sql --Crea una base de datos llamada Ejemplos. CREATE DATABASE Ejemplos Crea las tablas siguientes: /*DatosRestrictivos. Columnas: ID Es un SmallInt autonumérico que se rellenará con números impares.. No admite nulos. Clave primaria Nombre: Cadena de tamaño 15. No puede empezar por "N” ni por "X” Añade una restiricción UNIQUE. No admite nulos Numpelos: Int con valores comprendidos entre 0 y 145.000 TipoRopa: Carácter con uno de los siguientes valores: "C”, "F”, "E”, "P”, "B”, ”N” NumSuerte: TinyInt. Tiene que ser un número divisible por 3. Minutos: TinyInt Con valores comprendidos entre 20 y 85 o entre 120 y 185.*/ CREATE TABLE DatosRestrictivos( ID SmallInt Not Null CONSTRAINT PK_ID_DatosRestrictivos Primary Key IDENTITY(1,2) check(ID%2!=0), Nombre Varchar (15) Not Null CHECK (Nombre LIKE '[^n,x]%') UNIQUE, Numpelos Int CHECK(NumPelos between 0 and 145000), TipoRopa Char(1) CHECK(TipoRopa LIKE 2Q'[cfepbn]'), NumSuerte TinyInt CHECK(NumSuerte%3=0), Minutos TinyInt CHECK((Minutos between 20 and 85) OR (Minutos between 120 and 185)) ) DROP TABLE DatosRestrictivos /*DatosRelacionados. Columnas: NombreRelacionado: Cadena de tamaño 15. Define una FK para relacionarla con la columna "Nombre” de la tabla DatosRestrictivos. ¿Deberíamos poner la misma restricción que en la columna correspondiente? ¿Qué ocurriría si la ponemos? ¿Y si no la ponemos? PalabraTabu: Cadena de longitud max 20. No admitirá los valores "Barcenas”, "Gurtel”, "Púnica”, "Bankia” ni "sobre”. Tampoco admitirá ninguna palabra terminada en "eo” NumRarito: TinyInt menor que 20. No admitirá números primos. NumMasgrande: SmallInt. Valores comprendidos entre NumRarito y 1000. Definirlo como clave primaria. ¿Puede tener valores menores que 20? DatosAlMogollon. Columnas: ID. SmallInt. No admitirá múltiplos de 5. Definirlo como PK LimiteSuperior. SmallInt comprendido entre 1500 y 2000. OtroNumero. Será mayor que el ID y Menor que LimiteSuperior. Poner UNIQUE NumeroQueVinoDelMasAlla: SmallInt FK relacionada con NumMasGrande de la tabla DatosRelacionados Etiqueta. Cadena de 3 caracteres. No puede tener los valores "pao”, "peo”, "pio” ni "puo”*/
148c1d3209341efe7dfd2461c70705b40b0799cd
[ "SQL" ]
1
SQL
Juanmogal/SQL
1781da07fa7859613529a450728d673d9c619131
dd42e71ee5cfdc834d647f7b512ff43675f4898c
refs/heads/master
<file_sep>FROM ubuntu:18.04 # Install apache. RUN apt-get update && apt-get install -y --no-install-recommends apache2 libapache2-mod-qos ca-certificates && \ apt-get remove make && apt-get install make && \ apt-get clean && rm -rf /var/cache/apt/* && rm -rf /var/lib/apt/lists/* && \ a2enmod rewrite proxy proxy_http headers proxy_wstunnel # Set server name. RUN echo 'ServerName localhost' >> /etc/apache2/apache2.conf # Add vhosts and enable sites. COPY vhosts /etc/apache2/sites-available RUN cd /etc/apache2/sites-available && a2ensite * && a2dissite default-ssl 000-default EXPOSE 80 443 CMD ["/usr/sbin/apachectl", "-DFOREGROUND"] <file_sep>#!/bin/bash cd /home/serveruser/web/app/main exec gunicorn main.wsgi:application \ --bind 0.0.0.0:8000 \ --capture-output --enable-stdio-inheritance --log-level=debug --access-logfile=- --log-file=- <file_sep>version: "3" services: http: build: context: ./http args: UID: ${USER_ID} GID: ${GROUP_ID} container_name: app_http restart: always ports: - "80:80" - "443:443" volumes: - ./data/web/static:/home/serveruser/static:delegated depends_on: - wsgi networks: app_net: wsgi: build: context: ./wsgi args: UID: ${USER_ID} GID: ${GROUP_ID} container_name: app_wsgi restart: always volumes: - ./data/web:/home/serveruser/web:delegated networks: app_net: networks: app_net: <file_sep>FROM ubuntu:18.04 # Get user id and group id from arguments. ARG UID ARG GID # Create user. RUN groupadd -r serveruser -g $GID && useradd -ms /bin/bash serveruser -u $UID -g $GID # Install some packages. RUN apt-get update && apt-get install -y --no-install-recommends \ python3-minimal python3-setuptools python3-pip && \ pip3 install django gunicorn numpy && \ ln -s /usr/bin/python3 /usr/bin/python && \ ln -s /usr/bin/pip3 /usr/bin/pip && \ pip install --upgrade pip COPY docker-entrypoint.sh /home/serveruser/docker-entrypoint.sh RUN chmod +x /home/serveruser/docker-entrypoint.sh # Change permissions. RUN chown -R serveruser:serveruser /home/serveruser WORKDIR /home/serveruser/web EXPOSE 8000 USER serveruser CMD ["/home/serveruser/docker-entrypoint.sh"] # CMD ["tail", "-f", "/dev/null"] <file_sep># # Copy this file to your root directory and change settings accordingly. # # User id on the host OS. USER_ID=1000 # Group id on the host OS. GROUP_ID=1000 <file_sep># Django - Docker Starter pack This repo contains the starting point to create Django application on Docker. # Check the full explanation videos (GR) [![Πως να Ξεκινήσω, Python Tutorial](https://img.youtube.com/vi/5EX76-whtHw/0.jpg)](https://www.youtube.com/watch?v=5EX76-whtHw&list=PLuswtImoIwq8q097zQp-qIdQGA0IyObir) # Installation Requirements - You need to have [Docker](https://docs.docker.com/engine/installation/) and [Docker Compose](https://docs.docker.com/compose/install/) installed # Run Run in root folder, ~~~ cp .env.example .env docker-compose build && docker-compose up -d ~~~~ Login to the container, ~~~~ docker exec -u serveruser -it app_wsgi /bin/bash -c "TERM=$TERM exec bash" ~~~~ Initial setup, ~~~~ cd ~/web/app/main python manage.py migrate ~~~~ Create admin user, ~~~~ python manage.py createsuperuser ~~~~ Create static files, ~~~~ python manage.py collectstatic ~~~~ Check http://127.0.0.1/admin on your browser and login as admin. Exit the container, ~~~~ exit ~~~~ Stop the containers, ~~~~ docker-compose down ~~~~ # Warning Don't use this in production. It is for educational purposes only. The SECRET_KEY is in source control for Christ's sake. # By SocialNerds * [SocialNerds.gr](https://www.socialnerds.gr/) * [YouTube](https://www.youtube.com/SocialNerdsGR) * [Facebook](https://www.facebook.com/SocialNerdsGR) * [Twitter](https://twitter.com/socialnerdsgr)
54159fa715dc5ab05848847df12a222bf0c3b35a
[ "Markdown", "Dockerfile", "YAML", "Shell" ]
6
Dockerfile
SocialNerds/Python-Django-Starter-Pack
6533d1f67ad6cccba2a3bb8adc9add9bd35d9070
84c226e0e4090d65fe61eff99c0b8f248e8526ca
refs/heads/master
<file_sep>import React from 'react'; import styled from 'styled-components'; const StyledNameCard = styled.div` border: 1px solid rgba(0, 0, 0, 0.1); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); border-radius: 2px; height: 250px; width: 200px; padding: 1rem; margin: 1rem; text-align: center; /* color: red; */ ` const Avatar = styled.img` /* border: 1px solid red; */ height: 75px; width: 75px; border-radius: 100%; margin: 0 auto 20px; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2), 0 4px 6px -2px rgba(0, 0, 0, 0.04); ` const Button = styled.div` /* border: 1px solid gray; */ color: #fff; background-color: #ed3330; border-radius: 5px; display: inline-block; padding: 0.5rem 1rem; text-align: left; margin: 2rem 0; cursor: pointer; font-weight: 600; text-transform: uppercase; font-size: 13px; ` const Heading = styled.div` font-size: 1.5rem; font-weight: 600; ` const NameCard = props => ( <StyledNameCard> <Avatar src={props.avatar} /> <Heading>{props.name}</Heading> <div>{props.title}</div> <Button onClick={() => props.buttonHandler(props)}>Click Me</Button> </StyledNameCard> ) export default NameCard<file_sep>import React from 'react'; import NameCard from './NameCard' import './App.css'; import peach from '../src/peach.png' import qveenHerby from '../src/qveenHerby.jpg' const buttonHandler = (props) => { alert(`Hello, my name is ${props.name} and my title is ${props.title}`) } function App() { return ( <div style={{display: "flex", justifyContent: "center"}} className="App"> <NameCard name="<NAME>" title="Head Princess" avatar={peach} buttonHandler={(props) => buttonHandler(props)} /> <NameCard name="<NAME>" title="Developer" avatar={qveenHerby} buttonHandler={(props) => buttonHandler(props)} /> </div> ); } export default App;
c210ab16d3d268b5ea306e09d785307c0e6000e9
[ "JavaScript" ]
2
JavaScript
ericwhited/loop-react-props
3307c1ecd4c1f2a6d7c7f92f27a887823373213e
576743d08d4c6d2635f8c389c47bff6189f5c4a0
refs/heads/main
<repo_name>codephillip/best-react-todo<file_sep>/src/components/Footer/Footer.js import './Footer.css' const Footer = () => ( <footer> <span className="copyright">&copy; Copy right</span> </footer> ); export default Footer;<file_sep>/src/components/Header/Header.js import './Header.css' const Header = () => ( <header> <h1 className="titletext">Best Todo App</h1> </header> ); export default Header;<file_sep>/src/components/Body/Body.js const Body = () => { return ( <> <h1>Helloworld</h1> </> ); }; export default Body;
448af4609ee0fa3c225b106dbb61265980aae1b9
[ "JavaScript" ]
3
JavaScript
codephillip/best-react-todo
8ae8e6f8f8d14ccf69cdae84431175a676307456
ebe3c75150b00d0e2a79d3d936ee7b6d6f12d61f
refs/heads/master
<file_sep># Mood Desktop for Overwatch This repo readme *mainly* discusses how to run the code. If you don't know what mood.gg is or don't know what the point of the desktop app is please read the blog post [here](https://medium.com/@farzatv/deepoverwatch-combining-tensorflow-js-overwatch-and-music-1a84d4598bc0) and check out the actual website [here](https://mood.gg) :). ![lol](https://i.imgur.com/7PgA65g.jpg) To actually run the app locally, simply pull the repo and do ```npm install && npm start``` within the root directory. Make sure you have node installed! *So why is this desktop app special?* Well, it uses the very recently release TensorFlow.js for a pretty interesting task. To detect + predict what character a person is playing in Overwatch **all in real-time and all within the browser**. **No** Python, **no** crazy dependencies. It detects the character a person is playing in Overwatch by taking screenshots while they are in a game and runs them through my [DeepOverwatch](https://github.com/farzaa/DeepOverwatch) model. *But*, DeepOverwatch is all Keras based, which is written in Python. For this desktop app, I converted my trained Keras/Python based DeepOverwatch model to a TensorFlow.js model. I then load that model within TensorFlow.js and run the user's live gameplay screenshots, which are taken with [this](https://www.npmjs.com/package/screenshot-desktop) library, through the TensorFlow.js ```predict``` function to find out the character a person is playing! That means I never use Python within the actual desktop app anywhere. I just use the converted TensorFlow.js model :). Awesome! All the TensorFlow.js magic happens at *renderer.js*. It is very straightforward, so just take a look at it starting at ```loadModel()``` :). I also use OpenCV.js to cover an edge case. When the *Play of the Game* screen is shown, the UI will change completely to mimic the overlay of the original player. That means the desktop app *thinks* that the actual user switched characters so it will switch playlists. But thats not true! The overlay just changes! To fix this, I do a quick template match to check and see if the user is on the *Play of the Game* screen before switching playlists. <file_sep>const electron = require('electron') // Module to control application life. const app = electron.app // Module to create native browser window. const BrowserWindow = electron.BrowserWindow require('electron-debug')({showDevTools: true}); const path = require('path') const url = require('url') const {globalShortcut} = require('electron') const {ipcMain} = require('electron') var gkm = require('gkm'); const storage = require('electron-json-storage'); global.curr_path = app.getAppPath() ret = [] storage.get('DEFAULT', function(error, data) { if (error) throw error; if(data.PLAYSONGKEY == undefined) { console.log("Defualt doesn't exist! Lets make it") storage.set('DEFAULT', {PREVSONGKEY: "C", PLAYSONGKEY: "V", NEXTSONGKEY: "B", VOLDOWNKEY: "N", VOLUPKEY: "M", HERODETECTIONFLAG: true}, function(error) { if (error) throw error; }); ret[0] = "C" ret[1] = "V" ret[2] = "B" ret[3] = "N" ret[4] = "M" ret[5] = true } else { ret[0] = data.PREVSONGKEY; ret[1] = data.PLAYSONGKEY; ret[2] = data.NEXTSONGKEY; ret[3] = data.VOLDOWNKEY; ret[4] = data.VOLUPKEY; ret[5] = data.HERODETECTIONFLAG; } }); var shift = false; gkm.events.on('key.pressed', function(data) { console.log(data); //console.log("Shift... " + shift) if(data == "Left Control") { console.log("PRESSED SHIFT") shift = true; } }); gkm.events.on('key.released', function(data) { console.log(ret); if(data == ret[0]) { if(shift) { mainWindow.webContents.send('PREVIOUSSONG', 'Pinging prev song from server!') console.log("PREVSONG ACTIVATED") } } if(data == ret[1]) { if(shift) { mainWindow.webContents.send('PLAYSONG', 'Pinging play song from server!') console.log("PLAYSONG ACTIVATED") } } if(data == ret[2]) { if(shift) { mainWindow.webContents.send('NEXTSONG', 'Pinging next song from server!') console.log("NEXT ACTIVATED") } } if(data == ret[3]) { if(shift) { mainWindow.webContents.send('VOLDOWN', 'Pinging volume down from server!') console.log("VOL DOWN ACTIVATED") } } if(data == ret[4]) { if(shift) { mainWindow.webContents.send('VOLUP', 'Pinging volume up from server!') console.log("VOL UP ACTIVATED") } } if(data == "Left Control") { shift = false; } }); ipcMain.on('SetButtons', (event, arg) => { console.log("Recevied request for keys binding change form UI"); storage.clear(function(error) { if (error) throw error; storage.set('DEFAULT', {PREVSONGKEY: arg[0], PLAYSONGKEY: arg[1], NEXTSONGKEY: arg[2], VOLDOWNKEY: arg[3], VOLUPKEY: arg[4], HERODETECTIONFLAG: arg[5]}, function(error) { if (error) throw error; ret[0] = arg[0]; ret[1] = arg[1]; ret[2] = arg[2]; ret[3] = arg[3]; ret[4] = arg[4]; ret[5] = arg[5]; }); }); }); ipcMain.on('ClearStorageButton', (event, arg) => { storage.clear(function(error) { if (error) throw error; console.log("Storage cleared!"); }); }); ipcMain.on('READY', (event, arg) => { mainWindow.webContents.send('UPDATEBINDINGS', JSON.stringify({PREVSONGKEY: ret[0], PLAYSONGKEY: ret[1], NEXTSONGKEY: ret[2], VOLDOWNKEY: ret[3], VOLUPKEY: ret[4], HERODETECTIONFLAG: ret[5]})) }); ipcMain.on('HEROUPDATE', (event, arg) => { console.log(arg) mainWindow.webContents.send('UPDATEHERO', arg) }); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow function createWindow () { mainWindow = new BrowserWindow({width: 1200, height: 1000}); // mainWindow.loadURL('https://www.youtube.com/watch?v=gQWavVwsCFU') // and load the index.html of the app. mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) mainWindow.webContents.openDevTools() // Emitted when the window is closed. mainWindow.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app su pports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null }) //var send = JSON.stringify({PREVSONGKEY: ret[0], PLAYSONGKEY: ret[1], NEXTSONGKEY: ret[2]}) } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow() } }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here.\
61152aeaf04a99cc9c4e33f58d5fe12b7d02e657
[ "Markdown", "JavaScript" ]
2
Markdown
moracabanas/MoodGGDesktopForOW
50c7276caf649f5e7b393b7db37772b97a7fc6d1
8e8ec3b50d91b8a8356ce49fd08f1e7778284cf7
refs/heads/master
<repo_name>willangelico/ajax_with_jquery<file_sep>/post.php <?php // if($_REQUEST){ // echo json_encode(["msg"=>"Request"]); exit; // } //echo "testes"; if($_GET){ $data = listAll(); echo json_encode($data); exit; //header("HTTP/1.0 404 NOT FOUND"); } if($_POST){ //var_dump( $_POST ); exit; $name = $_POST['name']; $email = $_POST['email']; $telephone = $_POST['telephone']; if($name == ""){ echo json_encode(["status"=>false,"msg"=>"Fill in a name"]); exit; } if($email == ""){ echo json_encode(["status"=>false,"msg"=>"Fill in a email"]); exit; } if($telephone == ""){ echo json_encode(["status"=>false,"msg"=>"Fill in a telephone"]); exit; } $id = save($_POST); if($id){ $data = find($id); echo json_encode(["status"=>true,"msg"=>"Success! id:{$id}","contacts"=>$data]); exit; }else{ echo json_encode(["status"=>false,"msg"=>"ERRO DB"]); exit; } } function conn(){ $conn = new \PDO("mysql:host=localhost;dbname=ajax_jquery","root",""); return $conn; } function save($data){ $db = conn(); //$query = "Insert into contact (name, email, tel) values (:name,:email,:telephone)"; $query = "Insert into `contacts` (`name`, `email`, `telephone`) values (:name,:email,:telephone)"; $stmt = $db->prepare($query); $stmt->bindValue(':name',$data['name']); $stmt->bindValue(':email',$data['email']); $stmt->bindValue(':telephone',$data['telephone']); $stmt->execute(); return $db->lastInsertId(); // } function listAll(){ $db = conn(); $query = "Select * from `contacts` order by id DESC"; $stmt = $db->prepare($query); $stmt->execute(); return $stmt->fetchAll(); } function find($id){ $db = conn(); $query = "Select * from `contacts` where id=:id"; $stmt = $db->prepare($query); $stmt->bindValue(':id',$id); $stmt->execute(); return $stmt->fetch(\PDO::FETCH_ASSOC); }
524041152a9b74edd75c2f98bc05595098205254
[ "PHP" ]
1
PHP
willangelico/ajax_with_jquery
d865a7b4d820b135c11cfe474021ad6b54006370
219556952829fbd166b1d6520c98d0f5b34f36ce
refs/heads/master
<repo_name>MilloLab/free-wp-theme-clean-blog<file_sep>/functions.php <?php // adding custom footer social links support /////////////////////////////////////////////////////// function register_customize_menu($wp_customize) { $wp_customize->add_section('custom_header_img', array( 'title' => __('Header image', 'cleanblog'), 'panel' => '', 'priority' => 3 )); $wp_customize->add_setting( 'custom_header_img', array( 'default' => get_template_directory_uri() . '/img/home-bg.jpg', 'transport' => 'refresh' ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'custom_header_img', array( 'label' => __( 'Your header image', 'cleanblog' ), 'section' => 'custom_header_img', 'settings' => 'custom_header_img', 'context' => 'menu_custom_image' ) ) ); // Add Custom social links $wp_customize->add_section( 'custom_social_links' , array( 'title' => __('Social links','cleanblog'), 'panel' => '', 'priority' => 1000 ) ); $wp_customize->add_setting( 'custom_facebook_link', array( 'default' => __( 'http://facebook.com', 'cleanblog' ), 'transport' => 'refresh', 'sanitize_callback' => 'sanitize_text' ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'custom_facebook_link', array( 'label' => __( 'Your Facebook URL', 'cleanblog' ), 'section' => 'custom_social_links', 'settings' => 'custom_facebook_link', 'type' => 'text' ) ) ); $wp_customize->add_setting( 'custom_twitter_link', array( 'default' => __( 'http://twitter.com', 'cleanblog' ), 'transport' => 'refresh', 'sanitize_callback' => 'sanitize_text' ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'custom_twitter_link', array( 'label' => __( 'Your Twitter URL', 'cleanblog' ), 'section' => 'custom_social_links', 'settings' => 'custom_twitter_link', 'type' => 'text' ) ) ); $wp_customize->add_setting( 'custom_linkedin_link', array( 'default' => __( 'http://linkedin.com', 'cleanblog' ), 'transport' => 'refresh', 'sanitize_callback' => 'sanitize_text' ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'custom_linkedin_link', array( 'label' => __( 'Your LinkedIn URL', 'cleanblog' ), 'section' => 'custom_social_links', 'settings' => 'custom_linkedin_link', 'type' => 'text' ) ) ); $wp_customize->add_setting( 'custom_github_link', array( 'default' => __( 'http://github.com', 'cleanblog' ), 'transport' => 'refresh', 'sanitize_callback' => 'sanitize_text' ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'custom_github_link', array( 'label' => __( 'Your Github URL', 'cleanblog' ), 'section' => 'custom_social_links', 'settings' => 'custom_github_link', 'type' => 'text' ) ) ); // Sanitize text function sanitize_text( $text ) { return sanitize_text_field( $text ); } } // closing function add_action( 'customize_register', 'register_customize_menu' ); // Add theme support for Custom Header Image // $defaults = array( // 'default-image' => get_template_directory_uri() . '/img/home-bg.jpg', // 'uploads' => true // ); // add_theme_support( 'custom-header', $defaults ); // Theme plugins requirements //////////////////////////////////////////////////////// /** * This file represents an example of the code that themes would use to register * the required plugins. * * It is expected that theme authors would copy and paste this code into their * functions.php file, and amend to suit. * * @package TGM-Plugin-Activation * @subpackage Example * @version 2.5.0-alpha * @author <NAME> * @author <NAME> * @copyright Copyright (c) 2011, <NAME> * @license http://opensource.org/licenses/gpl-2.0.php GPL v2 or later * @link https://github.com/thomasgriffin/TGM-Plugin-Activation */ /** * Include the TGM_Plugin_Activation class. */ require_once dirname( __FILE__ ) . '/class-tgm-plugin-activation.php'; add_action( 'tgmpa_register', 'my_theme_register_required_plugins' ); /** * Register the required plugins for this theme. * * In this example, we register two plugins - one included with the TGMPA library * and one from the .org repo. * * The variable passed to tgmpa_register_plugins() should be an array of plugin * arrays. * * This function is hooked into tgmpa_init, which is fired within the * TGM_Plugin_Activation class constructor. */ function my_theme_register_required_plugins() { /* * Array of plugin arrays. Required keys are name and slug. * If the source is NOT from the .org repo, then source is also required. */ $plugins = array( // This is an example of how to include a plugin from the WordPress Plugin Repository. array( 'name' => 'WP Subtitle', 'slug' => 'wp-subtitle', 'required' => true, ), array( 'name' => 'Contact Form 7', 'slug' => 'contact-form-7', 'required' => true, ), ); /* * Array of configuration settings. Amend each line as needed. * If you want the default strings to be available under your own theme domain, * leave the strings uncommented. * Some of the strings are wrapped in a sprintf(), so see the comments at the * end of each line for what each argument will be. */ $config = array( 'id' => 'tgmpa', // Unique ID for hashing notices for multiple instances of TGMPA. 'default_path' => '', // Default absolute path to pre-packaged plugins. 'menu' => 'tgmpa-install-plugins', // Menu slug. 'parent_slug' => 'themes.php', // Parent menu slug. 'capability' => 'edit_theme_options', // Capability needed to view plugin install page, should be a capability associated with the parent menu used. 'has_notices' => true, // Show admin notices or not. 'dismissable' => true, // If false, a user cannot dismiss the nag message. 'dismiss_msg' => '', // If 'dismissable' is false, this message will be output at top of nag. 'is_automatic' => false, // Automatically activate plugins after installation or not. 'message' => '', // Message to output right before the plugins table. 'strings' => array( 'page_title' => __( 'Install Required Plugins', 'theme-slug' ), 'menu_title' => __( 'Install Plugins', 'theme-slug' ), 'installing' => __( 'Installing Plugin: %s', 'theme-slug' ), // %s = plugin name. 'oops' => __( 'Something went wrong with the plugin API.', 'theme-slug' ), 'notice_can_install_required' => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'theme-slug' ), // %1$s = plugin name(s). 'notice_can_install_recommended' => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'theme-slug' ), // %1$s = plugin name(s). 'notice_cannot_install' => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin.', 'Sorry, but you do not have the correct permissions to install the %s plugins.', 'theme-slug' ), // %1$s = plugin name(s). 'notice_can_activate_required' => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'theme-slug' ), // %1$s = plugin name(s). 'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'theme-slug' ), // %1$s = plugin name(s). 'notice_cannot_activate' => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin.', 'Sorry, but you do not have the correct permissions to activate the %s plugins.', 'theme-slug' ), // %1$s = plugin name(s). 'notice_ask_to_update' => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'theme-slug' ), // %1$s = plugin name(s). 'notice_cannot_update' => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin.', 'Sorry, but you do not have the correct permissions to update the %s plugins.', 'theme-slug' ), // %1$s = plugin name(s). 'install_link' => _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'theme-slug' ), 'activate_link' => _n_noop( 'Begin activating plugin', 'Begin activating plugins', 'theme-slug' ), 'return' => __( 'Return to Required Plugins Installer', 'theme-slug' ), 'plugin_activated' => __( 'Plugin activated successfully.', 'theme-slug' ), 'complete' => __( 'All plugins installed and activated successfully. %s', 'theme-slug' ), // %s = dashboard link. 'contact_admin' => __( 'Please contact the administrator of this site for help.', 'tgmpa' ), 'nag_type' => 'updated', // Determines admin notice type - can only be 'updated', 'update-nag' or 'error'. ) ); tgmpa( $plugins, $config ); } // adding css //////////////////////////////////////////////////////// function theme_styles() { wp_enqueue_style( 'bootstrap_css', get_template_directory_uri() . '/css/bootstrap.min.css' ); wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'font-awesome','http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css' ); wp_enqueue_style( 'google_font', 'http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' ); wp_enqueue_style( 'google_font2','http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' ); } add_action( 'wp_enqueue_scripts', 'theme_styles' ); // adding js //////////////////////////////////////////////////////// function theme_js() { global $wp_scripts; wp_register_script('html5_shiv', 'https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js', '', '', false); wp_register_script('respond_js', 'https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js', '', '', false); $wp_scripts->add_data('html5_shiv', 'conditional', 'lt IE 9'); $wp_scripts->add_data('respond_js', 'conditional', 'lt IE 9'); wp_enqueue_script( 'bootstrap_js', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '', true ); wp_enqueue_script( 'theme_js', get_template_directory_uri() . '/js/clean-blog.js', array('jquery'), '', true ); } add_action( 'wp_enqueue_scripts', 'theme_js'); // enabling featured image //////////////////////////////////////////////////////// add_theme_support( 'post-thumbnails' ); // enabling nav menu //////////////////////////////////////////////////////// function register_my_menu() { register_nav_menu('menu',__( 'Menu' )); } add_action( 'init', 'register_my_menu' ); ?><file_sep>/footer.php <!-- Footer --> <footer> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <ul class="list-inline text-center"> <?php if( get_theme_mod( 'custom_facebook_link') != "" ): ?> <li> <a href="<?php echo get_theme_mod( 'custom_facebook_link'); ?>" target="_blank"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-facebook fa-stack-1x fa-inverse"></i> </span> </a> </li> <?php endif; ?> <?php if( get_theme_mod( 'custom_twitter_link') != "" ): ?> <li> <a href="<?php echo get_theme_mod( 'custom_twitter_link'); ?>" target="_blank"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> </li> <?php endif; ?> <?php if( get_theme_mod( 'custom_linkedin_link') != "" ): ?> <li> <a href="<?php echo get_theme_mod( 'custom_linkedin_link'); ?>" target="_blank"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i> </span> </a> </li> <?php endif; ?> <?php if( get_theme_mod( 'custom_github_link') != "" ): ?> <li> <a href="<?php echo get_theme_mod( 'custom_github_link'); ?>" target="_blank"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> <?php endif; ?> <li> <a href="/feed" target="_blank"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-rss fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> <p class="copyright text-muted">Copyright &copy; <?php bloginfo('name') ?> <?php echo date('Y'); ?></p> </div> </div> </div> </footer> <?php wp_footer(); ?> </body> </html><file_sep>/page.php <?php get_header(); ?> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <?php if(have_posts()) : while(have_posts()) : the_post(); ?> <?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );?> <header class="intro-header" style="background-image: url('<?php echo $url; ?>')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="page-heading"> <h1><?php the_title(); ?></h1> <hr class="small"> <span class="subheading"><?php the_subtitle(); ?></span> </div> </div> </div> </div> </header> <!-- Main Content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <?php the_content(); ?> </div> </div> </div> <?php endwhile; endif; ?> <hr> <?php get_footer(); ?><file_sep>/home.php <?php get_header(); ?> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('<?php header_image(); ?>')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="site-heading"> <h1><?php bloginfo( 'name' ); ?></h1> <hr class="small"> <span class="subheading"><?php bloginfo( 'description' ); ?></span> </div> </div> </div> </div> </header> <!-- Main Content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <?php if(have_posts()) : while(have_posts()) : the_post(); ?> <div class="post-preview"> <a href="<?php the_permalink(); ?>"> <h2 class="post-title"> <?php the_title(); ?> </h2> <h3 class="post-subtitle"> <?php the_excerpt() ?> </h3> </a> <p class="post-meta">Posted by <?php the_author(); ?> on <?php the_date(); ?></p> </div> <hr> <?php endwhile; endif; ?> <!-- Pager --> <ul class="pager"> <li class="next"> <?php next_posts_link(); ?> </li> </ul> </div> </div> </div> <hr> <?php get_footer(); ?><file_sep>/README.md # [Clean Blog](http://startbootstrap.com/template-overviews/clean-blog/) Wordpress Theme by [MilloLab](http://millolab.com) [Clean Blog](http://startbootstrap.com/template-overviews/clean-blog/) is a stylish, responsive blog theme for [Bootstrap](http://getbootstrap.com/) created by [Start Bootstrap](http://startbootstrap.com/). This theme features a blog homepage, about page, contact page, and an example post page along with a working PHP contact form. MilloLab Team has developed a wordpress theme based on this beautiful template to all you folks! For free! ## Getting Started To use this theme, choose one of the following options to get started: * Fork this repository on GitHub * We are studying few online options to share the theme with you for free. ## Installation Just use [the zip file](https://github.com/MilloLab/free-wp-theme-clean-blog/blob/master/cleanblog.zip?raw=true) to install the theme at Appearance > Themes > Add and upload it. ### Plugins The theme automatically ask you to install the plugins needed, *WP Subtitle* and *Contact Form 7* ### Customize You can add the home image and social links through the menu Appearance > Theme > The Clean Blog > Customize. ### Contact page Just create a page and paste the shortcode generated by the Contact Form 7 plugin. And that's it! ## Bugs and Issues Have a bug or an issue with this theme? [Open a new issue](https://github.com/MilloLab/free-wp-theme-clean-blog/issues) here on GitHub or leave us a comment on [Facebook](http://facebook.com/millolab) or [Twitter](http://twitter.com/millolab). ## Creator Start Bootstrap was created by and is maintained by **<NAME>**, Managing Parter at [Iron Summit Media Strategies](http://www.ironsummitmedia.com/). * https://twitter.com/davidmillerskt * https://github.com/davidtmiller Start Bootstrap is based on the [Bootstrap](http://getbootstrap.com/) framework created by [<NAME>](https://twitter.com/mdo) and [<NAME>](https://twitter.com/fat). Millolab has coded the theme to share it with you! ## Copyright and License Copyright 2013-2015 Iron Summit Media Strategies, LLC. Code released under the [Apache 2.0](https://github.com/IronSummitMedia/startbootstrap-clean-blog/blob/gh-pages/LICENSE) license.
d9e24ad7ce9dd8b0c7bfdb381ebe03e087d1e63e
[ "Markdown", "PHP" ]
5
PHP
MilloLab/free-wp-theme-clean-blog
45922ebc1c4dcc4fd0aa2b8dc88095ee143ac4aa
9532dbc8b34d6e26d04b9c67113d9170a9ca9a31
refs/heads/master
<repo_name>davidwhitney/ConwaySummitDryRun<file_sep>/Conway/Runner/Program.cs using System; using System.Threading; using Runner.Core; namespace Runner { class Program { static void Main(string[] args) { var sim = new Simulation(); while (true) { sim.Step(); var state = sim.ToString(); Console.Clear(); Console.WriteLine(state); Thread.Sleep(100); } } } } <file_sep>/Conway/Runner.Core/Simulation.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Runner.Core { public class Simulation { public void Step() { throw new NotImplementedException(); } } }
42940b934bfa6fde332475f27a5241a76e191573
[ "C#" ]
2
C#
davidwhitney/ConwaySummitDryRun
5b2beb146df93992496abae21a6bc8e4cdb51f63
e3ac1d152b2df175373d1aca4feae9b716b8c7d5
refs/heads/master
<file_sep> def sql_helper(connect, exception, exception_handling, req, *params): """ used to implement the connection to differente database if params is a list or map, it's an executemany if the request is an insert, it return the key id connection must have .execute, .executemany, .lastrowid and .fetchall """ many = False if len(params) == 1: if isinstance(params[0], (list, map)): many = True params = params[0] is_insert = req.split()[0].lower() == 'insert' with connect() as con: try: if many: return con.executemany(req, params).fetchall() else: c = con.execute(req, params) except exception as e: exception_handling(e) if is_insert: return c.lastrowid return c.fetchall() <file_sep>from setuptools import setup setup( name='CRUD_vanilla', version='1.0', description='database tools to link models to data_access', author='Pythux', # author_email='', packages=[ 'CRUD_vanilla', 'CRUD_vanilla.connection', ], # same as name # install_requires=[], # external packages as dependencies ) <file_sep>from .crud_helper import CRUDHelper from .crud import CRUD from .interface import InterfaceCRUD from .database import DataBase import CRUD_vanilla.connection as connection <file_sep># database simple CRUD database access look the lswf project to see how it's used <file_sep> from abc import ABCMeta, abstractmethod from CRUD_vanilla import CRUD class InterfaceCRUD(CRUD, metaclass=ABCMeta): @property @abstractmethod def table(): raise NotImplementedError @property @abstractmethod def key_name(): raise NotImplementedError @abstractmethod def get_params_and_values(obj): raise NotImplementedError <file_sep>from CRUD_vanilla import CRUDHelper class CRUD(CRUDHelper): def create(self, obj): obj.key = self._create(*self.get_params_and_values(obj)) def read(self, obj): u_names, u_values = self.get_unique(obj) selected = self._read(obj.key, u_names, u_values) if selected: self.set_obj(obj, selected) return True return False def update(self, obj): self._update( obj.key, *self.get_params_and_values(obj)) def delete(self, obj): self._delete(obj) def update_or_create(self, obj): if not obj.key: self.read(obj) if obj.key: self.update(obj) else: self.create(obj) <file_sep> class CRUDHelper: def __init__(self, sql): self.sql = sql def _create(self, values_names, values): values_interog = ', '.join(['?'] * len(values_names)) return self.sql( 'insert into {}({}) values ({})' .format(self.table, ', '.join(values_names), values_interog), *values) def _read(self, key, values_names, values): if key: where = self.key_name + ' = ?', (key,) elif isinstance(values_names, list): where = (' AND '.join([name + ' = ?' for name in values_names]), values) else: where = values_names + ' = ?', (values,) r = self.sql('select * from {} where {}' .format(self.table, where[0]), *where[1]) if r == []: return None elif len(r) != 1: raise ValueError('_read must return a single element') else: return r[0] def _update(self, key, values_names, values): if not key: raise ValueError("can't update without the obj key") if not isinstance(values_names, list): values_names = [values_names] values_names = ', '.join([name + ' = ?' for name in values_names]) self.sql('update {} set {} where {} = ?' .format(self.table, values_names, self.key_name), *values, key) def _delete(self, obj): if not obj.key: raise ValueError("can't delete without the obj key") self.sql('delete from {} where {} = ?' .format(self.table, self.key_name), obj.key) obj.key = None <file_sep> class DataBase: def __init__(self, dict_entity): self.dict_entity = dict_entity def __getattr__(self, name): def chose_service(obj, *args): entity_name = obj.__class__.__name__ f = getattr(self.dict_entity[entity_name], name) return f(obj, *args) return chose_service <file_sep>from .sqlite import sql_sqlite <file_sep>import sqlite3 from .sql_helper import sql_helper def sql_sqlite(db_path, req, *params): def connect(): return sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES ) def exception_handling(e): raise sqlite3.ProgrammingError( str(e) + '\nreq = “{}”\nparams = “{}”'.format(req, params)) exception = ( sqlite3.ProgrammingError, sqlite3.InterfaceError, sqlite3.IntegrityError, sqlite3.OperationalError) return sql_helper( connect, exception, exception_handling, req, *params)
f146d089e1dfa0703c9d86b979a848fa725ee234
[ "Markdown", "Python" ]
10
Python
Pythux/py_CRUD_vanilla
73419a684c171396993d3343982ab458cf946064
83e89329570de54483769bae0cac62b8f7415a19
refs/heads/master
<repo_name>lincoln-center/sro-launch-page<file_sep>/assets/js/signup.min.js function isValidEmailAddress(e) { var t = new RegExp(".+@.+..+"); return t.test(e); } function enableSubmitIfValid() { var e = $("#email-address").val(); isValidEmailAddress(e) && $("#submit-button").attr("class", "btn btn-danger"); isValidEmailAddress(e) || $("#submit-button").attr("class", "btn btn-danger disabled"); } function submitEmail() { var e = $("#email-address").val(); if (isValidEmailAddress(e)) { $("#formwrap").empty(); var t = encodeURIComponent(e), n = "<h3><strong>Thank you!</strong> <small>We’ll be in touch soon to " + e + ".</small><img src='http://server1.emailcampaigns.net/autoadd/?c=2jBLA2&email=" + t + "&lid=49&Source=AtriumFlix'>"; $("#results").append(n); } } $(document).ready(function() { $("#email-address").each(function() { var e = $(this); e.data("oldVal", e.val()); e.bind("propertychange keyup input paste", function() { e.data("oldVal") !== e.val() && enableSubmitIfValid(); }); }); $("#email-signup").bind("submit", function() { submitEmail(); return !1; }); });
a4ec35ed14f02a80118b824e48626895e9c4a6fc
[ "JavaScript" ]
1
JavaScript
lincoln-center/sro-launch-page
f351cc7712a731af85d93d0db1306b649969faaa
89da84c8ca4f8af1a5a6d0f39628025114a29b92
refs/heads/master
<repo_name>tlchenshao/ds_homework1<file_sep>/homework1/test1_13_lg1705_ds1.cpp #include <stdio.h> #include "sqlist.h" void main() { list l; init_sqlist(NULL); insert_pos(&l,7,35); clear_sqlist(&l); //is_empty(&l); } /* void get_max(int *arr,int len,int *t) { int max = arr[0]; for (int i=0;i<len;++i) { if (max < arr[i]) { max = arr[i]; } } *t = max; } void main() { int arr[] = {55,33,99,66,77}; int len = sizeof(arr)/sizeof(arr[0]); int temp; get_max(arr,len,&temp); printf("%d\n",temp); } */ <file_sep>/homework1/sqlist.cpp #include "sqlist.h" #include <stdio.h> #include <assert.h> void init_sqlist(list *p)//初始化顺序表 { assert(p != NULL); for (int i=0;i<MAXSIZE;++i) { p->data[i] = 0; } p->len = 0; } bool is_empty(list *p) { if (p->len == 0) { return true; } return false; } bool is_full(list *p) { if (p->len == MAXSIZE) { return true; } return false; } int get_len(list *p) { return p->len; } void insert_tail(list *p,int value) { if (is_full(p)) { printf("error....\n"); return ; } p->data[p->len] = value; p->len ++; } void insert_head(list *p,int value) { if (!is_full(p)) { for(int i=p->len-1;i>=0;i--) { p->data[i+1] = p->data[i]; } p->data[0] = value; p->len ++; } } //-2 bool insert_pos(list *p,int pos,int value) { //异常位置不能插 满了不能插 if(is_full(p) || pos > p->len || pos < 0) { return false; } for(int i=p->len-1;i>=pos;--i) { p->data[i+1] = p->data[i]; } p->data[pos] = value; p->len ++; return true; } void clear_sqlist(list *p) { for (int i=0;i<MAXSIZE;++i) { p->data[i] = 0; } p->len = 0; }<file_sep>/homework1/sqlist.h #ifndef SQLIST //防止头文件被引入多次 #define SQLIST //非定长的顺序表 #define MAXSIZE 10 typedef int elem_type; typedef struct sqlist { elem_type data[MAXSIZE]; //定长顺序表 int len;// 代表顺序表中有几个元素 }list; void init_sqlist(list *p);//初始化顺序表 bool is_empty(list *p); bool is_full(list *p); int get_len(list *p); void insert_tail(list *p,elem_type value); void insert_head(list *p,elem_type value); bool insert_pos(list *p,int pos,elem_type value); void clear_sqlist(list *p); #endif
163130040f4b058533bddec5ba5499e3d3f981b7
[ "C", "C++" ]
3
C++
tlchenshao/ds_homework1
ce4b54cd6c9cb3cd29c25099cf9479d7d053f13a
cbe9fe5e622f810897d8d1ddde531459db569e78
refs/heads/master
<file_sep>package code._4_student_effort; public class Fish extends Animal implements Pet{ String name; Fish(String name){ super(0); this.name = name; } Fish(){ this(""); } @Override void walk(){ System.out.println("The fish can't walk because he has "+ this.legs + " legs!"); } @Override void eat() { System.out.println("The fish ate sea food!"); } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public void play() { System.out.println("The fish plays in the water!"); } } <file_sep>package code._4_student_effort; import java.util.Scanner; public class PairOf3 { public static boolean isFound(int[] a, int i, int n){ for(int x=0; x<n; x++){ if(a[x]==i) { return true; } } return false; } public static int findPairs(int v[], int n){ int apearences[] = new int[n]; int index = 0; int pairs = 0; outer: for(int i=0; i<n-2; i++){ if(isFound(apearences, i, index)==true) continue; for(int j=i+1; j<n-1; j++){ if(isFound(apearences, j, index)==true) continue; for(int k=i+2; k<n; k++){ if(isFound(apearences, k, index)==true) continue; if(v[i]+v[j]+v[k]==0){ apearences[index]=j; apearences[index+1]=k; index = index+2; pairs++; continue outer; } } } } return pairs; } public static void main(String[] args) { int n; System.out.print("Cate elemente vreti sa contina vectorul?: "); Scanner info = new Scanner(System.in); n = info.nextInt(); int vector[] = new int[n]; for(int i=0; i<n; i++) { System.out.print("Adaugati elemntul " + i + ": "); vector[i] = info.nextInt(); } System.out.println("In vector sunt "+ PairOf3.findPairs(vector, n) + " perechi!"); } } <file_sep>package code._4_student_effort; public class Film { Integer anAparitie; String nume; Actor[] actori; Film(Integer anAparitie, String nume, Actor[] actori){ this.anAparitie = anAparitie; this.nume = nume; this.actori = actori; } } <file_sep>package code._4_student_effort; public class TestAnimals { public static void main(String[] args) { Fish d = new Fish(); Cat c = new Cat("Fluffy"); Animal a = new Fish(); Animal e = new Spider(); Pet p = new Cat(); //Methods for obj d System.out.println("*** Method testing for obj d ***"); d.walk(); d.eat(); System.out.println(d.getName()); d.play(); d.setName("Sasha"); System.out.println(d.getName()); //Methods for obj c System.out.println("*** Method testing for obj c ***"); c.walk(); c.eat(); System.out.println(c.getName()); c.play(); c.setName("Jerry"); System.out.println(c.getName()); //Methods for obj a System.out.println("*** Method testing for obj a ***"); a.walk(); a.eat(); //Methods for obj e System.out.println("*** Method testing for obj e ***"); e.walk(); e.eat(); //Methods for obj p System.out.println("*** Method testing for obj p ***"); System.out.println(p.getName()); p.setName("Sasha"); System.out.println(p.getName()); p.play(); } }
b7b51e00e55d002c62714aee4d7e240907948f3d
[ "Java" ]
4
Java
GColumbu/java-training
949185d48ebe2333f4b3e3e5acb2cd3c26c25881
24046c23b062bffbfe8665d2014590195ae1bbb8
refs/heads/master
<repo_name>Rajeshwari10Bligar/StringHomework<file_sep>/ConcatinationForLoop.java package loveProgramming; public class ConcatinationForLoop { public static void main(String[] args){ String myString = " "; for(int i=20;i>=1;i--){ myString = myString+i; } System.out.println(myString); } }
685df18d9724784ad392cd604fef5ba80129364a
[ "Java" ]
1
Java
Rajeshwari10Bligar/StringHomework
a58db1bdc4cad5f8db5194c619d6e3c3f8524c58
031d0a894112d77a60f0c6dd3877f722092000a7
refs/heads/master
<repo_name>tosik/go-react-graphql-sandbox<file_sep>/server/server.go package main import ( "context" "log" "net/http" "os" "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/playground" "github.com/rs/cors" "gocloud.dev/docstore" _ "gocloud.dev/docstore/memdocstore" _ "gocloud.dev/docstore/mongodocstore" "github.com/tosik/go-react-graphql-sandbox/server/graph" "github.com/tosik/go-react-graphql-sandbox/server/graph/generated" "github.com/tosik/go-react-graphql-sandbox/server/graph/model" ) //go:generate go run github.com/99designs/gqlgen generate" const defaultPort = "8080" func main() { ctx := context.Background() // url := "mongo://foo/books?id_field=ID" url := "mem://foo/ID" coll, err := docstore.OpenCollection(ctx, url) defer coll.Close() if err != nil { log.Fatalln(err) panic(err) } if err := putSampleData(ctx, coll); err != nil { log.Fatalln(err) } listen(coll) } func putSampleData(ctx context.Context, coll *docstore.Collection) error { books := []model.Book{ {ID: graph.GenerateId(), Title: "Alice In Wonderland", Price: 123, Foo: 98765}, {ID: graph.GenerateId(), Title: "Cinderella", Price: 345, Foo: "STRING TYPE"}, } for _, book := range books { if err := coll.Put(ctx, &book); err != nil { return err } } return nil } func listen(coll *docstore.Collection) { port := os.Getenv("PORT") if port == "" { port = defaultPort } c := cors.New(cors.Options{ AllowedOrigins: []string{"http://localhost:3000"}, AllowCredentials: true, }) srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{ Resolvers: &graph.Resolver{ Coll: coll, }})) http.Handle("/", playground.Handler("GraphQL playground", "/query")) http.Handle("/query", c.Handler(srv)) log.Printf("connect to http://localhost:%s/ for GraphQL playground", port) log.Fatal(http.ListenAndServe(":"+port, nil)) } <file_sep>/server/graph/utilities.go package graph import ( "encoding/base64" "math/rand" "github.com/vmihailenco/msgpack" ) func GenerateId() string { b, err := msgpack.Marshal(rand.Int()) if err != nil { panic(err) } return base64.StdEncoding.EncodeToString(b) } <file_sep>/server/graph/schema.resolvers.go package graph // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. import ( "context" "fmt" "io" "log" "github.com/tosik/go-react-graphql-sandbox/server/graph/generated" "github.com/tosik/go-react-graphql-sandbox/server/graph/model" "gocloud.dev/docstore" ) func (r *bookConnectionResolver) Nodes(ctx context.Context, obj *model.BookConnection) ([]*model.Book, error) { panic(fmt.Errorf("not implemented")) } func (r *mutationResolver) CreateBook(ctx context.Context, input model.NewBook) (*model.Book, error) { newBook := model.Book{ ID: GenerateId(), Title: input.Title, Price: input.Price, Foo: input.Foo, } // err := r.Resolver.Coll.Actions().Put(&input).Get(&got).Do(ctx) err := r.Resolver.Coll.Put(ctx, &newBook) if err != nil { log.Fatalln(err) return nil, err } got := &model.Book{ID: newBook.ID} err = r.Resolver.Coll.Get(ctx, got) if err != nil { log.Fatalln(err) return nil, err } return got, nil } func (r *queryResolver) Books(ctx context.Context, first *int, afterCursor *string, beforeCursor *string) (*model.BookConnection, error) { paginationFunc := func(offset, limit int) (items []*model.Book, total *int, err error) { iter := r.Resolver.Coll.Query().OrderBy("ID", docstore.Descending).Limit(limit).Get(ctx) defer iter.Stop() sum := 0 dest := []*model.Book{} for { var book model.Book err := iter.Next(ctx, &book) if err == io.EOF { break } else if err != nil { log.Fatalln(err) return nil, nil, err } sum += 1 dest = append(dest, &book) } return dest, &sum, nil } dest, err := model.NewBookPage(10, first, afterCursor, beforeCursor, paginationFunc) return dest, err } // BookConnection returns generated.BookConnectionResolver implementation. func (r *Resolver) BookConnection() generated.BookConnectionResolver { return &bookConnectionResolver{r} } // Mutation returns generated.MutationResolver implementation. func (r *Resolver) Mutation() generated.MutationResolver { return &mutationResolver{r} } // Query returns generated.QueryResolver implementation. func (r *Resolver) Query() generated.QueryResolver { return &queryResolver{r} } type bookConnectionResolver struct{ *Resolver } type mutationResolver struct{ *Resolver } type queryResolver struct{ *Resolver } <file_sep>/server/go.mod module github.com/tosik/go-react-graphql-sandbox/server go 1.14 require ( github.com/99designs/gqlgen v0.11.3 github.com/gorilla/websocket v1.4.2 // indirect github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/mitchellh/mapstructure v1.2.2 // indirect github.com/pkg/errors v0.9.1 github.com/rs/cors v1.6.0 github.com/vektah/gqlparser/v2 v2.0.1 github.com/vmihailenco/msgpack v4.0.4+incompatible gitlab.com/hookactions/gqlgen-relay v1.0.1 gocloud.dev v0.19.0 gocloud.dev/docstore/mongodocstore v0.19.0 golang.org/x/net v0.0.0-20200226121028-0de0cce0169b // indirect golang.org/x/sys v0.0.0-20200321134203-328b4cd54aae // indirect golang.org/x/tools v0.0.0-20200321224714-0d839f3cf2ed // indirect gopkg.in/yaml.v2 v2.2.8 // indirect ) <file_sep>/docker-compose.yaml version: "3" services: db: image: postgres:10-alpine ports: - "5432:5432" environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=<PASSWORD> - PGPASSWORD=<PASSWORD> - POSTGRES_DB=development - DATABASE_HOST=localhost volumes: - $PWD/docker/db/init:/docker-entrypoint-initdb.d mongo: image: mongo restart: always environment: MONGO_INITDB_ROOT_USERNAME: user MONGO_INITDB_ROOT_PASSWORD: <PASSWORD> ports: - 27017:27017 volumes: - ./tmp/db:/data/db - ./tmp/configdb:/data/configdb <file_sep>/server/graph/model/book.go package model import "fmt" //go:generate sh -c "~/code/src/gitlab.com/hookactions/gqlgen-relay/gqlgen-relay -pkg model -name Book -type *Book -cursor > graph/model/book_relay.go" func (b *Book) GetID() fmt.Stringer { return b } func (b *Book) String() string { return b.ID } <file_sep>/server/server_test.go package main import ( "context" "testing" "gocloud.dev/docstore" ) func TestMain(t *testing.T) { url := "mem://test/ID" ctx := context.Background() coll, err := docstore.OpenCollection(ctx, url) defer coll.Close() if err != nil { t.Fatalf("cannot open memstore: %s", err) } err = putSampleData(ctx, coll) if err != nil { t.Fatalf("cannot put sample: %s", err) } }
ac261a979c26d269fd1284b73668989fbc3b6f28
[ "Go Module", "Go", "YAML" ]
7
Go
tosik/go-react-graphql-sandbox
29e505ca9377d544c8a308901ae2419f8f021db5
c97a6e722251dcc1d4fc206701d7ff9959cfd0df
refs/heads/master
<repo_name>bavanya/multiThreading-In-Java<file_sep>/README.md # multiThreading-In-Java Experimented with multi threading in Java by running simple programs on single thread and on multiple threads and compared the running time of both the programs. Few cases are possible where programs run faster on single thread than on multiple threads. Please have a look at this [article](https://medium.com/contentsquare-engineering-blog/multithreading-vs-multiprocessing-in-python-ece023ad55a) to learn more. <file_sep>/src/com/company/SkeletonMultiThreaded.java package com.company; public class SkeletonMultiThreaded implements Runnable{ public long number; public long multiple; public SkeletonMultiThreaded(long number, long multiple){ this.number = number; this.multiple = multiple; } public long getNumber(){ return number; } public long getMultiple(){ return multiple; } public long getResult(){ return number*multiple; } public void run(){ getResult(); } } <file_sep>/src/com/company/Main.java package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { long number; long noOfTimes; int noOfThreads; int countOfThreads; Scanner input = new Scanner(System.in); number = input.nextLong(); noOfTimes = input.nextLong(); long startTime1 = System.currentTimeMillis(); Skeleton skeleton = new Skeleton(number,noOfTimes); for( long i = 1 ; i <= skeleton.getNoOfTimes() ; i++ ) System.out.println(skeleton.getNumber() + " times " + i + " is " + skeleton.getMultiple(i)); System.out.println('\n'); long endTime1 = System.currentTimeMillis(); float timeTaken1 = (endTime1 - startTime1) / 1000F; System.out.println("Time taken for single process is" + timeTaken1 + " seconds"); number = input.nextLong(); noOfTimes = input.nextLong(); noOfThreads = input.nextInt(); countOfThreads = noOfThreads - 1; SkeletonMultiThreaded[] skeletonMultiThreaded = new SkeletonMultiThreaded[noOfThreads]; Thread[] t = new Thread[noOfThreads]; long startTime2 = System.currentTimeMillis(); for( long i = 1 ; i <= noOfTimes ; i++ ){ if(countOfThreads != -1){ skeletonMultiThreaded[noOfThreads - countOfThreads - 1] = new SkeletonMultiThreaded(number,i); countOfThreads--; } if(countOfThreads == -1) { for( int j = 0; j < noOfThreads ; j++){ t[j] = new Thread(skeletonMultiThreaded[j]); t[j].start(); } for( int j = 0; j < noOfThreads ; j++ ){ try { t[j].join(); System.out.println(skeletonMultiThreaded[j].getNumber() + " times " + skeletonMultiThreaded[j].getMultiple()+ " is " + skeletonMultiThreaded[j].getResult()); } catch (InterruptedException e) { e.printStackTrace(); } } countOfThreads = noOfThreads - 1; } } if( countOfThreads != noOfThreads - 1 ){ for( int j = 0; j <noOfThreads - countOfThreads-1 ; j++ ){ t[j] = new Thread(skeletonMultiThreaded[j]); t[j].start(); } for( int j = 0; j < noOfThreads - countOfThreads - 1 ; j++ ){ try { t[j].join(); System.out.println(skeletonMultiThreaded[j].getNumber() + " times " + skeletonMultiThreaded[j].getMultiple()+ " is " + skeletonMultiThreaded[j].getResult()); } catch (InterruptedException e) { e.printStackTrace(); } } } long endTime2 = System.currentTimeMillis(); float timeTaken2 = (endTime2 - startTime2) / 1000F; System.out.println("Time taken for multiThreaded process is" + timeTaken2 + " seconds"); } } <file_sep>/src/com/company/Skeleton.java package com.company; import java.lang.Math; public class Skeleton { public long number; public long noOfTimes; public Skeleton(long number, long noOfTimes){ this.number = number; this.noOfTimes = noOfTimes; } public long getNumber(){ return number; } public long getMultiple(long noOfTimes){ return number*noOfTimes; } public double getNoOfTimes() { return noOfTimes; } }
59088316722c9362991a3228ce895f92cd9cbc55
[ "Markdown", "Java" ]
4
Markdown
bavanya/multiThreading-In-Java
92e2e6501da2c7af314aa83fcddb60d6a9d3eafc
987e014ac395268bc00a6604236c1f97fedd168e
refs/heads/master
<repo_name>iiimosley/NSS-MF-Routes<file_sep>/app/app.js 'use strict'; let routes = angular.module("routes", ['ngRoute']) .config($routeProvider => { $routeProvider .when("/", { templateUrl: "../partials/main.html" }) .when("/sunbelt", { templateUrl: "../partials/highway.html", controller: "Highway1" }) .when("/pacific", { templateUrl: "../partials/highway.html", controller: "Highway2" }) .otherwise("/"); });<file_sep>/app/controllers/highway2.js "use strict"; angular.module("routes") .controller("Highway2", function ($scope) { $scope.highwayName = "Pacific Highway"; $scope.highwayDescription = "Iconic drive through California to the Northwestern states"; });<file_sep>/app/controllers/highway1.js "use strict"; angular.module("routes") .controller("Highway1", function ($scope) { $scope.highwayName = "Interstate 40"; $scope.highwayDescription = "Stretching east to west across the Sunbelt. Connecting many states to one steady path."; }); <file_sep>/README.md # NSS: Modern Frameworks - Route Routing/Listing Exercise ## Directives Create a basic AngularJs application with two views providing information of two seperate highways, including the the highways name and a description of the highway. ### Required Components + Angular application module, injecting `ngRoute` + `config` section for seperate routes + highway #1 + highway #2 + x2 controllers, defined in application + both containing `$scope.highwayName` & `$scope.highwayDescription` + scoped variable values set personally + x2 partials per controller ### Assignment Extension Add a default view/home-page to the application + +1 route to app module that will load a listing of highways + each listing to be anchor hyperlinks to each configured routes + add `otherwise` configuration to routing
efee51fe1c49f1fff2cc4dd84d333365f05b4c36
[ "JavaScript", "Markdown" ]
4
JavaScript
iiimosley/NSS-MF-Routes
fbc4ad3225353e5269b92b19c547e62f397512e8
7899feabaae3232641ddb1f1bb86343c44853d76
refs/heads/master
<file_sep>package service; import forms.UserForm; public interface UserManager { public void regUser(UserForm userForm); }
428204096beb5a869ec234ff84ab637ae803f789
[ "Java" ]
1
Java
ydw5271084/SSH
d1af4c42a1761d4b47d9ac5bd11eb52b2906ca44
c4aa623253826953f0dc089d9d9e8d2f387ca762
refs/heads/master
<file_sep>import { Action, applyMiddleware, combineReducers, createStore } from "redux"; import thunk, { ThunkDispatch } from "redux-thunk"; import { todoReducer } from "./reducers/todo"; import { counterReducer } from "./reducers/counter"; const rootReducer = combineReducers({ todoReducer, counterReducer, }) export const store = createStore(rootReducer, applyMiddleware(thunk)) export type TRootState = ReturnType<typeof rootReducer>; export type TAppDispatch = typeof store.dispatch; <file_sep>import axios from "axios"; class HttpService { public static getHeader(): any { return { Authorization: "Bearer " + window.localStorage.getItem("x-token"), }; } public static get(url: string) { const xhr = axios({ method: "GET", url: `/api/${url}`, headers: HttpService.getHeader(), }).then((res) => res.data); return xhr; } } export default HttpService; <file_sep>import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux" import { Action, AnyAction } from "redux" import { ThunkDispatch } from "redux-thunk" import { TAppDispatch, TRootState } from "../store" export const useAppDispatch = () => useDispatch<TAppDispatch>() export const useAppThunkDispatch = () => useDispatch<ThunkDispatch<TRootState, any, any>>() export const useAppSelector: TypedUseSelectorHook<TRootState> = useSelector <file_sep>import moment from "moment"; export interface ITodo { id: string; title?: string; momentFrom?: moment.Moment; momentDue?: moment.Moment; } export interface ITodoState { todos: ITodo[]; loading: boolean; error: string; } export enum ETodoActionType { SET_TODOS, SET_ERROR, SET_LOADING, } export interface ITodoActionSetTodos { type: ETodoActionType.SET_TODOS; payload: ITodo[]; } export interface ITodoActionSetError { type: ETodoActionType.SET_ERROR; payload: string; } export interface ITodoActionSetLoading { type: ETodoActionType.SET_LOADING; payload: boolean; } export type TTodoAction = | ITodoActionSetTodos | ITodoActionSetError | ITodoActionSetLoading; <file_sep>import { ETodoActionType, ITodoState, TTodoAction } from "../../types/todo"; const initialState: ITodoState = { todos: [], error: "", loading: false, } export const todoReducer = (state: Readonly<ITodoState> = initialState, action: Readonly<TTodoAction>): ITodoState => { switch(action.type){ case ETodoActionType.SET_TODOS: return { ...state, todos: action.payload } case ETodoActionType.SET_ERROR: return { ...state, error: action.payload } case ETodoActionType.SET_LOADING: return { ...state, loading: action.payload } default: return state } }<file_sep>export interface ICounterState { counter: number; } export enum ECounterActionType { SET_COUNTER } export interface ISetCounterAction { type: ECounterActionType.SET_COUNTER; payload: number; } export type TCounterAction = ISetCounterAction<file_sep>import { ETodoActionType, ITodo, TTodoAction } from "../../types/todo"; import { AnyAction, Dispatch } from "redux"; import { TAppDispatch, TRootState } from ".."; import { ThunkAction } from "redux-thunk"; export function setError(error: string): TTodoAction { return { type: ETodoActionType.SET_ERROR, payload: error }; } export function setLoading(loading: boolean): TTodoAction { return { type: ETodoActionType.SET_LOADING, payload: loading }; } export function setTodos(todos: ITodo[]): TTodoAction { return { type: ETodoActionType.SET_TODOS, payload: todos }; } export function fetchTodos() { return async function (dispatch: Dispatch, getState: () => TRootState) {}; } export const thunkSetError = (errorMessage: string) => async (dispatch: TAppDispatch, getState: () => TRootState) => { setTimeout(() => { dispatch(setError(errorMessage)); }, 1000); }; <file_sep>import { ECounterActionType, ICounterState, TCounterAction, } from "../../types/counter"; const initialState: ICounterState = { counter: 0, }; export const counterReducer = ( state: ICounterState = initialState, action: TCounterAction ): ICounterState => { switch (action.type) { case ECounterActionType.SET_COUNTER: return { ...state, counter: action.payload }; default: return state; } }; <file_sep>export const checkInputIsANumber = (inputValue: string) => { const outputValue: number = parseInt(inputValue); if (isNaN(outputValue)) return 0; return outputValue; };
e122319cec037a8f7d3995a1e8f4a3bccd866f2d
[ "TypeScript" ]
9
TypeScript
sergmcode/initial
545073a824bc6f99d50523386b6f85f43d0af9f0
f8ee86dfef911be35d50a8537b122f9642a895c1
refs/heads/master
<repo_name>chrisdothtml/push-it<file_sep>/main/utils.js const fs = require('pfs') exports.buildQuery = data => { return Object.keys(data) .map(key => `${key}=${data[key]}`) .join('&') } exports.pathExists = filepath => { return fs.access(filepath) .then(() => true) .catch(() => false) } exports.sortAlpha = (a, b) => { return a.localeCompare(b) } <file_sep>/renderer/common/MaterialIcon.jsx import React from 'react' import * as icons from '@material-ui/icons' import { camelCase } from 'lodash-es' export default function MaterialIcon (props) { const camelCaseName = camelCase(props.name) const classCaseName = camelCaseName.charAt(0).toUpperCase() + camelCaseName.slice(1) const Component = icons[classCaseName] const iconProps = Object.assign({}, props, { className: `material-icon icon-${props.name}` }) delete iconProps.name return <Component { ...iconProps } /> } <file_sep>/main/window-manager.js const menubarCreator = require('menubar') const path = require('path') const windowState = require('electron-window-state') const { BrowserWindow } = require('electron') const { buildQuery } = require('./utils.js') const ROOT_PATH = path.resolve(__dirname, '../') const IS_PRODUCTION = process.env.NODE_ENV === 'production' const WINDOWS = {} function getScreenUrl (filename, data = {}) { const query = buildQuery(data) const filepath = `${filename}.html?${query}` let dirpath if (IS_PRODUCTION) { dirpath = `file://${path.join(ROOT_PATH, 'dist')}` } else { dirpath = `http://localhost:${process.env.PORT || 8080}` } return `${dirpath}/${filepath}` } function createMenubar () { return menubarCreator({ alwaysOnTop: !IS_PRODUCTION, // dev only icon: path.resolve(ROOT_PATH, 'icons/icon.png'), index: getScreenUrl('repo-list'), preloadWindow: true, resizable: false, transparent: true, vibrancy: 'medium-light', }) } function createRepoWindow (repoPath) { const pathParts = repoPath.split(path.sep) const repoName = pathParts[pathParts.length - 1] const state = windowState({ defaultHeight: 750, defaultWidth: 1150, file: 'repo.json', }) const window = new BrowserWindow({ acceptFirstMouse: true, backgroundColor: '#fff', height: state.height, title: `Push It - ${repoName}`, titleBarStyle: 'hiddenInset', width: state.width, x: state.x, y: state.y, }) window.loadURL(getScreenUrl('repo', { repoName, repoPath })) state.manage(window) // TODO: add event handlers for window (destroy, etc) return window } exports.create = function (type, id) { let window switch (type) { case 'menubar': window = createMenubar() break case 'repo': window = createRepoWindow(id) break } if (id) { WINDOWS[`${type}-${id}`] = window } else { WINDOWS[type] = window } return window } exports.get = function (type, id) { let result if (id) { result = WINDOWS[`${type}-${id}`] } else { result = WINDOWS[type] } return result } <file_sep>/readme.md # Push It > Trying to build a faster, simpler git client with electron <file_sep>/main/git.js const fs = require('pfs') const isomorphicGit = require('isomorphic-git') const path = require('path') const { pathExists, sortAlpha } = require('./utils.js') const git = new Proxy(isomorphicGit, { wrapper: func => (dir, options = {}) => { return func(Object.assign(options, { dir, fs })) }, get (obj, prop) { if (typeof obj[prop] === 'function') { return this.wrapper(obj[prop]) } else { return obj[prop] } } }) // TODO: make this more efficient exports.getReposFromDir = async function (reposDir) { let result = [] try { const dirList = await fs.readdir(reposDir) const filtered = await Promise.all( dirList.map(async (repoName) => { const isGitRepo = await pathExists(path.join(reposDir, repoName, '.git')) return isGitRepo ? repoName : false }) ) return Promise.all( filtered .filter(Boolean) .sort(sortAlpha) .map(async (name) => { const fullpath = path.join(reposDir, name) return { branch: await git.currentBranch(fullpath), fullpath, name } }) ) } catch (error) { console.log(error) } return result } <file_sep>/renderer/screens/repo-list/RepoList.jsx import Octicon from '../../common/Octicon.jsx' import React from 'react' import { ipcRenderer } from 'electron' import './RepoList.css' function Repo (props) { const { repo } = props return ( <li className="repo"> <button className="clickbox" onClick={ () => ipcRenderer.send('open-repo', repo.fullpath) }> <span className="repo-name">{ repo.name }</span> <div className="repo-branch"> <Octicon name="git-branch" /> <span className="branch-label">{ repo.branch }</span> </div> </button> </li> ) } function List (props) { const { isLoading, repos } = props let result if (isLoading) { result = 'Loading...' } else if (repos.length) { result = ( <ul className="repos"> { repos.map((repo, i) => ( <Repo repo={ repo } key={ i } /> )) } </ul> ) } else { result = 'No repos :(' } return result } export default class RepoList extends React.Component { constructor (props) { super(props) this.state = { isLoading: true, repos: [] } } componentDidMount () { ipcRenderer.send('fetch-repos') ipcRenderer.on('receive-repos', (event, repos) => { this.setState({ isLoading: false, repos }) }) } render () { return ( <div className="repo-list"> <div className="toolbar"> <div className="ghost-bg"></div> <div className="content"> <button title="Clone new repo" onClick={ () => ipcRenderer.send('open-clone') }> <Octicon name="plus" /> </button> <button title="Settings" onClick={ () => ipcRenderer.send('open-settings') }> <Octicon name="gear" /> </button> </div> </div> <List { ...this.state } /> </div> ) } } <file_sep>/todo.md - add linting - add preferences - set repos location - splash screen - watch files in repo location(s) - make message for no repos - repo screen - handle main screen closing when other screens are open <file_sep>/main/index.js const keyBindings = require('./key-bindings.js') const path = require('path') const windowManager = require('./window-manager.js') const { app, ipcMain } = require('electron') const { getReposFromDir } = require('./git.js') app.on('ready', () => { windowManager.create('menubar') keyBindings.registerGlobal() }) ipcMain.on('fetch-repos', (event) => { // TODO: set in preferences - https://github.com/nathanbuchar/electron-settings const reposPath = '/Users/chris/projects' getReposFromDir(reposPath) .then(repos => event.sender.send('receive-repos', repos)) .catch(e => console.error(e)) }) ipcMain.on('fetch-repo', (event, repoPath) => { // TODO: get working dir, commit tree, stashes in parallel console.log('fetching repo', repoPath) }) ipcMain.on('open-clone', (event, repoPath) => { console.log('opening clone') }) ipcMain.on('open-repo', (event, repoPath) => { const window = windowManager.get('repo', repoPath) if (window && !window.isDestroyed()) { if (!window.isVisible() || !window.isFocused()) { window.show() window.focus() } } else { windowManager.create('repo', repoPath) } }) ipcMain.on('open-settings', (event, repoPath) => { console.log('opening settings') }) <file_sep>/renderer/common/utils.js export function parseQuery (queryString) { return queryString .replace(/^\?/, '') .split('&') .reduce((result, query) => { const [ key, value ] = query.split('=') return Object.assign(result, { [key]: (value || true) }) }, {}) }
ee5175c283b2efc20a47c227ad50f4c5ee8b2f54
[ "JavaScript", "Markdown" ]
9
JavaScript
chrisdothtml/push-it
70663bfe59717cc5ee93bdcfe0aa0f0c6756b4a7
0c2ef1ed7a30c710e09e3192bf452ed4e870547c
refs/heads/master
<repo_name>choikwangil95/wetube-Clone-coding<file_sep>/README.md # Webute Cloning Youtube with Vanilla and NodeJS<file_sep>/app.js import express from "express"; import morgan from "morgan"; import helmet from "helmet"; import cookieParser from "cookie-parser"; import bodyParser from "body-parser"; import {localsMiddleware} from "./middlewares"; // 변수를 넘겨주기위해 localsmiddleware 사용한건가? import userRouter from "./routers/userRouter"; import videoRouter from "./routers/videoRouter"; import globalRouter from "./routers/globalRouter"; import routes from "./routes"; // express server 호출 const app = express(); // app을 setting app.set('view engine', 'pug'); // 여기서부터 middleware app.use("/uploads", express.static("uploads")); //static은 주어진 directory에서 file을 전달하는 middleware app.use(localsMiddleware); //변수 가져오기 app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended : true})); app.use(helmet()); // 보안? app.use(morgan("dev")); // morgan은 어떤 종류의 접속인지 logging을 하여 알려준다 // URL을 get하는 Method로 브라우저에 요청 한 것 app.use(routes.home, globalRouter); app.use(routes.users, userRouter); // /user 에 userRouter을 주면 django에 include처럼 userRouter로 가서 route가 작동됨 app.use(routes.video, videoRouter); export default app; // 다른 파일에서 app을 사용할 수 있도록 app을 수출해준다
6b297739f7fbc61b718b616ffb1dd144610d8c0e
[ "Markdown", "JavaScript" ]
2
Markdown
choikwangil95/wetube-Clone-coding
07f26e4d596515e2fdd491f8abd61c7f87935e43
3eae5a2da2a373ca32a3a77d90c5a26e99597e58